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
//! CRAM record and fields.

mod builder;
mod convert;
pub mod feature;
mod flags;
mod next_mate_flags;
mod read_group_id;
pub mod resolve;
pub mod tag;

pub use self::{
    builder::Builder, feature::Feature, flags::Flags, next_mate_flags::NextMateFlags,
    read_group_id::ReadGroupId, tag::Tag,
};

use std::{fmt, str};

use noodles_bam as bam;
use noodles_sam as sam;

/// A CRAM record.
#[derive(Clone, PartialEq)]
pub struct Record {
    pub(crate) id: i64,
    pub(crate) bam_bit_flags: sam::record::Flags,
    pub(crate) cram_bit_flags: Flags,
    pub(crate) reference_sequence_id: Option<bam::record::ReferenceSequenceId>,
    pub(crate) read_length: usize,
    pub(crate) alignment_start: Option<sam::record::Position>,
    pub(crate) read_group: ReadGroupId,
    pub(crate) read_name: Vec<u8>,
    pub(crate) next_mate_bit_flags: NextMateFlags,
    pub(crate) next_fragment_reference_sequence_id: Option<bam::record::ReferenceSequenceId>,
    pub(crate) next_mate_alignment_start: Option<sam::record::Position>,
    pub(crate) template_size: i32,
    pub(crate) distance_to_next_fragment: i32,
    pub(crate) tags: Vec<Tag>,
    pub(crate) bases: Vec<u8>,
    pub(crate) features: Vec<Feature>,
    pub(crate) mapping_quality: sam::record::MappingQuality,
    pub(crate) quality_scores: Vec<u8>,
}

impl Record {
    /// Returns a builder to create a record from each of its fields.
    pub fn builder() -> Builder {
        Builder::default()
    }

    pub(crate) fn id(&self) -> i64 {
        self.id
    }

    /// Returns the BAM flags.
    ///
    /// This is also called the BAM bit flags.
    pub fn bam_flags(&self) -> sam::record::Flags {
        self.bam_bit_flags
    }

    /// Returns the CRAM flags.
    ///
    /// This is also called the CRAM bit flags or compression bit flags.
    pub fn flags(&self) -> Flags {
        self.cram_bit_flags
    }

    /// Returns the reference sequence ID.
    ///
    /// This is also called the reference ID. It is the position of the reference sequence in the
    /// SAM header.
    pub fn reference_sequence_id(&self) -> Option<bam::record::ReferenceSequenceId> {
        self.reference_sequence_id
    }

    /// Returns the read length.
    pub fn read_length(&self) -> usize {
        self.read_length
    }

    /// Returns the alignment start position.
    ///
    /// This value is 1-based.
    pub fn alignment_start(&self) -> Option<sam::record::Position> {
        self.alignment_start
    }

    /// Returns the alignment end position.
    ///
    /// This value is 1-based.
    pub fn alignment_end(&self) -> i32 {
        calculate_alignment_end(
            self.alignment_start().map(i32::from).unwrap_or_default(),
            self.read_length() as i32,
            self.features(),
        )
    }

    /// Returns the read group ID.
    ///
    /// This is also simply called the read group. It is the position of the read group in the SAM
    /// header.
    pub fn read_group_id(&self) -> ReadGroupId {
        self.read_group
    }

    /// Returns the read name.
    ///
    /// This may be the original read name or a generated one.
    pub fn read_name(&self) -> &[u8] {
        &self.read_name
    }

    /// Returns the next mate flags.
    ///
    /// This is also call the next mate bit flags.
    pub fn next_mate_flags(&self) -> NextMateFlags {
        self.next_mate_bit_flags
    }

    /// Returns the reference sequence ID of the next fragment.
    ///
    /// It is the position of the reference sequence in the SAM header.
    pub fn next_fragment_reference_sequence_id(&self) -> Option<bam::record::ReferenceSequenceId> {
        self.next_fragment_reference_sequence_id
    }

    /// Returns the alignment start position of the next mate.
    ///
    /// This value is 1-based.
    pub fn next_mate_alignment_start(&self) -> Option<sam::record::Position> {
        self.next_mate_alignment_start
    }

    /// Returns the template size.
    pub fn template_size(&self) -> i32 {
        self.template_size
    }

    /// Returns the distance to the next fragment.
    ///
    /// This is the number of records to the next fragment within a slice.
    pub fn distance_to_next_fragment(&self) -> i32 {
        self.distance_to_next_fragment
    }

    /// Returns the tag dictionary.
    pub fn tags(&self) -> &[Tag] {
        &self.tags
    }

    /// Returns the read bases.
    pub fn bases(&self) -> &[u8] {
        &self.bases
    }

    /// Returns the read features.
    pub fn features(&self) -> &[Feature] {
        &self.features
    }

    pub(crate) fn add_feature(&mut self, feature: Feature) {
        self.features.push(feature);
    }

    /// Returns the mapping quality.
    pub fn mapping_quality(&self) -> sam::record::MappingQuality {
        self.mapping_quality
    }

    /// Returns the per-base quality scores.
    pub fn quality_scores(&self) -> &[u8] {
        &self.quality_scores
    }
}

impl Default for Record {
    fn default() -> Self {
        Builder::default().build()
    }
}

impl fmt::Debug for Record {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let read_name = str::from_utf8(self.read_name());

        fmt.debug_struct("Record")
            .field("id", &self.id)
            .field("bam_bit_flags", &self.bam_flags())
            .field("cram_bit_flags", &self.flags())
            .field("reference_id", &self.reference_sequence_id)
            .field("read_length", &self.read_length)
            .field("alignment_start", &self.alignment_start)
            .field("read_group", &self.read_group)
            .field("read_name", &read_name)
            .field("next_mate_bit_flags", &self.next_mate_flags())
            .field(
                "next_fragment_reference_sequence_id",
                &self.next_fragment_reference_sequence_id,
            )
            .field("next_mate_alignment_start", &self.next_mate_alignment_start)
            .field("template_size", &self.template_size)
            .field("distance_to_next_fragment", &self.distance_to_next_fragment)
            .field("tags", &self.tags)
            .field("bases", &self.bases)
            .field("features", &self.features)
            .field("mapping_quality", &self.mapping_quality)
            .field("quality_scores", &self.quality_scores)
            .finish()
    }
}

fn calculate_alignment_span(read_length: i32, features: &[Feature]) -> i32 {
    features
        .iter()
        .fold(read_length, |alignment_span, feature| match feature {
            Feature::Insertion(_, bases) => alignment_span - bases.len() as i32,
            Feature::InsertBase(_, _) => alignment_span - 1,
            Feature::Deletion(_, len) => alignment_span + len,
            Feature::ReferenceSkip(_, len) => alignment_span + len,
            Feature::SoftClip(_, bases) => alignment_span - bases.len() as i32,
            _ => alignment_span,
        })
}

fn calculate_alignment_end(alignment_start: i32, read_length: i32, features: &[Feature]) -> i32 {
    let alignment_span = calculate_alignment_span(read_length, features);
    alignment_start + alignment_span - 1
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_calculate_alignment_span() {
        let features = [];
        assert_eq!(calculate_alignment_span(4, &features), 4);

        let features = [Feature::HardClip(1, 4)];
        assert_eq!(calculate_alignment_span(4, &features), 4);

        let features = [
            Feature::Insertion(1, vec![b'A', b'C']),
            Feature::InsertBase(4, b'G'),
            Feature::Deletion(6, 3),
            Feature::ReferenceSkip(10, 5),
            Feature::SoftClip(16, vec![b'A', b'C', b'G', b'T']),
        ];
        assert_eq!(calculate_alignment_span(20, &features), 21);
    }

    #[test]
    fn test_calculate_alignment_end() {
        let features = [];
        assert_eq!(calculate_alignment_end(1, 4, &features), 4);
    }
}