refeff-io 0.2.0

FEFF file-format readers and writers (feff.inp, .dat/.bin handoffs, PAD encoding) for the refeff FEFF10 port
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
//! Typed reader for FEFF `xsph.inp` module handoff files.
//!
//! XSPH consumes phase-scattering controls written by `rdinp`. This reader
//! keeps that module boundary explicit for the Rust numerical port.

use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use crate::{IoError, Result};

/// Parsed contents of a FEFF `xsph.inp` file.
#[derive(Debug, Clone, PartialEq)]
pub struct XsphInput {
    /// Integer module controls from the first data line.
    pub control: XsphControl,
    /// Real exchange correction values.
    pub vr0: f64,
    pub vi0: f64,
    /// Phase angular momentum cutoffs indexed by potential.
    pub lmaxph: Vec<i32>,
    /// Fixed-width potential labels indexed by potential.
    pub pot_labels: Vec<String>,
    /// Energy and grid controls.
    pub grid: XsphGrid,
    /// Spin moments indexed by potential.
    pub spinph: Vec<f64>,
    /// Optional advanced solver controls.
    pub advanced: XsphAdvanced,
    /// Electronic temperature in eV.
    pub electronic_temperature: f64,
    /// Chemical-shift correction mode.
    pub chsh_type: i32,
    /// NRIXS decomposition-channel count.
    pub decomposition_channels: i32,
    /// Optical calculation switch.
    pub lopt: bool,
    /// Radial wavefunction print switch.
    pub print_rl: bool,
    /// Structural format used by the source `xsph.inp` handoff.
    pub source_format: XsphInputSourceFormat,
}

/// First integer control line of `xsph.inp`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct XsphControl {
    pub mphase: i32,
    pub ipr2: i32,
    pub ixc: i32,
    pub ixc0: i32,
    pub ispec: i32,
    pub lreal: i32,
    pub lfms2: i32,
    pub nph: i32,
    pub l2lp: i32,
    pub i_plsmn: i32,
    pub n_poles: i32,
    pub i_gamma_ch: i32,
    pub i_grid: i32,
    pub i_core_state: i32,
    pub iscfxc: i32,
}

/// Grid and broadening controls from the `rgrd` data line.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct XsphGrid {
    pub rgrd: f64,
    pub rfms2: f64,
    pub gamach: f64,
    pub xkstep: f64,
    pub xkmax: f64,
    pub vixan: f64,
    pub eps0: f64,
    pub egap: f64,
}

/// Advanced XSPH switches.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct XsphAdvanced {
    pub izstd: i32,
    pub ifxc: i32,
    pub ipmbse: i32,
    pub itdlda: i32,
    pub nonlocal: i32,
    pub ibasis: i32,
}

/// Structural format used by a parsed FEFF `xsph.inp` file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct XsphInputSourceFormat {
    pub control_header: XsphControlHeaderFormat,
    pub grid_header: XsphGridHeaderFormat,
}

impl XsphInputSourceFormat {
    pub const fn modern() -> Self {
        Self {
            control_header: XsphControlHeaderFormat::Modern,
            grid_header: XsphGridHeaderFormat::Modern,
        }
    }

    pub const fn uses_legacy_fixed_xanes_mesh(self) -> bool {
        matches!(
            self.control_header,
            XsphControlHeaderFormat::LegacyWithPoles | XsphControlHeaderFormat::LegacyWithoutPoles
        ) || matches!(self.grid_header, XsphGridHeaderFormat::Legacy)
    }
}

/// Integer-control header shape used by a parsed FEFF `xsph.inp` file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XsphControlHeaderFormat {
    Modern,
    LegacyWithPoles,
    LegacyWithoutPoles,
}

impl XsphControlHeaderFormat {
    fn field_count(self) -> usize {
        match self {
            Self::Modern => 15,
            Self::LegacyWithPoles => 13,
            Self::LegacyWithoutPoles => 12,
        }
    }

    fn n_poles(self, values: &[i32]) -> i32 {
        match self {
            Self::Modern | Self::LegacyWithPoles => values[10],
            Self::LegacyWithoutPoles => 100,
        }
    }

    fn i_gamma_ch(self, values: &[i32]) -> i32 {
        match self {
            Self::Modern | Self::LegacyWithPoles => values[11],
            Self::LegacyWithoutPoles => values[10],
        }
    }

    fn i_grid(self, values: &[i32]) -> i32 {
        match self {
            Self::Modern | Self::LegacyWithPoles => values[12],
            Self::LegacyWithoutPoles => values[11],
        }
    }

    fn i_core_state(self, values: &[i32]) -> i32 {
        match self {
            Self::Modern => values[13],
            Self::LegacyWithPoles | Self::LegacyWithoutPoles => 0,
        }
    }

    fn iscfxc(self, values: &[i32]) -> i32 {
        match self {
            Self::Modern => values[14],
            Self::LegacyWithPoles | Self::LegacyWithoutPoles => 11,
        }
    }
}

/// Grid header shape used by a parsed FEFF `xsph.inp` file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XsphGridHeaderFormat {
    Modern,
    Legacy,
}

impl XsphGridHeaderFormat {
    fn field_count(self) -> usize {
        match self {
            Self::Modern => 8,
            Self::Legacy => 6,
        }
    }

    fn eps0(self, values: &[f64]) -> f64 {
        match self {
            Self::Modern => values[6],
            Self::Legacy => 0.0,
        }
    }

    fn egap(self, values: &[f64]) -> f64 {
        match self {
            Self::Modern => values[7],
            Self::Legacy => 0.0,
        }
    }

    fn has_labeled_following_rows(self) -> bool {
        matches!(self, Self::Modern)
    }
}

impl XsphInput {
    /// Parse a FEFF `xsph.inp` string.
    pub fn parse_str(source: impl Into<PathBuf>, text: &str) -> Result<Self> {
        let mut parser = XsphInputParser::new(source.into(), text);
        parser.parse()
    }
}

/// Render FEFF-compatible `xsph.inp` text.
pub fn xsph_input_string(input: &XsphInput) -> Result<String> {
    validate_xsph_input(input)?;

    let mut out = String::new();
    writeln!(
        out,
        "mphase,ipr2,ixc,ixc0,ispec,lreal,lfms2,nph,l2lp,iPlsmn,NPoles,iGammaCH,iGrid,iCoreState,iscfxc"
    )?;
    push_i4_row(
        &mut out,
        [
            input.control.mphase,
            input.control.ipr2,
            input.control.ixc,
            input.control.ixc0,
            input.control.ispec,
            input.control.lreal,
            input.control.lfms2,
            input.control.nph,
            input.control.l2lp,
            input.control.i_plsmn,
            input.control.n_poles,
            input.control.i_gamma_ch,
            input.control.i_grid,
            input.control.i_core_state,
            input.control.iscfxc,
        ],
    )?;
    writeln!(out, "vr0, vi0")?;
    writeln!(out, "{:13.5}{:13.5}", input.vr0, input.vi0)?;
    writeln!(out, " lmaxph(0:nph)")?;
    push_i4_row(&mut out, input.lmaxph.iter().copied())?;
    writeln!(out, " potlbl(iph)")?;
    for label in &input.pot_labels {
        out.push_str(&fixed_a6(label));
    }
    out.push('\n');
    writeln!(out, "rgrd, rfms2, gamach, xkstep, xkmax, vixan, Eps0, EGap")?;
    writeln!(
        out,
        "{:13.5}{:13.5}{:13.5}{:13.5}{:13.5}{:13.5}{:13.5}{:13.5}",
        input.grid.rgrd,
        input.grid.rfms2,
        input.grid.gamach,
        input.grid.xkstep,
        input.grid.xkmax,
        input.grid.vixan,
        input.grid.eps0,
        input.grid.egap
    )?;
    writeln!(out, "spinph(0:nph)")?;
    for spin in &input.spinph {
        write!(out, "{spin:13.5}")?;
    }
    out.push('\n');
    writeln!(out, "izstd, ifxc, ipmbse, itdlda, nonlocal, ibasis")?;
    push_i4_row(
        &mut out,
        [
            input.advanced.izstd,
            input.advanced.ifxc,
            input.advanced.ipmbse,
            input.advanced.itdlda,
            input.advanced.nonlocal,
            input.advanced.ibasis,
        ],
    )?;
    writeln!(out, "electronic temperature")?;
    writeln!(out, "{:13.5}", input.electronic_temperature)?;
    writeln!(out, "ChSh_Type:")?;
    writeln!(out, "{:4}", input.chsh_type)?;
    writeln!(
        out,
        " the number of decomposition channels ; only used for nrixs"
    )?;
    writeln!(out, "{:5}", input.decomposition_channels)?;
    writeln!(out, "lopt")?;
    writeln!(out, " {}", fortran_bool_field(input.lopt))?;
    writeln!(out, "PrintRL")?;
    writeln!(out, " {}", fortran_bool_field(input.print_rl))?;
    Ok(out)
}

fn validate_xsph_input(input: &XsphInput) -> Result<()> {
    let expected = input.control.nph.max(0) as usize + 1;
    for (field, len) in [
        ("lmaxph", input.lmaxph.len()),
        ("pot_labels", input.pot_labels.len()),
        ("spinph", input.spinph.len()),
    ] {
        if len != expected {
            return Err(IoError::Parse {
                path: "xsph.inp".into(),
                line: 0,
                message: format!(
                    "{field} length {len} does not match nph-derived count {expected}"
                ),
            });
        }
    }
    validate_finite("vr0", input.vr0)?;
    validate_finite("vi0", input.vi0)?;
    validate_finite("rgrd", input.grid.rgrd)?;
    validate_finite("rfms2", input.grid.rfms2)?;
    validate_finite("gamach", input.grid.gamach)?;
    validate_finite("xkstep", input.grid.xkstep)?;
    validate_finite("xkmax", input.grid.xkmax)?;
    validate_finite("vixan", input.grid.vixan)?;
    validate_finite("eps0", input.grid.eps0)?;
    validate_finite("egap", input.grid.egap)?;
    for spin in &input.spinph {
        validate_finite("spinph", *spin)?;
    }
    validate_finite("electronic_temperature", input.electronic_temperature)?;
    for label in &input.pot_labels {
        if label.contains(['\n', '\r']) {
            return Err(IoError::Parse {
                path: "xsph.inp".into(),
                line: 0,
                message: "XSPH potential labels cannot contain line terminators".to_string(),
            });
        }
    }
    Ok(())
}

fn validate_finite(field: &'static str, value: f64) -> Result<()> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(IoError::Parse {
            path: "xsph.inp".into(),
            line: 0,
            message: format!("{field} must be finite"),
        })
    }
}

fn fortran_bool_field(value: bool) -> &'static str {
    if value { "T" } else { "F" }
}

fn push_i4_row(out: &mut String, values: impl IntoIterator<Item = i32>) -> Result<()> {
    for value in values {
        write!(out, "{value:4}")?;
    }
    out.push('\n');
    Ok(())
}

fn fixed_a6(value: &str) -> String {
    let mut end = 0;
    for (index, character) in value.char_indices() {
        let next = index + character.len_utf8();
        if next > 6 {
            break;
        }
        end = next;
    }
    let mut out = value[..end].to_string();
    while out.len() < 6 {
        out.push(' ');
    }
    out
}

struct XsphInputParser<'a> {
    source: PathBuf,
    lines: std::iter::Enumerate<std::str::Lines<'a>>,
}

impl<'a> XsphInputParser<'a> {
    fn new(source: PathBuf, text: &'a str) -> Self {
        Self {
            source,
            lines: text.lines().enumerate(),
        }
    }

    fn parse(&mut self) -> Result<XsphInput> {
        let control_header = self.expect_control_header()?;
        let control_values =
            self.parse_values::<i32>(control_header.field_count(), "XSPH control line")?;
        let control = XsphControl {
            mphase: control_values[0],
            ipr2: control_values[1],
            ixc: control_values[2],
            ixc0: control_values[3],
            ispec: control_values[4],
            lreal: control_values[5],
            lfms2: control_values[6],
            nph: control_values[7],
            l2lp: control_values[8],
            i_plsmn: control_values[9],
            n_poles: control_header.n_poles(&control_values),
            i_gamma_ch: control_header.i_gamma_ch(&control_values),
            i_grid: control_header.i_grid(&control_values),
            i_core_state: control_header.i_core_state(&control_values),
            iscfxc: control_header.iscfxc(&control_values),
        };
        let potential_count = control.nph.max(0) as usize + 1;

        self.expect_header("vr0, vi0")?;
        let exchange = self.parse_values::<f64>(2, "XSPH exchange line")?;

        self.expect_header("lmaxph(0:nph)")?;
        let lmaxph = self.parse_values::<i32>(potential_count, "XSPH lmaxph line")?;

        self.expect_header("potlbl(iph)")?;
        let (_, label_line) = self.next_line("XSPH potential labels")?;
        let pot_labels = fixed_a6_labels(label_line, potential_count);

        let grid_header = self.expect_grid_header()?;
        let grid_values = self.parse_values::<f64>(grid_header.field_count(), "XSPH grid line")?;
        let grid = XsphGrid {
            rgrd: grid_values[0],
            rfms2: grid_values[1],
            gamach: grid_values[2],
            xkstep: grid_values[3],
            xkmax: grid_values[4],
            vixan: grid_values[5],
            eps0: grid_header.eps0(&grid_values),
            egap: grid_header.egap(&grid_values),
        };

        let optional_following_labels = !matches!(control_header, XsphControlHeaderFormat::Modern);
        let spinph = if grid_header.has_labeled_following_rows() && optional_following_labels {
            self.parse_values_after_optional_header(
                "spinph(0:nph)",
                potential_count,
                "XSPH spinph line",
            )?
        } else {
            if grid_header.has_labeled_following_rows() {
                self.expect_header("spinph(0:nph)")?;
            }
            self.parse_values::<f64>(potential_count, "XSPH spinph line")?
        };

        let advanced_values =
            if grid_header.has_labeled_following_rows() && optional_following_labels {
                self.parse_values_after_optional_header(
                    "izstd, ifxc, ipmbse, itdlda, nonlocal, ibasis",
                    6,
                    "XSPH advanced-control line",
                )?
            } else {
                if grid_header.has_labeled_following_rows() {
                    self.expect_header("izstd, ifxc, ipmbse, itdlda, nonlocal, ibasis")?;
                }
                self.parse_values::<i32>(6, "XSPH advanced-control line")?
            };
        let advanced = XsphAdvanced {
            izstd: advanced_values[0],
            ifxc: advanced_values[1],
            ipmbse: advanced_values[2],
            itdlda: advanced_values[3],
            nonlocal: advanced_values[4],
            ibasis: advanced_values[5],
        };

        let electronic_temperature = self.parse_optional_electronic_temperature()?;
        let chsh_type = self.parse_values::<i32>(1, "XSPH chemical-shift line")?[0];
        self.expect_header("the number of decomposition channels ; only used for nrixs")?;
        let decomposition_channels = self.parse_values::<i32>(1, "XSPH decomposition line")?[0];
        self.expect_header("lopt")?;
        let lopt = self.parse_bool_line("XSPH lopt line")?;
        let print_rl = self.parse_optional_print_rl()?;

        Ok(XsphInput {
            control,
            vr0: exchange[0],
            vi0: exchange[1],
            lmaxph,
            pot_labels,
            grid,
            spinph,
            advanced,
            electronic_temperature,
            chsh_type,
            decomposition_channels,
            lopt,
            print_rl,
            source_format: XsphInputSourceFormat {
                control_header,
                grid_header,
            },
        })
    }

    fn expect_control_header(&mut self) -> Result<XsphControlHeaderFormat> {
        let (line_number, line) = self.next_line("XSPH control header")?;
        match line.trim() {
            "mphase,ipr2,ixc,ixc0,ispec,lreal,lfms2,nph,l2lp,iPlsmn,NPoles,iGammaCH,iGrid,iCoreState,iscfxc" => {
                Ok(XsphControlHeaderFormat::Modern)
            }
            "mphase,ipr2,ixc,ixc0,ispec,lreal,lfms2,nph,l2lp,iPlsmn,NPoles,iGammaCH,iGrid" => {
                Ok(XsphControlHeaderFormat::LegacyWithPoles)
            }
            "mphase,ipr2,ixc,ixc0,ispec,lreal,lfms2,nph,l2lp,iPlsmn,iGammaCH,iGrid" => {
                Ok(XsphControlHeaderFormat::LegacyWithoutPoles)
            }
            _ => Err(self.parse_error(
                line_number,
                format!("expected XSPH control header, found {line:?}"),
            )),
        }
    }

    fn expect_grid_header(&mut self) -> Result<XsphGridHeaderFormat> {
        let (line_number, line) = self.next_line("XSPH grid header")?;
        match line.trim() {
            "rgrd, rfms2, gamach, xkstep, xkmax, vixan, Eps0, EGap" => {
                Ok(XsphGridHeaderFormat::Modern)
            }
            "rgrd, rfms2, gamach, xkstep, xkmax, vixan" => Ok(XsphGridHeaderFormat::Legacy),
            _ => Err(self.parse_error(
                line_number,
                format!("expected XSPH grid header, found {line:?}"),
            )),
        }
    }

    fn parse_optional_electronic_temperature(&mut self) -> Result<f64> {
        let (line_number, line) =
            self.next_line("XSPH electronic temperature or chemical-shift header")?;
        match line.trim() {
            "electronic temperature" => {
                let temperature = self.parse_values::<f64>(1, "XSPH temperature line")?[0];
                self.expect_header("ChSh_Type:")?;
                Ok(temperature)
            }
            "ChSh_Type:" => Ok(0.0),
            _ => Err(self.parse_error(
                line_number,
                format!(
                    "expected XSPH electronic temperature or chemical-shift header, found {line:?}"
                ),
            )),
        }
    }

    fn parse_optional_print_rl(&mut self) -> Result<bool> {
        let Some((index, line)) = self.lines.next() else {
            return Ok(false);
        };
        let line_number = index + 1;
        if line.trim() != "PrintRL" {
            return Err(self.parse_error(
                line_number,
                format!("expected header {:?}, found {line:?}", "PrintRL"),
            ));
        }
        self.parse_bool_line("XSPH PrintRL line")
    }

    fn expect_header(&mut self, expected: &str) -> Result<()> {
        let (line_number, line) = self.next_line(expected)?;
        if line.trim() == expected {
            Ok(())
        } else {
            Err(self.parse_error(
                line_number,
                format!("expected header {expected:?}, found {line:?}"),
            ))
        }
    }

    fn parse_values<T>(&mut self, count: usize, description: &str) -> Result<Vec<T>>
    where
        T: FromStr,
    {
        let (line_number, line) = self.next_line(description)?;
        self.parse_values_from_line(line_number, line, count, description)
    }

    fn parse_values_after_optional_header<T>(
        &mut self,
        header: &str,
        count: usize,
        description: &str,
    ) -> Result<Vec<T>>
    where
        T: FromStr,
    {
        let (line_number, line) = self.next_line(description)?;
        if line.trim() == header {
            self.parse_values::<T>(count, description)
        } else {
            self.parse_values_from_line(line_number, line, count, description)
        }
    }

    fn parse_values_from_line<T>(
        &self,
        line_number: usize,
        line: &str,
        count: usize,
        description: &str,
    ) -> Result<Vec<T>>
    where
        T: FromStr,
    {
        let fields: Vec<&str> = line.split_whitespace().collect();
        if fields.len() < count {
            return Err(self.parse_error(
                line_number,
                format!("{description} requires {count} fields"),
            ));
        }
        fields
            .iter()
            .take(count)
            .map(|field| parse_field(&self.source, line_number, field))
            .collect()
    }

    fn parse_bool_line(&mut self, description: &str) -> Result<bool> {
        let (line_number, line) = self.next_line(description)?;
        match line.trim() {
            "T" => Ok(true),
            "F" => Ok(false),
            value => Err(self.parse_error(line_number, format!("invalid FEFF bool {value:?}"))),
        }
    }

    fn next_line(&mut self, description: &str) -> Result<(usize, &'a str)> {
        self.lines
            .next()
            .map(|(index, line)| (index + 1, line))
            .ok_or_else(|| self.parse_error(0, format!("expected {description}")))
    }

    fn parse_error(&self, line: usize, message: impl Into<String>) -> IoError {
        IoError::Parse {
            path: self.source.clone(),
            line,
            message: message.into(),
        }
    }
}

fn fixed_a6_labels(line: &str, count: usize) -> Vec<String> {
    let bytes = line.as_bytes();
    (0..count)
        .map(|idx| {
            let start = idx * 6;
            let end = (start + 6).min(bytes.len());
            if start >= bytes.len() {
                String::new()
            } else {
                String::from_utf8_lossy(&bytes[start..end])
                    .trim_end()
                    .to_string()
            }
        })
        .collect()
}

fn parse_field<T>(source: &Path, line: usize, field: &str) -> Result<T>
where
    T: FromStr,
{
    field.parse::<T>().map_err(|_| IoError::Parse {
        path: source.to_path_buf(),
        line,
        message: format!("invalid numeric field {field:?}"),
    })
}

#[cfg(test)]
mod tests {
    use crate::{FeffDocument, FeffInput, rdinp};

    use super::{XsphControlHeaderFormat, XsphGridHeaderFormat, XsphInput, xsph_input_string};

    #[test]
    fn parses_generated_copper_xsph_input() -> crate::Result<()> {
        let input = FeffInput::parse_str(
            "feff.inp",
            r#"
TITLE Cu crystal
EDGE K
EXAFS 20
POTENTIALS
0 29 Cu
1 29 Cu
ATOMS
0.0 0.0 0.0 0 Cu0
1.805 1.805 0.0 1 Cu1
END
"#,
        )?;
        let document = FeffDocument::from_input(&input)?;
        let text = rdinp::xsph_inp_string(&document)?;
        let xsph = XsphInput::parse_str("xsph.inp", &text)?;

        assert_eq!(xsph.control.mphase, 1);
        assert_eq!(xsph.control.nph, 1);
        assert_eq!(xsph.control.n_poles, 100);
        assert_eq!(
            xsph.source_format.control_header,
            XsphControlHeaderFormat::Modern
        );
        assert_eq!(xsph.source_format.grid_header, XsphGridHeaderFormat::Modern);
        assert!(!xsph.source_format.uses_legacy_fixed_xanes_mesh());
        assert_eq!(xsph.pot_labels, ["Cu".to_string(), "Cu".to_string()]);
        assert_eq!(xsph.lmaxph, [3, 3]);
        assert_eq!(xsph.spinph, [0.0, 0.0]);
        assert!((xsph.grid.gamach - 1.72919).abs() < 1.0e-5);
        assert!(!xsph.lopt);
        assert!(!xsph.print_rl);
        assert_eq!(xsph_input_string(&xsph)?, text);
        Ok(())
    }

    #[test]
    fn parses_legacy_xsph_input_without_core_state_or_scxc() -> crate::Result<()> {
        let text = "\
mphase,ipr2,ixc,ixc0,ispec,lreal,lfms2,nph,l2lp,iPlsmn,NPoles,iGammaCH,iGrid
   1   0   0   2   3   0   0   2   0   0 100   0   0
vr0, vi0
      0.00000      1.00000
 lmaxph(0:nph)
   2   2   2
 potlbl(iph)
B     B     N
rgrd, rfms2, gamach, xkstep, xkmax, vixan, Eps0, EGap
      0.05000      5.00000      0.06473      0.07000      4.00000      0.00000      0.00000      0.00000
spinph(0:nph)
      0.00000      0.00000      0.00000
izstd, ifxc, ipmbse, itdlda, nonlocal, ibasis
   0   0   0   0   0   0
ChSh_Type:
   0
 the number of decomposition channels ; only used for nrixs
   -1
lopt
 F
";
        let xsph = XsphInput::parse_str("legacy-xsph.inp", text)?;

        assert_eq!(xsph.control.n_poles, 100);
        assert_eq!(xsph.control.i_core_state, 0);
        assert_eq!(xsph.control.iscfxc, 11);
        assert_eq!(
            xsph.source_format.control_header,
            XsphControlHeaderFormat::LegacyWithPoles
        );
        assert_eq!(xsph.source_format.grid_header, XsphGridHeaderFormat::Modern);
        assert!(xsph.source_format.uses_legacy_fixed_xanes_mesh());
        assert_eq!(xsph.electronic_temperature, 0.0);
        assert!(!xsph.print_rl);
        assert_eq!(
            xsph.pot_labels,
            ["B".to_string(), "B".to_string(), "N".to_string()]
        );
        Ok(())
    }

    #[test]
    fn parses_legacy_xsph_input_with_modern_grid_but_unlabeled_following_rows() -> crate::Result<()>
    {
        let text = "\
mphase,ipr2,ixc,ixc0,ispec,lreal,lfms2,nph,l2lp,iPlsmn,NPoles,iGammaCH,iGrid
   1   0   0   2   1   1   1   1   0   0 100   0   0
vr0, vi0
      0.00000      0.00000
 lmaxph(0:nph)
   3   3
 potlbl(iph)
Ge    Cl
rgrd, rfms2, gamach, xkstep, xkmax, vixan, Eps0, EGap
      0.05000      3.00000      2.28438      0.05000      8.00000      0.00000      0.00000      0.00000
      0.00000      0.00000
   0   0   0   0   0   0
ChSh_Type:
   0
 the number of decomposition channels ; only used for nrixs
    2
lopt
 F
";
        let xsph = XsphInput::parse_str("legacy-hybrid-xsph.inp", text)?;

        assert_eq!(
            xsph.source_format.control_header,
            XsphControlHeaderFormat::LegacyWithPoles
        );
        assert_eq!(xsph.source_format.grid_header, XsphGridHeaderFormat::Modern);
        assert_eq!(xsph.spinph, [0.0, 0.0]);
        assert_eq!(xsph.advanced.ibasis, 0);
        assert_eq!(xsph.decomposition_channels, 2);
        Ok(())
    }

    #[test]
    fn parses_older_xsph_input_without_poles_or_labeled_spin_rows() -> crate::Result<()> {
        let text = "\
mphase,ipr2,ixc,ixc0,ispec,lreal,lfms2,nph,l2lp,iPlsmn,iGammaCH,iGrid
   1   0   0   2   3   1   1   1   0   0   0   0
vr0, vi0
      0.00000      0.00000
 lmaxph(0:nph)
   3   3
 potlbl(iph)
Ge    Cl
rgrd, rfms2, gamach, xkstep, xkmax, vixan
      0.05000      3.00000      2.28438      0.05000      8.00000      0.00000
      0.00000      0.00000
   0   0   0   0   0   0
ChSh_Type:
   0
 the number of decomposition channels ; only used for nrixs
   -1
lopt
 F
";
        let xsph = XsphInput::parse_str("older-xsph.inp", text)?;

        assert_eq!(xsph.control.n_poles, 100);
        assert_eq!(xsph.control.i_gamma_ch, 0);
        assert_eq!(xsph.control.i_grid, 0);
        assert_eq!(xsph.control.i_core_state, 0);
        assert_eq!(xsph.control.iscfxc, 11);
        assert_eq!(
            xsph.source_format.control_header,
            XsphControlHeaderFormat::LegacyWithoutPoles
        );
        assert_eq!(xsph.source_format.grid_header, XsphGridHeaderFormat::Legacy);
        assert!(xsph.source_format.uses_legacy_fixed_xanes_mesh());
        assert_eq!(xsph.grid.eps0, 0.0);
        assert_eq!(xsph.grid.egap, 0.0);
        assert_eq!(xsph.spinph, [0.0, 0.0]);
        assert_eq!(xsph.advanced.ibasis, 0);
        assert!(!xsph.print_rl);
        Ok(())
    }

    #[test]
    fn rejects_invalid_xsph_rendering() {
        let input = XsphInput {
            control: super::XsphControl {
                mphase: 1,
                ipr2: 0,
                ixc: 0,
                ixc0: 0,
                ispec: 1,
                lreal: 0,
                lfms2: 0,
                nph: 0,
                l2lp: 0,
                i_plsmn: 0,
                n_poles: 100,
                i_gamma_ch: 0,
                i_grid: 1,
                i_core_state: -1,
                iscfxc: 11,
            },
            vr0: f64::NAN,
            vi0: 0.0,
            lmaxph: vec![3],
            pot_labels: vec!["Cu".to_string()],
            grid: super::XsphGrid {
                rgrd: 0.05,
                rfms2: -1.0,
                gamach: 1.0,
                xkstep: 0.07,
                xkmax: 20.0,
                vixan: 0.0,
                eps0: 0.0,
                egap: 0.0,
            },
            spinph: vec![0.0],
            advanced: super::XsphAdvanced {
                izstd: 0,
                ifxc: 0,
                ipmbse: 0,
                itdlda: 0,
                nonlocal: 0,
                ibasis: 0,
            },
            electronic_temperature: 0.0,
            chsh_type: 0,
            decomposition_channels: -1,
            lopt: false,
            print_rl: false,
            source_format: super::XsphInputSourceFormat::modern(),
        };
        assert!(xsph_input_string(&input).is_err());

        let mut bad_count = input;
        bad_count.vr0 = 0.0;
        bad_count.lmaxph.clear();
        assert!(xsph_input_string(&bad_count).is_err());
    }
}