Skip to main content

cyanea_align/
seed_extend.rs

1//! Seed-and-extend alignment for long reads.
2//!
3//! This module implements the classic seed-and-extend paradigm used by modern
4//! long-read aligners:
5//!
6//! 1. **Seed** — Extract minimizers from both query and target, then find
7//!    matching anchors (shared k-mer hashes).
8//! 2. **Chain** — Select the highest-scoring colinear subset of seeds using
9//!    dynamic programming with a gap penalty.
10//! 3. **Extend** — Perform banded Smith-Waterman alignment in the regions
11//!    between chained seeds, then concatenate the results.
12//!
13//! For long reads (10 kb+) this avoids the full O(mn) dynamic programming
14//! cost and runs in roughly O(m × bandwidth × number_of_chain_segments).
15
16use cyanea_core::{CyaneaError, Result};
17
18use crate::minimizers::{find_seed_matches, minimizers};
19use crate::scoring::ScoringScheme;
20use crate::simd::banded_sw;
21use crate::types::{AlignmentResult, CigarOp};
22
23/// A seed (anchor) between query and target sequences.
24#[derive(Debug, Clone, Copy)]
25pub struct Seed {
26    /// Position in the query sequence (0-based).
27    pub query_pos: usize,
28    /// Position in the target sequence (0-based).
29    pub target_pos: usize,
30}
31
32/// A chain of colinear seeds.
33#[derive(Debug, Clone)]
34pub struct SeedChain {
35    /// The seeds in this chain, ordered by target position.
36    pub seeds: Vec<Seed>,
37    /// Total chain score.
38    pub score: i64,
39}
40
41// ---------------------------------------------------------------------------
42// Seed chaining
43// ---------------------------------------------------------------------------
44
45/// Chain colinear seeds using dynamic programming.
46///
47/// Seeds must be colinear: both query and target positions strictly increase
48/// along the chain.  Each seed is scored proportionally to the k-mer length
49/// it represents (`k` matching bases), minus a gap penalty proportional to
50/// the distance between consecutive seeds.
51///
52/// # Arguments
53/// * `seeds` - Pairs of `(query_pos, target_pos)`.
54/// * `k`       - k-mer length (seed match length in bases).
55/// * `max_gap` - Maximum allowed gap (in either query or target coordinates)
56///   between consecutive seeds in the chain.
57///
58/// # Returns
59/// The highest-scoring chain.
60///
61/// # Errors
62/// Returns an error if `seeds` is empty.
63pub fn chain_seeds(seeds: &[(usize, usize)], k: usize, max_gap: usize) -> Result<SeedChain> {
64    if seeds.is_empty() {
65        return Err(CyaneaError::InvalidInput("no seeds to chain".into()));
66    }
67
68    // Convert to Seed structs and sort by target position, breaking ties by
69    // query position.
70    let mut sorted: Vec<Seed> = seeds
71        .iter()
72        .map(|&(qp, tp)| Seed {
73            query_pos: qp,
74            target_pos: tp,
75        })
76        .collect();
77    sorted.sort_unstable_by(|a, b| {
78        a.target_pos
79            .cmp(&b.target_pos)
80            .then(a.query_pos.cmp(&b.query_pos))
81    });
82
83    let n = sorted.len();
84    let seed_score: i64 = k.max(1) as i64; // each seed represents k matching bases
85
86    // DP: dp[i] = best chain score ending at seed i.
87    let mut dp: Vec<i64> = vec![seed_score; n];
88    // Traceback: prev[i] = predecessor index in the chain (or usize::MAX).
89    let mut prev: Vec<usize> = vec![usize::MAX; n];
90
91    for i in 1..n {
92        for j in (0..i).rev() {
93            // Colinear check: query positions must also be strictly increasing.
94            if sorted[j].query_pos >= sorted[i].query_pos {
95                continue;
96            }
97            // target_pos is already sorted, so sorted[j].target_pos <= sorted[i].target_pos.
98            // Require strict increase.
99            if sorted[j].target_pos >= sorted[i].target_pos {
100                continue;
101            }
102
103            let q_gap = sorted[i].query_pos - sorted[j].query_pos;
104            let t_gap = sorted[i].target_pos - sorted[j].target_pos;
105            let gap = q_gap.max(t_gap);
106
107            if gap > max_gap {
108                continue;
109            }
110
111            // Gap penalty: the larger of the two gaps, scaled down.
112            // Use 1 penalty unit per gap base, capped so it doesn't dominate.
113            let penalty = gap as i64;
114            let candidate = dp[j] + seed_score - penalty;
115
116            if candidate > dp[i] {
117                dp[i] = candidate;
118                prev[i] = j;
119            }
120        }
121    }
122
123    // Find the seed with the best score.
124    let mut best_idx = 0;
125    for i in 1..n {
126        if dp[i] > dp[best_idx] {
127            best_idx = i;
128        }
129    }
130
131    // Traceback to reconstruct the chain.
132    let mut chain_indices: Vec<usize> = Vec::new();
133    let mut idx = best_idx;
134    loop {
135        chain_indices.push(idx);
136        if prev[idx] == usize::MAX {
137            break;
138        }
139        idx = prev[idx];
140    }
141    chain_indices.reverse();
142
143    let chain_seeds: Vec<Seed> = chain_indices.iter().map(|&i| sorted[i]).collect();
144    let chain_score = dp[best_idx];
145
146    Ok(SeedChain {
147        seeds: chain_seeds,
148        score: chain_score,
149    })
150}
151
152// ---------------------------------------------------------------------------
153// Seed-and-extend alignment
154// ---------------------------------------------------------------------------
155
156/// Perform seed-and-extend alignment.
157///
158/// 1. Extract minimizers from both query and target.
159/// 2. Find matching seeds.
160/// 3. Chain the best colinear seeds.
161/// 4. Extend alignment around the chain using banded Smith-Waterman.
162///
163/// This is designed for long reads (10 kb+) where full O(mn) DP is too slow.
164///
165/// # Arguments
166/// * `query`     - Query sequence (DNA, ACGT).
167/// * `target`    - Target sequence (DNA, ACGT).
168/// * `scoring`   - Scoring scheme (typically DNA simple scoring).
169/// * `k`         - k-mer length for minimizers (recommended: 15).
170/// * `w`         - Window size for minimizers (recommended: 10).
171/// * `bandwidth` - Band width for banded extension alignment.
172///
173/// # Errors
174/// Returns an error if sequences are empty or too short for the given k.
175pub fn seed_extend_align(
176    query: &[u8],
177    target: &[u8],
178    scoring: &ScoringScheme,
179    k: usize,
180    w: usize,
181    bandwidth: usize,
182) -> Result<AlignmentResult> {
183    if query.is_empty() || target.is_empty() {
184        return Err(CyaneaError::InvalidInput("empty sequence".into()));
185    }
186
187    // If sequences are too short for minimizer extraction, fall back.
188    if query.len() < k || target.len() < k {
189        return banded_sw(query, target, scoring, bandwidth);
190    }
191
192    // Step 1: Extract minimizers.
193    let query_mins = minimizers(query, k, w)?;
194    let target_mins = minimizers(target, k, w)?;
195
196    // Step 2: Find matching seeds.
197    let seed_pairs = find_seed_matches(&query_mins, &target_mins);
198    if seed_pairs.is_empty() {
199        // No shared minimizers — fall back to full banded alignment.
200        return banded_sw(query, target, scoring, bandwidth);
201    }
202
203    // Step 3: Chain the seeds.
204    let max_gap = query.len().max(target.len());
205    let chain = chain_seeds(&seed_pairs, k, max_gap)?;
206    if chain.seeds.is_empty() {
207        return banded_sw(query, target, scoring, bandwidth);
208    }
209
210    // Step 4: Extend alignment in regions between chained seeds.
211    //
212    // Strategy:
213    //   - Prefix: region before the first seed
214    //   - Middle: regions between consecutive seeds
215    //   - Suffix: region after the last seed
216    //
217    // For each region we run banded_sw on the corresponding query/target slices,
218    // then concatenate the CIGAR strings.  Each seed itself contributes k
219    // matched bases (they share the same k-mer).
220
221    let mut total_score: i32 = 0;
222    let mut cigar: Vec<CigarOp> = Vec::new();
223    let mut aligned_query: Vec<u8> = Vec::new();
224    let mut aligned_target: Vec<u8> = Vec::new();
225
226    let first_seed = &chain.seeds[0];
227    let last_seed = &chain.seeds[chain.seeds.len() - 1];
228
229    // --- Prefix region ---
230    if first_seed.query_pos > 0 && first_seed.target_pos > 0 {
231        let q_prefix = &query[..first_seed.query_pos];
232        let t_prefix = &target[..first_seed.target_pos];
233        if let Ok(r) = banded_sw(q_prefix, t_prefix, scoring, bandwidth) {
234            total_score += r.score;
235            append_alignment(&mut aligned_query, &mut aligned_target, &mut cigar, &r);
236        }
237    }
238
239    // --- Process each seed and the inter-seed gap after it ---
240    for (idx, seed) in chain.seeds.iter().enumerate() {
241        // Emit the k-mer match for this seed.
242        let q_end = (seed.query_pos + k).min(query.len());
243        let t_end = (seed.target_pos + k).min(target.len());
244        let match_len = (q_end - seed.query_pos).min(t_end - seed.target_pos);
245
246        // Score the k-mer region base by base.  Minimizer hashes can
247        // collide, so we don't assume all bases match.
248        for i in 0..match_len {
249            let qb = query[seed.query_pos + i];
250            let tb = target[seed.target_pos + i];
251            total_score += scoring.score_pair(qb, tb);
252            aligned_query.push(qb);
253            aligned_target.push(tb);
254            if qb.to_ascii_uppercase() == tb.to_ascii_uppercase() {
255                push_cigar(&mut cigar, CigarOp::Match(1));
256            } else {
257                push_cigar(&mut cigar, CigarOp::Mismatch(1));
258            }
259        }
260
261        // Inter-seed gap: align the region between this seed's end and the
262        // next seed's start.
263        if idx + 1 < chain.seeds.len() {
264            let next = &chain.seeds[idx + 1];
265            let q_gap_start = seed.query_pos + k;
266            let q_gap_end = next.query_pos;
267            let t_gap_start = seed.target_pos + k;
268            let t_gap_end = next.target_pos;
269
270            if q_gap_start < q_gap_end && t_gap_start < t_gap_end {
271                let q_slice = &query[q_gap_start..q_gap_end];
272                let t_slice = &target[t_gap_start..t_gap_end];
273                if let Ok(r) = banded_sw(q_slice, t_slice, scoring, bandwidth) {
274                    total_score += r.score;
275                    append_alignment(&mut aligned_query, &mut aligned_target, &mut cigar, &r);
276                }
277            } else if q_gap_start < q_gap_end {
278                // Query has extra bases, target doesn't — deletion.
279                let del_len = q_gap_end - q_gap_start;
280                push_cigar(&mut cigar, CigarOp::Deletion(del_len));
281                for i in q_gap_start..q_gap_end {
282                    aligned_query.push(query[i]);
283                    aligned_target.push(b'-');
284                }
285                total_score += scoring.gap_open() + (del_len as i32 - 1) * scoring.gap_extend();
286            } else if t_gap_start < t_gap_end {
287                // Target has extra bases — insertion.
288                let ins_len = t_gap_end - t_gap_start;
289                push_cigar(&mut cigar, CigarOp::Insertion(ins_len));
290                for i in t_gap_start..t_gap_end {
291                    aligned_query.push(b'-');
292                    aligned_target.push(target[i]);
293                }
294                total_score += scoring.gap_open() + (ins_len as i32 - 1) * scoring.gap_extend();
295            }
296            // If both gap regions are empty or overlapping, skip (seeds are adjacent or overlapping).
297        }
298    }
299
300    // --- Suffix region ---
301    let q_suffix_start = last_seed.query_pos + k;
302    let t_suffix_start = last_seed.target_pos + k;
303    if q_suffix_start < query.len() && t_suffix_start < target.len() {
304        let q_suffix = &query[q_suffix_start..];
305        let t_suffix = &target[t_suffix_start..];
306        if let Ok(r) = banded_sw(q_suffix, t_suffix, scoring, bandwidth) {
307            total_score += r.score;
308            append_alignment(&mut aligned_query, &mut aligned_target, &mut cigar, &r);
309        }
310    }
311
312    // Compute alignment coordinates.
313    let query_start = if first_seed.query_pos > 0 {
314        0
315    } else {
316        first_seed.query_pos
317    };
318    let query_end = if q_suffix_start < query.len() {
319        query.len()
320    } else {
321        (last_seed.query_pos + k).min(query.len())
322    };
323    let target_start = if first_seed.target_pos > 0 {
324        0
325    } else {
326        first_seed.target_pos
327    };
328    let target_end = if t_suffix_start < target.len() {
329        target.len()
330    } else {
331        (last_seed.target_pos + k).min(target.len())
332    };
333
334    Ok(AlignmentResult {
335        score: total_score,
336        aligned_query,
337        aligned_target,
338        query_start,
339        query_end,
340        target_start,
341        target_end,
342        cigar,
343    })
344}
345
346// ---------------------------------------------------------------------------
347// Helpers
348// ---------------------------------------------------------------------------
349
350/// Push a CIGAR op, merging with the last op if they are the same variant.
351fn push_cigar(cigar: &mut Vec<CigarOp>, op: CigarOp) {
352    if let Some(last) = cigar.last_mut() {
353        let merged = match (*last, op) {
354            (CigarOp::Match(a), CigarOp::Match(b)) => Some(CigarOp::Match(a + b)),
355            (CigarOp::Mismatch(a), CigarOp::Mismatch(b)) => Some(CigarOp::Mismatch(a + b)),
356            (CigarOp::Insertion(a), CigarOp::Insertion(b)) => Some(CigarOp::Insertion(a + b)),
357            (CigarOp::Deletion(a), CigarOp::Deletion(b)) => Some(CigarOp::Deletion(a + b)),
358            _ => None,
359        };
360        if let Some(m) = merged {
361            *last = m;
362            return;
363        }
364    }
365    cigar.push(op);
366}
367
368/// Append alignment result data (aligned sequences and CIGAR ops).
369fn append_alignment(
370    aligned_query: &mut Vec<u8>,
371    aligned_target: &mut Vec<u8>,
372    cigar: &mut Vec<CigarOp>,
373    result: &AlignmentResult,
374) {
375    aligned_query.extend_from_slice(&result.aligned_query);
376    aligned_target.extend_from_slice(&result.aligned_target);
377    for &op in &result.cigar {
378        push_cigar(cigar, op);
379    }
380}
381
382// ===========================================================================
383// Tests
384// ===========================================================================
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use crate::scoring::{ScoringMatrix, ScoringScheme};
390
391    fn dna_scheme() -> ScoringScheme {
392        ScoringScheme::Simple(ScoringMatrix::dna_default())
393    }
394
395    // -----------------------------------------------------------------------
396    // Seed chaining
397    // -----------------------------------------------------------------------
398
399    #[test]
400    fn chain_colinear_seeds() {
401        // Simple diagonal seeds with k=15.
402        let seeds = vec![(0, 0), (10, 10), (20, 20)];
403        let chain = chain_seeds(&seeds, 15, 100).unwrap();
404        assert!(chain.seeds.len() >= 2, "should chain multiple seeds");
405        // Seeds should be colinear.
406        for pair in chain.seeds.windows(2) {
407            assert!(pair[0].query_pos < pair[1].query_pos);
408            assert!(pair[0].target_pos < pair[1].target_pos);
409        }
410    }
411
412    #[test]
413    fn chain_out_of_order_seeds() {
414        // Seeds given in non-sorted order should still be chained correctly.
415        let seeds = vec![(20, 20), (0, 0), (10, 10)];
416        let chain = chain_seeds(&seeds, 15, 100).unwrap();
417        assert!(chain.seeds.len() >= 2);
418        for pair in chain.seeds.windows(2) {
419            assert!(pair[0].target_pos < pair[1].target_pos);
420        }
421    }
422
423    #[test]
424    fn chain_non_colinear_filtered() {
425        // One seed is not colinear with the others.
426        let seeds = vec![(0, 0), (5, 50), (10, 10), (20, 20)];
427        let chain = chain_seeds(&seeds, 15, 100).unwrap();
428        // (5,50) should not appear together with (10,10) in the same chain
429        // because target 50 > 10 but appears before it in query order.
430        // The chain should pick the best colinear subset.
431        for pair in chain.seeds.windows(2) {
432            assert!(pair[0].query_pos < pair[1].query_pos);
433            assert!(pair[0].target_pos < pair[1].target_pos);
434        }
435    }
436
437    #[test]
438    fn chain_single_seed() {
439        let seeds = vec![(5, 5)];
440        let chain = chain_seeds(&seeds, 15, 100).unwrap();
441        assert_eq!(chain.seeds.len(), 1);
442    }
443
444    #[test]
445    fn chain_empty_seeds_error() {
446        let seeds: Vec<(usize, usize)> = vec![];
447        assert!(chain_seeds(&seeds, 15, 100).is_err());
448    }
449
450    #[test]
451    fn chain_gap_penalty_prefers_close_seeds() {
452        // Two possible chains: close seeds vs. far-apart seeds.
453        // Close seeds should win because of lower gap penalty.
454        let seeds = vec![
455            (0, 0),
456            (2, 2),     // close to (0,0)
457            (4, 4),     // close to (2,2)
458            (100, 100), // far from everything
459        ];
460        let chain = chain_seeds(&seeds, 15, 200).unwrap();
461        // With k=15 seed_score, chaining close seeds is profitable:
462        // (0,0)->(2,2)->(4,4) has score 15 + 15-2 + 15-2 = 41
463        // vs (100,100) standalone = 15.
464        assert!(chain.seeds.len() >= 2);
465    }
466
467    #[test]
468    fn chain_respects_max_gap() {
469        let seeds = vec![(0, 0), (200, 200)];
470        let chain = chain_seeds(&seeds, 15, 10).unwrap();
471        // Gap of 200 exceeds max_gap=10, so these can't be chained together.
472        assert_eq!(chain.seeds.len(), 1);
473    }
474
475    // -----------------------------------------------------------------------
476    // Seed-and-extend alignment
477    // -----------------------------------------------------------------------
478
479    #[test]
480    fn identical_sequences() {
481        let seq = b"ACGTACGTACGTACGT";
482        let result = seed_extend_align(seq, seq, &dna_scheme(), 3, 2, 5).unwrap();
483        assert!(
484            result.score > 0,
485            "identical seqs should have positive score"
486        );
487        // Check that the alignment covers the full length.
488        assert_eq!(result.query_start, 0);
489    }
490
491    #[test]
492    fn related_sequences_with_mutations() {
493        let query = b"ACGTACGTACGTACGT";
494        let target = b"ACGTACCTACGTACGT"; // G->C at pos 6
495        let result = seed_extend_align(query, target, &dna_scheme(), 3, 2, 5).unwrap();
496        assert!(result.score > 0);
497    }
498
499    #[test]
500    fn completely_different_sequences_fallback() {
501        // No shared k-mers -> falls back to banded alignment.
502        let query = b"AAAAAAAAAA";
503        let target = b"CCCCCCCCCC";
504        let result = seed_extend_align(query, target, &dna_scheme(), 3, 2, 10).unwrap();
505        // Smith-Waterman local alignment on completely different sequences
506        // should produce a non-negative score (SW is always >= 0).
507        assert!(result.score >= 0);
508    }
509
510    #[test]
511    fn empty_sequence_error() {
512        assert!(seed_extend_align(b"", b"ACGT", &dna_scheme(), 3, 2, 5).is_err());
513        assert!(seed_extend_align(b"ACGT", b"", &dna_scheme(), 3, 2, 5).is_err());
514    }
515
516    #[test]
517    fn short_sequences_fallback() {
518        // Sequences shorter than k fall back to banded alignment.
519        let result = seed_extend_align(b"AC", b"AC", &dna_scheme(), 3, 2, 5).unwrap();
520        assert!(result.score > 0);
521    }
522
523    #[test]
524    fn longer_sequences_with_shared_regions() {
525        // Construct sequences that share a long common substring.
526        let common = b"ACGTACGTACGTACGTACGTACGTACGTACGT"; // 32 bp
527        let mut query = Vec::new();
528        query.extend_from_slice(b"TTTTTTT"); // unique prefix
529        query.extend_from_slice(common);
530        query.extend_from_slice(b"GGGGGGG"); // unique suffix
531
532        let mut target = Vec::new();
533        target.extend_from_slice(b"CCCCCCC"); // different prefix
534        target.extend_from_slice(common);
535        target.extend_from_slice(b"AAAAAAA"); // different suffix
536
537        let result = seed_extend_align(&query, &target, &dna_scheme(), 5, 3, 10).unwrap();
538        assert!(result.score > 0, "should align the shared region");
539    }
540
541    #[test]
542    fn alignment_produces_valid_cigar() {
543        let seq = b"ACGTACGTACGTACGT";
544        let result = seed_extend_align(seq, seq, &dna_scheme(), 3, 2, 5).unwrap();
545        // CIGAR ops should all have non-zero length.
546        for op in &result.cigar {
547            assert!(op.len() > 0, "CIGAR ops should have non-zero length");
548        }
549    }
550
551    #[test]
552    fn alignment_with_insertions_and_deletions() {
553        // Target has an insertion relative to query.
554        let query = b"ACGTACGTACGT";
555        let target = b"ACGTAAACGTACGT"; // extra AA inserted
556        let result = seed_extend_align(query, target, &dna_scheme(), 3, 2, 5).unwrap();
557        // Should still produce a valid alignment.
558        assert!(result.score > 0 || result.score == 0);
559    }
560
561    #[test]
562    fn chain_scoring_positive() {
563        let seeds = vec![(0, 0), (1, 1), (2, 2), (3, 3)];
564        let chain = chain_seeds(&seeds, 15, 100).unwrap();
565        // Each seed is 1 apart, gap penalty is 1 per hop.
566        // With k=15: score = 15 + (15-1) + (15-1) + (15-1) = 57.
567        assert!(chain.score >= 15);
568        assert_eq!(chain.seeds.len(), 4);
569    }
570}