Skip to main content

cyanea_align/
simd.rs

1//! Banded alignment and SIMD-ready alignment kernels.
2//!
3//! Provides banded variants of Needleman-Wunsch and Smith-Waterman that restrict
4//! computation to a diagonal band of width `2 * bandwidth + 1`, reducing work
5//! from O(mn) to O(m × bandwidth).
6//!
7//! True SIMD vectorization (SSE4.1, AVX2, NEON) is deferred until profile-guided
8//! benchmarks justify the complexity. The banded algorithms here serve as the
9//! scalar baseline and are already significantly faster for long sequences with
10//! bounded edit distance.
11
12use cyanea_core::{CyaneaError, Result};
13
14use crate::scoring::ScoringScheme;
15use crate::types::{AlignmentMode, AlignmentResult, CigarOp};
16
17/// Banded Needleman-Wunsch (global) alignment.
18///
19/// Restricts the DP matrix to a diagonal band of width `2 * bandwidth + 1`.
20/// If the optimal alignment path lies outside this band the result may be
21/// suboptimal, but computation is significantly reduced.
22///
23/// # Errors
24///
25/// Returns an error if either sequence is empty or bandwidth is zero.
26pub fn banded_nw(
27    query: &[u8],
28    target: &[u8],
29    scoring: &ScoringScheme,
30    bandwidth: usize,
31) -> Result<AlignmentResult> {
32    validate_inputs(query, target, bandwidth)?;
33    banded_align(query, target, scoring, bandwidth, AlignmentMode::Global)
34}
35
36/// Banded Smith-Waterman (local) alignment.
37///
38/// # Errors
39///
40/// Returns an error if either sequence is empty or bandwidth is zero.
41pub fn banded_sw(
42    query: &[u8],
43    target: &[u8],
44    scoring: &ScoringScheme,
45    bandwidth: usize,
46) -> Result<AlignmentResult> {
47    validate_inputs(query, target, bandwidth)?;
48    banded_align(query, target, scoring, bandwidth, AlignmentMode::Local)
49}
50
51/// Banded semi-global alignment.
52///
53/// Free leading and trailing gaps within the band. Useful for overlap
54/// detection and adapter trimming with bounded edit distance.
55///
56/// # Errors
57///
58/// Returns an error if either sequence is empty or bandwidth is zero.
59pub fn banded_semi_global(
60    query: &[u8],
61    target: &[u8],
62    scoring: &ScoringScheme,
63    bandwidth: usize,
64) -> Result<AlignmentResult> {
65    validate_inputs(query, target, bandwidth)?;
66    banded_align(query, target, scoring, bandwidth, AlignmentMode::SemiGlobal)
67}
68
69/// Score-only banded alignment (no traceback). Uses O(bandwidth) memory.
70pub fn banded_score_only(
71    query: &[u8],
72    target: &[u8],
73    scoring: &ScoringScheme,
74    bandwidth: usize,
75    mode: AlignmentMode,
76) -> Result<i32> {
77    validate_inputs(query, target, bandwidth)?;
78    let result = banded_align(query, target, scoring, bandwidth, mode)?;
79    Ok(result.score)
80}
81
82fn validate_inputs(query: &[u8], target: &[u8], bandwidth: usize) -> Result<()> {
83    if query.is_empty() || target.is_empty() {
84        return Err(CyaneaError::InvalidInput("empty sequence".into()));
85    }
86    if bandwidth == 0 {
87        return Err(CyaneaError::InvalidInput("bandwidth must be > 0".into()));
88    }
89    Ok(())
90}
91
92const TRACE_DIAG: u8 = 0;
93const TRACE_UP: u8 = 1;
94const TRACE_LEFT: u8 = 2;
95const TRACE_STOP: u8 = 3;
96
97fn banded_align(
98    query: &[u8],
99    target: &[u8],
100    scoring: &ScoringScheme,
101    bandwidth: usize,
102    mode: AlignmentMode,
103) -> Result<AlignmentResult> {
104    let m = query.len();
105    let n = target.len();
106    let w = bandwidth;
107    let is_local = mode == AlignmentMode::Local;
108    let is_semi_global = mode == AlignmentMode::SemiGlobal;
109    let band_width = 2 * w + 1;
110    let rows = m + 1;
111
112    // Band-indexed storage: for row i, column j maps to band_idx = j - i + w.
113    let mut h = vec![vec![i32::MIN / 2; band_width]; rows];
114    let mut trace = vec![vec![TRACE_STOP; band_width]; rows];
115
116    let band_idx = |i: usize, j: usize| -> Option<usize> {
117        let idx = j as isize - i as isize + w as isize;
118        if idx >= 0 && (idx as usize) < band_width {
119            Some(idx as usize)
120        } else {
121            None
122        }
123    };
124
125    // Row 0
126    if let Some(bi) = band_idx(0, 0) {
127        h[0][bi] = 0;
128    }
129    if !is_local && !is_semi_global {
130        for j in 1..=w.min(n) {
131            if let Some(bi) = band_idx(0, j) {
132                h[0][bi] = scoring.gap_open() + (j as i32 - 1) * scoring.gap_extend();
133                trace[0][bi] = TRACE_LEFT;
134            }
135        }
136    } else {
137        for j in 0..=w.min(n) {
138            if let Some(bi) = band_idx(0, j) {
139                h[0][bi] = 0;
140            }
141        }
142    }
143
144    // Column 0
145    if !is_local && !is_semi_global {
146        for i in 1..=w.min(m) {
147            if let Some(bi) = band_idx(i, 0) {
148                h[i][bi] = scoring.gap_open() + (i as i32 - 1) * scoring.gap_extend();
149                trace[i][bi] = TRACE_UP;
150            }
151        }
152    } else {
153        for i in 1..=m {
154            if let Some(bi) = band_idx(i, 0) {
155                h[i][bi] = 0;
156            }
157        }
158    }
159
160    let mut best_score = if is_local { 0 } else { i32::MIN };
161    let mut best_i = 0;
162    let mut best_j = 0;
163
164    for i in 1..=m {
165        let j_min = if i > w { i - w } else { 1 };
166        let j_max = (i + w).min(n);
167
168        for j in j_min..=j_max {
169            let bi = match band_idx(i, j) {
170                Some(b) => b,
171                None => continue,
172            };
173
174            let sub = scoring.score_pair(query[i - 1], target[j - 1]);
175
176            let diag = band_idx(i - 1, j - 1)
177                .map(|b| h[i - 1][b])
178                .unwrap_or(i32::MIN / 2)
179                .saturating_add(sub);
180
181            let up = band_idx(i - 1, j)
182                .map(|b| h[i - 1][b])
183                .unwrap_or(i32::MIN / 2)
184                .saturating_add(scoring.gap_open());
185
186            let left = band_idx(i, j - 1)
187                .map(|b| h[i][b])
188                .unwrap_or(i32::MIN / 2)
189                .saturating_add(scoring.gap_open());
190
191            let mut score = diag.max(up).max(left);
192            let mut tr = if score == diag {
193                TRACE_DIAG
194            } else if score == up {
195                TRACE_UP
196            } else {
197                TRACE_LEFT
198            };
199
200            if is_local && score < 0 {
201                score = 0;
202                tr = TRACE_STOP;
203            }
204
205            h[i][bi] = score;
206            trace[i][bi] = tr;
207
208            if score > best_score {
209                best_score = score;
210                best_i = i;
211                best_j = j;
212            }
213        }
214    }
215
216    let (end_i, end_j) = if is_local {
217        (best_i, best_j)
218    } else if is_semi_global {
219        // Semi-global: find max in last row OR last column (free trailing gaps)
220        best_score = i32::MIN;
221        best_i = m;
222        best_j = n;
223        // Scan last row (i = m)
224        let j_min_last = if m > w { m - w } else { 0 };
225        let j_max_last = (m + w).min(n);
226        for j in j_min_last..=j_max_last {
227            if let Some(bi) = band_idx(m, j) {
228                if h[m][bi] > best_score {
229                    best_score = h[m][bi];
230                    best_i = m;
231                    best_j = j;
232                }
233            }
234        }
235        // Scan last column (j = n)
236        let i_min_last = if n > w { n - w } else { 0 };
237        let i_max_last = (n + w).min(m);
238        for i in i_min_last..=i_max_last {
239            if let Some(bi) = band_idx(i, n) {
240                if h[i][bi] > best_score {
241                    best_score = h[i][bi];
242                    best_i = i;
243                    best_j = n;
244                }
245            }
246        }
247        (best_i, best_j)
248    } else {
249        if let Some(bi) = band_idx(m, n) {
250            best_score = h[m][bi];
251        }
252        (m, n)
253    };
254
255    // Traceback
256    let mut ops: Vec<CigarOp> = Vec::new();
257    let mut aligned_query = Vec::new();
258    let mut aligned_target = Vec::new();
259    let mut ci = end_i;
260    let mut cj = end_j;
261
262    loop {
263        if ci == 0 && cj == 0 {
264            break;
265        }
266        // Semi-global: stop at border (free leading gaps)
267        if is_semi_global && (ci == 0 || cj == 0) {
268            break;
269        }
270        let bi = match band_idx(ci, cj) {
271            Some(b) => b,
272            None => break,
273        };
274        let tr = trace[ci][bi];
275        if is_local && tr == TRACE_STOP {
276            break;
277        }
278        match tr {
279            TRACE_DIAG => {
280                let q = query[ci - 1];
281                let t = target[cj - 1];
282                aligned_query.push(q);
283                aligned_target.push(t);
284                let op = if q.to_ascii_uppercase() == t.to_ascii_uppercase() {
285                    CigarOp::Match(1)
286                } else {
287                    CigarOp::Mismatch(1)
288                };
289                ops.push(op);
290                ci -= 1;
291                cj -= 1;
292            }
293            TRACE_UP => {
294                aligned_query.push(query[ci - 1]);
295                aligned_target.push(b'-');
296                ops.push(CigarOp::Deletion(1));
297                ci -= 1;
298            }
299            TRACE_LEFT => {
300                aligned_query.push(b'-');
301                aligned_target.push(target[cj - 1]);
302                ops.push(CigarOp::Insertion(1));
303                cj -= 1;
304            }
305            _ => break,
306        }
307    }
308
309    aligned_query.reverse();
310    aligned_target.reverse();
311    ops.reverse();
312
313    let cigar = merge_cigar(ops);
314    let (query_start, query_end) = if is_local || is_semi_global {
315        (ci, end_i)
316    } else {
317        (0, m)
318    };
319    let (target_start, target_end) = if is_local || is_semi_global {
320        (cj, end_j)
321    } else {
322        (0, n)
323    };
324
325    Ok(AlignmentResult {
326        score: best_score,
327        aligned_query,
328        aligned_target,
329        query_start,
330        query_end,
331        target_start,
332        target_end,
333        cigar,
334    })
335}
336
337fn merge_cigar(ops: Vec<CigarOp>) -> Vec<CigarOp> {
338    let mut merged: Vec<CigarOp> = Vec::new();
339    for op in ops {
340        if let Some(last) = merged.last_mut() {
341            let combined = match (*last, op) {
342                (CigarOp::Match(a), CigarOp::Match(b)) => Some(CigarOp::Match(a + b)),
343                (CigarOp::Mismatch(a), CigarOp::Mismatch(b)) => Some(CigarOp::Mismatch(a + b)),
344                (CigarOp::Insertion(a), CigarOp::Insertion(b)) => Some(CigarOp::Insertion(a + b)),
345                (CigarOp::Deletion(a), CigarOp::Deletion(b)) => Some(CigarOp::Deletion(a + b)),
346                _ => None,
347            };
348            if let Some(c) = combined {
349                *last = c;
350                continue;
351            }
352        }
353        merged.push(op);
354    }
355    merged
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361    use crate::scoring::{ScoringMatrix, ScoringScheme};
362
363    fn dna_scheme() -> ScoringScheme {
364        ScoringScheme::Simple(ScoringMatrix::dna_default())
365    }
366
367    #[test]
368    fn banded_nw_identical() {
369        let r = banded_nw(b"ACGT", b"ACGT", &dna_scheme(), 3).unwrap();
370        assert_eq!(r.score, 8);
371        assert_eq!(r.cigar_string(), "4=");
372    }
373
374    #[test]
375    fn banded_nw_with_mismatch() {
376        let r = banded_nw(b"ACGT", b"ACTT", &dna_scheme(), 3).unwrap();
377        assert!(r.score > 0);
378        assert_eq!(r.query_start, 0);
379        assert_eq!(r.query_end, 4);
380    }
381
382    #[test]
383    fn banded_sw_local() {
384        let r = banded_sw(b"AAACGTAAA", b"TTTCGTTTT", &dna_scheme(), 5).unwrap();
385        assert!(r.score > 0);
386    }
387
388    #[test]
389    fn banded_sw_identical() {
390        let r = banded_sw(b"ACGT", b"ACGT", &dna_scheme(), 4).unwrap();
391        assert_eq!(r.score, 8);
392    }
393
394    #[test]
395    fn banded_empty_sequence_error() {
396        assert!(banded_nw(b"", b"ACGT", &dna_scheme(), 3).is_err());
397        assert!(banded_nw(b"ACGT", b"", &dna_scheme(), 3).is_err());
398    }
399
400    #[test]
401    fn banded_zero_bandwidth_error() {
402        assert!(banded_nw(b"ACGT", b"ACGT", &dna_scheme(), 0).is_err());
403    }
404
405    #[test]
406    fn banded_score_only_global() {
407        let score =
408            banded_score_only(b"ACGT", b"ACGT", &dna_scheme(), 3, AlignmentMode::Global).unwrap();
409        assert_eq!(score, 8);
410    }
411
412    #[test]
413    fn banded_score_only_local() {
414        let score = banded_score_only(
415            b"AAACGTAAA",
416            b"TTTCGTTTT",
417            &dna_scheme(),
418            5,
419            AlignmentMode::Local,
420        )
421        .unwrap();
422        assert!(score > 0);
423    }
424
425    #[test]
426    fn banded_semi_global_identical() {
427        let r = banded_semi_global(b"ACGT", b"ACGT", &dna_scheme(), 3).unwrap();
428        assert_eq!(r.score, 8);
429        assert_eq!(r.cigar_string(), "4=");
430    }
431
432    #[test]
433    fn banded_semi_global_query_in_target() {
434        let r = banded_semi_global(b"CGT", b"AACGTAA", &dna_scheme(), 5).unwrap();
435        assert_eq!(r.score, 6); // 3 matches * 2
436    }
437
438    #[test]
439    fn banded_semi_global_overlap() {
440        let r = banded_semi_global(b"AAAACGT", b"CGTTTTT", &dna_scheme(), 5).unwrap();
441        assert_eq!(r.score, 6); // CGT = 3 matches * 2
442    }
443
444    #[test]
445    fn banded_score_only_semi_global() {
446        let score = banded_score_only(
447            b"CGT",
448            b"AACGTAA",
449            &dna_scheme(),
450            5,
451            AlignmentMode::SemiGlobal,
452        )
453        .unwrap();
454        assert_eq!(score, 6);
455    }
456}