rsomics-count 0.1.0

Genomic feature counting and count-matrix normalization
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::num::NonZeroUsize;
use std::path::Path;

use bstr::ByteSlice;
use noodles::{bgzf, sam};
use noodles_util::alignment;
use rsomics_bamio::raw::{RecordReader as RawRecordReader, RecordRef};
use rsomics_common::{Context, Result, RsomicsError};

use crate::model::{Block, Blocks};

enum Inner {
    Bam(rsomics_bamio::ParallelBamReader),
    General(alignment::io::Reader<Box<dyn Read>>),
}

pub(crate) struct Reader {
    inner: Inner,
    input: String,
}

#[derive(Clone, Debug)]
pub(crate) struct Segment {
    pub(crate) name: Option<Vec<u8>>,
    pub(crate) name_present: bool,
    pub(crate) group_start: bool,
    pub(crate) blocks: Blocks,
    pub(crate) reverse: bool,
    pub(crate) segmented: bool,
    pub(crate) first: bool,
    pub(crate) last: bool,
    pub(crate) unmapped: bool,
    pub(crate) secondary: bool,
    pub(crate) duplicate: bool,
    pub(crate) mapq: u8,
    pub(crate) nh: u32,
    pub(crate) hit_index: Option<u32>,
    pub(crate) split: bool,
    pub(crate) template_length: i32,
    pub(crate) reference: Option<usize>,
}

#[derive(Clone, Copy)]
pub(crate) enum NameMode {
    None,
    Owned,
    Grouped,
}

struct NameTracker {
    mode: NameMode,
    previous: Vec<u8>,
}

impl NameTracker {
    fn new(mode: NameMode) -> Self {
        Self {
            mode,
            previous: Vec::new(),
        }
    }

    fn read(&mut self, raw: Option<&[u8]>) -> (Option<Vec<u8>>, bool, bool) {
        let Some(raw) = raw.filter(|name| !name.is_empty() && *name != b"*") else {
            return (None, false, false);
        };
        match self.mode {
            NameMode::None => (None, true, false),
            NameMode::Owned => (Some(raw.to_vec()), true, false),
            NameMode::Grouped => {
                let group_start = self.previous != raw;
                if group_start {
                    self.previous.clear();
                    self.previous.extend_from_slice(raw);
                }
                (None, true, group_start)
            }
        }
    }
}

impl Reader {
    pub(crate) fn open(input: &Path, workers: Option<NonZeroUsize>) -> Result<Self> {
        let display = input.display().to_string();
        if input == Path::new("-") {
            if workers.is_some_and(|workers| workers.get() != 1) {
                return Err(RsomicsError::ConfigError(
                    "standard-input alignment decoding requires --threads 1".to_owned(),
                ));
            }
            let inner = alignment::io::reader::Builder::default()
                .build_from_reader(Box::new(io::stdin()) as Box<dyn Read>)
                .rs_context("opening alignment input -")?;
            return Ok(Self {
                inner: Inner::General(inner),
                input: display,
            });
        }

        match detect(input)? {
            Format::Cram => Err(RsomicsError::InvalidInput(format!(
                "CRAM is not supported in this release: {}",
                input.display()
            ))),
            Format::Bam => Ok(Self {
                inner: Inner::Bam(rsomics_bamio::open_with_workers(
                    input,
                    workers.unwrap_or_else(|| {
                        std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN)
                    }),
                )?),
                input: display,
            }),
            Format::Sam => {
                if workers.is_some_and(|workers| workers.get() != 1) {
                    return Err(RsomicsError::ConfigError(format!(
                        "SAM input requires --threads 1: {}",
                        input.display()
                    )));
                }
                let file = File::open(input)
                    .rs_with_context(|| format!("opening alignment input {}", input.display()))?;
                let inner = alignment::io::reader::Builder::default()
                    .build_from_reader(Box::new(file) as Box<dyn Read>)
                    .rs_with_context(|| format!("opening alignment input {}", input.display()))?;
                Ok(Self {
                    inner: Inner::General(inner),
                    input: display,
                })
            }
        }
    }

    pub(crate) fn read_header(&mut self) -> Result<sam::Header> {
        match &mut self.inner {
            Inner::Bam(reader) => reader.read_header(),
            Inner::General(reader) => reader.read_header(),
        }
        .map_err(|error| {
            RsomicsError::InvalidInput(format!(
                "reading alignment header from {}: {error}",
                self.input
            ))
        })
    }

    pub(crate) fn visit(
        &mut self,
        header: &sam::Header,
        aliases: &HashMap<String, String>,
        chrom_id: &dyn Fn(&str) -> Option<u32>,
        name_mode: NameMode,
        mut visit: impl FnMut(Segment) -> Result<()>,
    ) -> Result<()> {
        let mut names = NameTracker::new(name_mode);
        match &mut self.inner {
            Inner::Bam(reader) => {
                let chrom_by_ref = reference_ids(header, aliases, chrom_id)?;
                let mut records = RawRecordReader::new(reader.get_mut());
                while let Some(record) = records
                    .next()
                    .rs_with_context(|| format!("reading alignment record from {}", self.input))?
                {
                    visit(parse_raw_record(&record, &chrom_by_ref, &mut names)?)?;
                }
            }
            Inner::General(reader) => {
                for result in reader.records(header) {
                    let record = result.map_err(|error| record_error(&self.input, error))?;
                    visit(parse_record(
                        header,
                        record.as_ref(),
                        aliases,
                        chrom_id,
                        &mut names,
                    )?)?;
                }
            }
        }
        Ok(())
    }
}

fn parse_record(
    header: &sam::Header,
    record: &dyn sam::alignment::Record,
    aliases: &HashMap<String, String>,
    chrom_id: &dyn Fn(&str) -> Option<u32>,
    names: &mut NameTracker,
) -> Result<Segment> {
    use sam::alignment::record::data::field::Tag;

    let flags = record
        .flags()
        .map_err(|error| RsomicsError::InvalidInput(format!("invalid alignment flags: {error}")))?;
    let (name, name_present, group_start) = names.read(record.name().map(|name| name.as_ref()));
    let (reference, chrom) = reference_info(
        record.reference_sequence_id(header),
        header,
        aliases,
        chrom_id,
    )?;
    let (blocks, split) = if flags.is_unmapped() {
        (Blocks::new(), false)
    } else {
        reference.ok_or_else(|| {
            RsomicsError::InvalidInput(format!(
                "mapped record {} has no reference sequence",
                display_name(name.as_deref())
            ))
        })?;
        cigar_blocks(record, chrom)?
    };
    let data = record.data();
    let nh = integer_tag(data.get(&Tag::ALIGNMENT_HIT_COUNT), "NH")?.unwrap_or(1);
    if nh == 0 {
        return Err(RsomicsError::InvalidInput(format!(
            "record {} has NH=0",
            display_name(name.as_deref())
        )));
    }
    let hit_index = integer_tag(data.get(&Tag::HIT_INDEX), "HI")?;
    if hit_index == Some(0) {
        return Err(RsomicsError::InvalidInput(format!(
            "record {} has HI=0",
            display_name(name.as_deref())
        )));
    }
    let mapq = record
        .mapping_quality()
        .transpose()
        .map_err(|error| RsomicsError::InvalidInput(format!("invalid mapping quality: {error}")))?
        .map_or(0, |quality| quality.get());

    Ok(Segment {
        name,
        name_present,
        group_start,
        blocks,
        reverse: flags.is_reverse_complemented(),
        segmented: flags.is_segmented(),
        first: flags.is_first_segment(),
        last: flags.is_last_segment(),
        unmapped: flags.is_unmapped(),
        secondary: flags.is_secondary(),
        duplicate: flags.is_duplicate(),
        mapq,
        nh,
        hit_index,
        split,
        template_length: record.template_length().map_err(|error| {
            RsomicsError::InvalidInput(format!("invalid template length: {error}"))
        })?,
        reference,
    })
}

fn cigar_blocks(record: &dyn sam::alignment::Record, chrom: Option<u32>) -> Result<(Blocks, bool)> {
    use sam::alignment::record::cigar::op::Kind;

    let start = record
        .alignment_start()
        .transpose()
        .map_err(|error| RsomicsError::InvalidInput(format!("invalid alignment start: {error}")))?
        .ok_or_else(|| {
            RsomicsError::InvalidInput("mapped record has no alignment start".to_owned())
        })?;
    let mut cursor = u64::try_from(usize::from(start) - 1)
        .map_err(|_| RsomicsError::InvalidInput("alignment coordinate overflow".to_owned()))?;
    let mut block_start = cursor;
    let mut blocks = Blocks::new();
    let mut split = false;
    for result in record.cigar().iter() {
        let op = result
            .map_err(|error| RsomicsError::InvalidInput(format!("invalid CIGAR: {error}")))?;
        if op.is_empty() {
            return Err(RsomicsError::InvalidInput(
                "CIGAR operation has zero length".to_owned(),
            ));
        }
        match op.kind() {
            Kind::Skip => {
                split = true;
                if block_start < cursor {
                    blocks.push(Block::new(chrom, block_start, cursor)?);
                }
                cursor = cursor.checked_add(op.len() as u64).ok_or_else(|| {
                    RsomicsError::InvalidInput("CIGAR coordinate overflow".to_owned())
                })?;
                block_start = cursor;
            }
            kind if kind.consumes_reference() => {
                cursor = cursor.checked_add(op.len() as u64).ok_or_else(|| {
                    RsomicsError::InvalidInput("CIGAR coordinate overflow".to_owned())
                })?;
            }
            _ => {}
        }
    }
    if block_start < cursor {
        blocks.push(Block::new(chrom, block_start, cursor)?);
    }
    if blocks.is_empty() {
        return Err(RsomicsError::InvalidInput(
            "mapped record CIGAR consumes no reference bases".to_owned(),
        ));
    }
    Ok((blocks, split))
}

fn parse_raw_record(
    record: &RecordRef<'_>,
    chrom_by_ref: &[Option<u32>],
    names: &mut NameTracker,
) -> Result<Segment> {
    let flags = record.flags();
    let (name, name_present, group_start) = names.read(Some(record.name()));
    let reference = raw_reference_id(record.reference_sequence_id(), chrom_by_ref.len())?;
    let chrom = reference.and_then(|id| chrom_by_ref[id]);
    let unmapped = flags & 0x4 != 0;
    let (blocks, split) = if unmapped {
        (Blocks::new(), false)
    } else {
        reference.ok_or_else(|| {
            RsomicsError::InvalidInput(format!(
                "mapped record {} has no reference sequence",
                display_name(name.as_deref())
            ))
        })?;
        raw_cigar_blocks(record, chrom)?
    };
    let nh = raw_integer_tag(record, *b"NH")?.unwrap_or(1);
    if nh == 0 {
        return Err(RsomicsError::InvalidInput(format!(
            "record {} has NH=0",
            display_name(name.as_deref())
        )));
    }
    let hit_index = raw_integer_tag(record, *b"HI")?;
    if hit_index == Some(0) {
        return Err(RsomicsError::InvalidInput(format!(
            "record {} has HI=0",
            display_name(name.as_deref())
        )));
    }

    Ok(Segment {
        name,
        name_present,
        group_start,
        blocks,
        reverse: flags & 0x10 != 0,
        segmented: flags & 0x1 != 0,
        first: flags & 0x40 != 0,
        last: flags & 0x80 != 0,
        unmapped,
        secondary: flags & 0x100 != 0,
        duplicate: flags & 0x400 != 0,
        mapq: record.mapping_quality(),
        nh,
        hit_index,
        split,
        template_length: record.template_length(),
        reference,
    })
}

fn raw_reference_id(value: i32, count: usize) -> Result<Option<usize>> {
    if value == -1 {
        return Ok(None);
    }
    let id = usize::try_from(value).map_err(|_| {
        RsomicsError::InvalidInput(format!("invalid reference sequence identifier {value}"))
    })?;
    if id >= count {
        return Err(RsomicsError::InvalidInput(format!(
            "reference sequence identifier {id} is absent from header"
        )));
    }
    Ok(Some(id))
}

fn raw_cigar_blocks(record: &RecordRef<'_>, chrom: Option<u32>) -> Result<(Blocks, bool)> {
    let start = record.alignment_start();
    let mut cursor = u64::try_from(start).map_err(|_| {
        RsomicsError::InvalidInput("mapped record has no alignment start".to_owned())
    })?;
    let mut block_start = cursor;
    let mut blocks = Blocks::new();
    let mut split = false;
    for (kind, len) in record.cigar_ops() {
        if len == 0 {
            return Err(RsomicsError::InvalidInput(
                "CIGAR operation has zero length".to_owned(),
            ));
        }
        match kind {
            3 => {
                split = true;
                if block_start < cursor {
                    blocks.push(Block::new(chrom, block_start, cursor)?);
                }
                cursor = cursor.checked_add(u64::from(len)).ok_or_else(|| {
                    RsomicsError::InvalidInput("CIGAR coordinate overflow".to_owned())
                })?;
                block_start = cursor;
            }
            0 | 2 | 7 | 8 => {
                cursor = cursor.checked_add(u64::from(len)).ok_or_else(|| {
                    RsomicsError::InvalidInput("CIGAR coordinate overflow".to_owned())
                })?;
            }
            1 | 4 | 5 | 6 => {}
            _ => {
                return Err(RsomicsError::InvalidInput(format!(
                    "invalid BAM CIGAR operation code {kind}"
                )));
            }
        }
    }
    if block_start < cursor {
        blocks.push(Block::new(chrom, block_start, cursor)?);
    }
    if blocks.is_empty() {
        return Err(RsomicsError::InvalidInput(
            "mapped record CIGAR consumes no reference bases".to_owned(),
        ));
    }
    Ok((blocks, split))
}

fn raw_integer_tag(record: &RecordRef<'_>, tag: [u8; 2]) -> Result<Option<u32>> {
    let Some(kind) = record.aux_type(tag) else {
        return Ok(None);
    };
    let value = record.aux_value(tag).ok_or_else(|| {
        RsomicsError::InvalidInput(format!(
            "invalid {}{} alignment tag",
            char::from(tag[0]),
            char::from(tag[1])
        ))
    })?;
    let signed = match (kind, value) {
        (b'c', [value]) => i64::from(i8::from_le_bytes([*value])),
        (b'C', [value]) => i64::from(*value),
        (b's', [a, b]) => i64::from(i16::from_le_bytes([*a, *b])),
        (b'S', [a, b]) => i64::from(u16::from_le_bytes([*a, *b])),
        (b'i', [a, b, c, d]) => i64::from(i32::from_le_bytes([*a, *b, *c, *d])),
        (b'I', [a, b, c, d]) => i64::from(u32::from_le_bytes([*a, *b, *c, *d])),
        _ => {
            return Err(RsomicsError::InvalidInput(format!(
                "{}{} alignment tag is not an integer",
                char::from(tag[0]),
                char::from(tag[1])
            )));
        }
    };
    u32::try_from(signed).map(Some).map_err(|_| {
        RsomicsError::InvalidInput(format!(
            "{}{} alignment tag is out of range",
            char::from(tag[0]),
            char::from(tag[1])
        ))
    })
}

fn display_name(name: Option<&[u8]>) -> Cow<'_, str> {
    name.map(String::from_utf8_lossy)
        .unwrap_or(Cow::Borrowed("<unnamed>"))
}

fn integer_tag(
    value: Option<io::Result<sam::alignment::record::data::field::Value<'_>>>,
    tag: &str,
) -> Result<Option<u32>> {
    let Some(value) = value else {
        return Ok(None);
    };
    let value = value.map_err(|error| {
        RsomicsError::InvalidInput(format!("invalid {tag} alignment tag: {error}"))
    })?;
    let value = value.as_int().ok_or_else(|| {
        RsomicsError::InvalidInput(format!("{tag} alignment tag is not an integer"))
    })?;
    u32::try_from(value)
        .map(Some)
        .map_err(|_| RsomicsError::InvalidInput(format!("{tag} alignment tag is out of range")))
}

fn reference_info(
    id: Option<io::Result<usize>>,
    header: &sam::Header,
    aliases: &HashMap<String, String>,
    chrom_id: &dyn Fn(&str) -> Option<u32>,
) -> Result<(Option<usize>, Option<u32>)> {
    let Some(id) = id.transpose().map_err(|error| {
        RsomicsError::InvalidInput(format!("invalid reference sequence identifier: {error}"))
    })?
    else {
        return Ok((None, None));
    };
    let (name, _) = header.reference_sequences().get_index(id).ok_or_else(|| {
        RsomicsError::InvalidInput(format!(
            "reference sequence identifier {id} is absent from header"
        ))
    })?;
    let name = name.to_str().map_err(|error| {
        RsomicsError::InvalidInput(format!("reference sequence name is not UTF-8: {error}"))
    })?;
    let canonical = aliases.get(name).map_or(name, String::as_str);
    Ok((Some(id), chrom_id(canonical)))
}

fn reference_ids(
    header: &sam::Header,
    aliases: &HashMap<String, String>,
    chrom_id: &dyn Fn(&str) -> Option<u32>,
) -> Result<Vec<Option<u32>>> {
    header
        .reference_sequences()
        .keys()
        .map(|name| {
            let name = name.to_str().map_err(|error| {
                RsomicsError::InvalidInput(format!("reference sequence name is not UTF-8: {error}"))
            })?;
            let canonical = aliases.get(name).map_or(name, String::as_str);
            Ok(chrom_id(canonical))
        })
        .collect()
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Format {
    Sam,
    Bam,
    Cram,
}

fn detect(path: &Path) -> Result<Format> {
    let mut source = BufReader::new(
        File::open(path)
            .rs_with_context(|| format!("opening alignment input {}", path.display()))?,
    );
    let mut magic = [0; 4];
    source.read_exact(&mut magic).map_err(|error| {
        RsomicsError::InvalidInput(format!(
            "detecting alignment format for {}: {error}",
            path.display()
        ))
    })?;
    if magic == *b"CRAM" {
        return Ok(Format::Cram);
    }
    if magic == *b"BAM\x01" {
        return Ok(Format::Bam);
    }
    if magic[..2] != [0x1f, 0x8b] {
        return Ok(Format::Sam);
    }
    let mut reader = bgzf::io::Reader::new(
        File::open(path)
            .rs_with_context(|| format!("opening alignment input {}", path.display()))?,
    );
    reader.read_exact(&mut magic).map_err(|error| {
        RsomicsError::InvalidInput(format!(
            "detecting BGZF alignment format for {}: {error}",
            path.display()
        ))
    })?;
    Ok(if magic == *b"BAM\x01" {
        Format::Bam
    } else {
        Format::Sam
    })
}

fn record_error(input: &str, error: io::Error) -> RsomicsError {
    RsomicsError::InvalidInput(format!("reading alignment record from {input}: {error}"))
}

#[cfg(test)]
mod tests {
    use noodles::core::Position;
    use noodles::sam::alignment::{
        RecordBuf,
        record::cigar::{Op, op::Kind},
    };

    use super::*;

    #[test]
    fn cigar_skip_creates_reference_blocks() {
        let record = RecordBuf::builder()
            .set_alignment_start(Position::try_from(101).unwrap())
            .set_cigar(
                [
                    Op::new(Kind::Match, 20),
                    Op::new(Kind::Skip, 50),
                    Op::new(Kind::SequenceMatch, 10),
                ]
                .into_iter()
                .collect(),
            )
            .build();
        let (blocks, split) = cigar_blocks(&record, Some(0)).unwrap();
        assert_eq!((blocks[0].start, blocks[0].end), (100, 120));
        assert_eq!((blocks[1].start, blocks[1].end), (170, 180));
        assert!(split);
    }
}