phasesmith-io 0.4.1

Native file-format adapters for PhaseSmith
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! Deterministic readers for common text powder-pattern formats.

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fs;
use std::path::{Path, PathBuf};

use phasesmith_model::{DomainError, PatternRecord, TofPatternRecord};

type GsasBank = (Vec<String>, Vec<String>);
type GsasBanks = BTreeMap<usize, GsasBank>;

/// Caller-selected or detected powder text format.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PowderFormat {
    /// Detect GSAS bank headers or fall back to plain columns.
    #[default]
    Auto,
    /// Two or three whitespace/comma-separated columns.
    Columns,
    /// Unpacked constant-wavelength GSAS FXYE bank.
    GsasFxye,
    /// Packed constant-step GSAS STD bank.
    GsasStd,
}

/// Caller-selected or detected microsecond-domain powder text format.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TofPowderFormat {
    /// Detect a supported GSAS bank or fall back to center/density columns.
    #[default]
    Auto,
    /// Two or three columns: bin-center TOF, intensity density, and optional sigma.
    Columns,
    /// GSAS logarithmic FXYE bin boundaries with width-multiplied values.
    GsasSlogFxye,
    /// GSAS packed constant-step lower-bin boundaries and integrated counts.
    GsasConstStd,
}

/// Resource limits checked before or during parsing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PowderReadLimits {
    /// Maximum UTF-8 byte count.
    pub max_bytes: usize,
    /// Maximum number of output samples.
    pub max_rows: usize,
}

impl Default for PowderReadLimits {
    fn default() -> Self {
        Self {
            max_bytes: 64 * 1024 * 1024,
            max_rows: 5_000_000,
        }
    }
}

impl PowderReadLimits {
    /// Validate positive byte and row limits.
    ///
    /// # Errors
    ///
    /// Returns [`PowderIoError::InvalidLimits`] when either limit is zero.
    pub fn validate(self) -> Result<(), PowderIoError> {
        if self.max_bytes == 0 || self.max_rows == 0 {
            return Err(PowderIoError::InvalidLimits);
        }
        Ok(())
    }
}

/// One observed powder dataset plus source metadata.
#[derive(Clone, Debug, PartialEq)]
pub struct PowderData {
    /// Validated observed pattern with zero supplied background.
    pub pattern: PatternRecord,
    /// Concrete detected/selected format.
    pub format: PowderFormat,
    /// Source path when read from a file.
    pub source_path: Option<PathBuf>,
    /// Selected GSAS bank, absent for columns.
    pub bank: Option<usize>,
}

/// One observed TOF powder dataset with an explicitly microsecond-domain axis.
#[derive(Clone, Debug, PartialEq)]
pub struct TofPowderData {
    /// Validated bin-center TOF density pattern; it cannot be passed as a CW pattern.
    pub pattern: TofPatternRecord,
    /// Concrete detected/selected input convention.
    pub format: TofPowderFormat,
    /// Source path when read from a file.
    pub source_path: Option<PathBuf>,
    /// Selected positive GSAS bank, absent for plain columns.
    pub bank: Option<usize>,
    /// True when the selected bank declares logarithmic `SLOG` spacing.
    pub logarithmic_grid: bool,
}

/// Native powder input failure with stable categories.
#[derive(Debug)]
pub enum PowderIoError {
    /// A configured resource limit is zero.
    InvalidLimits,
    /// A selected GSAS bank is zero.
    InvalidBank,
    /// Input exceeds the configured byte limit.
    ByteLimitExceeded {
        /// Observed byte count.
        actual: u64,
        /// Configured maximum.
        maximum: usize,
    },
    /// Parsed rows exceed the configured maximum.
    RowLimitExceeded {
        /// Configured maximum.
        maximum: usize,
    },
    /// Filesystem or UTF-8 reading failed.
    Io(std::io::Error),
    /// A line contains invalid syntax.
    Parse {
        /// One-based input line, or zero for bank-wide metadata.
        line: usize,
        /// Stable explanation.
        message: String,
    },
    /// The requested bank is unavailable.
    MissingBank {
        /// Requested positive bank number.
        requested: usize,
        /// Available banks in numeric order.
        available: Vec<usize>,
    },
    /// Parsed numeric arrays violate the domain model.
    Domain(DomainError),
}

impl Display for PowderIoError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidLimits => formatter.write_str("powder read limits must be positive"),
            Self::InvalidBank => formatter.write_str("bank must be a positive integer"),
            Self::ByteLimitExceeded { actual, maximum } => {
                write!(
                    formatter,
                    "powder input exceeds max_bytes: {actual} > {maximum}"
                )
            }
            Self::RowLimitExceeded { maximum } => {
                write!(formatter, "powder data exceeds max_rows: {maximum}")
            }
            Self::Io(error) => Display::fmt(error, formatter),
            Self::Parse { line: 0, message } => formatter.write_str(message),
            Self::Parse { line, message } => write!(formatter, "line {line}: {message}"),
            Self::MissingBank {
                requested,
                available,
            } => {
                let values = available
                    .iter()
                    .map(usize::to_string)
                    .collect::<Vec<_>>()
                    .join(", ");
                write!(
                    formatter,
                    "GSAS bank {requested} not found; available banks: {}",
                    if values.is_empty() { "none" } else { &values }
                )
            }
            Self::Domain(error) => Display::fmt(error, formatter),
        }
    }
}

impl Error for PowderIoError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            Self::Domain(error) => Some(error),
            _ => None,
        }
    }
}

/// Read and parse one bounded UTF-8 powder file.
///
/// # Errors
///
/// Returns [`PowderIoError`] for filesystem, limit, syntax, or domain errors.
pub fn read_powder_file(
    path: impl AsRef<Path>,
    format: PowderFormat,
    bank: usize,
    limits: PowderReadLimits,
) -> Result<PowderData, PowderIoError> {
    limits.validate()?;
    if bank == 0 {
        return Err(PowderIoError::InvalidBank);
    }
    let path = path.as_ref();
    let size = fs::metadata(path).map_err(PowderIoError::Io)?.len();
    if size > u64::try_from(limits.max_bytes).unwrap_or(u64::MAX) {
        return Err(PowderIoError::ByteLimitExceeded {
            actual: size,
            maximum: limits.max_bytes,
        });
    }
    let text = fs::read_to_string(path).map_err(PowderIoError::Io)?;
    parse_powder_text_inner(&text, format, bank, limits, Some(path.to_owned()))
}

/// Parse bounded UTF-8 powder text without filesystem access.
///
/// # Errors
///
/// Returns [`PowderIoError`] for limit, syntax, or domain errors.
pub fn parse_powder_text(
    text: &str,
    format: PowderFormat,
    bank: usize,
    limits: PowderReadLimits,
) -> Result<PowderData, PowderIoError> {
    parse_powder_text_inner(text, format, bank, limits, None)
}

/// Read one bounded reduced TOF file into bin-center intensity densities.
///
/// The input convention is detected as plain center/density columns, GSAS SLOG
/// FXYE boundaries, or packed constant-step GSAS STD counts.
///
/// # Errors
///
/// Returns [`PowderIoError`] for filesystem, limit, syntax, bank, or domain errors.
pub fn read_tof_powder_file(
    path: impl AsRef<Path>,
    bank: usize,
    limits: PowderReadLimits,
) -> Result<TofPowderData, PowderIoError> {
    read_tof_powder_file_as(path, TofPowderFormat::Auto, bank, limits)
}

/// Read one bounded microsecond-domain powder file with an explicit convention.
///
/// # Errors
///
/// Returns [`PowderIoError`] for filesystem, limit, syntax, bank, or domain errors.
pub fn read_tof_powder_file_as(
    path: impl AsRef<Path>,
    format: TofPowderFormat,
    bank: usize,
    limits: PowderReadLimits,
) -> Result<TofPowderData, PowderIoError> {
    limits.validate()?;
    if bank == 0 {
        return Err(PowderIoError::InvalidBank);
    }
    let path = path.as_ref();
    let size = fs::metadata(path).map_err(PowderIoError::Io)?.len();
    if size > u64::try_from(limits.max_bytes).unwrap_or(u64::MAX) {
        return Err(PowderIoError::ByteLimitExceeded {
            actual: size,
            maximum: limits.max_bytes,
        });
    }
    let text = fs::read_to_string(path).map_err(PowderIoError::Io)?;
    parse_tof_powder_text_inner(&text, format, bank, limits, Some(path.to_owned()))
}

/// Parse one bounded reduced TOF input into bin-center intensity densities.
///
/// # Errors
///
/// Returns [`PowderIoError`] for limit, syntax, bank, or domain errors.
pub fn parse_tof_powder_text(
    text: &str,
    bank: usize,
    limits: PowderReadLimits,
) -> Result<TofPowderData, PowderIoError> {
    parse_tof_powder_text_as(text, TofPowderFormat::Auto, bank, limits)
}

/// Parse bounded microsecond-domain powder text with an explicit convention.
///
/// # Errors
///
/// Returns [`PowderIoError`] for limit, syntax, bank, or domain errors.
pub fn parse_tof_powder_text_as(
    text: &str,
    format: TofPowderFormat,
    bank: usize,
    limits: PowderReadLimits,
) -> Result<TofPowderData, PowderIoError> {
    parse_tof_powder_text_inner(text, format, bank, limits, None)
}

fn parse_tof_powder_text_inner(
    text: &str,
    format: TofPowderFormat,
    bank: usize,
    limits: PowderReadLimits,
    source_path: Option<PathBuf>,
) -> Result<TofPowderData, PowderIoError> {
    limits.validate()?;
    if bank == 0 {
        return Err(PowderIoError::InvalidBank);
    }
    if text.len() > limits.max_bytes {
        return Err(PowderIoError::ByteLimitExceeded {
            actual: u64::try_from(text.len()).unwrap_or(u64::MAX),
            maximum: limits.max_bytes,
        });
    }
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let resolved = match format {
        TofPowderFormat::Auto
            if text
                .lines()
                .any(|line| line.trim_start().starts_with("BANK")) =>
        {
            let banks = gsas_banks(text)?;
            let (header, _) = selected_bank(&banks, bank)?;
            if header
                .last()
                .is_some_and(|value| value.eq_ignore_ascii_case("FXYE"))
            {
                TofPowderFormat::GsasSlogFxye
            } else {
                TofPowderFormat::GsasConstStd
            }
        }
        TofPowderFormat::Auto => TofPowderFormat::Columns,
        selected => selected,
    };
    match resolved {
        TofPowderFormat::Columns => read_tof_columns(text, source_path, limits.max_rows),
        TofPowderFormat::GsasConstStd => {
            read_tof_gsas_std(text, source_path, bank, limits.max_rows)
        }
        TofPowderFormat::GsasSlogFxye => {
            read_tof_gsas_slog_fxye(text, source_path, bank, limits.max_rows)
        }
        TofPowderFormat::Auto => unreachable!("auto TOF format is resolved above"),
    }
}

fn read_tof_gsas_slog_fxye(
    text: &str,
    source_path: Option<PathBuf>,
    bank: usize,
    max_rows: usize,
) -> Result<TofPowderData, PowderIoError> {
    let banks = gsas_banks(text)?;
    let (header, lines) = selected_bank(&banks, bank)?;
    if header
        .get(4)
        .is_none_or(|value| !value.eq_ignore_ascii_case("SLOG"))
        || header
            .last()
            .is_none_or(|value| !value.eq_ignore_ascii_case("FXYE"))
    {
        return Err(parse_error(0, "TOF input requires a GSAS SLOG FXYE bank"));
    }
    let declared_rows = header
        .get(2)
        .and_then(|value| value.parse::<usize>().ok())
        .ok_or_else(|| parse_error(0, "invalid GSAS TOF bank dimensions"))?;
    let rows = numeric_rows(&lines.join("\n"), Some(3), max_rows)?;
    if rows.len() != declared_rows {
        return Err(parse_error(
            0,
            format!(
                "GSAS TOF bank contains {} rows; expected {declared_rows}",
                rows.len()
            ),
        ));
    }
    if rows.len() < 2 {
        return Err(parse_error(
            0,
            "GSAS TOF SLOG FXYE requires at least two bin-boundary rows",
        ));
    }
    let output_count = rows.len() - 1;
    let mut tof_us = Vec::with_capacity(output_count);
    let mut observed_y = Vec::with_capacity(output_count);
    let mut uncertainty = Vec::with_capacity(output_count);
    let mut mask = Vec::with_capacity(output_count);
    for pair in rows.windows(2) {
        let row = &pair[0];
        let next = &pair[1];
        let width = next[0] - row[0];
        if !width.is_finite() || width <= 0.0 {
            return Err(parse_error(
                0,
                "GSAS TOF bin boundaries must be finite and strictly increasing",
            ));
        }
        let supplied = row[2];
        if supplied < 0.0 {
            return Err(parse_error(0, "GSAS TOF uncertainty must be nonnegative"));
        }
        tof_us.push(0.5 * (row[0] + next[0]));
        observed_y.push(row[1] / width);
        uncertainty.push(if supplied == 0.0 {
            1.0
        } else {
            supplied / width
        });
        mask.push(supplied != 0.0 && row[1] != 0.0);
    }
    let mask = mask.iter().any(|included| !included).then_some(mask);
    let pattern = TofPatternRecord::new(tof_us, Some(observed_y), Some(uncertainty), mask, None)
        .map_err(PowderIoError::Domain)?;
    Ok(TofPowderData {
        pattern,
        format: TofPowderFormat::GsasSlogFxye,
        source_path,
        bank: Some(bank),
        logarithmic_grid: true,
    })
}

fn read_tof_columns(
    text: &str,
    source_path: Option<PathBuf>,
    max_rows: usize,
) -> Result<TofPowderData, PowderIoError> {
    let rows = numeric_rows(text, None, max_rows)?;
    let columns = rows
        .first()
        .map(Vec::len)
        .ok_or_else(|| parse_error(0, "powder input contains no numeric rows"))?;
    if !matches!(columns, 2 | 3) || rows.iter().any(|row| row.len() != columns) {
        return Err(parse_error(
            0,
            "TOF columns require two or three consistent numeric fields",
        ));
    }
    let uncertainty = (columns == 3).then(|| rows.iter().map(|row| row[2]).collect::<Vec<_>>());
    if uncertainty
        .as_deref()
        .is_some_and(|values| values.iter().any(|value| *value <= 0.0))
    {
        return Err(parse_error(
            0,
            "TOF column uncertainty must be finite and positive",
        ));
    }
    let pattern = TofPatternRecord::new(
        rows.iter().map(|row| row[0]).collect(),
        Some(rows.iter().map(|row| row[1]).collect()),
        uncertainty,
        None,
        None,
    )
    .map_err(PowderIoError::Domain)?;
    Ok(TofPowderData {
        pattern,
        format: TofPowderFormat::Columns,
        source_path,
        bank: None,
        logarithmic_grid: false,
    })
}

fn read_tof_gsas_std(
    text: &str,
    source_path: Option<PathBuf>,
    bank: usize,
    max_rows: usize,
) -> Result<TofPowderData, PowderIoError> {
    let banks = gsas_banks(text)?;
    let (header, lines) = selected_bank(&banks, bank)?;
    let encoding = if header.len() >= 10 {
        header.last().map_or("", String::as_str)
    } else {
        "STD"
    };
    if header.len() < 7
        || !header[4].eq_ignore_ascii_case("CONST")
        || !encoding.eq_ignore_ascii_case("STD")
    {
        return Err(parse_error(
            0,
            "TOF input requires a packed constant-step GSAS STD bank",
        ));
    }
    let row_count = header[2]
        .parse::<usize>()
        .map_err(|_| parse_error(0, "invalid packed GSAS TOF bank dimensions"))?;
    let lower_us = parse_header_f64(&header[5])?;
    let step_us = parse_header_f64(&header[6])?;
    if row_count == 0 || row_count > max_rows || !lower_us.is_finite() || !step_us.is_finite() {
        return Err(parse_error(
            0,
            "packed GSAS TOF bank dimensions exceed limits or are non-finite",
        ));
    }
    if step_us <= 0.0 {
        return Err(parse_error(0, "packed GSAS TOF step must be positive"));
    }
    let (counts, count_sigma) = packed_std_values(lines, row_count)?;
    let mut tof_us = Vec::with_capacity(row_count);
    let mut observed_y = Vec::with_capacity(row_count);
    let mut uncertainty = Vec::with_capacity(row_count);
    let mut mask = Vec::with_capacity(row_count);
    for (index, (&count, &sigma)) in counts.iter().zip(&count_sigma).enumerate() {
        let exact_index = u32::try_from(index)
            .map_err(|_| parse_error(0, "packed GSAS TOF bank dimensions exceed numeric limits"))?;
        tof_us.push(lower_us + (f64::from(exact_index) + 0.5) * step_us);
        observed_y.push(count / step_us);
        uncertainty.push(if count > 0.0 { sigma / step_us } else { 1.0 });
        mask.push(count > 0.0);
    }
    let pattern = TofPatternRecord::new(
        tof_us,
        Some(observed_y),
        Some(uncertainty),
        mask.iter().any(|included| !included).then_some(mask),
        None,
    )
    .map_err(PowderIoError::Domain)?;
    Ok(TofPowderData {
        pattern,
        format: TofPowderFormat::GsasConstStd,
        source_path,
        bank: Some(bank),
        logarithmic_grid: false,
    })
}

fn parse_powder_text_inner(
    text: &str,
    format: PowderFormat,
    bank: usize,
    limits: PowderReadLimits,
    source_path: Option<PathBuf>,
) -> Result<PowderData, PowderIoError> {
    limits.validate()?;
    if bank == 0 {
        return Err(PowderIoError::InvalidBank);
    }
    if text.len() > limits.max_bytes {
        return Err(PowderIoError::ByteLimitExceeded {
            actual: text.len() as u64,
            maximum: limits.max_bytes,
        });
    }
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let selected = match format {
        PowderFormat::Auto => detect_format(text, source_path.as_deref()),
        selected => selected,
    };
    match selected {
        PowderFormat::Columns => read_columns(text, source_path, limits.max_rows),
        PowderFormat::GsasFxye => read_gsas_fxye(text, source_path, bank, limits.max_rows),
        PowderFormat::GsasStd => read_gsas_std(text, source_path, bank, limits.max_rows),
        PowderFormat::Auto => unreachable!("auto format is resolved above"),
    }
}

fn detect_format(text: &str, source: Option<&Path>) -> PowderFormat {
    let headers = text
        .lines()
        .map(str::trim)
        .filter(|line| line.to_ascii_uppercase().starts_with("BANK "))
        .collect::<Vec<_>>();
    if headers
        .iter()
        .filter_map(|header| header.split_whitespace().next_back())
        .any(|encoding| encoding.eq_ignore_ascii_case("FXYE"))
    {
        return PowderFormat::GsasFxye;
    }
    if !headers.is_empty() {
        return PowderFormat::GsasStd;
    }
    if source
        .and_then(Path::extension)
        .is_some_and(|extension| extension.eq_ignore_ascii_case("fxye"))
    {
        return PowderFormat::GsasFxye;
    }
    PowderFormat::Columns
}

fn numeric_rows(
    text: &str,
    required_columns: Option<usize>,
    max_rows: usize,
) -> Result<Vec<Vec<f64>>, PowderIoError> {
    let mut rows = Vec::new();
    let mut columns = required_columns;
    for (index, raw) in text.lines().enumerate() {
        let line_number = index + 1;
        let mut line = raw.trim();
        if line.is_empty() || line.starts_with(['#', '!', ';']) {
            continue;
        }
        if let Some(offset) = line.find(['#', '!']) {
            line = line[..offset].trim();
        }
        if line.is_empty() {
            continue;
        }
        let fields = line.replace(',', " ");
        let fields = fields.split_whitespace().collect::<Vec<_>>();
        if columns.is_none() && !matches!(fields.len(), 2 | 3) {
            return Err(parse_error(line_number, "expected two or three columns"));
        }
        let expected = *columns.get_or_insert(fields.len());
        if fields.len() != expected {
            return Err(parse_error(
                line_number,
                format!("expected {expected} columns, got {}", fields.len()),
            ));
        }
        let row = fields
            .iter()
            .map(|field| {
                field
                    .parse::<f64>()
                    .map_err(|_| parse_error(line_number, "non-numeric powder value"))
            })
            .collect::<Result<Vec<_>, _>>()?;
        rows.push(row);
        if rows.len() > max_rows {
            return Err(PowderIoError::RowLimitExceeded { maximum: max_rows });
        }
    }
    if rows.is_empty() {
        return Err(parse_error(0, "powder data contains no numeric rows"));
    }
    Ok(rows)
}

fn powder_data(
    x_deg: Vec<f64>,
    observed_y: Vec<f64>,
    uncertainty: Option<Vec<f64>>,
    mask: Option<Vec<bool>>,
    format: PowderFormat,
    source_path: Option<PathBuf>,
    bank: Option<usize>,
) -> Result<PowderData, PowderIoError> {
    if x_deg.is_empty() {
        return Err(parse_error(0, "powder data contains no numeric rows"));
    }
    let pattern = PatternRecord::new(x_deg, Some(observed_y), uncertainty, mask, None)
        .map_err(PowderIoError::Domain)?;
    Ok(PowderData {
        pattern,
        format,
        source_path,
        bank,
    })
}

fn read_columns(
    text: &str,
    source: Option<PathBuf>,
    max_rows: usize,
) -> Result<PowderData, PowderIoError> {
    let rows = numeric_rows(text, None, max_rows)?;
    let has_uncertainty = rows[0].len() == 3;
    powder_data(
        rows.iter().map(|row| row[0]).collect(),
        rows.iter().map(|row| row[1]).collect(),
        has_uncertainty.then(|| rows.iter().map(|row| row[2]).collect()),
        None,
        PowderFormat::Columns,
        source,
        None,
    )
}

fn gsas_banks(text: &str) -> Result<GsasBanks, PowderIoError> {
    let mut banks = BTreeMap::new();
    let mut active = None;
    for (index, raw) in text.lines().enumerate() {
        let line = raw.trim();
        if line.to_ascii_uppercase().starts_with("BANK ") {
            let fields = line
                .split_whitespace()
                .map(str::to_owned)
                .collect::<Vec<_>>();
            let bank = fields
                .get(1)
                .and_then(|value| value.parse::<usize>().ok())
                .ok_or_else(|| parse_error(index + 1, "invalid GSAS bank header"))?;
            if banks.insert(bank, (fields, Vec::new())).is_some() {
                return Err(parse_error(
                    index + 1,
                    format!("duplicate GSAS bank {bank}"),
                ));
            }
            active = Some(bank);
        } else if let Some(bank) = active {
            banks
                .get_mut(&bank)
                .expect("active bank exists")
                .1
                .push(raw.to_owned());
        }
    }
    Ok(banks)
}

fn selected_bank(banks: &GsasBanks, bank: usize) -> Result<&GsasBank, PowderIoError> {
    banks.get(&bank).ok_or_else(|| PowderIoError::MissingBank {
        requested: bank,
        available: banks.keys().copied().collect(),
    })
}

fn read_gsas_fxye(
    text: &str,
    source: Option<PathBuf>,
    bank: usize,
    max_rows: usize,
) -> Result<PowderData, PowderIoError> {
    let banks = gsas_banks(text)?;
    if banks.values().any(|(header, _)| {
        header
            .last()
            .is_none_or(|value| !value.eq_ignore_ascii_case("FXYE"))
    }) {
        return Err(parse_error(
            0,
            "only unpacked GSAS FXYE banks are supported",
        ));
    }
    let (header, lines) = selected_bank(&banks, bank)?;
    debug_assert!(
        header
            .last()
            .is_some_and(|value| value.eq_ignore_ascii_case("FXYE"))
    );
    let rows = numeric_rows(&lines.join("\n"), Some(3), max_rows)?;
    let mut uncertainty = Vec::with_capacity(rows.len());
    let mut mask = Vec::with_capacity(rows.len());
    for row in &rows {
        let supplied = row[2];
        uncertainty.push(if supplied == 0.0 { 1.0 } else { supplied });
        mask.push(supplied != 0.0);
    }
    let mask = mask.iter().any(|included| !included).then_some(mask);
    powder_data(
        rows.iter().map(|row| row[0] / 100.0).collect(),
        rows.iter().map(|row| row[1]).collect(),
        Some(uncertainty),
        mask,
        PowderFormat::GsasFxye,
        source,
        Some(bank),
    )
}

fn read_gsas_std(
    text: &str,
    source: Option<PathBuf>,
    bank: usize,
    max_rows: usize,
) -> Result<PowderData, PowderIoError> {
    let banks = gsas_banks(text)?;
    let (header, lines) = selected_bank(&banks, bank)?;
    let encoding = if header.len() >= 10 {
        header.last().map_or("", String::as_str)
    } else {
        "STD"
    };
    if header.len() < 7
        || !header[4].eq_ignore_ascii_case("CONST")
        || !encoding.eq_ignore_ascii_case("STD")
    {
        return Err(parse_error(
            0,
            "only packed constant-step GSAS STD banks are supported",
        ));
    }
    let row_count = header[2]
        .parse::<usize>()
        .map_err(|_| parse_error(0, "invalid packed GSAS STD bank dimensions"))?;
    let start_deg = parse_header_f64(&header[5])? / 100.0;
    let step_deg = parse_header_f64(&header[6])? / 100.0;
    if row_count == 0 || row_count > max_rows || !start_deg.is_finite() || !step_deg.is_finite() {
        return Err(parse_error(
            0,
            "packed GSAS STD bank dimensions exceed limits or are non-finite",
        ));
    }
    if step_deg <= 0.0 {
        return Err(parse_error(0, "packed GSAS STD step must be positive"));
    }
    let mut intensities = Vec::with_capacity(row_count);
    let mut uncertainty = Vec::with_capacity(row_count);
    'lines: for (index, line) in lines.iter().enumerate() {
        for bytes in line.as_bytes().chunks(8) {
            let record = std::str::from_utf8(bytes)
                .map_err(|_| parse_error(index + 1, "invalid UTF-8 fixed-width record"))?;
            if record.trim().is_empty() {
                continue;
            }
            let normalization_field = record.get(..2).unwrap_or(record).trim();
            let normalization = if normalization_field.is_empty() {
                1_u32
            } else {
                normalization_field
                    .parse::<u32>()
                    .map_err(|_| parse_error(index + 1, "invalid fixed-width record"))?
                    .max(1)
            };
            let parsed_intensity = record
                .get(2..)
                .unwrap_or("")
                .trim()
                .parse::<f64>()
                .map_err(|_| parse_error(index + 1, "invalid fixed-width record"))?;
            if !parsed_intensity.is_finite() {
                return Err(parse_error(index + 1, "invalid fixed-width record"));
            }
            let intensity = parsed_intensity.max(0.0);
            intensities.push(intensity);
            uncertainty.push(if intensity > 0.0 {
                (intensity / f64::from(normalization)).sqrt()
            } else {
                1.0
            });
            if intensities.len() == row_count {
                break 'lines;
            }
        }
    }
    if intensities.len() != row_count {
        return Err(parse_error(
            0,
            format!(
                "packed GSAS STD bank contains {} records; expected {row_count}",
                intensities.len()
            ),
        ));
    }
    powder_data(
        coordinate_grid(start_deg, step_deg, row_count)?,
        intensities,
        Some(uncertainty),
        None,
        PowderFormat::GsasStd,
        source,
        Some(bank),
    )
}

fn packed_std_values(
    lines: &[String],
    row_count: usize,
) -> Result<(Vec<f64>, Vec<f64>), PowderIoError> {
    let mut intensities = Vec::with_capacity(row_count);
    let mut uncertainty = Vec::with_capacity(row_count);
    'lines: for (index, line) in lines.iter().enumerate() {
        for bytes in line.as_bytes().chunks(8) {
            let record = std::str::from_utf8(bytes)
                .map_err(|_| parse_error(index + 1, "invalid UTF-8 fixed-width record"))?;
            if record.trim().is_empty() {
                continue;
            }
            let normalization_field = record.get(..2).unwrap_or(record).trim();
            let normalization = if normalization_field.is_empty() {
                1_u32
            } else {
                normalization_field
                    .parse::<u32>()
                    .map_err(|_| parse_error(index + 1, "invalid fixed-width record"))?
                    .max(1)
            };
            let parsed_intensity = record
                .get(2..)
                .unwrap_or("")
                .trim()
                .parse::<f64>()
                .map_err(|_| parse_error(index + 1, "invalid fixed-width record"))?;
            if !parsed_intensity.is_finite() {
                return Err(parse_error(index + 1, "invalid fixed-width record"));
            }
            let intensity = parsed_intensity.max(0.0);
            intensities.push(intensity);
            uncertainty.push(if intensity > 0.0 {
                (intensity / f64::from(normalization)).sqrt()
            } else {
                1.0
            });
            if intensities.len() == row_count {
                break 'lines;
            }
        }
    }
    if intensities.len() != row_count {
        return Err(parse_error(
            0,
            format!(
                "packed GSAS STD bank contains {} records; expected {row_count}",
                intensities.len()
            ),
        ));
    }
    Ok((intensities, uncertainty))
}

fn coordinate_grid(
    start_deg: f64,
    step_deg: f64,
    row_count: usize,
) -> Result<Vec<f64>, PowderIoError> {
    (0..row_count)
        .map(|index| {
            let exact_index = u32::try_from(index).map_err(|_| {
                parse_error(
                    0,
                    "packed GSAS STD bank dimensions exceed limits or are non-finite",
                )
            })?;
            Ok(start_deg + step_deg * f64::from(exact_index))
        })
        .collect()
}

fn parse_header_f64(value: &str) -> Result<f64, PowderIoError> {
    value
        .parse::<f64>()
        .map_err(|_| parse_error(0, "invalid packed GSAS STD bank dimensions"))
}

fn parse_error(line: usize, message: impl Into<String>) -> PowderIoError {
    PowderIoError::Parse {
        line,
        message: message.into(),
    }
}