Skip to main content

cyanea_align/
types.rs

1//! Core types for sequence alignment results.
2
3use core::fmt;
4
5/// The alignment strategy to use.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum AlignmentMode {
9    /// Local alignment (Smith-Waterman) — finds the best-scoring local region.
10    Local,
11    /// Global alignment (Needleman-Wunsch) — aligns sequences end-to-end.
12    Global,
13    /// Semi-global alignment — one sequence aligned end-to-end, the other locally.
14    SemiGlobal,
15}
16
17/// A single CIGAR operation describing how aligned sequences relate.
18///
19/// The four core variants (`Match`/`=`, `Mismatch`/`X`, `Insertion`/`I`,
20/// `Deletion`/`D`) are produced by alignment algorithms. The five SAM-spec
21/// variants (`AlnMatch`/`M`, `Skip`/`N`, `SoftClip`/`S`, `HardClip`/`H`,
22/// `Padding`/`P`) support round-tripping SAM/BAM CIGAR strings.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25pub enum CigarOp {
26    /// Matching bases (identical in query and target). SAM op `=`.
27    Match(usize),
28    /// Mismatching bases (different in query and target). SAM op `X`.
29    Mismatch(usize),
30    /// Insertion in the query (gap in target). SAM op `I`.
31    Insertion(usize),
32    /// Deletion from the query (gap in query). SAM op `D`.
33    Deletion(usize),
34    /// Alignment match — may be match or mismatch (ambiguous). SAM op `M`.
35    AlnMatch(usize),
36    /// Skipped region on the reference (e.g. intron in RNA-seq). SAM op `N`.
37    Skip(usize),
38    /// Soft clipping — bases present in SEQ but not aligned. SAM op `S`.
39    SoftClip(usize),
40    /// Hard clipping — bases NOT present in SEQ. SAM op `H`.
41    HardClip(usize),
42    /// Silent deletion from padded reference. SAM op `P`.
43    Padding(usize),
44}
45
46impl CigarOp {
47    /// Single-character SAM CIGAR code.
48    pub fn code(&self) -> char {
49        match self {
50            CigarOp::Match(_) => '=',
51            CigarOp::Mismatch(_) => 'X',
52            CigarOp::Insertion(_) => 'I',
53            CigarOp::Deletion(_) => 'D',
54            CigarOp::AlnMatch(_) => 'M',
55            CigarOp::Skip(_) => 'N',
56            CigarOp::SoftClip(_) => 'S',
57            CigarOp::HardClip(_) => 'H',
58            CigarOp::Padding(_) => 'P',
59        }
60    }
61
62    /// Number of positions consumed by this operation.
63    pub fn len(&self) -> usize {
64        match self {
65            CigarOp::Match(n)
66            | CigarOp::Mismatch(n)
67            | CigarOp::Insertion(n)
68            | CigarOp::Deletion(n)
69            | CigarOp::AlnMatch(n)
70            | CigarOp::Skip(n)
71            | CigarOp::SoftClip(n)
72            | CigarOp::HardClip(n)
73            | CigarOp::Padding(n) => *n,
74        }
75    }
76
77    /// Whether this operation has zero length.
78    pub fn is_empty(&self) -> bool {
79        self.len() == 0
80    }
81
82    /// Whether this operation consumes bases on the reference.
83    pub fn consumes_reference(&self) -> bool {
84        matches!(
85            self,
86            CigarOp::Match(_)
87                | CigarOp::Mismatch(_)
88                | CigarOp::Deletion(_)
89                | CigarOp::AlnMatch(_)
90                | CigarOp::Skip(_)
91        )
92    }
93
94    /// Whether this operation consumes bases on the query.
95    pub fn consumes_query(&self) -> bool {
96        matches!(
97            self,
98            CigarOp::Match(_)
99                | CigarOp::Mismatch(_)
100                | CigarOp::Insertion(_)
101                | CigarOp::AlnMatch(_)
102                | CigarOp::SoftClip(_)
103        )
104    }
105}
106
107impl fmt::Display for CigarOp {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        write!(f, "{}{}", self.len(), self.code())
110    }
111}
112
113/// The result of a pairwise sequence alignment.
114#[derive(Debug, Clone)]
115#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
116pub struct AlignmentResult {
117    /// Alignment score.
118    pub score: i32,
119    /// Aligned query sequence (with `-` for gaps).
120    pub aligned_query: Vec<u8>,
121    /// Aligned target sequence (with `-` for gaps).
122    pub aligned_target: Vec<u8>,
123    /// Start position in the original query (0-based, inclusive).
124    pub query_start: usize,
125    /// End position in the original query (0-based, exclusive).
126    pub query_end: usize,
127    /// Start position in the original target (0-based, inclusive).
128    pub target_start: usize,
129    /// End position in the original target (0-based, exclusive).
130    pub target_end: usize,
131    /// CIGAR operations describing the alignment.
132    pub cigar: Vec<CigarOp>,
133}
134
135impl AlignmentResult {
136    /// Format the CIGAR vector as a compact string, e.g. `"4=1I3="`.
137    pub fn cigar_string(&self) -> String {
138        let mut s = String::new();
139        for op in &self.cigar {
140            s.push_str(&format!("{}{}", op.len(), op.code()));
141        }
142        s
143    }
144
145    /// Fraction of aligned columns that are exact matches, in `[0.0, 1.0]`.
146    ///
147    /// Returns 0.0 if the alignment is empty.
148    pub fn identity(&self) -> f64 {
149        let total = self.length();
150        if total == 0 {
151            return 0.0;
152        }
153        self.matches() as f64 / total as f64
154    }
155
156    /// Number of matching positions.
157    pub fn matches(&self) -> usize {
158        self.cigar
159            .iter()
160            .filter_map(|op| match op {
161                CigarOp::Match(n) => Some(n),
162                _ => None,
163            })
164            .sum()
165    }
166
167    /// Number of mismatching positions.
168    pub fn mismatches(&self) -> usize {
169        self.cigar
170            .iter()
171            .filter_map(|op| match op {
172                CigarOp::Mismatch(n) => Some(n),
173                _ => None,
174            })
175            .sum()
176    }
177
178    /// Number of gap positions (insertions + deletions).
179    pub fn gaps(&self) -> usize {
180        self.cigar
181            .iter()
182            .filter_map(|op| match op {
183                CigarOp::Insertion(n) | CigarOp::Deletion(n) => Some(n),
184                _ => None,
185            })
186            .sum()
187    }
188
189    /// Total length of the alignment (M, =, X, I, D columns).
190    ///
191    /// Excludes soft/hard clips, skips, and padding.
192    pub fn length(&self) -> usize {
193        self.cigar
194            .iter()
195            .filter(|op| matches!(
196                op,
197                CigarOp::Match(_)
198                    | CigarOp::Mismatch(_)
199                    | CigarOp::Insertion(_)
200                    | CigarOp::Deletion(_)
201                    | CigarOp::AlnMatch(_)
202            ))
203            .map(|op| op.len())
204            .sum()
205    }
206}
207
208impl cyanea_core::Scored for AlignmentResult {
209    fn score(&self) -> f64 {
210        self.score as f64
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn cigar_string_formatting() {
220        let result = AlignmentResult {
221            score: 10,
222            aligned_query: b"ACGT".to_vec(),
223            aligned_target: b"ACGT".to_vec(),
224            query_start: 0,
225            query_end: 4,
226            target_start: 0,
227            target_end: 4,
228            cigar: vec![CigarOp::Match(4)],
229        };
230        assert_eq!(result.cigar_string(), "4=");
231    }
232
233    #[test]
234    fn cigar_string_mixed_ops() {
235        let result = AlignmentResult {
236            score: 5,
237            aligned_query: Vec::new(),
238            aligned_target: Vec::new(),
239            query_start: 0,
240            query_end: 0,
241            target_start: 0,
242            target_end: 0,
243            cigar: vec![
244                CigarOp::Match(3),
245                CigarOp::Insertion(1),
246                CigarOp::Match(2),
247                CigarOp::Deletion(1),
248                CigarOp::Mismatch(1),
249            ],
250        };
251        assert_eq!(result.cigar_string(), "3=1I2=1D1X");
252    }
253
254    #[test]
255    fn identity_perfect_match() {
256        let result = AlignmentResult {
257            score: 8,
258            aligned_query: b"ACGT".to_vec(),
259            aligned_target: b"ACGT".to_vec(),
260            query_start: 0,
261            query_end: 4,
262            target_start: 0,
263            target_end: 4,
264            cigar: vec![CigarOp::Match(4)],
265        };
266        assert!((result.identity() - 1.0).abs() < f64::EPSILON);
267    }
268
269    #[test]
270    fn identity_with_mismatches_and_gaps() {
271        let result = AlignmentResult {
272            score: 0,
273            aligned_query: Vec::new(),
274            aligned_target: Vec::new(),
275            query_start: 0,
276            query_end: 0,
277            target_start: 0,
278            target_end: 0,
279            cigar: vec![
280                CigarOp::Match(3),
281                CigarOp::Mismatch(1),
282                CigarOp::Insertion(1),
283            ],
284        };
285        assert!((result.identity() - 0.6).abs() < f64::EPSILON);
286    }
287
288    #[test]
289    fn identity_empty_alignment() {
290        let result = AlignmentResult {
291            score: 0,
292            aligned_query: Vec::new(),
293            aligned_target: Vec::new(),
294            query_start: 0,
295            query_end: 0,
296            target_start: 0,
297            target_end: 0,
298            cigar: vec![],
299        };
300        assert!((result.identity() - 0.0).abs() < f64::EPSILON);
301    }
302
303    #[test]
304    fn gap_count() {
305        let result = AlignmentResult {
306            score: 0,
307            aligned_query: Vec::new(),
308            aligned_target: Vec::new(),
309            query_start: 0,
310            query_end: 0,
311            target_start: 0,
312            target_end: 0,
313            cigar: vec![
314                CigarOp::Match(2),
315                CigarOp::Insertion(3),
316                CigarOp::Match(1),
317                CigarOp::Deletion(2),
318            ],
319        };
320        assert_eq!(result.gaps(), 5);
321        assert_eq!(result.matches(), 3);
322        assert_eq!(result.length(), 8);
323    }
324
325    #[test]
326    fn scored_trait() {
327        use cyanea_core::Scored;
328        let result = AlignmentResult {
329            score: 42,
330            aligned_query: Vec::new(),
331            aligned_target: Vec::new(),
332            query_start: 0,
333            query_end: 0,
334            target_start: 0,
335            target_end: 0,
336            cigar: vec![],
337        };
338        assert!((result.score() - 42.0).abs() < f64::EPSILON);
339    }
340
341    #[test]
342    fn cigar_op_display() {
343        assert_eq!(format!("{}", CigarOp::Match(5)), "5=");
344        assert_eq!(format!("{}", CigarOp::Mismatch(2)), "2X");
345        assert_eq!(format!("{}", CigarOp::Insertion(1)), "1I");
346        assert_eq!(format!("{}", CigarOp::Deletion(3)), "3D");
347        assert_eq!(format!("{}", CigarOp::AlnMatch(10)), "10M");
348        assert_eq!(format!("{}", CigarOp::Skip(100)), "100N");
349        assert_eq!(format!("{}", CigarOp::SoftClip(4)), "4S");
350        assert_eq!(format!("{}", CigarOp::HardClip(2)), "2H");
351        assert_eq!(format!("{}", CigarOp::Padding(1)), "1P");
352    }
353
354    #[test]
355    fn consumes_reference_and_query() {
356        assert!(CigarOp::Match(1).consumes_reference());
357        assert!(CigarOp::Match(1).consumes_query());
358        assert!(CigarOp::Mismatch(1).consumes_reference());
359        assert!(CigarOp::Mismatch(1).consumes_query());
360        assert!(!CigarOp::Insertion(1).consumes_reference());
361        assert!(CigarOp::Insertion(1).consumes_query());
362        assert!(CigarOp::Deletion(1).consumes_reference());
363        assert!(!CigarOp::Deletion(1).consumes_query());
364        assert!(CigarOp::AlnMatch(1).consumes_reference());
365        assert!(CigarOp::AlnMatch(1).consumes_query());
366        assert!(CigarOp::Skip(1).consumes_reference());
367        assert!(!CigarOp::Skip(1).consumes_query());
368        assert!(!CigarOp::SoftClip(1).consumes_reference());
369        assert!(CigarOp::SoftClip(1).consumes_query());
370        assert!(!CigarOp::HardClip(1).consumes_reference());
371        assert!(!CigarOp::HardClip(1).consumes_query());
372        assert!(!CigarOp::Padding(1).consumes_reference());
373        assert!(!CigarOp::Padding(1).consumes_query());
374    }
375}