1use cyanea_core::{CyaneaError, Result};
25
26#[derive(Debug, Clone)]
32struct PoaNode {
33 base: u8,
35 successors: Vec<usize>,
37 predecessors: Vec<usize>,
39 weights: Vec<usize>,
41 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#[derive(Debug, Clone)]
63pub struct PoaGraph {
64 nodes: Vec<PoaNode>,
65 start_nodes: Vec<usize>,
67 n_sequences: usize,
69}
70
71#[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
89const TB_NONE: u8 = 0;
94const TB_DIAG: u8 = 1;
95const TB_UP: u8 = 2; const TB_LEFT: u8 = 3; impl PoaGraph {
103 pub fn new() -> Self {
105 Self {
106 nodes: Vec::new(),
107 start_nodes: Vec::new(),
108 n_sequences: 0,
109 }
110 }
111
112 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 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 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 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 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 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 score[0][0] = 0;
200
201 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 (rank_idx, &node_idx) in topo.iter().enumerate() {
209 let rank = rank_idx + 1; let node_base = self.nodes[node_idx].base;
211
212 let pred_ranks: Vec<usize> = if self.nodes[node_idx].predecessors.is_empty() {
215 vec![0] } else {
217 self.nodes[node_idx]
218 .predecessors
219 .iter()
220 .map(|&p| topo_rank[p] + 1)
221 .collect()
222 };
223
224 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 for j in 1..cols {
235 let seq_base = seq[j - 1];
236
237 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 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 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 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 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 break;
306 }
307 }
308 }
309
310 alignment.reverse();
311 alignment
312 }
313
314 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 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 if let Some(prev) = prev_node {
333 self.add_edge(prev, gn, 1);
334 } else if !self.start_nodes.contains(&gn) {
335 self.start_nodes.push(gn);
337 }
338 prev_node = Some(gn);
339 } else {
340 let new_idx = self.nodes.len();
342 self.nodes.push(PoaNode::new(seq_base));
343
344 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 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 }
373 (None, None) => {
374 }
376 }
377 }
378 }
379
380 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 let mut best_score = vec![0i64; self.nodes.len()];
395 let mut best_pred: Vec<Option<usize>> = vec![None; self.nodes.len()];
397
398 for &node_idx in &topo {
399 for &pred in &self.nodes[node_idx].predecessors {
401 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 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 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 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 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 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 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 pub fn num_nodes(&self) -> usize {
510 self.nodes.len()
511 }
512
513 pub fn num_sequences(&self) -> usize {
516 self.n_sequences
517 }
518}
519
520#[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 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 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 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 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 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 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 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 assert_eq!(topo.len(), 4);
660 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 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 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 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}