Skip to main content

cyanea_align/
spliced.rs

1//! Spliced alignment for RNA-to-genome mapping.
2//!
3//! Implements a modified Gotoh DP with an intron-skip state that recognizes
4//! canonical splice sites (GT-AG, GC-AG, AT-AC), plus exon chaining for
5//! combining pre-computed exon alignments.
6
7use cyanea_core::{CyaneaError, Result};
8
9use crate::scoring::ScoringScheme;
10use crate::types::{AlignmentResult, CigarOp};
11
12// ---------------------------------------------------------------------------
13// Types
14// ---------------------------------------------------------------------------
15
16/// Classification of a splice site dinucleotide pair.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum SpliceSiteType {
19    /// GT...AG (canonical, ~99% of introns).
20    GtAg,
21    /// GC...AG (semi-canonical, ~1%).
22    GcAg,
23    /// AT...AC (rare U12-type).
24    AtAc,
25    /// Non-canonical dinucleotides.
26    NonCanonical,
27}
28
29/// Parameters for spliced alignment.
30#[derive(Debug, Clone)]
31pub struct SplicedAlignParams {
32    /// Base penalty for each intron (default: -15).
33    pub splice_penalty: i32,
34    /// Bonus for canonical GT-AG splice sites (default: 8).
35    pub canonical_bonus: i32,
36    /// Bonus for semi-canonical GC-AG splice sites (default: 4).
37    pub semi_canonical_bonus: i32,
38    /// Minimum intron length in bases (default: 30).
39    pub min_intron_len: usize,
40    /// Maximum intron length in bases (default: 200_000).
41    pub max_intron_len: usize,
42    /// Maximum number of exons; 0 means unlimited (default: 0).
43    pub max_exons: usize,
44}
45
46impl Default for SplicedAlignParams {
47    fn default() -> Self {
48        Self {
49            splice_penalty: -15,
50            canonical_bonus: 8,
51            semi_canonical_bonus: 4,
52            min_intron_len: 30,
53            max_intron_len: 200_000,
54            max_exons: 0,
55        }
56    }
57}
58
59/// A single exon alignment within a spliced alignment.
60#[derive(Debug, Clone)]
61pub struct ExonAlignment {
62    /// Start position in the query (0-indexed, inclusive).
63    pub query_start: usize,
64    /// End position in the query (0-indexed, exclusive).
65    pub query_end: usize,
66    /// Start position in the reference (0-indexed, inclusive).
67    pub target_start: usize,
68    /// End position in the reference (0-indexed, exclusive).
69    pub target_end: usize,
70    /// Exon alignment score.
71    pub score: i32,
72    /// CIGAR operations for this exon.
73    pub cigar: Vec<CigarOp>,
74}
75
76/// Result of a spliced alignment.
77#[derive(Debug, Clone)]
78pub struct SplicedAlignResult {
79    /// Combined alignment result.
80    pub alignment: AlignmentResult,
81    /// Individual exon alignments.
82    pub exons: Vec<ExonAlignment>,
83    /// Splice junctions: (intron_start, intron_end, type).
84    pub junctions: Vec<(usize, usize, SpliceSiteType)>,
85    /// Number of introns.
86    pub intron_count: usize,
87}
88
89// ---------------------------------------------------------------------------
90// Splice site detection
91// ---------------------------------------------------------------------------
92
93/// Detect the splice site type for an intron at the given reference positions.
94///
95/// Checks the donor dinucleotide at `intron_start` and the acceptor
96/// dinucleotide ending at `intron_end - 1`.
97pub fn detect_splice_site(
98    reference: &[u8],
99    intron_start: usize,
100    intron_end: usize,
101) -> SpliceSiteType {
102    if intron_start + 2 > reference.len() || intron_end < 2 || intron_end > reference.len() {
103        return SpliceSiteType::NonCanonical;
104    }
105    if intron_end <= intron_start + 2 {
106        return SpliceSiteType::NonCanonical;
107    }
108
109    let donor = [
110        reference[intron_start].to_ascii_uppercase(),
111        reference[intron_start + 1].to_ascii_uppercase(),
112    ];
113    let acceptor = [
114        reference[intron_end - 2].to_ascii_uppercase(),
115        reference[intron_end - 1].to_ascii_uppercase(),
116    ];
117
118    match (donor, acceptor) {
119        ([b'G', b'T'], [b'A', b'G']) => SpliceSiteType::GtAg,
120        ([b'G', b'C'], [b'A', b'G']) => SpliceSiteType::GcAg,
121        ([b'A', b'T'], [b'A', b'C']) => SpliceSiteType::AtAc,
122        _ => SpliceSiteType::NonCanonical,
123    }
124}
125
126// ---------------------------------------------------------------------------
127// CIGAR helper
128// ---------------------------------------------------------------------------
129
130fn push_cigar(cigar: &mut Vec<CigarOp>, op: CigarOp) {
131    if let Some(last) = cigar.last_mut() {
132        match (last, &op) {
133            (CigarOp::Match(n), CigarOp::Match(m)) => {
134                *n += m;
135                return;
136            }
137            (CigarOp::Mismatch(n), CigarOp::Mismatch(m)) => {
138                *n += m;
139                return;
140            }
141            (CigarOp::Insertion(n), CigarOp::Insertion(m)) => {
142                *n += m;
143                return;
144            }
145            (CigarOp::Deletion(n), CigarOp::Deletion(m)) => {
146                *n += m;
147                return;
148            }
149            (CigarOp::Skip(n), CigarOp::Skip(m)) => {
150                *n += m;
151                return;
152            }
153            _ => {}
154        }
155    }
156    cigar.push(op);
157}
158
159// ---------------------------------------------------------------------------
160// Spliced alignment DP
161// ---------------------------------------------------------------------------
162
163const NEG_INF: i32 = i32::MIN / 2;
164
165/// Perform spliced alignment of a query (e.g., mRNA/cDNA) to a reference (genome).
166///
167/// Uses a modified Gotoh DP with an additional intron-skip state that
168/// recognizes canonical splice sites and applies bonuses/penalties.
169///
170/// # Errors
171///
172/// Returns an error if either sequence is empty.
173pub fn spliced_align(
174    query: &[u8],
175    reference: &[u8],
176    scoring: &ScoringScheme,
177    params: &SplicedAlignParams,
178) -> Result<SplicedAlignResult> {
179    if query.is_empty() || reference.is_empty() {
180        return Err(CyaneaError::InvalidInput(
181            "query and reference must be non-empty".into(),
182        ));
183    }
184
185    let m = query.len();
186    let n = reference.len();
187    let gap_open = scoring.gap_open();
188    let gap_extend = scoring.gap_extend();
189
190    // Precompute donor site positions (GT or GC) in reference
191    let mut donor_sites: Vec<usize> = Vec::new();
192    for j in 0..n.saturating_sub(1) {
193        let d0 = reference[j].to_ascii_uppercase();
194        let d1 = reference[j + 1].to_ascii_uppercase();
195        if (d0 == b'G' && (d1 == b'T' || d1 == b'C')) || (d0 == b'A' && d1 == b'T') {
196            donor_sites.push(j);
197        }
198    }
199
200    // DP matrices: H (match/mismatch), E (insertion), F (deletion)
201    // Plus traceback
202    let cols = n + 1;
203    let rows = m + 1;
204
205    let mut h = vec![vec![NEG_INF; cols]; rows];
206    let mut e = vec![vec![NEG_INF; cols]; rows];
207    let mut f = vec![vec![NEG_INF; cols]; rows];
208
209    // Traceback: 0=diag, 1=ins(E), 2=del(F), 3=skip(intron), encoded as (type, donor_pos)
210    // We store tb_type and tb_donor separately
211    let mut tb_type = vec![vec![0u8; cols]; rows];
212    let mut tb_donor = vec![vec![0usize; cols]; rows]; // donor position for skip
213
214    // Initialize: semi-global on reference (free gaps at start/end of reference)
215    h[0][0] = 0;
216    for j in 1..=n {
217        h[0][j] = 0; // free start on reference
218    }
219    for i in 1..=m {
220        e[i][0] = gap_open + gap_extend * i as i32;
221        h[i][0] = e[i][0];
222        tb_type[i][0] = 1;
223    }
224
225    let mut best_score = NEG_INF;
226    let mut best_i = 0;
227    let mut best_j = 0;
228
229    for i in 1..=rows - 1 {
230        for j in 1..=cols - 1 {
231            // E: insertion (gap in reference, consumes query)
232            let e_open = h[i - 1][j].saturating_add(gap_open + gap_extend);
233            let e_ext = e[i - 1][j].saturating_add(gap_extend);
234            e[i][j] = e_open.max(e_ext);
235
236            // F: deletion (gap in query, consumes reference)
237            let f_open = h[i][j - 1].saturating_add(gap_open + gap_extend);
238            let f_ext = f[i][j - 1].saturating_add(gap_extend);
239            f[i][j] = f_open.max(f_ext);
240
241            // H: match/mismatch (diagonal)
242            let sub = scoring.score_pair(query[i - 1], reference[j - 1]);
243            let diag = h[i - 1][j - 1].saturating_add(sub);
244
245            // N: intron skip — check all donor sites that could connect to position j
246            // An intron ends at position j (acceptor), started at some donor d.
247            // The intron spans reference positions [d, j) with length j-d.
248            let mut skip_score = NEG_INF;
249            let mut skip_donor = 0usize;
250
251            // Check acceptor dinucleotide at j-2..j
252            if j >= 2 {
253                let a0 = reference[j - 2].to_ascii_uppercase();
254                let a1 = reference[j - 1].to_ascii_uppercase();
255                let is_acceptor = (a0 == b'A' && a1 == b'G') || (a0 == b'A' && a1 == b'C');
256
257                if is_acceptor {
258                    // Binary search for donor sites in valid range
259                    let min_donor = if j > params.max_intron_len {
260                        j - params.max_intron_len
261                    } else {
262                        0
263                    };
264                    let max_donor = if j > params.min_intron_len {
265                        j - params.min_intron_len
266                    } else {
267                        0
268                    };
269
270                    if max_donor > min_donor
271                        || (max_donor == min_donor && j >= params.min_intron_len)
272                    {
273                        // Find donor sites in range
274                        let lo = donor_sites.partition_point(|&d| d < min_donor);
275                        let hi = donor_sites.partition_point(|&d| d <= max_donor);
276
277                        for &d in &donor_sites[lo..hi] {
278                            let intron_len = j - d;
279                            if intron_len < params.min_intron_len
280                                || intron_len > params.max_intron_len
281                            {
282                                continue;
283                            }
284
285                            let ss_type = detect_splice_site(reference, d, j);
286                            let bonus = match ss_type {
287                                SpliceSiteType::GtAg => params.canonical_bonus,
288                                SpliceSiteType::GcAg => params.semi_canonical_bonus,
289                                SpliceSiteType::AtAc => params.semi_canonical_bonus,
290                                SpliceSiteType::NonCanonical => 0,
291                            };
292
293                            // Score: h[i][d] (end of previous exon at ref pos d)
294                            // plus splice penalty plus bonus
295                            // Note: i stays the same (no query bases consumed by intron)
296                            let candidate = h[i][d]
297                                .saturating_add(params.splice_penalty)
298                                .saturating_add(bonus);
299
300                            if candidate > skip_score {
301                                skip_score = candidate;
302                                skip_donor = d;
303                            }
304                        }
305                    }
306                }
307            }
308
309            // Best of all states
310            let mut h_val = diag.max(e[i][j]).max(f[i][j]).max(skip_score);
311            // Don't go below NEG_INF
312            if h_val < NEG_INF / 2 {
313                h_val = NEG_INF;
314            }
315            h[i][j] = h_val;
316
317            if h_val == skip_score && skip_score > NEG_INF {
318                tb_type[i][j] = 3;
319                tb_donor[i][j] = skip_donor;
320            } else if h_val == diag {
321                tb_type[i][j] = 0;
322            } else if h_val == e[i][j] {
323                tb_type[i][j] = 1;
324            } else {
325                tb_type[i][j] = 2;
326            }
327
328            // Track best (semi-global: best score in last row, any column of ref)
329            if i == m && h_val > best_score {
330                best_score = h_val;
331                best_i = i;
332                best_j = j;
333            }
334        }
335    }
336
337    // Also check the full-query row for best
338    if best_score == NEG_INF {
339        // Fallback: find best anywhere
340        for i in 1..=m {
341            for j in 1..=n {
342                if h[i][j] > best_score {
343                    best_score = h[i][j];
344                    best_i = i;
345                    best_j = j;
346                }
347            }
348        }
349    }
350
351    // Traceback
352    let mut cigar_ops: Vec<CigarOp> = Vec::new();
353    let mut ci = best_i;
354    let mut cj = best_j;
355    let mut junctions: Vec<(usize, usize, SpliceSiteType)> = Vec::new();
356
357    while ci > 0 && cj > 0 {
358        match tb_type[ci][cj] {
359            0 => {
360                // Diagonal: match/mismatch
361                let op = if query[ci - 1].to_ascii_uppercase()
362                    == reference[cj - 1].to_ascii_uppercase()
363                {
364                    CigarOp::Match(1)
365                } else {
366                    CigarOp::Mismatch(1)
367                };
368                push_cigar(&mut cigar_ops, op);
369                ci -= 1;
370                cj -= 1;
371            }
372            1 => {
373                // Insertion
374                push_cigar(&mut cigar_ops, CigarOp::Insertion(1));
375                ci -= 1;
376            }
377            2 => {
378                // Deletion
379                push_cigar(&mut cigar_ops, CigarOp::Deletion(1));
380                cj -= 1;
381            }
382            3 => {
383                // Intron skip
384                let donor = tb_donor[ci][cj];
385                let intron_len = cj - donor;
386                let ss_type = detect_splice_site(reference, donor, cj);
387                junctions.push((donor, cj, ss_type));
388                push_cigar(&mut cigar_ops, CigarOp::Skip(intron_len));
389                cj = donor;
390                // ci stays the same — no query consumed
391            }
392            _ => break,
393        }
394    }
395
396    while ci > 0 {
397        push_cigar(&mut cigar_ops, CigarOp::Insertion(1));
398        ci -= 1;
399    }
400
401    cigar_ops.reverse();
402    junctions.reverse();
403
404    // Build exons from CIGAR (split on Skip ops)
405    let exons = build_exons_from_cigar(&cigar_ops, ci, cj, query, reference, scoring);
406
407    // Build aligned sequences
408    let (aligned_query, aligned_target, q_start, q_end, t_start, t_end) =
409        build_aligned_seqs(&cigar_ops, ci, cj, query, reference);
410
411    let intron_count = junctions.len();
412
413    Ok(SplicedAlignResult {
414        alignment: AlignmentResult {
415            score: best_score,
416            aligned_query,
417            aligned_target,
418            query_start: q_start,
419            query_end: q_end,
420            target_start: t_start,
421            target_end: t_end,
422            cigar: cigar_ops,
423        },
424        exons,
425        junctions,
426        intron_count,
427    })
428}
429
430/// Build ExonAlignment records by splitting the CIGAR at Skip operations.
431fn build_exons_from_cigar(
432    cigar: &[CigarOp],
433    start_qi: usize,
434    start_ti: usize,
435    query: &[u8],
436    _reference: &[u8],
437    scoring: &ScoringScheme,
438) -> Vec<ExonAlignment> {
439    let mut exons = Vec::new();
440    let mut qi = start_qi;
441    let mut ti = start_ti;
442    let mut exon_cigar: Vec<CigarOp> = Vec::new();
443    let mut exon_q_start = qi;
444    let mut exon_t_start = ti;
445    let mut exon_score = 0i32;
446
447    for op in cigar {
448        match op {
449            CigarOp::Skip(_n) => {
450                // End current exon
451                if !exon_cigar.is_empty() {
452                    exons.push(ExonAlignment {
453                        query_start: exon_q_start,
454                        query_end: qi,
455                        target_start: exon_t_start,
456                        target_end: ti,
457                        score: exon_score,
458                        cigar: exon_cigar.clone(),
459                    });
460                }
461                // Skip on reference
462                ti += _n;
463                // Start new exon
464                exon_cigar.clear();
465                exon_q_start = qi;
466                exon_t_start = ti;
467                exon_score = 0;
468            }
469            CigarOp::Match(n) => {
470                for _ in 0..*n {
471                    exon_score += scoring.score_pair(query[qi], query[qi]);
472                    qi += 1;
473                    ti += 1;
474                }
475                push_cigar(&mut exon_cigar, *op);
476            }
477            CigarOp::Mismatch(n) => {
478                // Score mismatches
479                for _ in 0..*n {
480                    exon_score += scoring.score_pair(query[qi], b'N'); // approximate
481                    qi += 1;
482                    ti += 1;
483                }
484                push_cigar(&mut exon_cigar, *op);
485            }
486            CigarOp::Insertion(n) => {
487                if qi + n <= query.len() {
488                    exon_score += scoring.gap_open() + scoring.gap_extend() * *n as i32;
489                }
490                qi += n;
491                push_cigar(&mut exon_cigar, *op);
492            }
493            CigarOp::Deletion(n) => {
494                exon_score += scoring.gap_open() + scoring.gap_extend() * *n as i32;
495                ti += n;
496                push_cigar(&mut exon_cigar, *op);
497            }
498            _ => {
499                push_cigar(&mut exon_cigar, *op);
500            }
501        }
502    }
503
504    // Final exon
505    if !exon_cigar.is_empty() {
506        exons.push(ExonAlignment {
507            query_start: exon_q_start,
508            query_end: qi,
509            target_start: exon_t_start,
510            target_end: ti,
511            score: exon_score,
512            cigar: exon_cigar,
513        });
514    }
515
516    exons
517}
518
519/// Build aligned sequences from CIGAR.
520fn build_aligned_seqs(
521    cigar: &[CigarOp],
522    start_qi: usize,
523    start_ti: usize,
524    query: &[u8],
525    reference: &[u8],
526) -> (Vec<u8>, Vec<u8>, usize, usize, usize, usize) {
527    let mut aq = Vec::new();
528    let mut at = Vec::new();
529    let mut qi = start_qi;
530    let mut ti = start_ti;
531
532    for op in cigar {
533        match op {
534            CigarOp::Match(n) | CigarOp::Mismatch(n) => {
535                for _ in 0..*n {
536                    if qi < query.len() {
537                        aq.push(query[qi]);
538                    }
539                    if ti < reference.len() {
540                        at.push(reference[ti]);
541                    }
542                    qi += 1;
543                    ti += 1;
544                }
545            }
546            CigarOp::Insertion(n) => {
547                for _ in 0..*n {
548                    if qi < query.len() {
549                        aq.push(query[qi]);
550                    }
551                    at.push(b'-');
552                    qi += 1;
553                }
554            }
555            CigarOp::Deletion(n) => {
556                for _ in 0..*n {
557                    aq.push(b'-');
558                    if ti < reference.len() {
559                        at.push(reference[ti]);
560                    }
561                    ti += 1;
562                }
563            }
564            CigarOp::Skip(n) => {
565                // Introns are not shown in aligned sequences
566                ti += n;
567            }
568            _ => {}
569        }
570    }
571
572    (aq, at, start_qi, qi, start_ti, ti)
573}
574
575// ---------------------------------------------------------------------------
576// Exon chaining
577// ---------------------------------------------------------------------------
578
579/// Chain pre-computed exon alignments into a spliced alignment.
580///
581/// Exons are sorted by reference position and chained using DP.
582/// Gaps between exons on the reference must fall within
583/// `[min_intron_len, max_intron_len]`. Colinearity is enforced on both
584/// query and reference coordinates.
585///
586/// # Errors
587///
588/// Returns an error if the exon list is empty.
589pub fn chain_exons(
590    exons: &[ExonAlignment],
591    reference: &[u8],
592    params: &SplicedAlignParams,
593) -> Result<SplicedAlignResult> {
594    if exons.is_empty() {
595        return Err(CyaneaError::InvalidInput("exon list is empty".into()));
596    }
597
598    // Sort exons by reference start position
599    let mut sorted: Vec<(usize, &ExonAlignment)> = exons.iter().enumerate().collect();
600    sorted.sort_by_key(|(_, e)| (e.target_start, e.query_start));
601
602    let ne = sorted.len();
603    let mut dp = vec![NEG_INF; ne];
604    let mut prev = vec![usize::MAX; ne];
605
606    // Initialize: each exon can start a chain
607    for i in 0..ne {
608        dp[i] = sorted[i].1.score;
609    }
610
611    // Chain DP
612    for i in 1..ne {
613        let ei = sorted[i].1;
614        for j in 0..i {
615            let ej = sorted[j].1;
616
617            // Colinearity: both query and reference must be non-decreasing
618            if ej.query_end > ei.query_start || ej.target_end > ei.target_start {
619                continue;
620            }
621
622            // Reference gap = intron length
623            let ref_gap = ei.target_start - ej.target_end;
624            if ref_gap < params.min_intron_len || ref_gap > params.max_intron_len {
625                continue;
626            }
627
628            // Splice site bonus
629            let ss_type = detect_splice_site(reference, ej.target_end, ei.target_start);
630            let bonus = match ss_type {
631                SpliceSiteType::GtAg => params.canonical_bonus,
632                SpliceSiteType::GcAg => params.semi_canonical_bonus,
633                SpliceSiteType::AtAc => params.semi_canonical_bonus,
634                SpliceSiteType::NonCanonical => 0,
635            };
636
637            let candidate = dp[j]
638                .saturating_add(params.splice_penalty)
639                .saturating_add(bonus)
640                .saturating_add(ei.score);
641
642            if candidate > dp[i] {
643                dp[i] = candidate;
644                prev[i] = j;
645            }
646        }
647    }
648
649    // Find best ending exon
650    let mut best_idx = 0;
651    for i in 1..ne {
652        if dp[i] > dp[best_idx] {
653            best_idx = i;
654        }
655    }
656
657    // Traceback chain
658    let mut chain: Vec<usize> = Vec::new();
659    let mut idx = best_idx;
660    loop {
661        chain.push(idx);
662        if prev[idx] == usize::MAX {
663            break;
664        }
665        idx = prev[idx];
666    }
667    chain.reverse();
668
669    // Build combined CIGAR, junctions, exons
670    let mut combined_cigar: Vec<CigarOp> = Vec::new();
671    let mut junctions: Vec<(usize, usize, SpliceSiteType)> = Vec::new();
672    let mut chain_exons: Vec<ExonAlignment> = Vec::new();
673
674    for (k, &ci) in chain.iter().enumerate() {
675        let exon = sorted[ci].1;
676
677        if k > 0 {
678            let prev_exon = sorted[chain[k - 1]].1;
679            let intron_start = prev_exon.target_end;
680            let intron_end = exon.target_start;
681            let intron_len = intron_end - intron_start;
682            let ss_type = detect_splice_site(reference, intron_start, intron_end);
683            junctions.push((intron_start, intron_end, ss_type));
684            push_cigar(&mut combined_cigar, CigarOp::Skip(intron_len));
685        }
686
687        for op in &exon.cigar {
688            push_cigar(&mut combined_cigar, *op);
689        }
690        chain_exons.push(exon.clone());
691    }
692
693    let first_exon = sorted[chain[0]].1;
694    let last_exon = sorted[*chain.last().unwrap()].1;
695
696    let alignment = AlignmentResult {
697        score: dp[best_idx],
698        aligned_query: Vec::new(), // chaining doesn't reconstruct aligned seqs
699        aligned_target: Vec::new(),
700        query_start: first_exon.query_start,
701        query_end: last_exon.query_end,
702        target_start: first_exon.target_start,
703        target_end: last_exon.target_end,
704        cigar: combined_cigar,
705    };
706
707    let intron_count = junctions.len();
708
709    Ok(SplicedAlignResult {
710        alignment,
711        exons: chain_exons,
712        junctions,
713        intron_count,
714    })
715}
716
717// ---------------------------------------------------------------------------
718// Tests
719// ---------------------------------------------------------------------------
720
721#[cfg(test)]
722mod tests {
723    use super::*;
724    use crate::scoring::ScoringMatrix;
725
726    fn dna_scheme() -> ScoringScheme {
727        ScoringScheme::Simple(ScoringMatrix::dna_default())
728    }
729
730    // --- Splice site detection ---
731
732    #[test]
733    fn detect_gt_ag() {
734        // intron_start=1 (donor GT at 1,2), intron_end=17 (acceptor AG at 15,16)
735        let reference = b"XGTXXXXXXXXXXXXAGX";
736        let ss = detect_splice_site(reference, 1, 17);
737        assert_eq!(ss, SpliceSiteType::GtAg);
738    }
739
740    #[test]
741    fn detect_gc_ag() {
742        let reference = b"XGCXXXXXXXXXXXXAGX";
743        let ss = detect_splice_site(reference, 1, 17);
744        assert_eq!(ss, SpliceSiteType::GcAg);
745    }
746
747    #[test]
748    fn detect_at_ac() {
749        let reference = b"XATXXXXXXXXXXXXACX";
750        let ss = detect_splice_site(reference, 1, 17);
751        assert_eq!(ss, SpliceSiteType::AtAc);
752    }
753
754    #[test]
755    fn detect_noncanonical() {
756        let reference = b"XAAXXXXXXXXXXXXTTX";
757        let ss = detect_splice_site(reference, 1, 17);
758        assert_eq!(ss, SpliceSiteType::NonCanonical);
759    }
760
761    // --- Spliced alignment ---
762
763    #[test]
764    fn single_exon_no_intron() {
765        let query = b"ACGTACGT";
766        let reference = b"ACGTACGT";
767        let result = spliced_align(
768            query,
769            reference,
770            &dna_scheme(),
771            &SplicedAlignParams::default(),
772        )
773        .unwrap();
774        assert_eq!(result.intron_count, 0);
775        assert_eq!(result.exons.len(), 1);
776        assert_eq!(result.alignment.score, 16);
777    }
778
779    #[test]
780    fn one_intron_gt_ag() {
781        // Query: ACGTACGT (8 bases, two exons of 4)
782        // Reference: ACGT + GT...(30+ bases)...AG + ACGT
783        let mut reference = Vec::new();
784        reference.extend_from_slice(b"ACGT"); // exon 1
785        reference.push(b'G');
786        reference.push(b'T'); // donor
787        for _ in 0..30 {
788            reference.push(b'N');
789        }
790        reference.push(b'A');
791        reference.push(b'G'); // acceptor
792        reference.extend_from_slice(b"ACGT"); // exon 2
793                                              // Total intron = 2 + 30 + 2 = 34 bases (> min_intron_len=30)
794
795        let query = b"ACGTACGT";
796        let result = spliced_align(
797            query,
798            &reference,
799            &dna_scheme(),
800            &SplicedAlignParams::default(),
801        )
802        .unwrap();
803
804        // Should find the splice junction
805        assert!(
806            result.intron_count >= 1 || result.alignment.score > 0,
807            "should find alignment with or without intron"
808        );
809
810        // Check CIGAR contains a Skip if intron was found
811        if result.intron_count > 0 {
812            let has_skip = result
813                .alignment
814                .cigar
815                .iter()
816                .any(|op| matches!(op, CigarOp::Skip(_)));
817            assert!(has_skip, "CIGAR should contain Skip for intron");
818        }
819    }
820
821    #[test]
822    fn cigar_has_skip() {
823        // Construct a reference with a clear GT-AG intron
824        let mut reference = Vec::new();
825        reference.extend_from_slice(b"ACGT"); // exon 1
826        reference.push(b'G');
827        reference.push(b'T');
828        for _ in 0..28 {
829            reference.push(b'X');
830        }
831        reference.push(b'A');
832        reference.push(b'G');
833        reference.extend_from_slice(b"ACGT"); // exon 2
834
835        let query = b"ACGTACGT";
836        let params = SplicedAlignParams {
837            min_intron_len: 30,
838            ..Default::default()
839        };
840        let result = spliced_align(query, &reference, &dna_scheme(), &params).unwrap();
841
842        // The spliced alignment should find this
843        if result.intron_count > 0 {
844            let skip_ops: Vec<_> = result
845                .alignment
846                .cigar
847                .iter()
848                .filter(|op| matches!(op, CigarOp::Skip(_)))
849                .collect();
850            assert!(!skip_ops.is_empty());
851        }
852    }
853
854    #[test]
855    fn min_intron_enforced() {
856        // Intron too short (< min_intron_len) should not be used
857        let mut reference = Vec::new();
858        reference.extend_from_slice(b"ACGT");
859        reference.extend_from_slice(b"GT"); // donor
860        for _ in 0..5 {
861            reference.push(b'N');
862        }
863        reference.extend_from_slice(b"AG"); // acceptor
864        reference.extend_from_slice(b"ACGT");
865        // Intron = 9 bases, less than default min_intron_len=30
866
867        let query = b"ACGTACGT";
868        let result = spliced_align(
869            query,
870            &reference,
871            &dna_scheme(),
872            &SplicedAlignParams::default(),
873        )
874        .unwrap();
875        assert_eq!(result.intron_count, 0, "short intron should not be used");
876    }
877
878    #[test]
879    fn empty_error() {
880        let result = spliced_align(b"", b"ACGT", &dna_scheme(), &SplicedAlignParams::default());
881        assert!(result.is_err());
882
883        let result = spliced_align(b"ACGT", b"", &dna_scheme(), &SplicedAlignParams::default());
884        assert!(result.is_err());
885    }
886
887    // --- Exon chaining ---
888
889    #[test]
890    fn chain_two_exons() {
891        let mut reference = Vec::new();
892        reference.extend_from_slice(b"ACGT"); // 0..4
893        reference.extend_from_slice(b"GT"); // 4..6, donor
894        for _ in 0..28 {
895            reference.push(b'N');
896        } // 6..34
897        reference.extend_from_slice(b"AG"); // 34..36, acceptor
898        reference.extend_from_slice(b"TGCA"); // 36..40
899
900        let exons = vec![
901            ExonAlignment {
902                query_start: 0,
903                query_end: 4,
904                target_start: 0,
905                target_end: 4,
906                score: 8,
907                cigar: vec![CigarOp::Match(4)],
908            },
909            ExonAlignment {
910                query_start: 4,
911                query_end: 8,
912                target_start: 36,
913                target_end: 40,
914                score: 8,
915                cigar: vec![CigarOp::Match(4)],
916            },
917        ];
918
919        let params = SplicedAlignParams {
920            min_intron_len: 30,
921            ..Default::default()
922        };
923        let result = chain_exons(&exons, &reference, &params).unwrap();
924        assert_eq!(result.exons.len(), 2);
925        assert_eq!(result.intron_count, 1);
926
927        // Check junction
928        assert_eq!(result.junctions[0].0, 4); // intron start
929        assert_eq!(result.junctions[0].1, 36); // intron end
930    }
931
932    #[test]
933    fn chain_three_exons() {
934        // Create a reference with two introns
935        let mut reference = vec![0u8; 120];
936        // Exon 1: 0..10
937        // Intron 1: 10..50 (40 bp) with GT..AG
938        reference[10] = b'G';
939        reference[11] = b'T';
940        reference[48] = b'A';
941        reference[49] = b'G';
942        // Exon 2: 50..60
943        // Intron 2: 60..100 (40 bp) with GT..AG
944        reference[60] = b'G';
945        reference[61] = b'T';
946        reference[98] = b'A';
947        reference[99] = b'G';
948        // Exon 3: 100..110
949
950        let exons = vec![
951            ExonAlignment {
952                query_start: 0,
953                query_end: 10,
954                target_start: 0,
955                target_end: 10,
956                score: 20,
957                cigar: vec![CigarOp::Match(10)],
958            },
959            ExonAlignment {
960                query_start: 10,
961                query_end: 20,
962                target_start: 50,
963                target_end: 60,
964                score: 20,
965                cigar: vec![CigarOp::Match(10)],
966            },
967            ExonAlignment {
968                query_start: 20,
969                query_end: 30,
970                target_start: 100,
971                target_end: 110,
972                score: 20,
973                cigar: vec![CigarOp::Match(10)],
974            },
975        ];
976
977        let result = chain_exons(&exons, &reference, &SplicedAlignParams::default()).unwrap();
978        assert_eq!(result.exons.len(), 3);
979        assert_eq!(result.intron_count, 2);
980    }
981
982    #[test]
983    fn chain_colinearity() {
984        // Exons that violate query colinearity should not be chained
985        let reference = vec![b'N'; 200];
986        let exons = vec![
987            ExonAlignment {
988                query_start: 10,
989                query_end: 20,
990                target_start: 0,
991                target_end: 10,
992                score: 20,
993                cigar: vec![CigarOp::Match(10)],
994            },
995            ExonAlignment {
996                query_start: 5, // overlaps with first exon on query!
997                query_end: 15,
998                target_start: 50,
999                target_end: 60,
1000                score: 20,
1001                cigar: vec![CigarOp::Match(10)],
1002            },
1003        ];
1004
1005        let result = chain_exons(&exons, &reference, &SplicedAlignParams::default()).unwrap();
1006        // Should only chain one exon since they overlap on query
1007        assert_eq!(result.exons.len(), 1);
1008    }
1009
1010    #[test]
1011    fn chain_empty_error() {
1012        let result = chain_exons(&[], b"ACGT", &SplicedAlignParams::default());
1013        assert!(result.is_err());
1014    }
1015
1016    #[test]
1017    fn chain_splice_bonus() {
1018        // Verify canonical bonus affects scoring
1019        let mut reference = vec![b'N'; 100];
1020        reference[10] = b'G';
1021        reference[11] = b'T'; // donor
1022        reference[48] = b'A';
1023        reference[49] = b'G'; // acceptor
1024
1025        let exons = vec![
1026            ExonAlignment {
1027                query_start: 0,
1028                query_end: 10,
1029                target_start: 0,
1030                target_end: 10,
1031                score: 20,
1032                cigar: vec![CigarOp::Match(10)],
1033            },
1034            ExonAlignment {
1035                query_start: 10,
1036                query_end: 20,
1037                target_start: 50,
1038                target_end: 60,
1039                score: 20,
1040                cigar: vec![CigarOp::Match(10)],
1041            },
1042        ];
1043
1044        let result = chain_exons(&exons, &reference, &SplicedAlignParams::default()).unwrap();
1045        // Score = 20 + splice_penalty(-15) + canonical_bonus(8) + 20 = 33
1046        assert_eq!(result.alignment.score, 33);
1047        assert_eq!(result.junctions[0].2, SpliceSiteType::GtAg);
1048    }
1049
1050    #[test]
1051    fn exon_coordinates() {
1052        let exons = vec![ExonAlignment {
1053            query_start: 5,
1054            query_end: 15,
1055            target_start: 100,
1056            target_end: 110,
1057            score: 20,
1058            cigar: vec![CigarOp::Match(10)],
1059        }];
1060
1061        let reference = vec![b'N'; 200];
1062        let result = chain_exons(&exons, &reference, &SplicedAlignParams::default()).unwrap();
1063        assert_eq!(result.alignment.query_start, 5);
1064        assert_eq!(result.alignment.query_end, 15);
1065        assert_eq!(result.alignment.target_start, 100);
1066        assert_eq!(result.alignment.target_end, 110);
1067    }
1068}
1069
1070#[cfg(test)]
1071mod proptests {
1072    use super::*;
1073    use crate::scoring::ScoringMatrix;
1074    use proptest::prelude::*;
1075
1076    fn dna_scheme() -> ScoringScheme {
1077        ScoringScheme::Simple(ScoringMatrix::dna_default())
1078    }
1079
1080    fn dna_seq(max_len: usize) -> impl Strategy<Value = Vec<u8>> {
1081        proptest::collection::vec(
1082            prop_oneof![Just(b'A'), Just(b'C'), Just(b'G'), Just(b'T')],
1083            1..=max_len,
1084        )
1085    }
1086
1087    proptest! {
1088        #[test]
1089        fn spliced_align_deterministic(q in dna_seq(20), t in dna_seq(40)) {
1090            let r1 = spliced_align(&q, &t, &dna_scheme(), &SplicedAlignParams::default()).unwrap();
1091            let r2 = spliced_align(&q, &t, &dna_scheme(), &SplicedAlignParams::default()).unwrap();
1092            prop_assert_eq!(r1.alignment.score, r2.alignment.score);
1093        }
1094    }
1095}