forked from onecodex/needletail
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecord.rs
More file actions
294 lines (261 loc) · 8.83 KB
/
record.rs
File metadata and controls
294 lines (261 loc) · 8.83 KB
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
use std::borrow::Cow;
use std::io::Write;
use memchr::memchr;
use crate::errors::{ParseError, PhredOffsetError};
use crate::parser::fasta::BufferPosition as FastaBufferPosition;
use crate::parser::fastq::BufferPosition as FastqBufferPosition;
use crate::parser::utils::{Format, LineEnding, Position};
use crate::quality::{decode_phred, PhredEncoding};
use crate::Sequence;
#[derive(Debug, Clone)]
enum BufferPositionKind<'a> {
Fasta(&'a FastaBufferPosition),
Fastq(&'a FastqBufferPosition),
}
/// A FASTA or FASTQ record
#[derive(Debug, Clone)]
pub struct SequenceRecord<'a> {
buffer: &'a [u8],
buf_pos: BufferPositionKind<'a>,
position: &'a Position,
line_ending: LineEnding,
}
impl<'a> SequenceRecord<'a> {
pub(crate) fn new_fasta(
buffer: &'a [u8],
buf_pos: &'a FastaBufferPosition,
position: &'a Position,
line_ending: Option<LineEnding>,
) -> Self {
Self {
buffer,
position,
buf_pos: BufferPositionKind::Fasta(buf_pos),
line_ending: line_ending.unwrap_or(LineEnding::Unix),
}
}
pub(crate) fn new_fastq(
buffer: &'a [u8],
buf_pos: &'a FastqBufferPosition,
position: &'a Position,
line_ending: Option<LineEnding>,
) -> Self {
Self {
buffer,
position,
buf_pos: BufferPositionKind::Fastq(buf_pos),
line_ending: line_ending.unwrap_or(LineEnding::Unix),
}
}
/// Returns the format of the record
#[inline]
pub fn format(&self) -> Format {
match self.buf_pos {
BufferPositionKind::Fasta(_) => Format::Fasta,
BufferPositionKind::Fastq(_) => Format::Fastq,
}
}
/// Returns the id of the record
#[inline]
pub fn id(&self) -> &[u8] {
match self.buf_pos {
BufferPositionKind::Fasta(bp) => bp.id(self.buffer),
BufferPositionKind::Fastq(bp) => bp.id(self.buffer),
}
}
/// Returns the raw sequence of the record. Only matters for FASTA since it can contain
/// newlines.
#[inline]
pub fn raw_seq(&self) -> &[u8] {
match self.buf_pos {
BufferPositionKind::Fasta(bp) => bp.raw_seq(self.buffer),
BufferPositionKind::Fastq(bp) => bp.seq(self.buffer),
}
}
/// Returns the cleaned up sequence of the record. For FASTQ it is the same as `raw_seq` but
/// for FASTA it is `raw_seq` minus all the `\r\n`
pub fn seq(&self) -> Cow<'_, [u8]> {
match self.buf_pos {
BufferPositionKind::Fasta(bp) => bp.seq(self.buffer),
BufferPositionKind::Fastq(bp) => bp.seq(self.buffer).into(),
}
}
/// Returns the Phred-encoded quality line if there is one. Always `None`
/// for FASTA and `Some` for FASTQ, even if the quality line is empty.
#[inline]
pub fn qual(&self) -> Option<&[u8]> {
match self.buf_pos {
BufferPositionKind::Fasta(_) => None,
BufferPositionKind::Fastq(bp) => Some(bp.qual(self.buffer)),
}
}
/// Decodes Phred quality data to quality scores. See documentation for
/// `needletail::quality::decode_phred`. This returns a `Result` containing
/// an `Option<Cow<'a, [u8]>>` of the decoded quality scores, which may be
/// coerced to `Vec<u8>` or `&[u8]`. In case the Phred quality data is
/// incompatible with the specified source encoding, an error is returned.
pub fn decode_phred(
&self,
encoding: PhredEncoding,
) -> Result<Option<Cow<'a, [u8]>>, PhredOffsetError> {
match self.qual() {
Some(qual) => {
// Try to encode the quality scores.
let encoded = decode_phred(qual, encoding)?; // Propagate error if any.
Ok(Some(encoded.into()))
}
None => Ok(None),
}
}
/// Returns the full sequence, including line endings. This doesn't include a trailing newline.
#[inline]
pub fn all(&self) -> &[u8] {
match self.buf_pos {
BufferPositionKind::Fasta(bp) => bp.all(self.buffer),
BufferPositionKind::Fastq(bp) => bp.all(self.buffer),
}
}
/// Return the number of bases in the sequence, computed efficiently.
#[inline]
pub fn num_bases(&self) -> usize {
match self.buf_pos {
BufferPositionKind::Fasta(bp) => bp.num_bases(self.buffer),
BufferPositionKind::Fastq(bp) => bp.num_bases(self.buffer),
}
}
/// Return the line number in the file of the start of the sequence
pub fn start_line_number(&self) -> u64 {
self.position.line
}
/// Return the line/byte position of the start of the sequence
pub fn position(&self) -> &Position {
self.position
}
/// Which line ending is this record using?
pub fn line_ending(&self) -> LineEnding {
self.line_ending
}
/// Write record back to a `Write` instance. By default it will use the original line ending but
/// you can force it to use another one.
pub fn write(
&self,
writer: &mut dyn Write,
forced_line_ending: Option<LineEnding>,
) -> Result<(), ParseError> {
match self.buf_pos {
BufferPositionKind::Fasta(_) => write_fasta(
self.id(),
self.raw_seq(),
writer,
forced_line_ending.unwrap_or(self.line_ending),
),
BufferPositionKind::Fastq(_) => write_fastq(
self.id(),
self.raw_seq(),
self.qual(),
writer,
forced_line_ending.unwrap_or(self.line_ending),
),
}
}
}
impl<'a> Sequence<'a> for SequenceRecord<'a> {
fn sequence(&'a self) -> &'a [u8] {
self.raw_seq()
}
}
/// Mask tabs in header lines to `|`s
pub fn mask_header_tabs(id: &[u8]) -> Option<Vec<u8>> {
memchr(b'\t', id).map(|_| {
id.iter()
.map(|x| if *x == b'\t' { b'|' } else { *x })
.collect()
})
}
/// Convert bad UTF8 characters into �s
pub fn mask_header_utf8(id: &[u8]) -> Option<Vec<u8>> {
// this may potentially change the length of the id; we should probably
// be doing something trickier like converting
match String::from_utf8_lossy(id) {
Cow::Owned(s) => Some(s.into_bytes()),
Cow::Borrowed(_) => None,
}
}
/// Write a FASTA record
pub fn write_fasta(
id: &[u8],
seq: &[u8],
writer: &mut dyn Write,
line_ending: LineEnding,
) -> Result<(), ParseError> {
let ending = line_ending.to_bytes();
writer.write_all(b">")?;
writer.write_all(id)?;
writer.write_all(&ending)?;
writer.write_all(seq)?;
writer.write_all(&ending)?;
Ok(())
}
pub fn write_fastq(
id: &[u8],
seq: &[u8],
qual: Option<&[u8]>,
writer: &mut dyn Write,
line_ending: LineEnding,
) -> Result<(), ParseError> {
let ending = line_ending.to_bytes();
writer.write_all(b"@")?;
writer.write_all(id)?;
writer.write_all(&ending)?;
writer.write_all(seq)?;
writer.write_all(&ending)?;
writer.write_all(b"+")?;
writer.write_all(&ending)?;
// this is kind of a hack, but we want to allow writing out sequences
// that don't have qualitys so this will mask to "good" if the quality
// slice is empty
if let Some(qual) = qual {
writer.write_all(qual)?;
} else {
writer.write_all(&vec![b'I'; seq.len()])?;
}
writer.write_all(&ending)?;
Ok(())
}
#[cfg(test)]
mod test {
use std::io::Cursor;
use crate::{parse_fastx_reader, quality::PhredEncoding};
fn seq(s: &[u8]) -> Cursor<&[u8]> {
Cursor::new(s)
}
#[test]
fn test_start_line_number() {
let mut reader =
parse_fastx_reader(seq(b"@test\nACGT\n+\nIIII\n@test2\nACGT\n+\nIIII")).unwrap();
let rec = reader.next().unwrap().unwrap();
assert_eq!(rec.start_line_number(), 1);
let rec = reader.next().unwrap().unwrap();
assert_eq!(rec.start_line_number(), 5);
}
#[test]
fn test_position() {
let mut reader = parse_fastx_reader(seq(
b"@test1\nACGT\n+\nIIII\n@test222\nACGT\n+\nIIII\n@test3\nACGT\n+\nIIII",
))
.unwrap();
let rec = reader.next().unwrap().unwrap();
assert_eq!(rec.position().byte(), 0);
let rec = reader.next().unwrap().unwrap();
assert_eq!(rec.position().byte(), 19);
let rec = reader.next().unwrap().unwrap();
assert_eq!(rec.position().byte(), 40);
}
#[test]
fn test_record_decode_phred() {
let mut reader = parse_fastx_reader(seq(b"@test1\nACGT\n+\nIIII")).unwrap();
let rec = reader.next().unwrap().unwrap();
let decoded_qual = rec.decode_phred(PhredEncoding::Phred33).unwrap().unwrap();
assert_eq!(decoded_qual.as_ref(), &[40, 40, 40, 40]);
}
}