cyanea-io 0.1.0

File format parsing for the Cyanea bioinformatics ecosystem
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
//! PHYLIP alignment format parser and writer.
//!
//! Supports both interleaved and sequential PHYLIP formats. The format
//! starts with a dimension line giving the number of taxa and sites,
//! followed by sequence data in either interleaved or sequential layout.
//!
//! Uses the "relaxed" naming convention where names are whitespace-delimited
//! tokens of arbitrary length (not the strict 10-character fixed-width format).

use cyanea_core::{CyaneaError, Result};

/// A parsed PHYLIP multiple sequence alignment.
#[derive(Debug, Clone)]
pub struct PhylipAlignment {
    /// Aligned sequences as `(name, aligned_sequence)` pairs.
    pub sequences: Vec<(String, String)>,
    /// Number of taxa declared in the header.
    pub n_taxa: usize,
    /// Number of sites (alignment columns) declared in the header.
    pub n_sites: usize,
}

/// Parse a PHYLIP interleaved alignment from a string.
///
/// The first line must contain `n_taxa n_sites`. The first block contains
/// sequence names followed by sequence data; subsequent blocks contain only
/// sequence data. Blocks are separated by blank lines.
///
/// # Examples
///
/// ```
/// # use cyanea_io::phylip::parse_phylip;
/// let input = " 2 8\nseq1  ACGT\nseq2  TGCA\n\nACGT\nTGCA\n";
/// let aln = parse_phylip(input).unwrap();
/// assert_eq!(aln.sequences[0].1, "ACGTACGT");
/// ```
pub fn parse_phylip(input: &str) -> Result<PhylipAlignment> {
    let mut lines = input.lines().peekable();

    // Parse dimension line
    let (n_taxa, n_sites) = parse_dimensions(&mut lines)?;

    // Skip blank lines after header
    skip_blank_lines(&mut lines);

    // First block: names + sequences
    let mut seq_names: Vec<String> = Vec::with_capacity(n_taxa);
    let mut seq_data: Vec<String> = Vec::with_capacity(n_taxa);

    for _ in 0..n_taxa {
        let line = lines.next().ok_or_else(|| {
            CyaneaError::Parse("unexpected end of input in first PHYLIP block".to_string())
        })?;
        let line = line.trim();
        if line.is_empty() {
            return Err(CyaneaError::Parse(
                "unexpected blank line in first PHYLIP block".to_string(),
            ));
        }

        let (name, seq) = split_name_seq(line)?;
        seq_names.push(name);
        seq_data.push(seq);
    }

    if seq_names.len() != n_taxa {
        return Err(CyaneaError::Parse(format!(
            "expected {} taxa in first block, found {}",
            n_taxa,
            seq_names.len()
        )));
    }

    // Subsequent blocks: sequences only (interleaved)
    loop {
        // Skip blank lines between blocks
        let had_content = skip_blank_lines(&mut lines);
        if lines.peek().is_none() {
            break;
        }
        if !had_content && lines.peek().is_none() {
            break;
        }

        for i in 0..n_taxa {
            let line = match lines.next() {
                Some(l) => l,
                None => break,
            };
            let trimmed = line.trim();
            if trimmed.is_empty() {
                break;
            }
            let seq: String = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
            seq_data[i].push_str(&seq);
        }
    }

    // Validate site counts
    for (i, seq) in seq_data.iter().enumerate() {
        if seq.len() != n_sites {
            return Err(CyaneaError::Parse(format!(
                "taxon '{}': expected {} sites, found {}",
                seq_names[i], n_sites, seq.len()
            )));
        }
    }

    let sequences: Vec<(String, String)> = seq_names
        .into_iter()
        .zip(seq_data)
        .collect();

    Ok(PhylipAlignment {
        sequences,
        n_taxa,
        n_sites,
    })
}

/// Parse a PHYLIP sequential alignment from a string.
///
/// The first line must contain `n_taxa n_sites`. Each taxon entry begins
/// with a name line followed by one or more sequence lines until the
/// expected number of sites is reached.
///
/// # Examples
///
/// ```
/// # use cyanea_io::phylip::parse_phylip_sequential;
/// let input = " 2 8\nseq1\nACGTACGT\nseq2\nTGCATGCA\n";
/// let aln = parse_phylip_sequential(input).unwrap();
/// assert_eq!(aln.sequences.len(), 2);
/// ```
pub fn parse_phylip_sequential(input: &str) -> Result<PhylipAlignment> {
    let mut lines = input.lines().peekable();

    let (n_taxa, n_sites) = parse_dimensions(&mut lines)?;

    skip_blank_lines(&mut lines);

    let mut sequences: Vec<(String, String)> = Vec::with_capacity(n_taxa);

    for _ in 0..n_taxa {
        // Skip blank lines between taxa
        skip_blank_lines(&mut lines);

        // First line for each taxon: name [optional_seq_fragment]
        let first_line = lines.next().ok_or_else(|| {
            CyaneaError::Parse("unexpected end of input in sequential PHYLIP".to_string())
        })?;
        let first_line = first_line.trim();

        let (name, initial_seq) = split_name_seq(first_line)?;
        let mut seq = initial_seq;

        // Read more lines until we have n_sites characters
        while seq.len() < n_sites {
            let line = lines.next().ok_or_else(|| {
                CyaneaError::Parse(format!(
                    "unexpected end of input for taxon '{}': got {} of {} sites",
                    name,
                    seq.len(),
                    n_sites
                ))
            })?;
            let fragment: String = line.trim().chars().filter(|c| !c.is_whitespace()).collect();
            seq.push_str(&fragment);
        }

        if seq.len() != n_sites {
            return Err(CyaneaError::Parse(format!(
                "taxon '{}': expected {} sites, found {}",
                name, n_sites, seq.len()
            )));
        }

        sequences.push((name, seq));
    }

    if sequences.len() != n_taxa {
        return Err(CyaneaError::Parse(format!(
            "expected {} taxa, found {}",
            n_taxa,
            sequences.len()
        )));
    }

    Ok(PhylipAlignment {
        sequences,
        n_taxa,
        n_sites,
    })
}

/// Write a PHYLIP alignment in interleaved format.
///
/// Uses relaxed format with whitespace-delimited names.
///
/// # Examples
///
/// ```
/// # use cyanea_io::phylip::{PhylipAlignment, write_phylip};
/// let aln = PhylipAlignment {
///     sequences: vec![("s1".to_string(), "ACGT".to_string())],
///     n_taxa: 1,
///     n_sites: 4,
/// };
/// let output = write_phylip(&aln);
/// assert!(output.starts_with(" 1 4"));
/// ```
pub fn write_phylip(aln: &PhylipAlignment) -> String {
    const BLOCK_SIZE: usize = 60;

    let mut out = String::new();
    out.push_str(&format!(" {} {}\n", aln.n_taxa, aln.n_sites));

    if aln.sequences.is_empty() {
        return out;
    }

    let max_name_len = aln.sequences.iter().map(|(n, _)| n.len()).max().unwrap_or(0);
    let pad = max_name_len + 2;

    let total_len = aln.n_sites;
    let mut offset = 0;

    while offset < total_len {
        let end = std::cmp::min(offset + BLOCK_SIZE, total_len);

        for (name, seq) in &aln.sequences {
            if offset == 0 {
                // First block: include names
                let fragment = if end <= seq.len() {
                    &seq[offset..end]
                } else {
                    &seq[offset..]
                };
                out.push_str(&format!("{:<width$}{}\n", name, fragment, width = pad));
            } else {
                // Subsequent blocks: sequences only
                let fragment = if end <= seq.len() {
                    &seq[offset..end]
                } else if offset < seq.len() {
                    &seq[offset..]
                } else {
                    ""
                };
                out.push_str(&format!("{}\n", fragment));
            }
        }

        if offset + BLOCK_SIZE < total_len {
            out.push('\n');
        }

        offset = end;
    }

    out
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

fn parse_dimensions<'a, I: Iterator<Item = &'a str>>(
    lines: &mut std::iter::Peekable<I>,
) -> Result<(usize, usize)> {
    let dim_line = loop {
        match lines.next() {
            Some(l) => {
                let trimmed = l.trim();
                if !trimmed.is_empty() {
                    break trimmed.to_string();
                }
            }
            None => {
                return Err(CyaneaError::Parse(
                    "empty input: no PHYLIP dimension line".to_string(),
                ))
            }
        }
    };

    let parts: Vec<&str> = dim_line.split_whitespace().collect();
    if parts.len() < 2 {
        return Err(CyaneaError::Parse(format!(
            "invalid PHYLIP dimension line: '{}'",
            dim_line
        )));
    }

    let n_taxa: usize = parts[0].parse().map_err(|_| {
        CyaneaError::Parse(format!("invalid n_taxa '{}' in dimension line", parts[0]))
    })?;

    let n_sites: usize = parts[1].parse().map_err(|_| {
        CyaneaError::Parse(format!("invalid n_sites '{}' in dimension line", parts[1]))
    })?;

    Ok((n_taxa, n_sites))
}

fn skip_blank_lines<'a, I: Iterator<Item = &'a str>>(
    lines: &mut std::iter::Peekable<I>,
) -> bool {
    let mut skipped = false;
    while let Some(line) = lines.peek() {
        if line.trim().is_empty() {
            skipped = true;
            lines.next();
        } else {
            break;
        }
    }
    skipped
}

fn split_name_seq(line: &str) -> Result<(String, String)> {
    let parts: Vec<&str> = line.splitn(2, char::is_whitespace).collect();
    if parts.is_empty() || parts[0].is_empty() {
        return Err(CyaneaError::Parse(format!(
            "could not parse name from line: '{}'",
            line
        )));
    }
    let name = parts[0].to_string();
    let seq = if parts.len() > 1 {
        parts[1].chars().filter(|c| !c.is_whitespace()).collect()
    } else {
        String::new()
    };
    Ok((name, seq))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn phylip_round_trip() {
        let aln = PhylipAlignment {
            sequences: vec![
                ("seq1".to_string(), "ACGTACGT".to_string()),
                ("seq2".to_string(), "TGCATGCA".to_string()),
            ],
            n_taxa: 2,
            n_sites: 8,
        };

        let written = write_phylip(&aln);
        let parsed = parse_phylip(&written).unwrap();
        assert_eq!(parsed.n_taxa, 2);
        assert_eq!(parsed.n_sites, 8);
        assert_eq!(parsed.sequences[0].0, "seq1");
        assert_eq!(parsed.sequences[0].1, "ACGTACGT");
        assert_eq!(parsed.sequences[1].0, "seq2");
        assert_eq!(parsed.sequences[1].1, "TGCATGCA");
    }

    #[test]
    fn phylip_sequential_parse() {
        let input = " 2 10\nAlpha\nACGTACGTAC\nBeta\nTGCATGCATG\n";
        let aln = parse_phylip_sequential(input).unwrap();
        assert_eq!(aln.n_taxa, 2);
        assert_eq!(aln.n_sites, 10);
        assert_eq!(aln.sequences[0].0, "Alpha");
        assert_eq!(aln.sequences[0].1, "ACGTACGTAC");
        assert_eq!(aln.sequences[1].0, "Beta");
        assert_eq!(aln.sequences[1].1, "TGCATGCATG");
    }

    #[test]
    fn phylip_interleaved_parse() {
        let input = " 2 8\nseq1  ACGT\nseq2  TGCA\n\nACGT\nTGCA\n";
        let aln = parse_phylip(input).unwrap();
        assert_eq!(aln.n_taxa, 2);
        assert_eq!(aln.n_sites, 8);
        assert_eq!(aln.sequences[0].1, "ACGTACGT");
        assert_eq!(aln.sequences[1].1, "TGCATGCA");
    }

    #[test]
    fn phylip_dimension_mismatch_error() {
        let input = " 2 10\nseq1  ACGT\nseq2  TGCA\n";
        let result = parse_phylip(input);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("expected 10 sites"));
    }

    #[test]
    fn phylip_whitespace_handling() {
        // Extra whitespace in sequences should be stripped
        let input = " 3 8\nalpha     ACGT ACGT\nbeta      TGCA TGCA\ngamma     AAAA CCCC\n";
        let aln = parse_phylip(input).unwrap();
        assert_eq!(aln.n_taxa, 3);
        assert_eq!(aln.sequences[0].1, "ACGTACGT");
        assert_eq!(aln.sequences[1].1, "TGCATGCA");
        assert_eq!(aln.sequences[2].1, "AAAACCCC");
    }
}