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
//! Bounded legacy GSAS TOF instrument-parameter import.
//!
//! Profile functions 1 and 3 are translated into the shared published
//! back-to-back-exponential coefficient law. The adapter emits `PhaseSmith`'s
//! typed 15-coefficient model; legacy records never enter the core.

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

use phasesmith_core::{
    TOF_INCIDENT_SPECTRUM_COEFFICIENT_COUNT, TofBankGeometry, TofError, TofIncidentSpectrum,
    TofInstrument,
};

/// Resource limit checked before decoding a legacy instrument file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GsasTofInstrumentReadLimits {
    /// Maximum UTF-8 byte count.
    pub max_bytes: usize,
}

impl Default for GsasTofInstrumentReadLimits {
    fn default() -> Self {
        Self {
            max_bytes: 4 * 1024 * 1024,
        }
    }
}

impl GsasTofInstrumentReadLimits {
    /// Reject a zero allocation boundary.
    ///
    /// # Errors
    ///
    /// Returns [`GsasTofInstrumentIoError::InvalidLimits`] for zero bytes.
    pub fn validate(self) -> Result<(), GsasTofInstrumentIoError> {
        if self.max_bytes == 0 {
            return Err(GsasTofInstrumentIoError::InvalidLimits);
        }
        Ok(())
    }
}

/// One translated legacy GSAS TOF bank plus source metadata.
#[derive(Clone, Debug, PartialEq)]
pub struct GsasTofInstrumentData {
    /// `PhaseSmith`'s validated public 15-coefficient model.
    pub instrument: TofInstrument,
    /// Selected positive legacy bank.
    pub bank: usize,
    /// Legacy GSAS profile function number. Currently 1 or 3.
    pub profile_function: usize,
    /// Parsed fixed bank scattering angle when a `BNKPAR` record is present.
    pub bank_geometry: Option<TofBankGeometry>,
    /// Parsed type-4 Maxwellian/Chebyshev incident spectrum when present.
    pub incident_spectrum: Option<TofIncidentSpectrum>,
    /// Source path when read from a file.
    pub source_path: Option<PathBuf>,
}

/// Stable failure categories for legacy GSAS TOF instrument import.
#[derive(Debug)]
pub enum GsasTofInstrumentIoError {
    /// The configured byte limit is zero.
    InvalidLimits,
    /// The selected bank is zero or too large for the two-column legacy key.
    InvalidBank,
    /// Input exceeds the configured byte limit.
    ByteLimitExceeded {
        /// Observed bytes.
        actual: u64,
        /// Configured maximum.
        maximum: usize,
    },
    /// Filesystem or UTF-8 reading failed.
    Io(std::io::Error),
    /// A required bank record is absent.
    MissingRecord {
        /// Selected bank.
        bank: usize,
        /// Legacy record name.
        record: &'static str,
    },
    /// A record does not contain the required finite values.
    InvalidRecord {
        /// Selected bank.
        bank: usize,
        /// Legacy record name.
        record: &'static str,
    },
    /// Only independently documented legacy translations are supported.
    UnsupportedProfileFunction {
        /// Selected bank.
        bank: usize,
        /// Parsed legacy function number.
        found: usize,
    },
    /// The selected bank declares an incident-spectrum function not translated here.
    UnsupportedIncidentSpectrumFunction {
        /// Selected legacy bank.
        bank: usize,
        /// Parsed legacy incident-spectrum function number.
        found: usize,
    },
    /// Translated coefficients violate the core model.
    Profile(TofError),
}

impl Display for GsasTofInstrumentIoError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidLimits => {
                formatter.write_str("GSAS TOF instrument max_bytes must be positive")
            }
            Self::InvalidBank => formatter.write_str("GSAS TOF bank must lie in 1..=99"),
            Self::ByteLimitExceeded { actual, maximum } => write!(
                formatter,
                "GSAS TOF instrument input exceeds max_bytes: {actual} > {maximum}"
            ),
            Self::Io(error) => Display::fmt(error, formatter),
            Self::MissingRecord { bank, record } => {
                write!(formatter, "GSAS TOF bank {bank} has no {record} record")
            }
            Self::InvalidRecord { bank, record } => {
                write!(
                    formatter,
                    "GSAS TOF bank {bank} has an invalid {record} record"
                )
            }
            Self::UnsupportedProfileFunction { bank, found } => write!(
                formatter,
                "GSAS TOF bank {bank} uses unsupported profile function {found}; only functions 1 and 3 are supported"
            ),
            Self::UnsupportedIncidentSpectrumFunction { bank, found } => write!(
                formatter,
                "GSAS TOF bank {bank} uses unsupported incident-spectrum function {found}; only functions 0 and 4 are supported"
            ),
            Self::Profile(error) => Display::fmt(error, formatter),
        }
    }
}

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

/// Read one bounded legacy GSAS TOF profile-function-1 or -3 bank.
///
/// # Errors
///
/// Returns [`GsasTofInstrumentIoError`] for filesystem, limit, bank, syntax,
/// unsupported-profile, or translated-domain failures.
pub fn read_gsas_tof_instrument_file(
    path: impl AsRef<Path>,
    bank: usize,
    limits: GsasTofInstrumentReadLimits,
) -> Result<GsasTofInstrumentData, GsasTofInstrumentIoError> {
    validate_request(bank, limits)?;
    let path = path.as_ref();
    let size = fs::metadata(path)
        .map_err(GsasTofInstrumentIoError::Io)?
        .len();
    if size > u64::try_from(limits.max_bytes).unwrap_or(u64::MAX) {
        return Err(GsasTofInstrumentIoError::ByteLimitExceeded {
            actual: size,
            maximum: limits.max_bytes,
        });
    }
    let text = fs::read_to_string(path).map_err(GsasTofInstrumentIoError::Io)?;
    parse_inner(&text, bank, limits, Some(path.to_owned()))
}

/// Parse one bounded legacy GSAS TOF profile-function-1 or -3 bank from text.
///
/// # Errors
///
/// Returns [`GsasTofInstrumentIoError`] for limit, bank, syntax,
/// unsupported-profile, or translated-domain failures.
pub fn parse_gsas_tof_instrument_text(
    text: &str,
    bank: usize,
    limits: GsasTofInstrumentReadLimits,
) -> Result<GsasTofInstrumentData, GsasTofInstrumentIoError> {
    parse_inner(text, bank, limits, None)
}

fn parse_inner(
    text: &str,
    bank: usize,
    limits: GsasTofInstrumentReadLimits,
    source_path: Option<PathBuf>,
) -> Result<GsasTofInstrumentData, GsasTofInstrumentIoError> {
    validate_request(bank, limits)?;
    if text.len() > limits.max_bytes {
        return Err(GsasTofInstrumentIoError::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 icons = record_values(text, bank, "ICONS", &format!("INS {bank:>2} ICONS"))?;
    if icons.len() < 4 {
        return Err(invalid(bank, "ICONS"));
    }
    let bank_geometry = parse_optional_bank_geometry(text, bank)?;
    let incident_spectrum = parse_optional_incident_spectrum(text, bank)?;
    let compact_header = format!("INS {bank:>2}PRCF1 ");
    let spaced_header = format!("INS {bank:>2}PRCF  ");
    let compact = text.lines().any(|line| line.starts_with(&compact_header));
    let function = profile_function(
        text,
        bank,
        if compact {
            &compact_header
        } else {
            &spaced_header
        },
    )?;
    if !matches!(function, 1 | 3) {
        return Err(GsasTofInstrumentIoError::UnsupportedProfileFunction {
            bank,
            found: function,
        });
    }
    let (exponential_prefix, gaussian_prefix) = if compact {
        (
            format!("INS {bank:>2}PRCF11"),
            format!("INS {bank:>2}PRCF12"),
        )
    } else {
        (
            format!("INS {bank:>2}PRCF 1"),
            format!("INS {bank:>2}PRCF 2"),
        )
    };
    let exponential = record_values(text, bank, "PRCF11", &exponential_prefix)?;
    let gaussian = record_values(text, bank, "PRCF12", &gaussian_prefix)?;
    if exponential.len() < if function == 1 { 4 } else { 3 } {
        return Err(invalid(bank, "PRCF11"));
    }
    if gaussian.len() < if function == 1 { 3 } else { 2 } {
        return Err(invalid(bank, "PRCF12"));
    }

    // Legacy ICONS stores DIFC, DIFA, Zero, and an unused fourth field. It
    // does not carry DIFB. Function 1 places an unused coefficient before
    // alpha/beta0/beta1 and before sigma1/sigma2; function 3 starts each
    // group directly. Remaining typed coefficients are explicit zeros.
    let (alpha, beta0, beta1, sigma1, sigma2) = if function == 1 {
        (
            exponential[1],
            exponential[2],
            exponential[3],
            gaussian[1],
            gaussian[2],
        )
    } else {
        (
            exponential[0],
            exponential[1],
            exponential[2],
            gaussian[0],
            gaussian[1],
        )
    };
    let instrument = TofInstrument {
        zero_us: icons[2],
        difc_us_per_angstrom: icons[0],
        difa_us_per_angstrom2: icons[1],
        difb_us_angstrom: 0.0,
        alpha_coefficient: alpha,
        beta0_per_us: beta0,
        beta1_angstrom4_per_us: beta1,
        betaq_angstrom2_per_us: 0.0,
        sigma0_us2: 0.0,
        sigma1_us2_per_angstrom2: sigma1,
        sigma2_us2_per_angstrom4: sigma2,
        sigmaq_us2_per_angstrom: 0.0,
        x_us_per_angstrom: 0.0,
        y_us_per_angstrom2: 0.0,
        z_us: 0.0,
    };
    instrument
        .validate()
        .map_err(GsasTofInstrumentIoError::Profile)?;
    Ok(GsasTofInstrumentData {
        instrument,
        bank,
        profile_function: function,
        bank_geometry,
        incident_spectrum,
        source_path,
    })
}

fn validate_request(
    bank: usize,
    limits: GsasTofInstrumentReadLimits,
) -> Result<(), GsasTofInstrumentIoError> {
    limits.validate()?;
    if !(1..=99).contains(&bank) {
        return Err(GsasTofInstrumentIoError::InvalidBank);
    }
    Ok(())
}

fn record_values(
    text: &str,
    bank: usize,
    record: &'static str,
    prefix: &str,
) -> Result<Vec<f64>, GsasTofInstrumentIoError> {
    let line = text
        .lines()
        .find(|line| line.starts_with(prefix))
        .ok_or(GsasTofInstrumentIoError::MissingRecord { bank, record })?;
    let values = line[prefix.len()..]
        .split_whitespace()
        .map(str::parse::<f64>)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| invalid(bank, record))?;
    if values.is_empty() || values.iter().any(|value| !value.is_finite()) {
        return Err(invalid(bank, record));
    }
    Ok(values)
}

fn optional_record_values(
    text: &str,
    bank: usize,
    record: &'static str,
    prefix: &str,
) -> Result<Option<Vec<f64>>, GsasTofInstrumentIoError> {
    let Some(line) = text.lines().find(|line| line.starts_with(prefix)) else {
        return Ok(None);
    };
    let values = line[prefix.len()..]
        .split_whitespace()
        .map(str::parse::<f64>)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| invalid(bank, record))?;
    if values.is_empty() || values.iter().any(|value| !value.is_finite()) {
        return Err(invalid(bank, record));
    }
    Ok(Some(values))
}

fn parse_optional_bank_geometry(
    text: &str,
    bank: usize,
) -> Result<Option<TofBankGeometry>, GsasTofInstrumentIoError> {
    optional_record_values(text, bank, "BNKPAR", &format!("INS {bank:>2}BNKPAR"))?
        .map(|values| {
            if values.len() < 2 {
                return Err(invalid(bank, "BNKPAR"));
            }
            let geometry = TofBankGeometry {
                two_theta_deg: values[1],
            };
            geometry.validate().map_err(|_| invalid(bank, "BNKPAR"))?;
            Ok(geometry)
        })
        .transpose()
}

fn parse_optional_incident_spectrum(
    text: &str,
    bank: usize,
) -> Result<Option<TofIncidentSpectrum>, GsasTofInstrumentIoError> {
    let prefix = format!("INS {bank:>2}I ITYP");
    let Some(line) = text.lines().find(|line| line.starts_with(&prefix)) else {
        return Ok(None);
    };
    let mut tokens = line[prefix.len()..].split_whitespace();
    let function = tokens
        .next()
        .ok_or_else(|| invalid(bank, "I ITYP"))?
        .parse::<usize>()
        .map_err(|_| invalid(bank, "I ITYP"))?;
    let min_tof_ms = tokens
        .next()
        .ok_or_else(|| invalid(bank, "I ITYP"))?
        .parse::<f64>()
        .map_err(|_| invalid(bank, "I ITYP"))?;
    let max_tof_ms = tokens
        .next()
        .ok_or_else(|| invalid(bank, "I ITYP"))?
        .parse::<f64>()
        .map_err(|_| invalid(bank, "I ITYP"))?;
    if function == 0 {
        return Ok(None);
    }
    if function != 4 {
        return Err(
            GsasTofInstrumentIoError::UnsupportedIncidentSpectrumFunction {
                bank,
                found: function,
            },
        );
    }
    let mut coefficients = Vec::with_capacity(TOF_INCIDENT_SPECTRUM_COEFFICIENT_COUNT);
    for record_index in 1..=3 {
        coefficients.extend(record_values(
            text,
            bank,
            "ICOFF",
            &format!("INS {bank:>2}ICOFF{record_index}"),
        )?);
    }
    if coefficients.len() != TOF_INCIDENT_SPECTRUM_COEFFICIENT_COUNT {
        return Err(invalid(bank, "ICOFF"));
    }
    let coefficients: [f64; TOF_INCIDENT_SPECTRUM_COEFFICIENT_COUNT] = coefficients
        .try_into()
        .map_err(|_| invalid(bank, "ICOFF"))?;
    TofIncidentSpectrum::new(min_tof_ms * 1_000.0, max_tof_ms * 1_000.0, coefficients)
        .map(Some)
        .map_err(|_| invalid(bank, "I ITYP"))
}

fn profile_function(
    text: &str,
    bank: usize,
    prefix: &str,
) -> Result<usize, GsasTofInstrumentIoError> {
    let line = text.lines().find(|line| line.starts_with(prefix)).ok_or(
        GsasTofInstrumentIoError::MissingRecord {
            bank,
            record: "PRCF1",
        },
    )?;
    let mut tokens = line[prefix.len()..].split_whitespace();
    let function = tokens
        .next()
        .ok_or_else(|| invalid(bank, "PRCF1"))?
        .parse::<usize>()
        .map_err(|_| invalid(bank, "PRCF1"))?;
    Ok(function)
}

const fn invalid(bank: usize, record: &'static str) -> GsasTofInstrumentIoError {
    GsasTofInstrumentIoError::InvalidRecord { bank, record }
}