use cyanea_core::{CyaneaError, Result};
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct SparseAlignResult {
pub score: usize,
pub anchors: Vec<(usize, usize)>,
pub k: usize,
}
struct FenwickMax {
tree: Vec<(usize, i32)>,
n: usize,
}
impl FenwickMax {
fn new(n: usize) -> Self {
Self {
tree: vec![(0, -1); n + 1],
n,
}
}
fn update(&mut self, mut i: usize, v: usize, bp: i32) {
i += 1; while i <= self.n {
if v > self.tree[i].0 {
self.tree[i] = (v, bp);
}
i += i & i.wrapping_neg();
}
}
fn query(&self, mut i: usize) -> (usize, i32) {
i += 1; let mut best = (0usize, -1i32);
while i > 0 {
if self.tree[i].0 > best.0 {
best = self.tree[i];
}
i -= i & i.wrapping_neg();
}
best
}
}
pub fn find_kmer_matches(seq_a: &[u8], seq_b: &[u8], k: usize) -> Vec<(usize, usize)> {
if seq_a.len() < k || seq_b.len() < k {
return Vec::new();
}
let mut index: HashMap<&[u8], Vec<usize>> = HashMap::new();
for i in 0..=seq_a.len() - k {
index.entry(&seq_a[i..i + k]).or_default().push(i);
}
let mut matches = Vec::new();
for j in 0..=seq_b.len() - k {
if let Some(positions) = index.get(&seq_b[j..j + k]) {
for &i in positions {
matches.push((i, j));
}
}
}
matches
}
pub fn lcsk_plusplus(matches: &[(usize, usize)], k: usize) -> (usize, Vec<(usize, usize)>) {
if matches.is_empty() || k == 0 {
return (0, Vec::new());
}
let n = matches.len();
let mut sorted: Vec<(usize, usize)> = matches.to_vec();
sorted.sort_unstable_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
let mut a_coords: Vec<usize> = sorted.iter().map(|&(a, _)| a).collect();
a_coords.sort_unstable();
a_coords.dedup();
let compress = |val: usize| -> usize {
a_coords.binary_search(&val).unwrap_or_else(|x| x)
};
let mut dp: Vec<usize> = vec![0; n];
let mut prev: Vec<i32> = vec![-1; n];
let mut fenwick = FenwickMax::new(a_coords.len());
let mut insert_ptr: usize = 0;
let mut adjacent: HashMap<(usize, usize), (usize, i32)> = HashMap::new();
for idx in 0..n {
let (a_i, b_i) = sorted[idx];
while insert_ptr < n && sorted[insert_ptr].1 + k <= b_i {
let (a_p, _) = sorted[insert_ptr];
let ca = compress(a_p);
fenwick.update(ca, dp[insert_ptr], insert_ptr as i32);
insert_ptr += 1;
}
dp[idx] = k;
prev[idx] = -1;
if a_i >= k {
let upper = a_i - k;
let ca_upper = match a_coords.binary_search(&upper) {
Ok(pos) => pos,
Err(pos) => {
if pos == 0 {
usize::MAX } else {
pos - 1
}
}
};
if ca_upper != usize::MAX {
let (best_val, best_bp) = fenwick.query(ca_upper);
if best_val > 0 {
let candidate = best_val + k;
if candidate > dp[idx] {
dp[idx] = candidate;
prev[idx] = best_bp;
}
}
}
}
if a_i > 0 && b_i > 0 {
if let Some(&(adj_val, adj_idx)) = adjacent.get(&(a_i, b_i)) {
let candidate = adj_val + 1;
if candidate > dp[idx] {
dp[idx] = candidate;
prev[idx] = adj_idx;
}
}
}
let adj_key = (a_i + 1, b_i + 1);
match adjacent.get(&adj_key) {
Some(&(existing_val, _)) if existing_val >= dp[idx] => {}
_ => {
adjacent.insert(adj_key, (dp[idx], idx as i32));
}
}
}
let mut best_idx = 0;
for i in 1..n {
if dp[i] > dp[best_idx] {
best_idx = i;
}
}
let score = dp[best_idx];
let mut chain_indices: Vec<usize> = Vec::new();
let mut idx = best_idx as i32;
while idx >= 0 {
chain_indices.push(idx as usize);
idx = prev[idx as usize];
}
chain_indices.reverse();
let chain: Vec<(usize, usize)> = chain_indices.iter().map(|&i| sorted[i]).collect();
(score, chain)
}
pub fn sparse_align(seq_a: &[u8], seq_b: &[u8], k: usize) -> Result<SparseAlignResult> {
if k == 0 {
return Err(CyaneaError::InvalidInput(
"k must be greater than 0".into(),
));
}
if seq_a.len() < k {
return Err(CyaneaError::InvalidInput(format!(
"sequence A length ({}) is shorter than k ({})",
seq_a.len(),
k,
)));
}
if seq_b.len() < k {
return Err(CyaneaError::InvalidInput(format!(
"sequence B length ({}) is shorter than k ({})",
seq_b.len(),
k,
)));
}
let matches = find_kmer_matches(seq_a, seq_b, k);
let (score, anchors) = lcsk_plusplus(&matches, k);
Ok(SparseAlignResult { score, anchors, k })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fenwick_basic_update_query() {
let mut fw = FenwickMax::new(10);
fw.update(3, 5, 0);
fw.update(7, 3, 1);
assert_eq!(fw.query(3).0, 5);
assert_eq!(fw.query(7).0, 5); fw.update(5, 10, 2);
assert_eq!(fw.query(5).0, 10);
assert_eq!(fw.query(9).0, 10);
}
#[test]
fn fenwick_empty() {
let fw = FenwickMax::new(5);
assert_eq!(fw.query(4), (0, -1));
}
#[test]
fn kmer_matches_identical() {
let seq = b"ACGT";
let matches = find_kmer_matches(seq, seq, 2);
assert_eq!(matches.len(), 3);
for &(a, b) in &matches {
assert_eq!(a, b);
}
}
#[test]
fn kmer_matches_no_overlap() {
let a = b"AAAA";
let b = b"CCCC";
let matches = find_kmer_matches(a, b, 2);
assert!(matches.is_empty());
}
#[test]
fn kmer_matches_short_sequence() {
let matches = find_kmer_matches(b"AC", b"ACGT", 3);
assert!(matches.is_empty());
}
#[test]
fn lcsk_empty_matches() {
let (score, chain) = lcsk_plusplus(&[], 4);
assert_eq!(score, 0);
assert!(chain.is_empty());
}
#[test]
fn lcsk_single_match() {
let matches = vec![(0, 0)];
let (score, chain) = lcsk_plusplus(&matches, 4);
assert_eq!(score, 4);
assert_eq!(chain.len(), 1);
assert_eq!(chain[0], (0, 0));
}
#[test]
fn lcsk_non_overlapping_chain() {
let matches = vec![(0, 0), (5, 5)];
let (score, chain) = lcsk_plusplus(&matches, 3);
assert_eq!(score, 6);
assert_eq!(chain.len(), 2);
}
#[test]
fn lcsk_adjacent_plusplus() {
let matches = vec![(0, 0), (1, 1), (2, 2)];
let (score, chain) = lcsk_plusplus(&matches, 3);
assert_eq!(score, 5);
assert_eq!(chain.len(), 3);
}
#[test]
fn identical_sequences() {
let seq = b"ACGTACGTACGT";
let result = sparse_align(seq, seq, 4).unwrap();
assert_eq!(result.score, seq.len());
assert_eq!(result.k, 4);
assert!(!result.anchors.is_empty());
}
#[test]
fn completely_different_sequences() {
let a = b"AAAAAAAAAA";
let b = b"CCCCCCCCCC";
let result = sparse_align(a, b, 4).unwrap();
assert_eq!(result.score, 0);
assert!(result.anchors.is_empty());
}
#[test]
fn known_lcs_case() {
let a = b"ACGTACGT";
let b = b"ACGTXXACGT";
let result = sparse_align(a, b, 4).unwrap();
assert!(
result.score >= 8,
"expected score >= 8, got {}",
result.score
);
}
#[test]
fn single_kmer_match() {
let a = b"AAAACGTAAAA";
let b = b"TTTTCGTTTTT";
let result = sparse_align(a, b, 3).unwrap();
assert!(result.score >= 3, "expected at least one k-mer match");
assert!(!result.anchors.is_empty());
}
#[test]
fn repetitive_sequences() {
let a = b"ACACACACACAC";
let b = b"ACACACACACAC";
let result = sparse_align(a, b, 2).unwrap();
assert_eq!(result.score, a.len());
for pair in result.anchors.windows(2) {
assert!(pair[0].0 < pair[1].0, "anchors must be colinear on a-axis");
assert!(pair[0].1 < pair[1].1, "anchors must be colinear on b-axis");
}
}
#[test]
fn error_on_k_zero() {
let result = sparse_align(b"ACGT", b"ACGT", 0);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("k must be greater than 0"));
}
#[test]
fn error_on_sequence_shorter_than_k() {
let result = sparse_align(b"AC", b"ACGTACGT", 4);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("shorter than k"));
let result = sparse_align(b"ACGTACGT", b"AC", 4);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("shorter than k"));
}
#[test]
fn empty_matches_gives_zero() {
let a = b"AAAA";
let b = b"CCCC";
let result = sparse_align(a, b, 2).unwrap();
assert_eq!(result.score, 0);
assert!(result.anchors.is_empty());
}
#[test]
fn chain_is_colinear() {
let a = b"ACGTACGTACGTACGT";
let b = b"XXACGTXXACGTXX";
let result = sparse_align(a, b, 4).unwrap();
for pair in result.anchors.windows(2) {
assert!(
pair[0].0 < pair[1].0,
"a-positions must strictly increase: {} < {}",
pair[0].0,
pair[1].0
);
assert!(
pair[0].1 < pair[1].1,
"b-positions must strictly increase: {} < {}",
pair[0].1,
pair[1].1
);
}
}
#[test]
fn score_does_not_exceed_shorter_sequence() {
let a = b"ACGTACGT";
let b = b"ACGTACGTACGTACGT";
let result = sparse_align(a, b, 3).unwrap();
assert!(
result.score <= a.len(),
"score {} should not exceed shorter sequence length {}",
result.score,
a.len()
);
}
#[test]
fn k_equals_sequence_length() {
let seq = b"ACGT";
let result = sparse_align(seq, seq, 4).unwrap();
assert_eq!(result.score, 4);
assert_eq!(result.anchors.len(), 1);
assert_eq!(result.anchors[0], (0, 0));
}
}