Skip to main content

cyanea_align/
lcsk.rs

1//! LCSk++ sparse alignment algorithm.
2//!
3//! Computes the longest common subsequence in k-mer space (LCSk++) between two
4//! sequences.  Rather than aligning every base pair via O(mn) dynamic
5//! programming, this approach:
6//!
7//! 1. **Finds k-mer matches** — positions where an identical k-mer occurs in
8//!    both sequences.
9//! 2. **Chains matches** — selects the highest-scoring colinear subset using a
10//!    Fenwick-tree-accelerated DP in O(n log n) time.
11//!
12//! The LCSk++ score counts the number of matching bases covered by the optimal
13//! chain, allowing adjacent anchors to merge (the "++" extension over plain
14//! LCSk).
15//!
16//! Reference: Filip Pavetić et al., "Fast and simple algorithms for computing
17//! both LCSk and LCSk+", *Information Processing Letters*, 2017.
18//!
19//! # Example
20//!
21//! ```
22//! use cyanea_align::lcsk::{sparse_align, SparseAlignResult};
23//!
24//! let result = sparse_align(b"ACGTACGT", b"ACGTACGT", 4).unwrap();
25//! assert_eq!(result.score, 8);
26//! assert_eq!(result.k, 4);
27//! ```
28
29use cyanea_core::{CyaneaError, Result};
30use std::collections::HashMap;
31
32// ---------------------------------------------------------------------------
33// Public types
34// ---------------------------------------------------------------------------
35
36/// Result of a sparse alignment.
37#[derive(Debug, Clone)]
38pub struct SparseAlignResult {
39    /// LCSk++ score (number of matching bases in the chain).
40    pub score: usize,
41    /// Anchored match positions: (pos_in_a, pos_in_b) for each k-mer anchor in the chain.
42    pub anchors: Vec<(usize, usize)>,
43    /// k-mer length used.
44    pub k: usize,
45}
46
47// ---------------------------------------------------------------------------
48// Fenwick tree for maximum prefix queries
49// ---------------------------------------------------------------------------
50
51/// Fenwick tree (Binary Indexed Tree) for maximum prefix queries.
52///
53/// Each node stores a `(value, backpointer)` pair.  `update` sets position `i`
54/// to value `v` (if it improves the current maximum), and `query` returns the
55/// maximum `(value, backpointer)` over the prefix `[0, i]`.
56struct FenwickMax {
57    tree: Vec<(usize, i32)>,
58    n: usize,
59}
60
61impl FenwickMax {
62    fn new(n: usize) -> Self {
63        Self {
64            tree: vec![(0, -1); n + 1],
65            n,
66        }
67    }
68
69    /// Update position `i` with value `v` and backpointer `bp`.
70    ///
71    /// Only updates if `v` strictly exceeds the current stored value at each
72    /// affected tree node.
73    fn update(&mut self, mut i: usize, v: usize, bp: i32) {
74        i += 1; // 1-indexed
75        while i <= self.n {
76            if v > self.tree[i].0 {
77                self.tree[i] = (v, bp);
78            }
79            i += i & i.wrapping_neg();
80        }
81    }
82
83    /// Query maximum value in `[0, i]`, returning `(value, backpointer)`.
84    fn query(&self, mut i: usize) -> (usize, i32) {
85        i += 1; // 1-indexed
86        let mut best = (0usize, -1i32);
87        while i > 0 {
88            if self.tree[i].0 > best.0 {
89                best = self.tree[i];
90            }
91            i -= i & i.wrapping_neg();
92        }
93        best
94    }
95}
96
97// ---------------------------------------------------------------------------
98// K-mer matching
99// ---------------------------------------------------------------------------
100
101/// Find all positions where k-mers match between two sequences.
102///
103/// Returns a vector of `(pos_in_a, pos_in_b)` pairs for every occurrence of an
104/// identical k-mer in both `seq_a` and `seq_b`.  The pairs are not sorted in
105/// any particular order.
106///
107/// # Panics
108///
109/// Callers must ensure `k > 0` and that both sequences are at least `k` bases
110/// long.  The public [`sparse_align`] function validates these preconditions.
111pub fn find_kmer_matches(seq_a: &[u8], seq_b: &[u8], k: usize) -> Vec<(usize, usize)> {
112    if seq_a.len() < k || seq_b.len() < k {
113        return Vec::new();
114    }
115
116    // Index all k-mers in seq_a by their byte content.
117    let mut index: HashMap<&[u8], Vec<usize>> = HashMap::new();
118    for i in 0..=seq_a.len() - k {
119        index.entry(&seq_a[i..i + k]).or_default().push(i);
120    }
121
122    // Scan seq_b and collect matches.
123    let mut matches = Vec::new();
124    for j in 0..=seq_b.len() - k {
125        if let Some(positions) = index.get(&seq_b[j..j + k]) {
126            for &i in positions {
127                matches.push((i, j));
128            }
129        }
130    }
131
132    matches
133}
134
135// ---------------------------------------------------------------------------
136// Core LCSk++ algorithm
137// ---------------------------------------------------------------------------
138
139/// Core LCSk++ algorithm using Fenwick-tree-accelerated DP.
140///
141/// Takes a list of k-mer match positions `(pos_in_a, pos_in_b)` and returns the
142/// optimal chain score together with the chain anchors.
143///
144/// # Algorithm
145///
146/// Matches are sorted by `(pos_b, pos_a)`.  For each match `(i, j)`, the DP
147/// recurrence is:
148///
149/// ```text
150/// dp[i][j] = k + max { dp[i'][j'] : i' + k <= i and j' + k <= j }
151/// ```
152///
153/// The "++" extension additionally checks whether the previous anchor is
154/// immediately adjacent (i.e. `i' + k == i` and `j' + k == j`), in which case a
155/// single base is added instead of a full k-mer to avoid double-counting
156/// overlapping coverage.
157///
158/// Coordinate compression and a Fenwick tree reduce the per-match work to
159/// O(log n).
160///
161/// Returns `(score, chain)` where `chain` contains the anchors in order.
162pub fn lcsk_plusplus(matches: &[(usize, usize)], k: usize) -> (usize, Vec<(usize, usize)>) {
163    if matches.is_empty() || k == 0 {
164        return (0, Vec::new());
165    }
166
167    let n = matches.len();
168
169    // Sort matches by (pos_b, pos_a).
170    let mut sorted: Vec<(usize, usize)> = matches.to_vec();
171    sorted.sort_unstable_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
172
173    // Coordinate compression on the "a" axis.
174    // We need to query: for all previous matches with a' + k <= a_current,
175    // what is the maximum DP value?  We compress the "end-of-anchor" positions
176    // (a + k - 1) into a contiguous range for the Fenwick tree.
177    let mut a_coords: Vec<usize> = sorted.iter().map(|&(a, _)| a).collect();
178    a_coords.sort_unstable();
179    a_coords.dedup();
180    let compress = |val: usize| -> usize { a_coords.binary_search(&val).unwrap_or_else(|x| x) };
181
182    // DP arrays.
183    let mut dp: Vec<usize> = vec![0; n];
184    let mut prev: Vec<i32> = vec![-1; n];
185
186    // Fenwick tree over compressed a-coordinates.
187    // We process matches in order of increasing pos_b.  When we process match
188    // at (a, b), we need predecessors with b' + k <= b (non-overlapping on the
189    // b axis) and a' + k <= a (non-overlapping on the a axis).
190    //
191    // Strategy: process in sweepline order over b.  Group matches by b value.
192    // Before processing group at b_cur, insert all matches with b' + k <= b_cur
193    // into the Fenwick tree.
194    let mut fenwick = FenwickMax::new(a_coords.len());
195
196    // Track which matches have been inserted into the Fenwick tree.
197    // We use a pointer into the sorted array, advancing as b increases.
198    // Matches are sorted by b, so we can insert in order.
199    let mut insert_ptr: usize = 0;
200
201    // We also need to handle the "++" adjacency check.  For that we maintain a
202    // map from (a + k, b + k) -> (dp_value, match_index) for the immediately-
203    // preceding adjacent extension.
204    let mut adjacent: HashMap<(usize, usize), (usize, i32)> = HashMap::new();
205
206    // Process each match.
207    for idx in 0..n {
208        let (a_i, b_i) = sorted[idx];
209
210        // Insert all matches whose b-end (b' + k) <= b_i into the Fenwick tree.
211        // Since sorted is by b, we advance insert_ptr while sorted[insert_ptr].1 + k <= b_i.
212        while insert_ptr < n && sorted[insert_ptr].1 + k <= b_i {
213            let (a_p, _) = sorted[insert_ptr];
214            let ca = compress(a_p);
215            fenwick.update(ca, dp[insert_ptr], insert_ptr as i32);
216            insert_ptr += 1;
217        }
218
219        // Base case: this anchor starts a new chain.
220        dp[idx] = k;
221        prev[idx] = -1;
222
223        // Case 1: non-overlapping predecessor via Fenwick tree.
224        // We need a' + k <= a_i, which means a' <= a_i - k.
225        if a_i >= k {
226            // Find the largest compressed index with a_coords[c] <= a_i - k.
227            let upper = a_i - k;
228            let ca_upper = match a_coords.binary_search(&upper) {
229                Ok(pos) => pos,
230                Err(pos) => {
231                    if pos == 0 {
232                        usize::MAX // no valid predecessor
233                    } else {
234                        pos - 1
235                    }
236                }
237            };
238            if ca_upper != usize::MAX {
239                let (best_val, best_bp) = fenwick.query(ca_upper);
240                if best_val > 0 {
241                    let candidate = best_val + k;
242                    if candidate > dp[idx] {
243                        dp[idx] = candidate;
244                        prev[idx] = best_bp;
245                    }
246                }
247            }
248        }
249
250        // Case 2: "++" adjacent extension.
251        // Check if there is a predecessor at (a_i - 1, b_i - 1), meaning the
252        // previous anchor ends exactly where this one starts (shifted by 1 base).
253        if a_i > 0 && b_i > 0 {
254            if let Some(&(adj_val, adj_idx)) = adjacent.get(&(a_i, b_i)) {
255                // Adjacent extension adds 1 base (not k, to avoid double-counting).
256                let candidate = adj_val + 1;
257                if candidate > dp[idx] {
258                    dp[idx] = candidate;
259                    prev[idx] = adj_idx;
260                }
261            }
262        }
263
264        // Record this match for future "++" adjacency checks.
265        // A match at (a_i, b_i) with k-mer length k ends at (a_i + k, b_i + k).
266        // The next adjacent anchor would start at (a_i + 1, b_i + 1), so the
267        // adjacency key is (a_i + 1, b_i + 1).
268        let adj_key = (a_i + 1, b_i + 1);
269        match adjacent.get(&adj_key) {
270            Some(&(existing_val, _)) if existing_val >= dp[idx] => {}
271            _ => {
272                adjacent.insert(adj_key, (dp[idx], idx as i32));
273            }
274        }
275    }
276
277    // Find the global best.
278    let mut best_idx = 0;
279    for i in 1..n {
280        if dp[i] > dp[best_idx] {
281            best_idx = i;
282        }
283    }
284
285    let score = dp[best_idx];
286
287    // Traceback to recover the chain.
288    let mut chain_indices: Vec<usize> = Vec::new();
289    let mut idx = best_idx as i32;
290    while idx >= 0 {
291        chain_indices.push(idx as usize);
292        idx = prev[idx as usize];
293    }
294    chain_indices.reverse();
295
296    let chain: Vec<(usize, usize)> = chain_indices.iter().map(|&i| sorted[i]).collect();
297
298    (score, chain)
299}
300
301// ---------------------------------------------------------------------------
302// Public API
303// ---------------------------------------------------------------------------
304
305/// Perform sparse alignment between two sequences using LCSk++.
306///
307/// This is the full pipeline: find k-mer matches, run the LCSk++ DP, and
308/// return a [`SparseAlignResult`].
309///
310/// # Arguments
311/// * `seq_a` - First sequence (arbitrary alphabet).
312/// * `seq_b` - Second sequence.
313/// * `k`     - k-mer length.  Must be > 0 and both sequences must be at least
314///   `k` bases long.
315///
316/// # Errors
317///
318/// Returns [`CyaneaError::InvalidInput`] if `k == 0` or either sequence is
319/// shorter than `k`.
320///
321/// # Example
322///
323/// ```
324/// use cyanea_align::lcsk::sparse_align;
325///
326/// let result = sparse_align(b"ACGTACGT", b"ACGTACGT", 4).unwrap();
327/// assert_eq!(result.score, 8);
328/// ```
329pub fn sparse_align(seq_a: &[u8], seq_b: &[u8], k: usize) -> Result<SparseAlignResult> {
330    if k == 0 {
331        return Err(CyaneaError::InvalidInput("k must be greater than 0".into()));
332    }
333    if seq_a.len() < k {
334        return Err(CyaneaError::InvalidInput(format!(
335            "sequence A length ({}) is shorter than k ({})",
336            seq_a.len(),
337            k,
338        )));
339    }
340    if seq_b.len() < k {
341        return Err(CyaneaError::InvalidInput(format!(
342            "sequence B length ({}) is shorter than k ({})",
343            seq_b.len(),
344            k,
345        )));
346    }
347
348    let matches = find_kmer_matches(seq_a, seq_b, k);
349    let (score, anchors) = lcsk_plusplus(&matches, k);
350
351    Ok(SparseAlignResult { score, anchors, k })
352}
353
354// ===========================================================================
355// Tests
356// ===========================================================================
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    // -----------------------------------------------------------------------
363    // Fenwick tree
364    // -----------------------------------------------------------------------
365
366    #[test]
367    fn fenwick_basic_update_query() {
368        let mut fw = FenwickMax::new(10);
369        fw.update(3, 5, 0);
370        fw.update(7, 3, 1);
371        assert_eq!(fw.query(3).0, 5);
372        assert_eq!(fw.query(7).0, 5); // prefix max includes index 3
373        fw.update(5, 10, 2);
374        assert_eq!(fw.query(5).0, 10);
375        assert_eq!(fw.query(9).0, 10);
376    }
377
378    #[test]
379    fn fenwick_empty() {
380        let fw = FenwickMax::new(5);
381        assert_eq!(fw.query(4), (0, -1));
382    }
383
384    // -----------------------------------------------------------------------
385    // find_kmer_matches
386    // -----------------------------------------------------------------------
387
388    #[test]
389    fn kmer_matches_identical() {
390        let seq = b"ACGT";
391        let matches = find_kmer_matches(seq, seq, 2);
392        // k-mers: AC, CG, GT — each matches at the same position.
393        assert_eq!(matches.len(), 3);
394        for &(a, b) in &matches {
395            assert_eq!(a, b);
396        }
397    }
398
399    #[test]
400    fn kmer_matches_no_overlap() {
401        let a = b"AAAA";
402        let b = b"CCCC";
403        let matches = find_kmer_matches(a, b, 2);
404        assert!(matches.is_empty());
405    }
406
407    #[test]
408    fn kmer_matches_short_sequence() {
409        let matches = find_kmer_matches(b"AC", b"ACGT", 3);
410        assert!(matches.is_empty());
411    }
412
413    // -----------------------------------------------------------------------
414    // lcsk_plusplus
415    // -----------------------------------------------------------------------
416
417    #[test]
418    fn lcsk_empty_matches() {
419        let (score, chain) = lcsk_plusplus(&[], 4);
420        assert_eq!(score, 0);
421        assert!(chain.is_empty());
422    }
423
424    #[test]
425    fn lcsk_single_match() {
426        let matches = vec![(0, 0)];
427        let (score, chain) = lcsk_plusplus(&matches, 4);
428        assert_eq!(score, 4);
429        assert_eq!(chain.len(), 1);
430        assert_eq!(chain[0], (0, 0));
431    }
432
433    #[test]
434    fn lcsk_non_overlapping_chain() {
435        // Two non-overlapping anchors with k=3: (0,0) and (5,5).
436        // They don't overlap (0+3=3 <= 5), so score = 3 + 3 = 6.
437        let matches = vec![(0, 0), (5, 5)];
438        let (score, chain) = lcsk_plusplus(&matches, 3);
439        assert_eq!(score, 6);
440        assert_eq!(chain.len(), 2);
441    }
442
443    #[test]
444    fn lcsk_adjacent_plusplus() {
445        // Adjacent anchors: (0,0), (1,1), (2,2) with k=3.
446        // With "++" extension: first anchor contributes 3, each subsequent
447        // adjacent one contributes 1 → score = 3 + 1 + 1 = 5.
448        // This corresponds to covering positions 0..5 in both sequences.
449        let matches = vec![(0, 0), (1, 1), (2, 2)];
450        let (score, chain) = lcsk_plusplus(&matches, 3);
451        assert_eq!(score, 5);
452        assert_eq!(chain.len(), 3);
453    }
454
455    // -----------------------------------------------------------------------
456    // sparse_align — full pipeline
457    // -----------------------------------------------------------------------
458
459    #[test]
460    fn identical_sequences() {
461        let seq = b"ACGTACGTACGT";
462        let result = sparse_align(seq, seq, 4).unwrap();
463        assert_eq!(result.score, seq.len());
464        assert_eq!(result.k, 4);
465        assert!(!result.anchors.is_empty());
466    }
467
468    #[test]
469    fn completely_different_sequences() {
470        let a = b"AAAAAAAAAA";
471        let b = b"CCCCCCCCCC";
472        let result = sparse_align(a, b, 4).unwrap();
473        assert_eq!(result.score, 0);
474        assert!(result.anchors.is_empty());
475    }
476
477    #[test]
478    fn known_lcs_case() {
479        // "ACGTACGT" vs "ACGTXXACGT" with k=4.
480        // Shared 4-mers from seq_a: ACGT(0), CGTA(1), GTAC(2), TACG(3), ACGT(4).
481        // In seq_b: ACGT at pos 0 and 6, ACGT at pos 6.
482        // Best chain should cover at least 8 matching bases.
483        let a = b"ACGTACGT";
484        let b = b"ACGTXXACGT";
485        let result = sparse_align(a, b, 4).unwrap();
486        assert!(
487            result.score >= 8,
488            "expected score >= 8, got {}",
489            result.score
490        );
491    }
492
493    #[test]
494    fn single_kmer_match() {
495        // Only one shared k-mer.
496        let a = b"AAAACGTAAAA";
497        let b = b"TTTTCGTTTTT";
498        let result = sparse_align(a, b, 3).unwrap();
499        assert!(result.score >= 3, "expected at least one k-mer match");
500        assert!(!result.anchors.is_empty());
501    }
502
503    #[test]
504    fn repetitive_sequences() {
505        // Repetitive k-mers produce many match pairs; the algorithm should
506        // still find a valid colinear chain.
507        let a = b"ACACACACACAC";
508        let b = b"ACACACACACAC";
509        let result = sparse_align(a, b, 2).unwrap();
510        assert_eq!(result.score, a.len());
511        // All anchors should be colinear.
512        for pair in result.anchors.windows(2) {
513            assert!(pair[0].0 < pair[1].0, "anchors must be colinear on a-axis");
514            assert!(pair[0].1 < pair[1].1, "anchors must be colinear on b-axis");
515        }
516    }
517
518    #[test]
519    fn error_on_k_zero() {
520        let result = sparse_align(b"ACGT", b"ACGT", 0);
521        assert!(result.is_err());
522        let err = result.unwrap_err().to_string();
523        assert!(err.contains("k must be greater than 0"));
524    }
525
526    #[test]
527    fn error_on_sequence_shorter_than_k() {
528        // seq_a too short.
529        let result = sparse_align(b"AC", b"ACGTACGT", 4);
530        assert!(result.is_err());
531        let err = result.unwrap_err().to_string();
532        assert!(err.contains("shorter than k"));
533
534        // seq_b too short.
535        let result = sparse_align(b"ACGTACGT", b"AC", 4);
536        assert!(result.is_err());
537        let err = result.unwrap_err().to_string();
538        assert!(err.contains("shorter than k"));
539    }
540
541    #[test]
542    fn empty_matches_gives_zero() {
543        // Sequences with no shared k-mers.
544        let a = b"AAAA";
545        let b = b"CCCC";
546        let result = sparse_align(a, b, 2).unwrap();
547        assert_eq!(result.score, 0);
548        assert!(result.anchors.is_empty());
549    }
550
551    #[test]
552    fn chain_is_colinear() {
553        // Verify colinearity invariant on a non-trivial case.
554        let a = b"ACGTACGTACGTACGT";
555        let b = b"XXACGTXXACGTXX";
556        let result = sparse_align(a, b, 4).unwrap();
557        for pair in result.anchors.windows(2) {
558            assert!(
559                pair[0].0 < pair[1].0,
560                "a-positions must strictly increase: {} < {}",
561                pair[0].0,
562                pair[1].0
563            );
564            assert!(
565                pair[0].1 < pair[1].1,
566                "b-positions must strictly increase: {} < {}",
567                pair[0].1,
568                pair[1].1
569            );
570        }
571    }
572
573    #[test]
574    fn score_does_not_exceed_shorter_sequence() {
575        let a = b"ACGTACGT";
576        let b = b"ACGTACGTACGTACGT";
577        let result = sparse_align(a, b, 3).unwrap();
578        assert!(
579            result.score <= a.len(),
580            "score {} should not exceed shorter sequence length {}",
581            result.score,
582            a.len()
583        );
584    }
585
586    #[test]
587    fn k_equals_sequence_length() {
588        let seq = b"ACGT";
589        let result = sparse_align(seq, seq, 4).unwrap();
590        assert_eq!(result.score, 4);
591        assert_eq!(result.anchors.len(), 1);
592        assert_eq!(result.anchors[0], (0, 0));
593    }
594}