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| {
196                matches!(
197                    op,
198                    CigarOp::Match(_)
199                        | CigarOp::Mismatch(_)
200                        | CigarOp::Insertion(_)
201                        | CigarOp::Deletion(_)
202                        | CigarOp::AlnMatch(_)
203                )
204            })
205            .map(|op| op.len())
206            .sum()
207    }
208}
209
210impl cyanea_core::Scored for AlignmentResult {
211    fn score(&self) -> f64 {
212        self.score as f64
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn cigar_string_formatting() {
222        let result = AlignmentResult {
223            score: 10,
224            aligned_query: b"ACGT".to_vec(),
225            aligned_target: b"ACGT".to_vec(),
226            query_start: 0,
227            query_end: 4,
228            target_start: 0,
229            target_end: 4,
230            cigar: vec![CigarOp::Match(4)],
231        };
232        assert_eq!(result.cigar_string(), "4=");
233    }
234
235    #[test]
236    fn cigar_string_mixed_ops() {
237        let result = AlignmentResult {
238            score: 5,
239            aligned_query: Vec::new(),
240            aligned_target: Vec::new(),
241            query_start: 0,
242            query_end: 0,
243            target_start: 0,
244            target_end: 0,
245            cigar: vec![
246                CigarOp::Match(3),
247                CigarOp::Insertion(1),
248                CigarOp::Match(2),
249                CigarOp::Deletion(1),
250                CigarOp::Mismatch(1),
251            ],
252        };
253        assert_eq!(result.cigar_string(), "3=1I2=1D1X");
254    }
255
256    #[test]
257    fn identity_perfect_match() {
258        let result = AlignmentResult {
259            score: 8,
260            aligned_query: b"ACGT".to_vec(),
261            aligned_target: b"ACGT".to_vec(),
262            query_start: 0,
263            query_end: 4,
264            target_start: 0,
265            target_end: 4,
266            cigar: vec![CigarOp::Match(4)],
267        };
268        assert!((result.identity() - 1.0).abs() < f64::EPSILON);
269    }
270
271    #[test]
272    fn identity_with_mismatches_and_gaps() {
273        let result = AlignmentResult {
274            score: 0,
275            aligned_query: Vec::new(),
276            aligned_target: Vec::new(),
277            query_start: 0,
278            query_end: 0,
279            target_start: 0,
280            target_end: 0,
281            cigar: vec![
282                CigarOp::Match(3),
283                CigarOp::Mismatch(1),
284                CigarOp::Insertion(1),
285            ],
286        };
287        assert!((result.identity() - 0.6).abs() < f64::EPSILON);
288    }
289
290    #[test]
291    fn identity_empty_alignment() {
292        let result = AlignmentResult {
293            score: 0,
294            aligned_query: Vec::new(),
295            aligned_target: Vec::new(),
296            query_start: 0,
297            query_end: 0,
298            target_start: 0,
299            target_end: 0,
300            cigar: vec![],
301        };
302        assert!((result.identity() - 0.0).abs() < f64::EPSILON);
303    }
304
305    #[test]
306    fn gap_count() {
307        let result = AlignmentResult {
308            score: 0,
309            aligned_query: Vec::new(),
310            aligned_target: Vec::new(),
311            query_start: 0,
312            query_end: 0,
313            target_start: 0,
314            target_end: 0,
315            cigar: vec![
316                CigarOp::Match(2),
317                CigarOp::Insertion(3),
318                CigarOp::Match(1),
319                CigarOp::Deletion(2),
320            ],
321        };
322        assert_eq!(result.gaps(), 5);
323        assert_eq!(result.matches(), 3);
324        assert_eq!(result.length(), 8);
325    }
326
327    #[test]
328    fn scored_trait() {
329        use cyanea_core::Scored;
330        let result = AlignmentResult {
331            score: 42,
332            aligned_query: Vec::new(),
333            aligned_target: Vec::new(),
334            query_start: 0,
335            query_end: 0,
336            target_start: 0,
337            target_end: 0,
338            cigar: vec![],
339        };
340        assert!((result.score() - 42.0).abs() < f64::EPSILON);
341    }
342
343    #[test]
344    fn cigar_op_display() {
345        assert_eq!(format!("{}", CigarOp::Match(5)), "5=");
346        assert_eq!(format!("{}", CigarOp::Mismatch(2)), "2X");
347        assert_eq!(format!("{}", CigarOp::Insertion(1)), "1I");
348        assert_eq!(format!("{}", CigarOp::Deletion(3)), "3D");
349        assert_eq!(format!("{}", CigarOp::AlnMatch(10)), "10M");
350        assert_eq!(format!("{}", CigarOp::Skip(100)), "100N");
351        assert_eq!(format!("{}", CigarOp::SoftClip(4)), "4S");
352        assert_eq!(format!("{}", CigarOp::HardClip(2)), "2H");
353        assert_eq!(format!("{}", CigarOp::Padding(1)), "1P");
354    }
355
356    #[test]
357    fn consumes_reference_and_query() {
358        assert!(CigarOp::Match(1).consumes_reference());
359        assert!(CigarOp::Match(1).consumes_query());
360        assert!(CigarOp::Mismatch(1).consumes_reference());
361        assert!(CigarOp::Mismatch(1).consumes_query());
362        assert!(!CigarOp::Insertion(1).consumes_reference());
363        assert!(CigarOp::Insertion(1).consumes_query());
364        assert!(CigarOp::Deletion(1).consumes_reference());
365        assert!(!CigarOp::Deletion(1).consumes_query());
366        assert!(CigarOp::AlnMatch(1).consumes_reference());
367        assert!(CigarOp::AlnMatch(1).consumes_query());
368        assert!(CigarOp::Skip(1).consumes_reference());
369        assert!(!CigarOp::Skip(1).consumes_query());
370        assert!(!CigarOp::SoftClip(1).consumes_reference());
371        assert!(CigarOp::SoftClip(1).consumes_query());
372        assert!(!CigarOp::HardClip(1).consumes_reference());
373        assert!(!CigarOp::HardClip(1).consumes_query());
374        assert!(!CigarOp::Padding(1).consumes_reference());
375        assert!(!CigarOp::Padding(1).consumes_query());
376    }
377}