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
use std::io;
use std::io::prelude::*;
use std::ascii::AsciiExt;
use std::collections;
use std::fs;
use std::path::Path;
use std::convert::AsRef;
use std::cmp::min;
use csv;
use utils::{TextSlice, Text};
pub struct Reader<R: io::Read> {
reader: io::BufReader<R>,
line: String,
}
impl Reader<fs::File> {
pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
fs::File::open(path).map(Reader::new)
}
}
impl<R: io::Read> Reader<R> {
pub fn new(reader: R) -> Self {
Reader {
reader: io::BufReader::new(reader),
line: String::new(),
}
}
pub fn read(&mut self, record: &mut Record) -> io::Result<()> {
record.clear();
if self.line.is_empty() {
try!(self.reader.read_line(&mut self.line));
if self.line.is_empty() {
return Ok(());
}
}
if !self.line.starts_with('>') {
return Err(io::Error::new(io::ErrorKind::Other, "Expected > at record start."));
}
record.header.push_str(&self.line);
loop {
self.line.clear();
try!(self.reader.read_line(&mut self.line));
if self.line.is_empty() || self.line.starts_with('>') {
break;
}
record.seq.push_str(self.line.trim_right());
}
Ok(())
}
pub fn records(self) -> Records<R> {
Records { reader: self }
}
}
pub struct Index {
inner: collections::HashMap<String, IndexRecord>,
seqs: Vec<String>,
}
impl Index {
pub fn new<R: io::Read>(fai: R) -> csv::Result<Self> {
let mut inner = collections::HashMap::new();
let mut seqs = vec![];
let mut fai_reader = csv::Reader::from_reader(fai).delimiter(b'\t').has_headers(false);
for row in fai_reader.decode() {
let (name, record): (String, IndexRecord) = try!(row);
seqs.push(name.clone());
inner.insert(name, record);
}
Ok(Index {
inner: inner,
seqs: seqs,
})
}
pub fn from_file<P: AsRef<Path>>(path: &P) -> csv::Result<Self> {
match fs::File::open(path) {
Ok(fai) => Self::new(fai),
Err(e) => Err(csv::Error::Io(e)),
}
}
pub fn with_fasta_file<P: AsRef<Path>>(fasta_path: &P) -> csv::Result<Self> {
let mut ext = fasta_path.as_ref().extension().unwrap().to_str().unwrap().to_owned();
ext.push_str(".fai");
let fai_path = fasta_path.as_ref().with_extension(ext);
Self::from_file(&fai_path)
}
pub fn sequences(&self) -> Vec<Sequence> {
self.seqs
.iter()
.map(|name| {
Sequence {
name: name.clone(),
len: self.inner.get(name).unwrap().len,
}
})
.collect()
}
}
pub struct IndexedReader<R: io::Read + io::Seek> {
reader: io::BufReader<R>,
pub index: Index,
}
impl IndexedReader<fs::File> {
pub fn from_file<P: AsRef<Path>>(path: &P) -> csv::Result<Self> {
let index = try!(Index::with_fasta_file(path));
match fs::File::open(path) {
Ok(fasta) => Ok(IndexedReader::with_index(fasta, index)),
Err(e) => Err(csv::Error::Io(e)),
}
}
}
impl<R: io::Read + io::Seek> IndexedReader<R> {
pub fn new<I: io::Read>(fasta: R, fai: I) -> csv::Result<Self> {
let index = try!(Index::new(fai));
Ok(IndexedReader {
reader: io::BufReader::new(fasta),
index: index,
})
}
pub fn with_index(fasta: R, index: Index) -> Self {
IndexedReader {
reader: io::BufReader::new(fasta),
index: index,
}
}
pub fn read_all(&mut self, seqname: &str, seq: &mut Text) -> io::Result<()> {
match self.index.inner.get(seqname) {
Some(&idx) => self.read(seqname, 0, idx.len, seq),
None => Err(io::Error::new(io::ErrorKind::Other, "Unknown sequence name.")),
}
}
pub fn read(&mut self,
seqname: &str,
start: u64,
stop: u64,
seq: &mut Text)
-> io::Result<()> {
match self.index.inner.get(seqname) {
Some(idx) => {
seq.clear();
if stop > idx.len {
return Err(io::Error::new(io::ErrorKind::Other, "FASTA read interval was out of bounds"));
}
if start > stop {
return Err(io::Error::new(io::ErrorKind::Other, "Invalid query interval"));
}
let stop = min(stop, idx.len);
let length = stop - start as u64;
let mut buf = vec![0u8; idx.line_bases as usize];
loop {
let current_start = start + seq.len() as u64;
let line_start = current_start / idx.line_bases * idx.line_bytes;
let line_offset = current_start % idx.line_bases;
let offset = idx.offset + line_start + line_offset;
let left_to_read = length - seq.len() as u64;
let left_in_line = min(left_to_read, idx.line_bases - line_offset) as usize;
try!(self.reader.seek(io::SeekFrom::Start(offset)));
try!(self.reader.read_exact(&mut buf[..left_in_line]));
seq.extend_from_slice(&buf[..left_in_line]);
if seq.len() as u64 == length
{
break;
}
}
Ok(())
}
None => Err(io::Error::new(io::ErrorKind::Other, "Unknown sequence name.")),
}
}
}
#[derive(RustcDecodable, Debug, Copy, Clone)]
struct IndexRecord {
len: u64,
offset: u64,
line_bases: u64,
line_bytes: u64,
}
pub struct Sequence {
pub name: String,
pub len: u64,
}
pub struct Writer<W: io::Write> {
writer: io::BufWriter<W>,
}
impl Writer<fs::File> {
pub fn to_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
fs::File::create(path).map(Writer::new)
}
}
impl<W: io::Write> Writer<W> {
pub fn new(writer: W) -> Self {
Writer { writer: io::BufWriter::new(writer) }
}
pub fn write_record(&mut self, record: &Record) -> io::Result<()> {
self.write(record.id().unwrap_or(""), record.desc(), record.seq())
}
pub fn write(&mut self, id: &str, desc: Option<&str>, seq: TextSlice) -> io::Result<()> {
try!(self.writer.write(b">"));
try!(self.writer.write(id.as_bytes()));
if desc.is_some() {
try!(self.writer.write(b" "));
try!(self.writer.write(desc.unwrap().as_bytes()));
}
try!(self.writer.write(b"\n"));
try!(self.writer.write(seq));
try!(self.writer.write(b"\n"));
Ok(())
}
pub fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
}
#[derive(Default)]
pub struct Record {
header: String,
seq: String,
}
impl Record {
pub fn new() -> Self {
Record {
header: String::new(),
seq: String::new(),
}
}
pub fn is_empty(&self) -> bool {
self.header.is_empty() && self.seq.is_empty()
}
pub fn check(&self) -> Result<(), &str> {
if self.id().is_none() {
return Err("Expecting id for FastQ record.");
}
if !self.seq.is_ascii() {
return Err("Non-ascii character found in sequence.");
}
Ok(())
}
pub fn id(&self) -> Option<&str> {
self.header[1..].trim_right().splitn(2, ' ').next()
}
pub fn desc(&self) -> Option<&str> {
self.header[1..].trim_right().splitn(2, ' ').skip(1).next()
}
pub fn seq(&self) -> TextSlice {
self.seq.as_bytes()
}
fn clear(&mut self) {
self.header.clear();
self.seq.clear();
}
}
pub struct Records<R: io::Read> {
reader: Reader<R>,
}
impl<R: io::Read> Iterator for Records<R> {
type Item = io::Result<Record>;
fn next(&mut self) -> Option<io::Result<Record>> {
let mut record = Record::new();
match self.reader.read(&mut record) {
Ok(()) if record.is_empty() => None,
Ok(()) => Some(Ok(record)),
Err(err) => Some(Err(err)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io;
const FASTA_FILE: &'static [u8] = b">id desc
ACCGTAGGCTGA
CCGTAGGCTGAA
CGTAGGCTGAAA
GTAGGCTGAAAA
CCCC
>id2
ATTGTTGTTTTA
ATTGTTGTTTTA
ATTGTTGTTTTA
GGGG
";
const FAI_FILE: &'static [u8] = b"id\t52\t9\t12\t13
id2\t40\t71\t12\t13
";
const WRITE_FASTA_FILE: &'static [u8] = b">id desc
ACCGTAGGCTGA
>id2
ATTGTTGTTTTA
";
#[test]
fn test_reader() {
let reader = Reader::new(FASTA_FILE);
let ids = [Some("id"), Some("id2")];
let descs = [Some("desc"), None];
let seqs: [&[u8]; 2] = [b"ACCGTAGGCTGACCGTAGGCTGAACGTAGGCTGAAAGTAGGCTGAAAACCCC",
b"ATTGTTGTTTTAATTGTTGTTTTAATTGTTGTTTTAGGGG"];
for (i, r) in reader.records().enumerate() {
let record = r.ok().expect("Error reading record");
assert_eq!(record.check(), Ok(()));
assert_eq!(record.id(), ids[i]);
assert_eq!(record.desc(), descs[i]);
assert_eq!(record.seq(), seqs[i]);
}
}
#[test]
fn test_indexed_reader() {
let mut reader = IndexedReader::new(io::Cursor::new(FASTA_FILE), FAI_FILE)
.ok()
.expect("Error reading index");
let mut seq = Vec::new();
reader.read("id", 1, 5, &mut seq).ok().expect("Error reading sequence.");
assert_eq!(seq, b"CCGT");
reader.read("id", 1, 31, &mut seq).ok().expect("Error reading sequence.");
assert_eq!(seq, b"CCGTAGGCTGACCGTAGGCTGAACGTAGGC");
reader.read("id", 13, 23, &mut seq).ok().expect("Error reading sequence.");
assert_eq!(seq, b"CGTAGGCTGA");
reader.read("id", 36, 52, &mut seq).ok().expect("Error reading sequence.");
assert_eq!(seq, b"GTAGGCTGAAAACCCC");
reader.read("id2", 12, 40, &mut seq).ok().expect("Error reading sequence.");
assert_eq!(seq, b"ATTGTTGTTTTAATTGTTGTTTTAGGGG");
reader.read("id2", 12, 12, &mut seq).ok().expect("Error reading sequence.");
assert_eq!(seq, b"");
reader.read("id2", 12, 13, &mut seq).ok().expect("Error reading sequence.");
assert_eq!(seq, b"A");
assert!(reader.read("id2", 12, 11, &mut seq).is_err());
assert!(reader.read("id2", 12, 1000, &mut seq).is_err());
}
#[test]
fn test_writer() {
let mut writer = Writer::new(Vec::new());
writer.write("id", Some("desc"), b"ACCGTAGGCTGA").ok().expect("Expected successful write");
writer.write("id2", None, b"ATTGTTGTTTTA").ok().expect("Expected successful write");
writer.flush().ok().expect("Expected successful write");
assert_eq!(writer.writer.get_ref(), &WRITE_FASTA_FILE);
}
}