geddes 0.2.0

A Rust library for parsing XRD pattern files
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
use crate::error::Error;
use quick_xml::events::Event;
use quick_xml::Reader;
use std::io::{BufRead, BufReader, Read, Seek};
use zip::ZipArchive;

/// Intermediate structure to hold parsed data before converting to the public Pattern struct.
#[derive(Debug)]
pub struct ParsedPattern {
    pub x: Vec<f64>,
    pub y: Vec<f64>,
    pub e: Option<Vec<f64>>,
}

/// Helper to parse x, y, and optional e from string parts.
fn parse_columns(parts: &[&str], x: &mut Vec<f64>, y: &mut Vec<f64>, e: &mut Vec<f64>) {
    if parts.len() >= 2 {
        if let (Ok(val_x), Ok(val_y)) = (parts[0].parse::<f64>(), parts[1].parse::<f64>()) {
            x.push(val_x);
            y.push(val_y);
            if parts.len() >= 3 {
                if let Ok(val_e) = parts[2].parse::<f64>() {
                    e.push(val_e);
                }
            }
        }
    }
}

/// Parses standard XY files (two or three columns: x, y, [e]).
///
/// Ignores lines starting with '#' or '!'.
pub fn parse_xy<R: Read>(reader: R) -> Result<ParsedPattern, Error> {
    let reader = BufReader::new(reader);
    let mut x = Vec::new();
    let mut y = Vec::new();
    let mut e = Vec::new();

    for line in reader.lines() {
        let line = line?;
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') || line.starts_with('!') {
            continue;
        }
        let parts: Vec<&str> = line.split_whitespace().collect();
        parse_columns(&parts, &mut x, &mut y, &mut e);
    }

    let has_error = !e.is_empty() && e.len() == x.len();
    Ok(ParsedPattern {
        x,
        y,
        e: if has_error { Some(e) } else { None },
    })
}

/// Parses CSV files.
///
/// Supports comma or whitespace as delimiters.
pub fn parse_csv<R: Read>(reader: R) -> Result<ParsedPattern, Error> {
    let reader = BufReader::new(reader);
    let mut x = Vec::new();
    let mut y = Vec::new();
    let mut e = Vec::new();

    for line in reader.lines() {
        let line = line?;
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') || line.starts_with('!') {
            continue;
        }
        // Support both comma-separated and whitespace-separated CSV-like files.
        let parts: Vec<&str> = line
            .split(|c: char| c == ',' || c.is_whitespace())
            .map(|p| p.trim())
            .filter(|p| !p.is_empty())
            .collect();
        parse_columns(&parts, &mut x, &mut y, &mut e);
    }

    let has_error = !e.is_empty() && e.len() == x.len();
    Ok(ParsedPattern {
        x,
        y,
        e: if has_error { Some(e) } else { None },
    })
}

/// Parses Rigaku RASX files (zipped XML/text format).
///
/// Looks for a `Profile*.txt` file inside the archive.
pub fn parse_rasx<R: Read + Seek>(reader: R) -> Result<ParsedPattern, Error> {
    let mut archive = ZipArchive::new(reader)?;

    let names: Vec<String> = (0..archive.len())
        .filter_map(|i| archive.by_index(i).ok().map(|f| f.name().to_string()))
        .collect();

    // Prioritize Data0/Profile0.txt, or find any Profile*.txt
    let profile_name = names
        .iter()
        .find(|n| n.as_str() == "Data0/Profile0.txt")
        .or_else(|| {
            names
                .iter()
                .find(|n| n.contains("Profile") && n.ends_with(".txt"))
        })
        .ok_or_else(|| Error::FileNotFoundInArchive("Profile*.txt".to_string()))?;

    let file = archive.by_name(profile_name)?;
    let reader = BufReader::new(file);

    let mut x = Vec::new();
    let mut y = Vec::new();

    for line in reader.lines() {
        let line = line?;
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 2 {
            if let (Ok(val_x), Ok(val_y)) = (parts[0].parse::<f64>(), parts[1].parse::<f64>()) {
                x.push(val_x);
                y.push(val_y);
            }
        }
    }
    Ok(ParsedPattern { x, y, e: None })
}

/// Parses Panalytical XRDML files (XML-based).
///
/// Extracts the 2Theta start/end positions and the intensities list.
pub fn parse_xrdml<R: Read>(reader: R) -> Result<ParsedPattern, Error> {
    let reader = BufReader::new(reader);
    let mut xml = Reader::from_reader(reader);
    xml.config_mut().trim_text(true);

    let mut buf = Vec::new();
    let mut intensities = Vec::new();
    let mut in_intensities = false;
    let mut in_positions_2theta = false;
    let mut capture_start = false;
    let mut capture_end = false;
    let mut start_pos: Option<f64> = None;
    let mut end_pos: Option<f64> = None;

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => match e.local_name().as_ref() {
                b"positions" => {
                    in_positions_2theta = false;
                    for attr in e.attributes() {
                        let attr = attr.map_err(|err| {
                            Error::Parse(format!("XRDML attribute error: {err}"))
                        })?;
                        if attr.key.as_ref() == b"axis" {
                            let axis = attr
                                .unescape_value()
                                .map_err(|err| {
                                    Error::Parse(format!(
                                        "XRDML attribute decode error: {err}"
                                    ))
                                })?
                                .into_owned();
                            if axis == "2Theta" {
                                in_positions_2theta = true;
                            }
                        }
                    }
                }
                b"startPosition" => {
                    if in_positions_2theta {
                        capture_start = true;
                    }
                }
                b"endPosition" => {
                    if in_positions_2theta {
                        capture_end = true;
                    }
                }
                b"intensities" => {
                    in_intensities = true;
                }
                _ => {}
            },
            Ok(Event::Text(e)) => {
                let text = e
                    .decode()
                    .map_err(|err| Error::Parse(format!("XRDML text decode error: {err}")))?;
                let text = text.trim();
                if text.is_empty() {
                    // Skip empty text nodes.
                } else if capture_start {
                    start_pos = Some(text.parse::<f64>().map_err(|_| {
                        Error::Parse("XRDML invalid 2Theta start position".into())
                    })?);
                } else if capture_end {
                    end_pos = Some(text.parse::<f64>().map_err(|_| {
                        Error::Parse("XRDML invalid 2Theta end position".into())
                    })?);
                } else if in_intensities {
                    for part in text.split_whitespace() {
                        if let Ok(value) = part.parse::<f64>() {
                            intensities.push(value);
                        }
                    }
                }
            }
            Ok(Event::End(e)) => match e.local_name().as_ref() {
                b"positions" => {
                    in_positions_2theta = false;
                }
                b"startPosition" => {
                    capture_start = false;
                }
                b"endPosition" => {
                    capture_end = false;
                }
                b"intensities" => {
                    in_intensities = false;
                    if !intensities.is_empty() && start_pos.is_some() && end_pos.is_some() {
                        break;
                    }
                }
                _ => {}
            },
            Ok(Event::Eof) => break,
            Err(err) => {
                return Err(Error::Parse(format!("XRDML parse error: {err}")));
            }
            _ => {}
        }
        buf.clear();
    }

    let start = start_pos
        .ok_or_else(|| Error::Parse("XRDML missing 2Theta start position".into()))?;
    let end =
        end_pos.ok_or_else(|| Error::Parse("XRDML missing 2Theta end position".into()))?;

    if intensities.is_empty() {
        return Err(Error::Parse("XRDML intensities not found".into()));
    }

    let mut x = Vec::with_capacity(intensities.len());
    if intensities.len() == 1 {
        x.push(start);
    } else {
        let step = (end - start) / (intensities.len() as f64 - 1.0);
        for i in 0..intensities.len() {
            x.push(start + (i as f64) * step);
        }
    }

    Ok(ParsedPattern {
        x,
        y: intensities,
        e: None,
    })
}

/// Parses GSAS RAW files.
///
/// Expects a `BANK` header line to determine start angle and step size.
pub fn parse_gsas_raw<R: Read>(reader: R) -> Result<ParsedPattern, Error> {
    let reader = BufReader::new(reader);
    let mut lines = reader.lines();

    let mut start = 0.0;
    let mut step = 0.0;

    let mut header_found = false;

    for line_res in lines.by_ref() {
        let line = line_res?;
        if line.starts_with("BANK") {
            let parts: Vec<&str> = line.split_whitespace().collect();
            // BANK 1 4941 494 CONST 1600.0 1.7 0.0 0.0 STD
            if parts.len() >= 7 {
                let start_raw = parts[5]
                    .parse::<f64>()
                    .map_err(|_| Error::Parse("Invalid start".into()))?;
                let step_raw = parts[6]
                    .parse::<f64>()
                    .map_err(|_| Error::Parse("Invalid step".into()))?;

                // GSAS standard: centidegrees
                start = start_raw / 100.0;
                step = step_raw / 100.0;
                header_found = true;
                break;
            }
        }
    }

    if !header_found {
        return Err(Error::Parse(
            "BANK header not found in RAW file".into(),
        ));
    }

    let mut y = Vec::new();

    for line in lines {
        let line = line?;
        if line.starts_with("BANK") {
            break;
        }
        let parts = line.split_whitespace();
        for part in parts {
            if let Ok(val) = part.parse::<f64>() {
                y.push(val);
            }
        }
    }

    // Generate x
    let mut x = Vec::with_capacity(y.len());
    for i in 0..y.len() {
        x.push(start + (i as f64) * step);
    }

    Ok(ParsedPattern { x, y, e: None })
}

/// Parses Bruker binary RAW files.
///
/// Uses heuristics to locate the intensity block and axis metadata.
///
/// Bruker RAW4 files are not fully documented and may store intensity points
/// either as contiguous `f32` values or as interleaved records near the file
/// tail (e.g. `f32 value` + `u32 status`).
pub fn parse_bruker_raw<R: Read>(mut reader: R) -> Result<ParsedPattern, Error> {
    let mut buf = Vec::new();
    reader.read_to_end(&mut buf)?;

    if !buf.starts_with(b"RAW") {
        return Err(Error::Parse(
            "Unsupported Bruker RAW header".into(),
        ));
    }

    let mut selected: Option<(BrukerDataLayout, f64, f64, f64)> = None;
    for layout in [
        find_bruker_interleaved_tail_block(&buf),
        find_bruker_plain_f32_tail_block(&buf),
    ]
    .into_iter()
    .flatten()
    {
        if !bruker_layout_data_plausible(&buf, layout) {
            continue;
        }
        let count_offsets = find_bruker_count_offsets(&buf, layout.count, layout.data_offset);
        if let Some((start, step)) = find_bruker_start_step(
            &buf,
            &count_offsets,
            layout.count,
            layout.data_offset,
        ) {
            let score = score_bruker_start_step(start, step, layout.count);
            match selected {
                Some((_, _, _, best_score)) if score <= best_score => {}
                _ => selected = Some((layout, start, step, score)),
            }
        }
    }

    let (layout, start, step, _) = selected.ok_or_else(|| {
        Error::Parse("Failed to locate Bruker RAW start/step metadata".into())
    })?;
    let count = layout.count;

    let count_usize = count as usize;
    let mut y = Vec::with_capacity(count_usize);
    for i in 0..count_usize {
        let off = layout.data_offset + i * layout.stride + layout.value_offset;
        let val = read_f32_le(&buf, off).ok_or_else(|| {
            Error::Parse("Bruker RAW intensity data truncated".into())
        })?;
        y.push(val as f64);
    }

    let mut x = Vec::with_capacity(count_usize);
    for i in 0..count_usize {
        x.push(start + step * (i as f64));
    }

    Ok(ParsedPattern { x, y, e: None })
}

#[derive(Debug, Clone, Copy)]
struct BrukerDataLayout {
    count: u32,
    data_offset: usize,
    stride: usize,
    value_offset: usize,
}

fn find_bruker_plain_f32_tail_block(buf: &[u8]) -> Option<BrukerDataLayout> {
    let len = buf.len();
    let mut best: Option<BrukerDataLayout> = None;

    for off in 0..len.saturating_sub(4) {
        let count = read_u32_le(buf, off)?;
        if count < 10 || count > 5_000_000 {
            continue;
        }
        let data_len = (count as usize) * 4;
        if data_len > len {
            continue;
        }
        let data_offset = len - data_len;
        if data_offset <= off {
            continue;
        }

        let layout = BrukerDataLayout {
            count,
            data_offset,
            stride: 4,
            value_offset: 0,
        };

        match best {
            Some(best_layout) if count <= best_layout.count => {}
            _ => best = Some(layout),
        }
    }

    best
}

fn find_bruker_interleaved_tail_block(buf: &[u8]) -> Option<BrukerDataLayout> {
    const MIN_POINTS: usize = 32;
    const FLAG_MAX: u32 = 3;

    let len = buf.len();
    let mut best: Option<BrukerDataLayout> = None;

    for value_offset in [0usize, 4usize] {
        let companion_offset = if value_offset == 0 { 4usize } else { 0usize };
        let mut run = 0usize;

        while len >= (run + 1) * 8 {
            let rec_off = len - (run + 1) * 8;
            let flag = match read_u32_le(buf, rec_off + companion_offset) {
                Some(v) => v,
                None => break,
            };
            if flag > FLAG_MAX {
                break;
            }
            let val = match read_f32_le(buf, rec_off + value_offset) {
                Some(v) => v,
                None => break,
            };
            if !val.is_finite() || val.abs() > 1.0e9 {
                break;
            }
            run += 1;
        }

        if run < MIN_POINTS {
            continue;
        }

        let candidate = BrukerDataLayout {
            count: run as u32,
            data_offset: len - run * 8,
            stride: 8,
            value_offset,
        };

        match best {
            Some(current) if candidate.count <= current.count => {}
            _ => best = Some(candidate),
        }
    }

    best
}

fn bruker_layout_data_plausible(buf: &[u8], layout: BrukerDataLayout) -> bool {
    let count = layout.count as usize;
    if count == 0 {
        return false;
    }

    // Sample evenly across the candidate stream. A high fraction of subnormal
    // values strongly indicates we are reading marker words as floats.
    let samples = count.min(64);
    let mut subnormal = 0usize;

    for s in 0..samples {
        let idx = if samples == 1 {
            0
        } else {
            s * (count - 1) / (samples - 1)
        };
        let off = layout.data_offset + idx * layout.stride + layout.value_offset;
        let val = match read_f32_le(buf, off) {
            Some(v) => v,
            None => return false,
        };
        if !val.is_finite() {
            return false;
        }
        if val != 0.0 && val.abs() < f32::MIN_POSITIVE {
            subnormal += 1;
        }
    }

    (subnormal as f64) / (samples as f64) <= 0.2
}

fn find_bruker_count_offsets(buf: &[u8], count: u32, search_end: usize) -> Vec<usize> {
    if search_end < 4 {
        return Vec::new();
    }
    let end = search_end.min(buf.len().saturating_sub(4));
    let mut offsets = Vec::new();

    for off in 0..=end {
        if read_u32_le(buf, off) == Some(count) {
            offsets.push(off);
        }
    }
    offsets
}

fn find_bruker_start_step(
    buf: &[u8],
    count_offsets: &[usize],
    count: u32,
    search_end: usize,
) -> Option<(f64, f64)> {
    let mut best: Option<(f64, f64, f64)> = None;

    for &count_offset in count_offsets {
        if let Some(start_off) = count_offset.checked_sub(16) {
            if let (Some(start), Some(step)) =
                (read_f64_le(buf, start_off), read_f64_le(buf, start_off + 8))
            {
                if bruker_start_step_valid(start, step, count) {
                    let score = score_bruker_start_step(start, step, count);
                    match best {
                        Some((_, _, best_score)) if score <= best_score => {}
                        _ => best = Some((start, step, score)),
                    }
                }
            }
        }
    }

    if best.is_some() {
        return best.map(|(start, step, _)| (start, step));
    }

    // Some Bruker RAW variants do not expose a count marker adjacent to axis
    // metadata. Fall back to scanning the pre-data region for plausible pairs.
    let end = search_end.min(buf.len().saturating_sub(16));
    for off in 0..=end {
        let (start, step) = match (read_f64_le(buf, off), read_f64_le(buf, off + 8)) {
            (Some(start), Some(step)) => (start, step),
            _ => continue,
        };
        if bruker_start_step_valid(start, step, count) {
            let score = score_bruker_start_step(start, step, count);
            match best {
                Some((_, _, best_score)) if score <= best_score => {}
                _ => best = Some((start, step, score)),
            }
        }
    }

    best.map(|(start, step, _)| (start, step))
}

fn bruker_start_step_valid(start: f64, step: f64, count: u32) -> bool {
    if !start.is_finite() || !step.is_finite() || step <= 1.0e-6 || step > 10.0 {
        return false;
    }
    let n = count as f64;
    let end = start + step * (n - 1.0);
    if !end.is_finite() {
        return false;
    }
    let span = step * ((n - 1.0).max(0.0));
    if !span.is_finite() || !(1.0..=360.0).contains(&span) {
        return false;
    }
    true
}

fn score_bruker_start_step(start: f64, step: f64, count: u32) -> f64 {
    let span = step * ((count as f64 - 1.0).max(0.0));
    let mut score = span.min(360.0);
    if (0.0..=180.0).contains(&start) {
        score += 50.0;
    }
    if (1.0e-4..=0.5).contains(&step) {
        score += 25.0;
    }
    score
}

fn read_u32_le(buf: &[u8], offset: usize) -> Option<u32> {
    let bytes = buf.get(offset..offset + 4)?;
    Some(u32::from_le_bytes(bytes.try_into().ok()?))
}

fn read_f32_le(buf: &[u8], offset: usize) -> Option<f32> {
    let bytes = buf.get(offset..offset + 4)?;
    Some(f32::from_le_bytes(bytes.try_into().ok()?))
}

fn read_f64_le(buf: &[u8], offset: usize) -> Option<f64> {
    let bytes = buf.get(offset..offset + 8)?;
    Some(f64::from_le_bytes(bytes.try_into().ok()?))
}