Skip to main content

deepbiop_bam/features/
mod.rs

1//! Feature extraction from BAM alignment records for machine learning
2
3use ahash::HashMap;
4use anyhow::{Context, Result};
5use noodles::sam;
6use noodles::sam::alignment::record::Cigar;
7
8/// Features extracted from an alignment record for ML analysis
9#[derive(Debug, Clone)]
10pub struct AlignmentFeatures {
11    /// Mapping quality score (0-255, 0=unmapped, 255=highest quality)
12    pub mapping_quality: u8,
13
14    /// Is the read mapped to the reference?
15    pub is_mapped: bool,
16
17    /// Is this read part of a paired-end sequencing run?
18    pub is_paired: bool,
19
20    /// Is this a supplementary alignment?
21    pub is_supplementary: bool,
22
23    /// Is this a secondary alignment?
24    pub is_secondary: bool,
25
26    /// Is the mate read mapped (for paired reads)?
27    pub is_mate_mapped: Option<bool>,
28
29    /// Template length (insert size for paired reads)
30    pub template_length: i32,
31
32    /// Number of aligned bases (from CIGAR)
33    pub aligned_length: usize,
34
35    /// Number of matches (M operations in CIGAR)
36    pub num_matches: usize,
37
38    /// Number of insertions (I operations in CIGAR)
39    pub num_insertions: usize,
40
41    /// Number of deletions (D operations in CIGAR)
42    pub num_deletions: usize,
43
44    /// Number of soft clips (S operations in CIGAR)
45    pub num_soft_clips: usize,
46
47    /// Number of hard clips (H operations in CIGAR)
48    pub num_hard_clips: usize,
49
50    /// Edit distance to reference (from NM tag if present)
51    pub edit_distance: Option<u32>,
52
53    /// Additional SAM tags
54    pub tags: HashMap<String, String>,
55}
56
57impl AlignmentFeatures {
58    /// Extract features from a SAM/BAM record
59    ///
60    /// # Example
61    ///
62    /// ```no_run
63    /// use deepbiop_bam::features::AlignmentFeatures;
64    /// use noodles::bam;
65    ///
66    /// # fn example(record: &bam::Record) -> anyhow::Result<()> {
67    /// let features = AlignmentFeatures::from_record(record)?;
68    /// println!("Mapping quality: {}", features.mapping_quality);
69    /// println!("Is mapped: {}", features.is_mapped);
70    /// # Ok(())
71    /// # }
72    /// ```
73    pub fn from_record(record: &impl sam::alignment::Record) -> Result<Self> {
74        // Extract flags
75        let flags = record.flags()?;
76        let is_mapped = !flags.is_unmapped();
77        let is_paired = flags.is_segmented();
78        let is_supplementary = flags.is_supplementary();
79        let is_secondary = flags.is_secondary();
80
81        // Mate mapping status (only for paired reads)
82        let is_mate_mapped = if is_paired {
83            Some(!flags.is_mate_unmapped())
84        } else {
85            None
86        };
87
88        // Mapping quality
89        let mapping_quality = match record.mapping_quality() {
90            Some(mq_result) => {
91                let mq = mq_result.context("Failed to read mapping quality")?;
92                u8::from(mq)
93            }
94            None => 0,
95        };
96
97        // Template length
98        let template_length = record.template_length()?;
99
100        // Parse CIGAR to extract alignment statistics
101        let (
102            aligned_length,
103            num_matches,
104            num_insertions,
105            num_deletions,
106            num_soft_clips,
107            num_hard_clips,
108        ) = Self::parse_cigar(record)?;
109
110        // Extract edit distance from NM tag
111        let edit_distance = Self::extract_edit_distance(record);
112
113        // Extract additional tags as strings
114        let tags = Self::extract_tags(record);
115
116        Ok(Self {
117            mapping_quality,
118            is_mapped,
119            is_paired,
120            is_supplementary,
121            is_secondary,
122            is_mate_mapped,
123            template_length,
124            aligned_length,
125            num_matches,
126            num_insertions,
127            num_deletions,
128            num_soft_clips,
129            num_hard_clips,
130            edit_distance,
131            tags,
132        })
133    }
134
135    /// Parse CIGAR string to extract alignment statistics
136    fn parse_cigar(
137        record: &impl sam::alignment::Record,
138    ) -> Result<(usize, usize, usize, usize, usize, usize)> {
139        let cigar = record.cigar();
140
141        let mut aligned_length = 0;
142        let mut num_matches = 0;
143        let mut num_insertions = 0;
144        let mut num_deletions = 0;
145        let mut num_soft_clips = 0;
146        let mut num_hard_clips = 0;
147
148        for result in cigar.iter() {
149            let op = result.context("Failed to parse CIGAR operation")?;
150            let len = op.len();
151
152            use noodles::sam::alignment::record::cigar::op::Kind;
153            match op.kind() {
154                Kind::Match | Kind::SequenceMatch | Kind::SequenceMismatch => {
155                    num_matches += len;
156                    aligned_length += len;
157                }
158                Kind::Insertion => {
159                    num_insertions += len;
160                }
161                Kind::Deletion => {
162                    num_deletions += len;
163                    aligned_length += len;
164                }
165                Kind::SoftClip => {
166                    num_soft_clips += len;
167                }
168                Kind::HardClip => {
169                    num_hard_clips += len;
170                }
171                Kind::Skip => {
172                    aligned_length += len;
173                }
174                Kind::Pad => {
175                    // Padding doesn't consume reference or query
176                }
177            }
178        }
179
180        Ok((
181            aligned_length,
182            num_matches,
183            num_insertions,
184            num_deletions,
185            num_soft_clips,
186            num_hard_clips,
187        ))
188    }
189
190    /// Extract edit distance from NM tag
191    fn extract_edit_distance(record: &impl sam::alignment::Record) -> Option<u32> {
192        // Try to get NM tag (edit distance)
193        let data = record.data();
194
195        // Iterate through tags to find NM
196        for (tag, value) in data.iter().flatten() {
197            if tag.as_ref() == b"NM" {
198                // Try to extract integer value from Value enum
199                // Value types can be Int8, UInt8, Int16, etc.
200                use noodles::sam::alignment::record::data::field::Value;
201                match value {
202                    Value::Int8(n) => return Some(n as u32),
203                    Value::UInt8(n) => return Some(n as u32),
204                    Value::Int16(n) => return Some(n as u32),
205                    Value::UInt16(n) => return Some(n as u32),
206                    Value::Int32(n) => return Some(n as u32),
207                    Value::UInt32(n) => return Some(n),
208                    _ => {}
209                }
210            }
211        }
212
213        None
214    }
215
216    /// Extract SAM tags as string map
217    fn extract_tags(record: &impl sam::alignment::Record) -> HashMap<String, String> {
218        let mut tags = HashMap::default();
219        let data = record.data();
220
221        for (tag, value) in data.iter().flatten() {
222            let tag_str = String::from_utf8_lossy(tag.as_ref()).to_string();
223            // Convert Value enum to string representation
224            let value_str = format!("{:?}", value);
225            tags.insert(tag_str, value_str);
226        }
227
228        tags
229    }
230
231    /// Calculate alignment identity (matches / aligned_length)
232    pub fn identity(&self) -> f32 {
233        if self.aligned_length == 0 {
234            0.0
235        } else {
236            self.num_matches as f32 / self.aligned_length as f32
237        }
238    }
239
240    /// Calculate indel rate ((insertions + deletions) / aligned_length)
241    pub fn indel_rate(&self) -> f32 {
242        if self.aligned_length == 0 {
243            0.0
244        } else {
245            (self.num_insertions + self.num_deletions) as f32 / self.aligned_length as f32
246        }
247    }
248
249    /// Check if this is a high-quality alignment (mapping quality >= threshold)
250    pub fn is_high_quality(&self, min_quality: u8) -> bool {
251        self.is_mapped && self.mapping_quality >= min_quality
252    }
253
254    /// Check if this is a proper pair (both mates mapped, reasonable insert size)
255    pub fn is_proper_pair(&self, max_insert_size: i32) -> bool {
256        self.is_paired
257            && self.is_mapped
258            && self.is_mate_mapped.unwrap_or(false)
259            && self.template_length.abs() <= max_insert_size
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn test_alignment_features_calculations() {
269        let features = AlignmentFeatures {
270            mapping_quality: 60,
271            is_mapped: true,
272            is_paired: true,
273            is_supplementary: false,
274            is_secondary: false,
275            is_mate_mapped: Some(true),
276            template_length: 300,
277            aligned_length: 100,
278            num_matches: 95,
279            num_insertions: 2,
280            num_deletions: 3,
281            num_soft_clips: 5,
282            num_hard_clips: 0,
283            edit_distance: Some(5),
284            tags: HashMap::default(),
285        };
286
287        assert_eq!(features.identity(), 0.95);
288        assert_eq!(features.indel_rate(), 0.05);
289        assert!(features.is_high_quality(30));
290        assert!(features.is_proper_pair(500));
291    }
292}