Skip to main content

cyanea_align/
poa.rs

1//! Partial Order Alignment (POA) for multi-sequence consensus.
2//!
3//! Implements the POA algorithm described in:
4//! C. Lee, C. Grasso, M. F. Sharlow, "Multiple sequence alignment using
5//! partial order graphs", *Bioinformatics*, 18(3):452--464, 2002.
6//!
7//! Sequences are progressively aligned to a DAG and integrated, building a
8//! partial order graph that represents the multiple alignment. Consensus is
9//! extracted by finding the heaviest weighted path through the DAG.
10//!
11//! # Example
12//!
13//! ```
14//! use cyanea_align::poa::{PoaGraph, PoaScoring};
15//!
16//! let mut graph = PoaGraph::from_sequence(b"ACGTACGT");
17//! let scoring = PoaScoring::default();
18//! graph.add_sequence(b"ACGTACGT", &scoring).unwrap();
19//! graph.add_sequence(b"ACGAACGT", &scoring).unwrap();
20//! let consensus = graph.consensus();
21//! assert_eq!(consensus, b"ACGTACGT");
22//! ```
23
24use cyanea_core::{CyaneaError, Result};
25
26// ---------------------------------------------------------------------------
27// Data structures
28// ---------------------------------------------------------------------------
29
30/// A node in the POA graph.
31#[derive(Debug, Clone)]
32struct PoaNode {
33    /// The base at this node.
34    base: u8,
35    /// Indices of successor nodes (outgoing edges).
36    successors: Vec<usize>,
37    /// Indices of predecessor nodes (incoming edges).
38    predecessors: Vec<usize>,
39    /// Edge weights to successors (parallel to `successors` vec).
40    weights: Vec<usize>,
41    /// Alignment info: which nodes from other sequences this aligns to.
42    aligned_to: Vec<usize>,
43}
44
45impl PoaNode {
46    fn new(base: u8) -> Self {
47        Self {
48            base,
49            successors: Vec::new(),
50            predecessors: Vec::new(),
51            weights: Vec::new(),
52            aligned_to: Vec::new(),
53        }
54    }
55}
56
57/// Partial Order Alignment graph for multi-sequence consensus.
58///
59/// Implements the Lee 2002 algorithm: sequences are progressively aligned
60/// to the graph and integrated, building a DAG that represents the
61/// multiple alignment.
62#[derive(Debug, Clone)]
63pub struct PoaGraph {
64    nodes: Vec<PoaNode>,
65    /// Start nodes (no predecessors) for topological traversal.
66    start_nodes: Vec<usize>,
67    /// Number of sequences that have been added to the graph.
68    n_sequences: usize,
69}
70
71/// Scoring parameters for POA.
72#[derive(Debug, Clone, Copy)]
73pub struct PoaScoring {
74    pub match_score: i32,
75    pub mismatch_score: i32,
76    pub gap_score: i32,
77}
78
79impl Default for PoaScoring {
80    fn default() -> Self {
81        Self {
82            match_score: 2,
83            mismatch_score: -1,
84            gap_score: -2,
85        }
86    }
87}
88
89// ---------------------------------------------------------------------------
90// Traceback direction constants
91// ---------------------------------------------------------------------------
92
93const TB_NONE: u8 = 0;
94const TB_DIAG: u8 = 1;
95const TB_UP: u8 = 2; // gap in sequence (consume graph node)
96const TB_LEFT: u8 = 3; // gap in graph (consume sequence position)
97
98// ---------------------------------------------------------------------------
99// Implementation
100// ---------------------------------------------------------------------------
101
102impl PoaGraph {
103    /// Create an empty POA graph.
104    pub fn new() -> Self {
105        Self {
106            nodes: Vec::new(),
107            start_nodes: Vec::new(),
108            n_sequences: 0,
109        }
110    }
111
112    /// Initialize a POA graph from the first sequence (linear chain of nodes).
113    pub fn from_sequence(seq: &[u8]) -> Self {
114        let mut graph = Self::new();
115        if seq.is_empty() {
116            return graph;
117        }
118
119        for (i, &base) in seq.iter().enumerate() {
120            let node = PoaNode::new(base);
121            graph.nodes.push(node);
122
123            if i > 0 {
124                graph.add_edge(i - 1, i, 1);
125            }
126        }
127
128        graph.start_nodes.push(0);
129        graph.n_sequences = 1;
130        graph
131    }
132
133    /// Add a directed edge from `from` to `to` with the given weight.
134    /// If the edge already exists, increment its weight.
135    fn add_edge(&mut self, from: usize, to: usize, weight: usize) {
136        if let Some(pos) = self.nodes[from].successors.iter().position(|&s| s == to) {
137            self.nodes[from].weights[pos] += weight;
138        } else {
139            self.nodes[from].successors.push(to);
140            self.nodes[from].weights.push(weight);
141            self.nodes[to].predecessors.push(from);
142        }
143    }
144
145    /// Align a sequence to the graph using DP (Lee 2002), then integrate
146    /// the aligned sequence into the graph.
147    ///
148    /// # Errors
149    ///
150    /// Returns an error if the sequence is empty or the graph is empty.
151    pub fn add_sequence(&mut self, seq: &[u8], scoring: &PoaScoring) -> Result<()> {
152        if seq.is_empty() {
153            return Err(CyaneaError::InvalidInput(
154                "sequence must not be empty".into(),
155            ));
156        }
157        if self.nodes.is_empty() {
158            return Err(CyaneaError::InvalidInput(
159                "graph is empty; use from_sequence to initialize".into(),
160            ));
161        }
162
163        let topo = self.topological_sort();
164        let alignment = self.align_to_graph(seq, scoring, &topo);
165        self.integrate_alignment(seq, &alignment);
166        self.n_sequences += 1;
167
168        Ok(())
169    }
170
171    /// Align a sequence to the graph via DP over the topological ordering.
172    ///
173    /// Returns a list of `(Option<graph_node>, Option<seq_pos>)` pairs
174    /// representing the alignment from traceback.
175    fn align_to_graph(
176        &self,
177        seq: &[u8],
178        scoring: &PoaScoring,
179        topo: &[usize],
180    ) -> Vec<(Option<usize>, Option<usize>)> {
181        let n_nodes = self.nodes.len();
182        let seq_len = seq.len();
183
184        // Map from node index to topological rank for fast lookup.
185        let mut topo_rank = vec![0usize; n_nodes];
186        for (rank, &node_idx) in topo.iter().enumerate() {
187            topo_rank[node_idx] = rank;
188        }
189
190        // DP score matrix: score[topo_rank][seq_pos + 1]
191        // Row 0 is the "before any graph node" row.
192        // Col 0 is the "before any sequence base" column.
193        let rows = topo.len() + 1;
194        let cols = seq_len + 1;
195        let mut score = vec![vec![i32::MIN / 2; cols]; rows];
196        let mut trace = vec![vec![(TB_NONE, 0usize); cols]; rows];
197
198        // Initialize: starting before any node or base is score 0.
199        score[0][0] = 0;
200
201        // Initialize first row: gaps in the graph (consuming sequence bases).
202        for j in 1..cols {
203            score[0][j] = scoring.gap_score * j as i32;
204            trace[0][j] = (TB_LEFT, 0);
205        }
206
207        // For each graph node in topological order.
208        for (rank_idx, &node_idx) in topo.iter().enumerate() {
209            let rank = rank_idx + 1; // +1 because row 0 is the "no node" row
210            let node_base = self.nodes[node_idx].base;
211
212            // Find the best score arriving at this node from predecessors
213            // (or from the start if this is a start node).
214            let pred_ranks: Vec<usize> = if self.nodes[node_idx].predecessors.is_empty() {
215                vec![0] // Use the "no node" row
216            } else {
217                self.nodes[node_idx]
218                    .predecessors
219                    .iter()
220                    .map(|&p| topo_rank[p] + 1)
221                    .collect()
222            };
223
224            // Column 0: gap in the sequence (consuming graph node).
225            for &pr in &pred_ranks {
226                let gap_val = score[pr][0] + scoring.gap_score;
227                if gap_val > score[rank][0] {
228                    score[rank][0] = gap_val;
229                    trace[rank][0] = (TB_UP, pr);
230                }
231            }
232
233            // Fill DP for each sequence position.
234            for j in 1..cols {
235                let seq_base = seq[j - 1];
236
237                // Diagonal: match/mismatch from a predecessor row.
238                let sub = if seq_base.to_ascii_uppercase() == node_base.to_ascii_uppercase() {
239                    scoring.match_score
240                } else {
241                    scoring.mismatch_score
242                };
243                for &pr in &pred_ranks {
244                    let diag = score[pr][j - 1] + sub;
245                    if diag > score[rank][j] {
246                        score[rank][j] = diag;
247                        trace[rank][j] = (TB_DIAG, pr);
248                    }
249                }
250
251                // Up: gap in sequence (consume graph node, skip seq base).
252                for &pr in &pred_ranks {
253                    let up = score[pr][j] + scoring.gap_score;
254                    if up > score[rank][j] {
255                        score[rank][j] = up;
256                        trace[rank][j] = (TB_UP, pr);
257                    }
258                }
259
260                // Left: gap in graph (consume seq base, stay at same graph position).
261                let left = score[rank][j - 1] + scoring.gap_score;
262                if left > score[rank][j] {
263                    score[rank][j] = left;
264                    trace[rank][j] = (TB_LEFT, rank);
265                }
266            }
267        }
268
269        // Find the best ending position: last column of any node row.
270        let mut best_score = i32::MIN;
271        let mut best_rank = 0;
272        for rank in 1..rows {
273            if score[rank][seq_len] > best_score {
274                best_score = score[rank][seq_len];
275                best_rank = rank;
276            }
277        }
278
279        // Traceback.
280        let mut alignment = Vec::new();
281        let mut r = best_rank;
282        let mut c = seq_len;
283
284        while r > 0 || c > 0 {
285            let (dir, prev_rank) = trace[r][c];
286
287            match dir {
288                TB_DIAG => {
289                    let node_idx = topo[r - 1];
290                    alignment.push((Some(node_idx), Some(c - 1)));
291                    r = prev_rank;
292                    c -= 1;
293                }
294                TB_UP => {
295                    let node_idx = topo[r - 1];
296                    alignment.push((Some(node_idx), None));
297                    r = prev_rank;
298                }
299                TB_LEFT => {
300                    alignment.push((None, Some(c - 1)));
301                    c -= 1;
302                }
303                _ => {
304                    // TB_NONE at (0, 0) — we are done.
305                    break;
306                }
307            }
308        }
309
310        alignment.reverse();
311        alignment
312    }
313
314    /// Integrate an aligned sequence into the graph.
315    ///
316    /// For matched positions where bases agree, we reuse the existing node and
317    /// increase edge weight. For mismatches, we add a new node and record it
318    /// in `aligned_to`. For insertions (sequence bases with no graph node),
319    /// we add new nodes to the graph.
320    fn integrate_alignment(&mut self, seq: &[u8], alignment: &[(Option<usize>, Option<usize>)]) {
321        let mut prev_node: Option<usize> = None;
322
323        for &(graph_node, seq_pos) in alignment {
324            match (graph_node, seq_pos) {
325                (Some(gn), Some(sp)) => {
326                    // Aligned pair: graph node gn aligns to sequence position sp.
327                    let seq_base = seq[sp];
328                    let node_base = self.nodes[gn].base;
329
330                    if seq_base.to_ascii_uppercase() == node_base.to_ascii_uppercase() {
331                        // Match: reuse the node, just add/increase edge from prev.
332                        if let Some(prev) = prev_node {
333                            self.add_edge(prev, gn, 1);
334                        } else if !self.start_nodes.contains(&gn) {
335                            // This node becomes a start node for this sequence.
336                            self.start_nodes.push(gn);
337                        }
338                        prev_node = Some(gn);
339                    } else {
340                        // Mismatch: add a new node with the sequence base.
341                        let new_idx = self.nodes.len();
342                        self.nodes.push(PoaNode::new(seq_base));
343
344                        // Record alignment relationship.
345                        self.nodes[gn].aligned_to.push(new_idx);
346                        self.nodes[new_idx].aligned_to.push(gn);
347
348                        if let Some(prev) = prev_node {
349                            self.add_edge(prev, new_idx, 1);
350                        } else {
351                            self.start_nodes.push(new_idx);
352                        }
353                        prev_node = Some(new_idx);
354                    }
355                }
356                (None, Some(sp)) => {
357                    // Insertion in sequence: add a new node.
358                    let seq_base = seq[sp];
359                    let new_idx = self.nodes.len();
360                    self.nodes.push(PoaNode::new(seq_base));
361
362                    if let Some(prev) = prev_node {
363                        self.add_edge(prev, new_idx, 1);
364                    } else {
365                        self.start_nodes.push(new_idx);
366                    }
367                    prev_node = Some(new_idx);
368                }
369                (Some(_gn), None) => {
370                    // Deletion in sequence: graph node not consumed.
371                    // We skip this node — no contribution from this sequence.
372                }
373                (None, None) => {
374                    // Should not happen, but ignore.
375                }
376            }
377        }
378    }
379
380    /// Extract consensus by finding the heaviest weighted path through the DAG.
381    ///
382    /// Uses topological-order DP: for each node, the score is the maximum
383    /// incoming edge weight plus the predecessor's best score. The consensus
384    /// is the path from the highest-scoring node traced back through best
385    /// predecessors.
386    pub fn consensus(&self) -> Vec<u8> {
387        if self.nodes.is_empty() {
388            return Vec::new();
389        }
390
391        let topo = self.topological_sort();
392
393        // best_score[node] = maximum total weight of any path ending at node.
394        let mut best_score = vec![0i64; self.nodes.len()];
395        // best_pred[node] = predecessor on the heaviest path (None for start).
396        let mut best_pred: Vec<Option<usize>> = vec![None; self.nodes.len()];
397
398        for &node_idx in &topo {
399            // For start nodes (no predecessors), score stays 0.
400            for &pred in &self.nodes[node_idx].predecessors {
401                // Find the weight of this edge in the predecessor's successor list.
402                let weight = self.edge_weight(pred, node_idx);
403                let candidate = best_score[pred] + weight as i64;
404
405                if candidate > best_score[node_idx] {
406                    best_score[node_idx] = candidate;
407                    best_pred[node_idx] = Some(pred);
408                }
409            }
410        }
411
412        // Find the node with the maximum score.
413        let mut best_end = 0;
414        let mut max_score = i64::MIN;
415        for &node_idx in &topo {
416            if best_score[node_idx] > max_score {
417                max_score = best_score[node_idx];
418                best_end = node_idx;
419            }
420        }
421
422        // Traceback: follow best_pred from best_end to a start node.
423        let mut path = Vec::new();
424        let mut current = best_end;
425        path.push(self.nodes[current].base);
426
427        while let Some(pred) = best_pred[current] {
428            path.push(self.nodes[pred].base);
429            current = pred;
430        }
431
432        path.reverse();
433        path
434    }
435
436    /// Look up the weight of the edge from `from` to `to`.
437    fn edge_weight(&self, from: usize, to: usize) -> usize {
438        if let Some(pos) = self.nodes[from].successors.iter().position(|&s| s == to) {
439            self.nodes[from].weights[pos]
440        } else {
441            0
442        }
443    }
444
445    /// Topological sort of the graph using Kahn's algorithm.
446    pub fn topological_sort(&self) -> Vec<usize> {
447        let n = self.nodes.len();
448        let mut in_degree = vec![0usize; n];
449
450        for node in &self.nodes {
451            for &succ in &node.successors {
452                in_degree[succ] += 1;
453            }
454        }
455
456        let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
457        let mut order = Vec::with_capacity(n);
458
459        while let Some(node_idx) = queue.pop() {
460            order.push(node_idx);
461            for &succ in &self.nodes[node_idx].successors {
462                in_degree[succ] -= 1;
463                if in_degree[succ] == 0 {
464                    queue.push(succ);
465                }
466            }
467        }
468
469        order
470    }
471
472    /// Produce a DOT-format string for visualization of the graph.
473    ///
474    /// Nodes are labeled with their base character and index. Edge labels
475    /// show the weight.
476    pub fn to_dot(&self) -> String {
477        let mut dot = String::from("digraph POA {\n");
478        dot.push_str("    rankdir=LR;\n");
479
480        for (i, node) in self.nodes.iter().enumerate() {
481            let base = node.base as char;
482            dot.push_str(&format!("    n{} [label=\"{}({})\"];\n", i, base, i));
483        }
484
485        for (i, node) in self.nodes.iter().enumerate() {
486            for (edge_idx, &succ) in node.successors.iter().enumerate() {
487                let w = node.weights[edge_idx];
488                dot.push_str(&format!("    n{} -> n{} [label=\"{}\"];\n", i, succ, w));
489            }
490        }
491
492        // Show aligned_to relationships as dashed edges.
493        for (i, node) in self.nodes.iter().enumerate() {
494            for &aligned in &node.aligned_to {
495                if i < aligned {
496                    dot.push_str(&format!(
497                        "    n{} -> n{} [style=dashed, color=gray, dir=none];\n",
498                        i, aligned
499                    ));
500                }
501            }
502        }
503
504        dot.push_str("}\n");
505        dot
506    }
507
508    /// Number of nodes in the graph.
509    pub fn num_nodes(&self) -> usize {
510        self.nodes.len()
511    }
512
513    /// Number of sequences that have been added to (or used to initialize)
514    /// the graph.
515    pub fn num_sequences(&self) -> usize {
516        self.n_sequences
517    }
518}
519
520// ---------------------------------------------------------------------------
521// Tests
522// ---------------------------------------------------------------------------
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    #[test]
529    fn single_sequence_consensus() {
530        let seq = b"ACGTACGT";
531        let graph = PoaGraph::from_sequence(seq);
532        let consensus = graph.consensus();
533        assert_eq!(consensus, seq.to_vec());
534    }
535
536    #[test]
537    fn two_identical_sequences() {
538        let seq = b"ACGTACGT";
539        let mut graph = PoaGraph::from_sequence(seq);
540        let scoring = PoaScoring::default();
541        graph.add_sequence(seq, &scoring).unwrap();
542        let consensus = graph.consensus();
543        assert_eq!(consensus, seq.to_vec());
544        assert_eq!(graph.num_sequences(), 2);
545    }
546
547    #[test]
548    fn two_sequences_single_snp() {
549        // Original sequence is the reference. A second sequence has one SNP.
550        // With only two sequences, the consensus should be the original because
551        // the original path has the same weight as the alternate path, and
552        // topological order favors the first-added nodes.
553        let mut graph = PoaGraph::from_sequence(b"ACGTACGT");
554        let scoring = PoaScoring::default();
555        graph.add_sequence(b"ACGAACGT", &scoring).unwrap();
556        let consensus = graph.consensus();
557        // Both paths have weight 1 through the SNP. The consensus should
558        // be one of the two valid sequences.
559        assert!(
560            consensus == b"ACGTACGT" || consensus == b"ACGAACGT",
561            "unexpected consensus: {:?}",
562            String::from_utf8_lossy(&consensus)
563        );
564    }
565
566    #[test]
567    fn three_sequences_majority_rules() {
568        // Two sequences say T, one says A at position 3.
569        // Majority should win.
570        let mut graph = PoaGraph::from_sequence(b"ACGTAC");
571        let scoring = PoaScoring::default();
572        graph.add_sequence(b"ACGTAC", &scoring).unwrap();
573        graph.add_sequence(b"ACGAAC", &scoring).unwrap();
574        let consensus = graph.consensus();
575        assert_eq!(
576            consensus,
577            b"ACGTAC".to_vec(),
578            "consensus should follow majority: {:?}",
579            String::from_utf8_lossy(&consensus)
580        );
581    }
582
583    #[test]
584    fn three_sequences_with_insertion() {
585        // Two sequences agree on original, one has an extra base inserted.
586        // Majority rules: consensus should follow the two without insertion.
587        let mut graph = PoaGraph::from_sequence(b"ACGTAC");
588        let scoring = PoaScoring::default();
589        graph.add_sequence(b"ACGTAC", &scoring).unwrap();
590        graph.add_sequence(b"ACGXTAC", &scoring).unwrap();
591        let consensus = graph.consensus();
592        assert_eq!(
593            consensus,
594            b"ACGTAC".to_vec(),
595            "consensus should follow majority without insertion: {:?}",
596            String::from_utf8_lossy(&consensus)
597        );
598    }
599
600    #[test]
601    fn two_sequences_with_deletion() {
602        // Second sequence has one base deleted.
603        let mut graph = PoaGraph::from_sequence(b"ACGTAC");
604        let scoring = PoaScoring::default();
605        graph.add_sequence(b"ACGAC", &scoring).unwrap();
606        let consensus = graph.consensus();
607        // The original path has all edges weight >= 1, and the shortcut
608        // edge (skipping T) has weight 1. Original path wins because it
609        // has more edges contributing total weight.
610        assert_eq!(
611            consensus,
612            b"ACGTAC".to_vec(),
613            "consensus should be original with deletion: {:?}",
614            String::from_utf8_lossy(&consensus)
615        );
616    }
617
618    #[test]
619    fn empty_sequence_error() {
620        let mut graph = PoaGraph::from_sequence(b"ACGT");
621        let scoring = PoaScoring::default();
622        let result = graph.add_sequence(b"", &scoring);
623        assert!(result.is_err());
624    }
625
626    #[test]
627    fn add_to_empty_graph_error() {
628        let mut graph = PoaGraph::new();
629        let scoring = PoaScoring::default();
630        let result = graph.add_sequence(b"ACGT", &scoring);
631        assert!(result.is_err());
632    }
633
634    #[test]
635    fn from_sequence_creates_linear_graph() {
636        let seq = b"ACGT";
637        let graph = PoaGraph::from_sequence(seq);
638        assert_eq!(graph.num_nodes(), 4);
639        assert_eq!(graph.num_sequences(), 1);
640        assert_eq!(graph.start_nodes, vec![0]);
641
642        // Check linear chain structure.
643        for i in 0..3 {
644            assert_eq!(graph.nodes[i].successors, vec![i + 1]);
645            assert_eq!(graph.nodes[i].weights, vec![1]);
646        }
647        assert!(graph.nodes[3].successors.is_empty());
648        assert!(graph.nodes[0].predecessors.is_empty());
649        for i in 1..4 {
650            assert_eq!(graph.nodes[i].predecessors, vec![i - 1]);
651        }
652    }
653
654    #[test]
655    fn topological_sort_linear() {
656        let graph = PoaGraph::from_sequence(b"ACGT");
657        let topo = graph.topological_sort();
658        // For a linear graph, topological order should visit all 4 nodes.
659        assert_eq!(topo.len(), 4);
660        // Each node should appear before its successor.
661        for i in 0..3 {
662            let pos_i = topo.iter().position(|&x| x == i).unwrap();
663            let pos_next = topo.iter().position(|&x| x == i + 1).unwrap();
664            assert!(pos_i < pos_next);
665        }
666    }
667
668    #[test]
669    fn to_dot_valid_syntax() {
670        let mut graph = PoaGraph::from_sequence(b"AC");
671        let scoring = PoaScoring::default();
672        graph.add_sequence(b"AT", &scoring).unwrap();
673
674        let dot = graph.to_dot();
675        assert!(dot.starts_with("digraph POA {"));
676        assert!(dot.ends_with("}\n"));
677        assert!(dot.contains("->"));
678        assert!(dot.contains("rankdir=LR"));
679        // Should have node labels.
680        assert!(dot.contains("[label="));
681    }
682
683    #[test]
684    fn empty_graph_consensus() {
685        let graph = PoaGraph::new();
686        let consensus = graph.consensus();
687        assert!(consensus.is_empty());
688    }
689
690    #[test]
691    fn single_base_sequences() {
692        let mut graph = PoaGraph::from_sequence(b"A");
693        let scoring = PoaScoring::default();
694        graph.add_sequence(b"A", &scoring).unwrap();
695        let consensus = graph.consensus();
696        assert_eq!(consensus, b"A".to_vec());
697    }
698
699    #[test]
700    fn num_sequences_tracks_correctly() {
701        let mut graph = PoaGraph::from_sequence(b"ACGT");
702        assert_eq!(graph.num_sequences(), 1);
703        let scoring = PoaScoring::default();
704        graph.add_sequence(b"ACGT", &scoring).unwrap();
705        assert_eq!(graph.num_sequences(), 2);
706        graph.add_sequence(b"ACGT", &scoring).unwrap();
707        assert_eq!(graph.num_sequences(), 3);
708    }
709
710    #[test]
711    fn five_sequences_strong_consensus() {
712        let mut graph = PoaGraph::from_sequence(b"ACGTACGT");
713        let scoring = PoaScoring::default();
714        // Four copies of the same sequence.
715        for _ in 0..4 {
716            graph.add_sequence(b"ACGTACGT", &scoring).unwrap();
717        }
718        let consensus = graph.consensus();
719        assert_eq!(consensus, b"ACGTACGT".to_vec());
720        assert_eq!(graph.num_sequences(), 5);
721    }
722
723    #[test]
724    fn from_sequence_empty() {
725        let graph = PoaGraph::from_sequence(b"");
726        assert_eq!(graph.num_nodes(), 0);
727        assert_eq!(graph.num_sequences(), 0);
728        assert!(graph.consensus().is_empty());
729    }
730
731    #[test]
732    fn custom_scoring() {
733        let scoring = PoaScoring {
734            match_score: 5,
735            mismatch_score: -4,
736            gap_score: -8,
737        };
738        let mut graph = PoaGraph::from_sequence(b"ACGT");
739        graph.add_sequence(b"ACGT", &scoring).unwrap();
740        let consensus = graph.consensus();
741        assert_eq!(consensus, b"ACGT".to_vec());
742    }
743
744    #[test]
745    fn three_way_majority_with_snp() {
746        // Position 2: two sequences have G, one has A.
747        let mut graph = PoaGraph::from_sequence(b"AAGAA");
748        let scoring = PoaScoring::default();
749        graph.add_sequence(b"AAGAA", &scoring).unwrap();
750        graph.add_sequence(b"AAAAA", &scoring).unwrap();
751        let consensus = graph.consensus();
752        assert_eq!(
753            consensus,
754            b"AAGAA".to_vec(),
755            "majority G should win: {:?}",
756            String::from_utf8_lossy(&consensus)
757        );
758    }
759}