Exercise: Filter FASTQ with noodles-fastq
Goal
Use noodles-fastq to read FASTQ records, drop those shorter than a minimum length, and write the survivors back out:
fn filter_fastq<R: BufRead, W: Write>(
reader: R,
writer: W,
min_len: usize,
) -> std::io::Result<(usize, usize)>Return value: (kept, total) — how many records survived and how many we saw.
This is the first exercise that writes a bioinformatics file format as well as reading one.
The crate
[dependencies]
noodles-fastq = "0.20"You need:
fastq::io::Reader::new(BufRead)and its.records()iteratorfastq::io::Writer::new(Write)and its.write_record(&record)record.sequence(): the returned value has its own.len()method — call it directly. (record.sequence().as_ref()also works if you first bind it aslet seq: &[u8] = ...so the compiler can pick the rightAsRefimpl.)
The exercise
cd day4/ex-fastq-filterMake all three tests pass. They use Cursor<&[u8]> for input and Vec<u8> for output, so no temp files.
How to run
cargo test
cargo run -- data/sample.fastq /tmp/filtered.fastq 5Hints
let mut reader = fastq::io::Reader::new(reader);
let mut writer = fastq::io::Writer::new(writer);
let mut total = 0;
let mut kept = 0;
for result in reader.records() {
let record = result?;
total += 1;
if record.sequence().len() >= min_len {
writer.write_record(&record)?;
kept += 1;
}
}
Ok((kept, total))<W: Write> and not W = File
By taking any Write, we can: - write to a file in main (via File::create), - write to a Vec<u8> in tests, - write to stdout (std::io::stdout()), - gzip-encode the output by wrapping in flate2::write::GzEncoder, - all without changing the function.
This is the same trade we made on day 4 exercise 2 for the reader: a tiny bit of generic syntax buys total composability.
Solution
See day4/ex-fastq-filter-solution/src/main.rs for the full reference. About 15 lines.
Where this leads
- Day 4 exercise 5: bundle the filtered output, the stats from exercise 2, and a plot from exercise 4 into a single
.zipreport. - Day 5: parallelise filtering across many input files with
rayon.