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
use std::path::Path;

use ndarray::{Array1, Array2, Array3};

use crate::error::{IoError, Result};

use super::common::{
    array2_from_fortran, array3_from_fortran, checked_count2, checked_count3, decode_pad_line,
    i32_from_i64, invalid_pot_bin, usize_from_i64,
};
use super::types::{
    POT_BIN_COEFFICIENTS, POT_BIN_IORB_SLOTS, POT_BIN_MISC_SCALARS, POT_BIN_ORBITALS,
    POT_BIN_RADIAL_POINTS, PotBinData, PotBinScalars,
};
use super::validate::validate_pot_bin;

const POT_BIN_LEGACY_ORBITALS: usize = 30;
const POT_BIN_LEGACY_IORB_SLOTS: usize = 8;

/// Parse FEFF `pot.bin` text.
pub fn parse_pot_bin(text: &str) -> Result<PotBinData> {
    let mut lines = PotBinLines::new(text);
    let header = lines.int_values("header", 9)?;
    let title_count = usize_from_i64(header[0], "ntitle")?;
    let potential_count = usize_from_i64(header[1], "nph")?
        .checked_add(1)
        .ok_or_else(|| invalid_pot_bin("nph", "potential count overflowed"))?;
    let pad_width = usize_from_i64(header[2], "npadx")?;
    let nohole = i32_from_i64(header[3], "nohole")?;
    let ihole = i32_from_i64(header[4], "ihole")?;
    let interstitial_selector = i32_from_i64(header[5], "inters")?;
    let automatic_folp = i32_from_i64(header[6], "iafolp")?;
    let jump_mode = i32_from_i64(header[7], "jumprm")?;
    let unfreeze_f = i32_from_i64(header[8], "iunf")?;

    let mut titles = Vec::with_capacity(title_count);
    for _ in 0..title_count {
        titles.push(lines.title()?);
    }

    let misc = lines.pad_reals("dum", pad_width, POT_BIN_MISC_SCALARS)?;
    let scalars = PotBinScalars::from_slice(&misc)?;
    let muffin_tin_indices = lines.usize_array("imt", potential_count)?;
    let muffin_tin_radii = lines.real_array("rmt", pad_width, potential_count)?;
    let norman_indices = lines.usize_array("inrm", potential_count)?;
    let atomic_numbers = lines.usize_array("iz", potential_count)?;
    let kappa_values = lines.i32_values_until_next_pad("kappa")?;
    let orbital_count = validate_stored_orbital_count("kappa", kappa_values.len())?;
    let kappa = pad_i32_orbitals("kappa", kappa_values)?;
    let norman_radii = lines.real_array("rnrm", pad_width, potential_count)?;
    let overlap_factors = lines.real_array("folp", pad_width, potential_count)?;
    let max_overlap_factors = lines.real_array("folpx", pad_width, potential_count)?;
    let potential_multiplicities = lines.real_array("xnatph", pad_width, potential_count)?;
    let ionization = lines.real_array("xion", pad_width, potential_count)?;
    let initial_large_component = lines.real_array("dgc0", pad_width, POT_BIN_RADIAL_POINTS)?;
    let initial_small_component = lines.real_array("dpc0", pad_width, POT_BIN_RADIAL_POINTS)?;

    let radial_orbital_potential =
        checked_count3("dgc", POT_BIN_RADIAL_POINTS, orbital_count, potential_count)?;
    let coefficient_orbital_potential =
        checked_count3("adgc", POT_BIN_COEFFICIENTS, orbital_count, potential_count)?;
    let radial_potential = checked_count2("edens", POT_BIN_RADIAL_POINTS, potential_count)?;
    let orbital_potential = checked_count2("xnval", orbital_count, potential_count)?;

    let large_components = pad_orbital_axis3(
        "dgc",
        array3_from_fortran(
            "dgc",
            lines.pad_reals("dgc", pad_width, radial_orbital_potential)?,
            POT_BIN_RADIAL_POINTS,
            orbital_count,
            potential_count,
        )?,
    )?;
    let small_components = pad_orbital_axis3(
        "dpc",
        array3_from_fortran(
            "dpc",
            lines.pad_reals("dpc", pad_width, radial_orbital_potential)?,
            POT_BIN_RADIAL_POINTS,
            orbital_count,
            potential_count,
        )?,
    )?;
    let large_coefficients = pad_orbital_axis3(
        "adgc",
        array3_from_fortran(
            "adgc",
            lines.pad_reals("adgc", pad_width, coefficient_orbital_potential)?,
            POT_BIN_COEFFICIENTS,
            orbital_count,
            potential_count,
        )?,
    )?;
    let small_coefficients = pad_orbital_axis3(
        "adpc",
        array3_from_fortran(
            "adpc",
            lines.pad_reals("adpc", pad_width, coefficient_orbital_potential)?,
            POT_BIN_COEFFICIENTS,
            orbital_count,
            potential_count,
        )?,
    )?;
    let electron_density = array2_from_fortran(
        "edens",
        lines.pad_reals("edens", pad_width, radial_potential)?,
        POT_BIN_RADIAL_POINTS,
        potential_count,
    )?;
    let coulomb_potential = array2_from_fortran(
        "vclap",
        lines.pad_reals("vclap", pad_width, radial_potential)?,
        POT_BIN_RADIAL_POINTS,
        potential_count,
    )?;
    let total_potential = array2_from_fortran(
        "vtot",
        lines.pad_reals("vtot", pad_width, radial_potential)?,
        POT_BIN_RADIAL_POINTS,
        potential_count,
    )?;
    let valence_density = array2_from_fortran(
        "edenvl",
        lines.pad_reals("edenvl", pad_width, radial_potential)?,
        POT_BIN_RADIAL_POINTS,
        potential_count,
    )?;
    let valence_potential = array2_from_fortran(
        "vvalgs",
        lines.pad_reals("vvalgs", pad_width, radial_potential)?,
        POT_BIN_RADIAL_POINTS,
        potential_count,
    )?;
    let magnetization_density = array2_from_fortran(
        "dmag",
        lines.pad_reals("dmag", pad_width, radial_potential)?,
        POT_BIN_RADIAL_POINTS,
        potential_count,
    )?;
    let orbital_occupancy = pad_orbital_axis2(
        "xnval",
        array2_from_fortran(
            "xnval",
            lines.pad_reals("xnval", pad_width, orbital_potential)?,
            orbital_count,
            potential_count,
        )?,
    )?;
    let orbital_energies =
        pad_f64_orbitals("eorb", lines.real_array("eorb", pad_width, orbital_count)?)?;

    let mut occupied_orbital_indices = Array2::<i32>::zeros((POT_BIN_IORB_SLOTS, potential_count));
    if lines.next_is_int_line() {
        let iorb_values = lines.i32_values_until_next_pad("iorb")?;
        let iorb_slot_count = validate_stored_iorb_slot_count(
            iorb_values
                .len()
                .checked_div(potential_count)
                .filter(|_| iorb_values.len() % potential_count == 0)
                .ok_or_else(|| IoError::PotBinShape {
                    field: "iorb",
                    actual: vec![iorb_values.len()],
                    expected: vec![
                        potential_count * POT_BIN_LEGACY_IORB_SLOTS,
                        potential_count * POT_BIN_IORB_SLOTS,
                    ],
                })?,
        )?;
        for potential in 0..potential_count {
            for slot in 0..iorb_slot_count {
                occupied_orbital_indices[(slot, potential)] =
                    iorb_values[potential * iorb_slot_count + slot];
            }
        }
    }

    let norman_charges = lines.real_array("qnrm", pad_width, potential_count)?;
    let xnmues = lines.pad_reals_to_eof("xnmues", pad_width)?;
    if xnmues.is_empty() || xnmues.len() % potential_count != 0 {
        return Err(IoError::PotBinShape {
            field: "xnmues",
            actual: vec![xnmues.len()],
            expected: vec![potential_count],
        });
    }
    let angular_count = xnmues.len() / potential_count;
    let valence_occupancy = array2_from_fortran("xnmues", xnmues, angular_count, potential_count)?;
    lines.finish()?;

    let data = PotBinData {
        titles,
        pad_width,
        nohole,
        ihole,
        interstitial_selector,
        automatic_folp,
        jump_mode,
        unfreeze_f,
        scalars,
        muffin_tin_indices,
        muffin_tin_radii,
        norman_indices,
        atomic_numbers,
        kappa,
        norman_radii,
        overlap_factors,
        max_overlap_factors,
        potential_multiplicities,
        ionization,
        initial_large_component,
        initial_small_component,
        large_components,
        small_components,
        large_coefficients,
        small_coefficients,
        electron_density,
        coulomb_potential,
        total_potential,
        valence_density,
        valence_potential,
        magnetization_density,
        orbital_occupancy,
        orbital_energies,
        occupied_orbital_indices,
        norman_charges,
        valence_occupancy,
        raw_text: Some(text.to_string()),
    };
    validate_pot_bin(&data)?;
    Ok(data)
}

fn validate_stored_orbital_count(field: &'static str, actual: usize) -> Result<usize> {
    match actual {
        POT_BIN_ORBITALS | POT_BIN_LEGACY_ORBITALS => Ok(actual),
        _ => Err(IoError::PotBinShape {
            field,
            actual: vec![actual],
            expected: vec![POT_BIN_LEGACY_ORBITALS, POT_BIN_ORBITALS],
        }),
    }
}

fn validate_stored_iorb_slot_count(actual: usize) -> Result<usize> {
    match actual {
        POT_BIN_IORB_SLOTS | POT_BIN_LEGACY_IORB_SLOTS => Ok(actual),
        _ => Err(IoError::PotBinShape {
            field: "iorb",
            actual: vec![actual],
            expected: vec![POT_BIN_LEGACY_IORB_SLOTS, POT_BIN_IORB_SLOTS],
        }),
    }
}

fn pad_i32_orbitals(field: &'static str, values: Vec<i32>) -> Result<Array1<i32>> {
    validate_stored_orbital_count(field, values.len())?;
    let mut padded = Array1::<i32>::zeros(POT_BIN_ORBITALS);
    for (index, value) in values.into_iter().enumerate() {
        padded[index] = value;
    }
    Ok(padded)
}

fn pad_f64_orbitals(field: &'static str, values: Array1<f64>) -> Result<Array1<f64>> {
    validate_stored_orbital_count(field, values.len())?;
    if values.len() == POT_BIN_ORBITALS {
        return Ok(values);
    }
    let mut padded = Array1::<f64>::zeros(POT_BIN_ORBITALS);
    for (index, value) in values.into_iter().enumerate() {
        padded[index] = value;
    }
    Ok(padded)
}

fn pad_orbital_axis2(field: &'static str, values: Array2<f64>) -> Result<Array2<f64>> {
    let (stored_orbitals, potential_count) = values.dim();
    validate_stored_orbital_count(field, stored_orbitals)?;
    if stored_orbitals == POT_BIN_ORBITALS {
        return Ok(values);
    }
    let mut padded = Array2::<f64>::zeros((POT_BIN_ORBITALS, potential_count));
    for potential in 0..potential_count {
        for orbital in 0..stored_orbitals {
            padded[(orbital, potential)] = values[(orbital, potential)];
        }
    }
    Ok(padded)
}

fn pad_orbital_axis3(field: &'static str, values: Array3<f64>) -> Result<Array3<f64>> {
    let (rows, stored_orbitals, potential_count) = values.dim();
    validate_stored_orbital_count(field, stored_orbitals)?;
    if stored_orbitals == POT_BIN_ORBITALS {
        return Ok(values);
    }
    let mut padded = Array3::<f64>::zeros((rows, POT_BIN_ORBITALS, potential_count));
    for potential in 0..potential_count {
        for orbital in 0..stored_orbitals {
            for row in 0..rows {
                padded[(row, orbital, potential)] = values[(row, orbital, potential)];
            }
        }
    }
    Ok(padded)
}

/// Read FEFF `pot.bin` text from a file.
pub fn read_pot_bin(path: impl AsRef<Path>) -> Result<PotBinData> {
    let path = path.as_ref();
    let text = std::fs::read_to_string(path).map_err(|source| IoError::io(path, source))?;
    parse_pot_bin(&text)
}

struct PotBinLines<'a> {
    lines: Vec<&'a str>,
    position: usize,
}

impl<'a> PotBinLines<'a> {
    fn new(text: &'a str) -> Self {
        Self {
            lines: text.lines().collect(),
            position: 0,
        }
    }

    fn finish(self) -> Result<()> {
        let count = self.lines[self.position..]
            .iter()
            .filter(|line| !line.trim().is_empty())
            .count();
        if count == 0 {
            Ok(())
        } else {
            Err(IoError::PotBinTrailingLines { count })
        }
    }

    fn title(&mut self) -> Result<String> {
        let line = self.next_line("title")?;
        Ok(line.to_string())
    }

    fn int_values(&mut self, field: &'static str, expected: usize) -> Result<Vec<i64>> {
        let mut values = Vec::with_capacity(expected);
        while values.len() < expected {
            let line = self.next_line(field)?;
            for token in line.split_whitespace() {
                if values.len() == expected {
                    break;
                }
                values.push(token.parse::<i64>().map_err(|_| IoError::PotBinParse {
                    field,
                    token: token.to_string(),
                })?);
            }
        }
        Ok(values)
    }

    fn i32_values_until_next_pad(&mut self, field: &'static str) -> Result<Vec<i32>> {
        let mut values = Vec::new();
        while self.position < self.lines.len() {
            let line = self.lines[self.position];
            if line.trim_start().starts_with('!') {
                break;
            }
            if line.trim().is_empty() {
                self.position += 1;
                continue;
            }
            for token in line.split_whitespace() {
                let value = token.parse::<i64>().map_err(|_| IoError::PotBinParse {
                    field,
                    token: token.to_string(),
                })?;
                values.push(i32_from_i64(value, field)?);
            }
            self.position += 1;
        }
        if values.is_empty() {
            return Err(IoError::PotBinMissing { field });
        }
        Ok(values)
    }

    fn usize_array(&mut self, field: &'static str, len: usize) -> Result<Array1<usize>> {
        let values = self
            .int_values(field, len)?
            .into_iter()
            .map(|value| usize_from_i64(value, field))
            .collect::<Result<Vec<_>>>()?;
        Ok(Array1::from_vec(values))
    }

    fn real_array(
        &mut self,
        field: &'static str,
        pad_width: usize,
        len: usize,
    ) -> Result<Array1<f64>> {
        Ok(Array1::from_vec(self.pad_reals(field, pad_width, len)?))
    }

    fn pad_reals(
        &mut self,
        field: &'static str,
        pad_width: usize,
        expected: usize,
    ) -> Result<Vec<f64>> {
        let mut values = Vec::with_capacity(expected);
        while values.len() < expected {
            let line = self.next_line(field)?;
            let decoded = decode_pad_line(field, line, pad_width)?;
            if decoded.is_empty() {
                return Err(IoError::PadPayload {
                    payload_len: 0,
                    unit_len: pad_width,
                });
            }
            for value in decoded {
                if values.len() < expected {
                    values.push(value);
                }
            }
        }
        Ok(values)
    }

    fn pad_reals_to_eof(&mut self, field: &'static str, pad_width: usize) -> Result<Vec<f64>> {
        let mut values = Vec::new();
        while self.position < self.lines.len() {
            let line = self.next_line(field)?;
            if line.trim().is_empty() {
                continue;
            }
            values.extend(decode_pad_line(field, line, pad_width)?);
        }
        Ok(values)
    }

    fn next_is_int_line(&self) -> bool {
        self.lines.get(self.position).is_some_and(|line| {
            let mut saw_token = false;
            for token in line.split_whitespace() {
                saw_token = true;
                if token.parse::<i64>().is_err() {
                    return false;
                }
            }
            saw_token
        })
    }

    fn next_line(&mut self, field: &'static str) -> Result<&'a str> {
        let line = self
            .lines
            .get(self.position)
            .copied()
            .ok_or(IoError::PotBinMissing { field })?;
        self.position += 1;
        Ok(line)
    }
}