nanalogue 0.1.9

BAM/Mod BAM parsing and analysis tool with a single-molecule focus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! # Gets information on one read id
//!
//! This module retrieves information about reads
//! from a BAM file and converts it into a JSON.
use crate::{CurrRead, Error, InputMods, OptionalTag, ThresholdState};
use rust_htslib::bam;
use std::iter;
use std::rc::Rc;

/// Gets information on reads and prints it to standard output
/// in a JSON format.
///
/// # Errors
/// Returns an error if BAM record reading, parsing, or writing to output fails.
#[expect(clippy::missing_panics_doc, reason = "no error expected here")]
pub fn run<W, D>(
    handle: &mut W,
    bam_records: D,
    mut mods: InputMods<OptionalTag>,
    detailed: Option<bool>,
) -> Result<(), Error>
where
    W: std::io::Write,
    D: IntoIterator<Item = Result<Rc<bam::Record>, rust_htslib::errors::Error>>,
{
    // If the detailed options are not set, then we report a simple mod count.
    // For this, we set threshold to 128 i.e. 0.5.
    if detailed.is_none() {
        match mods.mod_prob_filter {
            ref mut v @ ThresholdState::GtEq(w) => *v = ThresholdState::GtEq(u8::max(128, w)),
            ref mut v @ ThresholdState::InvertGtEqLtEq(w) => {
                *v = ThresholdState::Both((128, w));
            }
            ref mut v @ ThresholdState::Both((w, x)) => {
                *v = ThresholdState::Both((u8::max(128, w), x));
            }
        }
    }

    let mut is_first_record_written = vec![false].into_iter().chain(iter::repeat(true));

    write!(handle, "[")?;

    // Go record by record in the BAM file, and print entries
    for k in bam_records {
        let record = k?;

        if is_first_record_written.next().expect("no error") {
            writeln!(handle, ",")?;
        } else {
            writeln!(handle)?;
        }
        let curr_read = CurrRead::default()
            .try_from_only_alignment(&record)?
            .set_mod_data_restricted_options(&record, &mods)?;
        write!(
            handle,
            "{}",
            match detailed {
                None => curr_read.to_string(),
                Some(false) => serde_json::to_string(&curr_read)?,
                Some(true) => serde_json::to_string_pretty(&curr_read)?,
            }
        )?;
    }

    writeln!(handle, "\n]")?;
    Ok(())
}

// Tests follow

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{InputModsBuilder, OrdPair, nanalogue_bam_reader};
    use rust_htslib::bam::Read as _;
    use serde_json::Value;

    #[test]
    fn run_with_example_2_zero_len() -> Result<(), Error> {
        // Collect records and filter out zero-length sequences (like the main program does)
        let mut reader = nanalogue_bam_reader("./examples/example_2_zero_len.sam")?;
        let records: Vec<Result<Rc<bam::Record>, rust_htslib::errors::Error>> = reader
            .rc_records()
            .filter(|r| r.as_ref().map_or(true, |v| v.seq_len() > 0))
            .collect();

        // Gets an output from the function and compares with expected
        let mut output_buffer = Vec::new();
        run(
            &mut output_buffer,
            records.into_iter(),
            InputMods::default(),
            None,
        )?;
        let output_json = String::from_utf8(output_buffer)?;
        let parsed: Value = serde_json::from_str(&output_json)?;
        let expected = serde_json::json!([
            {
                "read_id": "read2",
                "sequence_length": 48,
                "contig": "dummyIII",
                "reference_start": 23,
                "reference_end": 71,
                "alignment_length": 48,
                "alignment_type": "primary_forward",
                "mod_count": "NA"
            }
        ]);
        assert_eq!(parsed, expected);

        Ok(())
    }

    #[test]
    fn run_with_unmapped_filter() -> Result<(), Error> {
        // Collect records and filter to only include unmapped reads (like --read-filter unmapped)
        let mut reader = nanalogue_bam_reader("./examples/example_1.bam")?;
        let records: Vec<Result<Rc<bam::Record>, rust_htslib::errors::Error>> = reader
            .rc_records()
            .filter(|r| r.as_ref().map_or(true, |v| v.flags() == 4))
            .collect();

        // Gets an output from the function and compares with expected
        let mut output_buffer = Vec::new();
        run(
            &mut output_buffer,
            records.into_iter(),
            InputMods::default(),
            None,
        )?;
        let output_json = String::from_utf8(output_buffer)?;
        let parsed: Value = serde_json::from_str(&output_json)?;
        let expected = serde_json::json!([
            {
                "read_id": "a4f36092-b4d5-47a9-813e-c22c3b477a0c",
                "sequence_length": 48,
                "alignment_type": "unmapped",
                "mod_count": "G-7200:0;T+T:3;(probabilities >= 0.5020, PHRED base qual >= 0)"
            }
        ]);
        assert_eq!(parsed, expected);

        Ok(())
    }

    #[test]
    fn run_with_region_filter_dummy_i() -> Result<(), Error> {
        // Collect records and filter to only include those in the dummyI region (like --region dummyI)
        let mut reader = nanalogue_bam_reader("./examples/example_1.bam")?;
        let records: Vec<Result<Rc<bam::Record>, rust_htslib::errors::Error>> = reader
            .rc_records()
            .filter(|r| {
                r.as_ref()
                    .map_or(true, |v| !v.is_unmapped() && v.tid() == 0)
            })
            .collect();

        // Gets an output from the function and compares with expected
        let mut output_buffer = Vec::new();
        run(
            &mut output_buffer,
            records.into_iter(),
            InputMods::default(),
            None,
        )?;
        let output_json = String::from_utf8(output_buffer)?;
        let parsed: Value = serde_json::from_str(&output_json)?;
        let expected = serde_json::json!([
            {
                "read_id": "5d10eb9a-aae1-4db8-8ec6-7ebb34d32575",
                "sequence_length": 8,
                "contig": "dummyI",
                "reference_start": 9,
                "reference_end": 17,
                "alignment_length": 8,
                "alignment_type": "primary_forward",
                "mod_count": "T+T:0;(probabilities >= 0.5020, PHRED base qual >= 0)"
            }
        ]);
        assert_eq!(parsed, expected);

        Ok(())
    }

    /// Helper function to test `example_6.sam` with different `InputMods` configurations
    fn run_example_6_test(
        mod_options: InputMods<OptionalTag>,
        expected: &Value,
    ) -> Result<(), Error> {
        // Collect records from example_6.sam
        let mut reader = nanalogue_bam_reader("./examples/example_6.sam")?;
        let records: Vec<Result<Rc<bam::Record>, rust_htslib::errors::Error>> =
            reader.records().map(|r| r.map(Rc::new)).collect();

        // Gets an output from the function and compares with expected
        let mut output_buffer = Vec::new();
        run(&mut output_buffer, records.into_iter(), mod_options, None)?;
        let output_json = String::from_utf8(output_buffer)?;
        let parsed: Value = serde_json::from_str(&output_json)?;

        assert_eq!(parsed, *expected);
        Ok(())
    }

    #[test]
    fn run_with_example_6() -> Result<(), Error> {
        run_example_6_test(
            InputMods::default(),
            &serde_json::json!([
                {
                    "read_id": "5d10eb9a-aae1-4db8-8ec6-7ebb34d32575",
                    "sequence_length": 8,
                    "contig": "dummyI",
                    "reference_start": 9,
                    "reference_end": 17,
                    "alignment_length": 8,
                    "alignment_type": "primary_forward",
                    "mod_count": "NA"
                },
                {
                    "read_id": "fffffff1-10d2-49cb-8ca3-e8d48979001b",
                    "sequence_length": 33,
                    "contig": "dummyII",
                    "reference_start": 3,
                    "reference_end": 36,
                    "alignment_length": 33,
                    "alignment_type": "primary_reverse",
                    "mod_count": "T+T:1;(probabilities >= 0.5020, PHRED base qual >= 0)"
                }
            ]),
        )
    }

    #[test]
    fn run_with_example_6_aggressive_filtering_1() -> Result<(), Error> {
        let mod_options = InputModsBuilder::<OptionalTag>::default()
            .mod_prob_filter(ThresholdState::GtEq(255))
            .build()?;
        run_example_6_test(
            mod_options,
            &serde_json::json!([
                {
                    "read_id": "5d10eb9a-aae1-4db8-8ec6-7ebb34d32575",
                    "sequence_length": 8,
                    "contig": "dummyI",
                    "reference_start": 9,
                    "reference_end": 17,
                    "alignment_length": 8,
                    "alignment_type": "primary_forward",
                    "mod_count": "NA"
                },
                {
                    "read_id": "fffffff1-10d2-49cb-8ca3-e8d48979001b",
                    "sequence_length": 33,
                    "contig": "dummyII",
                    "reference_start": 3,
                    "reference_end": 36,
                    "alignment_length": 33,
                    "alignment_type": "primary_reverse",
                    "mod_count": "T+T:0;(probabilities >= 1.0000, PHRED base qual >= 0)"
                }
            ]),
        )
    }

    #[test]
    fn run_with_example_6_aggressive_filtering_2() -> Result<(), Error> {
        let mod_options = InputModsBuilder::<OptionalTag>::default()
            .mod_prob_filter(ThresholdState::Both((
                100,
                OrdPair::new(200, 220).expect("no error"),
            )))
            .build()?;
        run_example_6_test(
            mod_options,
            &serde_json::json!([
                {
                    "read_id": "5d10eb9a-aae1-4db8-8ec6-7ebb34d32575",
                    "sequence_length": 8,
                    "contig": "dummyI",
                    "reference_start": 9,
                    "reference_end": 17,
                    "alignment_length": 8,
                    "alignment_type": "primary_forward",
                    "mod_count": "NA"
                },
                {
                    "read_id": "fffffff1-10d2-49cb-8ca3-e8d48979001b",
                    "sequence_length": 33,
                    "contig": "dummyII",
                    "reference_start": 3,
                    "reference_end": 36,
                    "alignment_length": 33,
                    "alignment_type": "primary_reverse",
                    "mod_count": "T+T:1;(probabilities >= 0.5020 and (probabilities < 0.7843 or > 0.8627), PHRED base qual >= 0)"
                }
            ]),
        )
    }

    #[test]
    fn run_with_example_6_aggressive_filtering_3() -> Result<(), Error> {
        let mod_options = InputModsBuilder::<OptionalTag>::default()
            .mod_prob_filter(ThresholdState::InvertGtEqLtEq(
                OrdPair::new(100, 110).expect("no error"),
            ))
            .build()?;
        run_example_6_test(
            mod_options,
            &serde_json::json!([
                {
                    "read_id": "5d10eb9a-aae1-4db8-8ec6-7ebb34d32575",
                    "sequence_length": 8,
                    "contig": "dummyI",
                    "reference_start": 9,
                    "reference_end": 17,
                    "alignment_length": 8,
                    "alignment_type": "primary_forward",
                    "mod_count": "NA"
                },
                {
                    "read_id": "fffffff1-10d2-49cb-8ca3-e8d48979001b",
                    "sequence_length": 33,
                    "contig": "dummyII",
                    "reference_start": 3,
                    "reference_end": 36,
                    "alignment_length": 33,
                    "alignment_type": "primary_reverse",
                    "mod_count": "T+T:1;(probabilities >= 0.5020 and (probabilities < 0.3922 or > 0.4314), PHRED base qual >= 0)"
                }
            ]),
        )
    }

    #[test]
    fn run_with_detailed_pretty_print() -> Result<(), Error> {
        // Collect records from example_1.bam to test detailed pretty-print mode
        let mut reader = nanalogue_bam_reader("./examples/example_1.bam")?;
        let records: Vec<Result<Rc<bam::Record>, rust_htslib::errors::Error>> =
            reader.rc_records().collect();

        // Run with detailed=Some(true) for pretty-printed JSON
        let mut output_buffer = Vec::new();
        run(
            &mut output_buffer,
            records.into_iter(),
            InputMods::default(),
            Some(true),
        )?;
        let output_json = String::from_utf8(output_buffer)?;

        // Load expected output from file
        let expected_output =
            std::fs::read_to_string("./examples/example_1_detailed_pretty_print")?;

        // Parse both as JSON values to compare structure
        let parsed_output: Value = serde_json::from_str(&output_json)?;
        let parsed_expected: Value = serde_json::from_str(&expected_output)?;

        // Verify the JSON structures are identical
        assert_eq!(
            parsed_output, parsed_expected,
            "Pretty-printed detailed output should match expected file"
        );

        Ok(())
    }

    #[test]
    fn run_with_detailed_compact_print() -> Result<(), Error> {
        // Collect records from example_1.bam to test detailed compact mode
        let mut reader = nanalogue_bam_reader("./examples/example_1.bam")?;
        let records: Vec<Result<Rc<bam::Record>, rust_htslib::errors::Error>> =
            reader.rc_records().collect();

        // Run with detailed=Some(false) for compact JSON
        let mut output_buffer = Vec::new();
        run(
            &mut output_buffer,
            records.into_iter(),
            InputMods::default(),
            Some(false),
        )?;
        let output_json = String::from_utf8(output_buffer)?;

        // Load expected output from file
        let expected_output = std::fs::read_to_string("./examples/example_1_detailed_print")?;

        // Parse both as JSON values to compare structure
        let parsed_output: Value = serde_json::from_str(&output_json)?;
        let parsed_expected: Value = serde_json::from_str(&expected_output)?;

        // Verify the JSON structures are identical
        assert_eq!(
            parsed_output, parsed_expected,
            "Compact detailed output should match expected file"
        );

        Ok(())
    }
}