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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// Copyright 2014-2018 Johannes Köster, Henning Timm.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! FastQ reading and writing.
//!
//! # Example
//!
//! ```
//! use std::io;
//! use bio::io::fastq;
//! let reader = fastq::Reader::new(io::stdin());
//! ```

use std::convert::AsRef;
use std::fmt;
use std::fs;
use std::io;
use std::io::prelude::*;
use std::path::Path;

use bio_types::sequence::SequenceRead;

use crate::utils::TextSlice;

/// Trait for FASTQ readers.
pub trait FastqRead {
    fn read(&mut self, record: &mut Record) -> io::Result<()>;
}

/// A FastQ reader.
#[derive(Debug)]
pub struct Reader<R: io::Read> {
    reader: io::BufReader<R>,
    line_buf: String,
}

impl Reader<fs::File> {
    /// Read from a given 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> {
    /// Read from a given `io::Read`.
    pub fn new(reader: R) -> Self {
        Reader {
            reader: io::BufReader::new(reader),
            line_buf: String::new(),
        }
    }

    /// Return an iterator over the records of this FastQ file.
    ///
    /// # Errors
    ///
    /// This function will return an error if a record is incomplete
    /// or syntax is violated.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bio::io::fastq;
    /// let fq: &'static [u8] = b"@id description\nACGT\n+\n!!!!\n";
    /// let records = fastq::Reader::new(fq).records().map(|record| record.unwrap());
    /// for record in records {
    ///     assert!(record.check().is_ok())
    /// }
    /// ```
    pub fn records(self) -> Records<R> {
        Records { reader: self }
    }
}

impl<R> FastqRead for Reader<R>
where
    R: io::Read,
{
    /// Read the next FASTQ entry into the given `Record`.
    /// An empty record indicates that no more records can be read.
    ///
    /// This method is useful when you want to read records as fast as
    /// possible because it allows the reuse of a `Record` allocation.
    ///
    /// A more ergonomic approach to reading FASTQ records, is the
    /// [records](Reader::records) iterator.
    ///
    /// # Errors
    ///
    /// This function will return an error if the record is incomplete,
    /// syntax is violated or any form of I/O error is encountered.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use std::error::Error;
    /// # use bio::io::fastq::{Reader, FastqRead};
    /// # use bio::io::fastq::Record;
    /// # fn main() -> Result<(), Box<Error>> {
    /// const fastq_file: &'static [u8] = b"@id desc
    /// AAAA
    /// +
    /// IIII
    /// ";
    /// let mut reader = Reader::new(fastq_file);
    /// let mut record = Record::new();
    ///
    /// // Check for errors parsing the record
    /// reader.read(&mut record)?;
    ///
    /// assert_eq!(record.id(), "id");
    /// assert_eq!(record.desc().unwrap(), "desc");
    /// assert_eq!(record.seq().to_vec(), b"AAAA");
    /// assert_eq!(record.qual().to_vec(), b"IIII");
    /// # Ok(())
    /// # }
    /// ```
    fn read(&mut self, record: &mut Record) -> io::Result<()> {
        record.clear();
        self.line_buf.clear();

        self.reader.read_line(&mut self.line_buf)?;

        if !self.line_buf.is_empty() {
            if !self.line_buf.starts_with('@') {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Expected @ at record start.",
                ));
            }
            let mut header_fields = self.line_buf[1..].trim_end().splitn(2, ' ');
            record.id = header_fields.next().unwrap_or_default().to_owned();
            record.desc = header_fields.next().map(|s| s.to_owned());
            self.reader.read_line(&mut record.seq)?;
            self.reader.read_line(&mut self.line_buf)?;
            self.reader.read_line(&mut record.qual)?;
            if record.qual.is_empty() {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Incomplete record. Each FastQ record has to consist \
                     of 4 lines: header, sequence, separator and \
                     qualities.",
                ));
            }
        }

        Ok(())
    }
}

/// A FastQ record.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Record {
    id: String,
    desc: Option<String>,
    seq: String,
    qual: String,
}

impl Record {
    /// Create a new, empty FastQ record.
    pub fn new() -> Self {
        Record {
            id: String::new(),
            desc: None,
            seq: String::new(),
            qual: String::new(),
        }
    }

    /// Create a new FastQ record from given attributes.
    pub fn with_attrs(id: &str, desc: Option<&str>, seq: TextSlice<'_>, qual: &[u8]) -> Self {
        let desc = match desc {
            Some(desc) => Some(desc.to_owned()),
            _ => None,
        };
        Record {
            id: id.to_owned(),
            desc,
            seq: String::from_utf8(seq.to_vec()).unwrap(),
            qual: String::from_utf8(qual.to_vec()).unwrap(),
        }
    }

    /// Check if record is empty.
    pub fn is_empty(&self) -> bool {
        self.id.is_empty() && self.desc.is_none() && self.seq.is_empty() && self.qual.is_empty()
    }

    /// Check validity of FastQ record.
    pub fn check(&self) -> Result<(), &str> {
        if self.id().is_empty() {
            return Err("Expecting id for FastQ record.");
        }
        if !self.seq.is_ascii() {
            return Err("Non-ascii character found in sequence.");
        }
        if !self.qual.is_ascii() {
            return Err("Non-ascii character found in qualities.");
        }
        if self.seq().len() != self.qual().len() {
            return Err("Unequal length of sequence an qualities.");
        }

        Ok(())
    }

    /// Return the id of the record.
    pub fn id(&self) -> &str {
        self.id.as_ref()
    }

    /// Return descriptions if present.
    pub fn desc(&self) -> Option<&str> {
        match self.desc.as_ref() {
            Some(desc) => Some(&desc),
            None => None,
        }
    }

    /// Return the sequence of the record.
    pub fn seq(&self) -> TextSlice<'_> {
        self.seq.trim_end().as_bytes()
    }

    /// Return the base qualities of the record.
    pub fn qual(&self) -> &[u8] {
        self.qual.trim_end().as_bytes()
    }

    /// Clear the record.
    fn clear(&mut self) {
        self.id.clear();
        self.desc = None;
        self.seq.clear();
        self.qual.clear();
    }
}

impl fmt::Display for Record {
    /// Allows for using `Record` in a given formatter `f`. In general this is for
    /// creating a `String` representation of a `Record` and, optionally, writing it to
    /// a file.
    ///
    /// # Errors
    /// Returns [`std::fmt::Error`](https://doc.rust-lang.org/std/fmt/struct.Error.html)
    /// if there is an issue formatting to the stream.
    ///
    /// # Examples
    ///
    /// Read in a Fastq `Record` and create a `String` representation of it.
    ///
    /// ```rust
    /// use bio::io::fastq::Reader;
    /// use std::fmt::Write;
    /// // create a "fake" fastq file
    /// let fq: &'static [u8] = b"@id description\nACGT\n+\n!!!!\n";
    /// let mut records = Reader::new(fq).records().map(|r| r.unwrap());
    /// let record = records.next().unwrap();
    ///
    /// let mut actual = String::new();
    /// // populate `actual` with a string representation of our record
    /// write!(actual, "{}", record).unwrap();
    ///
    /// let expected = std::str::from_utf8(fq).unwrap();
    ///
    /// assert_eq!(actual, expected)
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let header = match self.desc() {
            Some(d) => format!("{} {}", self.id().to_owned(), d),
            None => self.id().to_owned(),
        };
        write!(
            f,
            "@{}\n{}\n+\n{}\n",
            header,
            std::str::from_utf8(self.seq()).unwrap(),
            std::str::from_utf8(self.qual()).unwrap()
        )
    }
}

impl SequenceRead for Record {
    fn name(&self) -> &[u8] {
        self.id.as_bytes()
    }

    fn base(&self, i: usize) -> u8 {
        self.seq()[i]
    }

    fn base_qual(&self, i: usize) -> u8 {
        self.qual()[i]
    }

    fn len(&self) -> usize {
        self.seq().len()
    }
}

/// An iterator over the records of a FastQ file.
#[derive(Debug)]
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)),
        }
    }
}

/// A FastQ writer.
#[derive(Debug)]
pub struct Writer<W: io::Write> {
    writer: io::BufWriter<W>,
}

impl Writer<fs::File> {
    /// Write to a given file path.
    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> {
    /// Write to a given `io::Write`.
    pub fn new(writer: W) -> Self {
        Writer {
            writer: io::BufWriter::new(writer),
        }
    }

    /// Directly write a FastQ record.
    pub fn write_record(&mut self, record: &Record) -> io::Result<()> {
        self.write(record.id(), record.desc(), record.seq(), record.qual())
    }

    /// Write a FastQ record with given id, optional description, sequence and qualities.
    pub fn write(
        &mut self,
        id: &str,
        desc: Option<&str>,
        seq: TextSlice<'_>,
        qual: &[u8],
    ) -> io::Result<()> {
        self.writer.write_all(b"@")?;
        self.writer.write_all(id.as_bytes())?;
        if let Some(desc) = desc {
            self.writer.write_all(b" ")?;
            self.writer.write_all(desc.as_bytes())?;
        }
        self.writer.write_all(b"\n")?;
        self.writer.write_all(seq)?;
        self.writer.write_all(b"\n+\n")?;
        self.writer.write_all(qual)?;
        self.writer.write_all(b"\n")?;

        Ok(())
    }

    /// Flush the writer, ensuring that everything is written.
    pub fn flush(&mut self) -> io::Result<()> {
        self.writer.flush()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fmt::Write as FmtWrite;
    use std::io;

    const FASTQ_FILE: &'static [u8] = b"@id desc
ACCGTAGGCTGA
+
IIIIIIJJJJJJ
";

    #[test]
    fn test_reader() {
        let reader = Reader::new(FASTQ_FILE);
        let records: Vec<io::Result<Record>> = reader.records().collect();
        assert!(records.len() == 1);
        for res in records {
            let record = res.ok().unwrap();
            assert_eq!(record.check(), Ok(()));
            assert_eq!(record.id(), "id");
            assert_eq!(record.desc(), Some("desc"));
            assert_eq!(record.seq(), b"ACCGTAGGCTGA");
            assert_eq!(record.qual(), b"IIIIIIJJJJJJ");
        }
    }

    #[test]
    fn test_display_record_no_desc_id_without_space_after() {
        let fq: &'static [u8] = b"@id\nACGT\n+\n!!!!\n";
        let mut records = Reader::new(fq).records().map(|r| r.unwrap());
        let record = records.next().unwrap();
        let mut actual = String::new();
        write!(actual, "{}", record).unwrap();

        let expected = std::str::from_utf8(fq).unwrap();

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_display_record_with_desc_id_has_space_between_id_and_desc() {
        let fq: &'static [u8] = b"@id description\nACGT\n+\n!!!!\n";
        let mut records = Reader::new(fq).records().map(|r| r.unwrap());
        let record = records.next().unwrap();
        let mut actual = String::new();
        write!(actual, "{}", record).unwrap();

        let expected = std::str::from_utf8(fq).unwrap();

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_fqread_trait() {
        let path = "reads.fq.gz";
        let mut fq_reader: Box<dyn FastqRead> = match path.ends_with(".gz") {
            true => Box::new(Reader::new(io::BufReader::new(FASTQ_FILE))),
            false => Box::new(Reader::new(FASTQ_FILE)),
        };
        // The read method can be called, since it is implemented by
        // `Read`. Right now, the records method would not work.
        let mut record = Record::new();
        fq_reader.read(&mut record).unwrap();
        // Check if the returned result is correct.
        assert_eq!(record.check(), Ok(()));
        assert_eq!(record.id(), "id");
        assert_eq!(record.desc(), Some("desc"));
        assert_eq!(record.seq(), b"ACCGTAGGCTGA");
        assert_eq!(record.qual(), b"IIIIIIJJJJJJ");
    }

    #[test]
    fn test_record_with_attrs() {
        let record = Record::with_attrs("id_str", Some("desc"), b"ATGCGGG", b"QQQQQQQ");
        assert_eq!(record.id(), "id_str");
        assert_eq!(record.desc(), Some("desc"));
        assert_eq!(record.seq(), b"ATGCGGG");
        assert_eq!(record.qual(), b"QQQQQQQ");
    }

    #[test]
    fn test_writer() {
        let mut writer = Writer::new(Vec::new());
        writer
            .write("id", Some("desc"), b"ACCGTAGGCTGA", b"IIIIIIJJJJJJ")
            .ok()
            .expect("Expected successful write");
        writer.flush().ok().expect("Expected successful write");
        assert_eq!(writer.writer.get_ref(), &FASTQ_FILE);
    }

    #[test]
    fn test_check_record_id_is_empty_raises_err() {
        let record = Record::with_attrs("", None, b"ACGT", b"!!!!");

        let actual = record.check().unwrap_err();
        let expected = "Expecting id for FastQ record.";

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_check_record_seq_is_not_ascii_raises_err() {
        let record = Record::with_attrs("id", None, "Prüfung".as_ref(), b"!!!!");

        let actual = record.check().unwrap_err();
        let expected = "Non-ascii character found in sequence.";

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_check_record_quality_is_not_ascii_raises_err() {
        let record = Record::with_attrs("id", None, b"ACGT", "Qualität".as_ref());

        let actual = record.check().unwrap_err();
        let expected = "Non-ascii character found in qualities.";

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_check_record_quality_and_seq_diff_len_raises_err() {
        let record = Record::with_attrs("id", None, b"ACGT", b"!!!");

        let actual = record.check().unwrap_err();
        let expected = "Unequal length of sequence an qualities.";

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_check_valid_record() {
        let record = Record::with_attrs("id", None, b"ACGT", b"!!!!");

        assert!(record.check().is_ok())
    }

    #[test]
    fn test_read_header_does_not_start_with_correct_char_raises_err() {
        let fq: &'static [u8] = b">id description\nACGT\n+\n!!!!\n";
        let mut reader = Reader::new(fq);
        let mut record = Record::new();

        let actual = reader.read(&mut record).unwrap_err();
        let expected = io::Error::new(io::ErrorKind::Other, "Expected @ at record start.");

        assert_eq!(actual.kind(), expected.kind());
        assert_eq!(actual.to_string(), expected.to_string())
    }

    #[test]
    fn test_read_quality_is_empty_raises_err() {
        let fq: &'static [u8] = b"@id description\nACGT\n+\n";
        let mut reader = Reader::new(fq);
        let mut record = Record::new();

        let actual = reader.read(&mut record).unwrap_err();
        let expected = io::Error::new(io::ErrorKind::Other, "Incomplete record. Each FastQ record has to consist of 4 lines: header, sequence, separator and qualities.");

        assert_eq!(actual.kind(), expected.kind());
        assert_eq!(actual.to_string(), expected.to_string())
    }

    #[test]
    fn test_record_iterator_next_read_returns_err_causes_next_to_return_some_err() {
        let fq: &'static [u8] = b"@id description\nACGT\n+\n";
        let mut records = Reader::new(fq).records();

        let actual = records.next().unwrap().unwrap_err();
        let expected = io::Error::new(io::ErrorKind::Other, "Incomplete record. Each FastQ record has to consist of 4 lines: header, sequence, separator and qualities.");

        assert_eq!(actual.kind(), expected.kind());
        assert_eq!(actual.to_string(), expected.to_string())
    }

    #[test]
    fn test_reader_from_file_path_doesnt_exist_returns_err() {
        let path = Path::new("/I/dont/exist.fq");

        let actual = Reader::from_file(path).unwrap_err();
        let expected = io::Error::new(io::ErrorKind::NotFound, "foo");

        assert_eq!(actual.kind(), expected.kind());
        assert!(actual.to_string().starts_with("No such file or directory"))
    }

    #[test]
    fn test_reader_from_file_path_exists_returns_ok() {
        let path = Path::new("Cargo.toml");

        assert!(Reader::from_file(path).is_ok())
    }

    #[test]
    fn test_sequence_read_for_record_trait_method_name() {
        let record = Record::with_attrs("id", None, b"ACGT", b"!!!!");

        let actual = record.name();
        let expected = b"id";

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_sequence_read_for_record_trait_method_base_idx_in_range() {
        let fq: &'static [u8] = b"@id description\nACGT\n+\n!!!!\n";
        let mut reader = Reader::new(fq);
        let mut record = Record::new();
        reader.read(&mut record).unwrap();
        let idx = 2;

        let actual = record.base(idx);
        let expected = b'G';

        assert_eq!(actual, expected)
    }

    #[test]
    #[should_panic]
    fn test_sequence_read_for_record_trait_method_base_idx_out_of_range() {
        let fq: &'static [u8] = b"@id description\nACGT\n+\n!!!!\n";
        let mut reader = Reader::new(fq);
        let mut record = Record::new();
        reader.read(&mut record).unwrap();
        // idx 4 is where the newline character would be - we dont want that included
        let idx = 4;

        record.base(idx);
    }

    #[test]
    fn test_sequence_read_for_record_trait_method_base_qual_idx_in_range() {
        let fq: &'static [u8] = b"@id description\nACGT\n+\n!!!!\n";
        let mut reader = Reader::new(fq);
        let mut record = Record::new();
        reader.read(&mut record).unwrap();
        let idx = 2;

        let actual = record.base_qual(idx);
        let expected = b'!';

        assert_eq!(actual, expected)
    }

    #[test]
    #[should_panic]
    fn test_sequence_read_for_record_trait_method_base_qual_idx_out_of_range() {
        let fq: &'static [u8] = b"@id description\nACGT\n+\n!!!!\n";
        let mut reader = Reader::new(fq);
        let mut record = Record::new();
        reader.read(&mut record).unwrap();
        // idx 4 is where the newline character would be - we dont want that included
        let idx = 4;

        record.base_qual(idx);
    }

    #[test]
    fn test_sequence_read_for_record_trait_method_len() {
        let fq: &'static [u8] = b"@id description\nACGT\n+\n!!!!\n";
        let mut reader = Reader::new(fq);
        let mut record = Record::new();
        reader.read(&mut record).unwrap();

        let actual = record.len();
        let expected = 4;

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_writer_to_file_dir_doesnt_exist_returns_err() {
        let path = Path::new("/I/dont/exist.fq");

        let actual = Writer::to_file(path).unwrap_err();
        let expected = io::Error::new(io::ErrorKind::NotFound, "foo");

        assert_eq!(actual.kind(), expected.kind());
        assert!(actual.to_string().starts_with("No such file or directory"))
    }

    #[test]
    fn test_writer_to_file_dir_exists_returns_ok() {
        let path = Path::new("/tmp/out.fq");

        assert!(Writer::to_file(path).is_ok())
    }

    #[test]
    fn test_write_record() {
        let path = Path::new("test.fq");
        let file = fs::File::create(path).unwrap();
        {
            let handle = io::BufWriter::new(file);
            let mut writer = Writer { writer: handle };
            let record = Record::with_attrs("id", Some("desc"), b"ACGT", b"!!!!");

            let write_result = writer.write_record(&record);
            assert!(write_result.is_ok());
        }

        let actual = fs::read_to_string(path).unwrap();
        let expected = "@id desc\nACGT\n+\n!!!!\n";

        assert!(fs::remove_file(path).is_ok());
        assert_eq!(actual, expected)
    }
}