deepbiop_bam/features/
mod.rs1use ahash::HashMap;
4use anyhow::{Context, Result};
5use noodles::sam;
6use noodles::sam::alignment::record::Cigar;
7
8#[derive(Debug, Clone)]
10pub struct AlignmentFeatures {
11 pub mapping_quality: u8,
13
14 pub is_mapped: bool,
16
17 pub is_paired: bool,
19
20 pub is_supplementary: bool,
22
23 pub is_secondary: bool,
25
26 pub is_mate_mapped: Option<bool>,
28
29 pub template_length: i32,
31
32 pub aligned_length: usize,
34
35 pub num_matches: usize,
37
38 pub num_insertions: usize,
40
41 pub num_deletions: usize,
43
44 pub num_soft_clips: usize,
46
47 pub num_hard_clips: usize,
49
50 pub edit_distance: Option<u32>,
52
53 pub tags: HashMap<String, String>,
55}
56
57impl AlignmentFeatures {
58 pub fn from_record(record: &impl sam::alignment::Record) -> Result<Self> {
74 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 let is_mate_mapped = if is_paired {
83 Some(!flags.is_mate_unmapped())
84 } else {
85 None
86 };
87
88 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 let template_length = record.template_length()?;
99
100 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 let edit_distance = Self::extract_edit_distance(record);
112
113 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 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 }
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 fn extract_edit_distance(record: &impl sam::alignment::Record) -> Option<u32> {
192 let data = record.data();
194
195 for (tag, value) in data.iter().flatten() {
197 if tag.as_ref() == b"NM" {
198 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 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 let value_str = format!("{:?}", value);
225 tags.insert(tag_str, value_str);
226 }
227
228 tags
229 }
230
231 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 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 pub fn is_high_quality(&self, min_quality: u8) -> bool {
251 self.is_mapped && self.mapping_quality >= min_quality
252 }
253
254 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}