#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
use anyhow::{bail, ensure, Context, Result};
use env_logger::Env;
use flate2::bufread::MultiGzDecoder;
use flume::{bounded, Receiver, Sender};
use fqgrep_lib::matcher::{validate_fixed_pattern, Matcher, MatcherFactory, MatcherOpts};
use fqgrep_lib::{is_fastq_path, is_gzip_path};
use gzp::BUFSIZE;
use isatty::stdout_isatty;
use itertools::{self, izip, Itertools};
use lazy_static::lazy_static;
use parking_lot::Mutex;
use proglog::{CountFormatterKind, ProgLog, ProgLogBuilder};
use rayon::prelude::*;
use seq_io::fastq::{self, OwnedRecord, Record};
use std::process::ExitCode;
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Read, Write},
path::PathBuf,
str::FromStr,
};
use structopt::clap::arg_enum;
use structopt::{clap::AppSettings, StructOpt};
const CHUNKSIZE: usize = 5000; const READER_CHANNEL_SIZE: usize = 100;
const WRITER_CHANNEL_SIZE: usize = 2000;
lazy_static! {
pub static ref NUM_CPU: String = num_cpus::get().to_string();
}
pub mod built_info {
use lazy_static::lazy_static;
include!(concat!(env!("OUT_DIR"), "/built.rs"));
fn get_software_version() -> String {
let prefix = if let Some(s) = GIT_COMMIT_HASH {
format!("{}-{}", PKG_VERSION, s[0..8].to_owned())
} else {
PKG_VERSION.to_string()
};
let suffix = match GIT_DIRTY {
Some(true) => "-dirty",
_ => "",
};
format!("{}{}", prefix, suffix)
}
lazy_static! {
pub static ref VERSION: String = get_software_version();
}
}
struct FastqWriter {
tx: Sender<Vec<OwnedRecord>>,
lock: Mutex<()>,
}
impl FastqWriter {
fn new(count_tx: Sender<usize>, count: bool, paired: bool, output: Option<PathBuf>) -> Self {
let (tx, rx): (Sender<Vec<OwnedRecord>>, Receiver<Vec<OwnedRecord>>) =
bounded(WRITER_CHANNEL_SIZE);
std::thread::spawn(move || {
let mut maybe_writer: Option<Box<dyn Write>> = {
if count {
None
} else if let Some(file_path) = output {
Some(Box::new(BufWriter::with_capacity(
BUFSIZE,
File::create(file_path).unwrap(),
)))
} else {
Some(Box::new(BufWriter::with_capacity(
BUFSIZE,
std::io::stdout(),
)))
}
};
let mut num_matches = 0;
while let Ok(reads) = rx.recv() {
num_matches += reads.len();
if let Some(ref mut writer) = maybe_writer {
for read in reads {
fastq::write_to(&mut *writer, &read.head, &read.seq, &read.qual)
.expect("failed writing read");
}
};
}
if paired {
num_matches /= 2;
}
if count {
std::io::stdout()
.write_all(format!("{}\n", num_matches).as_bytes())
.unwrap();
}
if let Some(mut writer) = maybe_writer {
writer.flush().expect("Error flushing writer");
};
count_tx
.send(num_matches)
.expect("failed sending final count");
});
let lock = Mutex::new(());
Self { tx, lock }
}
}
fn spawn_reader(file: PathBuf, decompress: bool) -> Receiver<Vec<OwnedRecord>> {
let (tx, rx) = bounded(READER_CHANNEL_SIZE);
std::thread::spawn(move || {
let raw_handle = if file.as_os_str() == "-" {
Box::new(std::io::stdin()) as Box<dyn Read>
} else {
let handle = File::open(&file)
.with_context(|| format!("Error opening input: {}", file.display()))
.unwrap();
Box::new(handle) as Box<dyn Read>
};
let buf_handle = BufReader::with_capacity(BUFSIZE, raw_handle);
let maybe_decoder_handle = {
let is_gzip = is_gzip_path(&file) || (!is_fastq_path(&file) && decompress);
if is_gzip {
Box::new(MultiGzDecoder::new(buf_handle)) as Box<dyn Read>
} else {
Box::new(buf_handle) as Box<dyn Read>
}
};
let fastq_reader = fastq::Reader::with_capacity(maybe_decoder_handle, BUFSIZE)
.into_records()
.chunks(CHUNKSIZE * num_cpus::get());
for chunk in &fastq_reader {
tx.send(chunk.map(|r| r.expect("Error reading")).collect())
.expect("Error sending");
}
});
rx
}
arg_enum! {
#[derive(PartialEq, Debug, Clone)]
enum Color {
Never,
Always,
Auto,
}
}
#[derive(StructOpt, Debug, Clone)]
#[structopt(
name = "fqgrep",
global_setting(AppSettings::ColoredHelp),
global_setting(AppSettings::DeriveDisplayOrder),
version = built_info::VERSION.as_str())
]
#[allow(clippy::struct_excessive_bools)]
struct Opts {
#[structopt(long, short = "t", default_value = NUM_CPU.as_str())]
threads: usize,
#[structopt(long = "color", default_value = "never")]
color: Color,
#[structopt(long, short = "c")]
count: bool,
#[structopt(long, short = "e")]
regexp: Vec<String>,
#[structopt(long, short = "F")]
fixed_strings: bool,
#[structopt(long, short = "f")]
file: Option<PathBuf>,
#[structopt(short = "v")]
invert_match: bool,
#[structopt(short = "Z", long)]
decompress: bool,
#[structopt(long)]
paired: bool,
#[structopt(long)]
reverse_complement: bool,
#[structopt(long)]
progress: bool,
args: Vec<String>,
#[structopt(long, hidden = true)]
output: Option<PathBuf>,
}
fn read_patterns(file: &PathBuf) -> Result<Vec<String>> {
let f = File::open(file).expect("error in opening file");
let r = BufReader::new(f);
let mut v = Vec::new();
for result in r.lines() {
v.push(result?);
}
Ok(v)
}
fn main() -> ExitCode {
if let Some(fqgrep_output) = fqgrep(&setup()) {
ExitCode::from(fqgrep_output)
} else {
ExitCode::SUCCESS
}
}
fn fqgrep(opts: &Opts) -> Option<u8> {
let outer = std::panic::catch_unwind(|| fqgrep_from_opts(opts));
match outer {
Err(_) => {
eprintln!("Error: fqgrep panicked. Please report this as a bug!");
Some(101)
}
Ok(inner) => match inner {
Ok(0) => Some(1),
Ok(_) => None,
Err(e) => {
eprintln!("Error: {}", e);
Some(2)
}
},
}
}
#[allow(clippy::too_many_lines)]
fn fqgrep_from_opts(opts: &Opts) -> Result<usize> {
let mut opts = opts.clone();
if let Some(file) = &opts.file {
for pattern in read_patterns(file)? {
opts.regexp.push(pattern);
}
}
let (pattern, mut files): (Option<String>, Vec<PathBuf>) = {
let (pattern, file_strings): (Option<String>, Vec<String>) = if opts.regexp.is_empty() {
ensure!(
!opts.args.is_empty(),
"Pattern must be given with -e or as the first positional argument "
);
let files = opts.args.iter().skip(1).cloned().collect();
(Some(opts.args[0].clone()), files)
} else {
(None, opts.args.clone())
};
let files = file_strings
.iter()
.map(|s| {
PathBuf::from_str(s)
.with_context(|| format!("Cannot create a path from: {}", s))
.unwrap()
})
.collect();
(pattern, files)
};
if opts.paired {
ensure!(
files.len() <= 1 || files.len() % 2 == 0,
"Input files must be a multiple of two, or either a single file or standard input (assume interleaved) with --paired"
);
}
if opts.fixed_strings {
if let Some(pattern) = &pattern {
validate_fixed_pattern(pattern)?;
} else if !opts.regexp.is_empty() {
for pattern in &opts.regexp {
validate_fixed_pattern(pattern)?;
}
} else {
bail!("A pattern must be given as a positional argument or with -e/--regexp")
}
}
let progress_logger = if opts.progress {
Some(
ProgLogBuilder::new()
.name("fqgrep-progress")
.noun("reads")
.verb("Searched")
.unit(50_000_000)
.count_formatter(CountFormatterKind::Comma)
.build(),
)
} else {
None
};
let match_opts = MatcherOpts {
invert_match: opts.invert_match,
reverse_complement: opts.reverse_complement,
color: opts.color == Color::Always || (opts.color == Color::Auto && stdout_isatty()),
};
let matcher: Box<dyn Matcher + Sync + Send> =
MatcherFactory::new_matcher(&pattern, opts.fixed_strings, &opts.regexp, match_opts);
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(opts.threads)
.build()
.unwrap();
let (count_tx, count_rx): (Sender<usize>, Receiver<usize>) = bounded(1);
let writer = FastqWriter::new(count_tx, opts.count, opts.paired, opts.output.clone());
pool.install(|| {
if files.is_empty() {
files.push(PathBuf::from_str("-").unwrap());
}
if opts.paired {
if files.len() == 1 {
let rx = spawn_reader(files[0].clone(), opts.decompress);
for reads in izip!(rx.iter()) {
let paired_reads = reads
.into_iter()
.tuples::<(OwnedRecord, OwnedRecord)>()
.collect_vec();
process_paired_reads(paired_reads, &matcher, &writer, &progress_logger);
}
} else {
for file_pairs in files.chunks_exact(2) {
let rx1 = spawn_reader(file_pairs[0].clone(), opts.decompress);
let rx2 = spawn_reader(file_pairs[1].clone(), opts.decompress);
for (reads1, reads2) in izip!(rx1.iter(), rx2.iter()) {
let paired_reads = reads1.into_iter().zip(reads2.into_iter()).collect_vec();
process_paired_reads(paired_reads, &matcher, &writer, &progress_logger);
}
}
}
} else {
for file in files {
let rx = spawn_reader(file.clone(), opts.decompress);
for reads in rx.iter() {
let matched_reads: Vec<OwnedRecord> = reads
.into_par_iter()
.map(|mut read| -> Option<OwnedRecord> {
if let Some(progress) = &progress_logger {
progress.record();
}
if matcher.read_match(&mut read) {
Some(read)
} else {
None
}
})
.flatten()
.collect();
let _lock = writer.lock.lock();
writer.tx.send(matched_reads).expect("Failed to send read");
}
}
}
});
drop(writer);
match count_rx.recv() {
Ok(count) => Ok(count),
Err(error) => Err(error).with_context(|| "failed receive final match counts"),
}
}
#[allow(clippy::borrowed_box)] fn process_paired_reads(
reads: Vec<(OwnedRecord, OwnedRecord)>,
matcher: &Box<dyn Matcher + Sync + Send>,
writer: &FastqWriter,
progress_logger: &Option<ProgLog>,
) {
let matched_reads = reads
.into_par_iter()
.map(|(mut read1, mut read2)| {
if let Some(progress) = progress_logger {
progress.record();
progress.record();
}
assert!(
read1.head() == read2.head(),
"Mismatching read pair! R1: {} R2: {}",
std::str::from_utf8(read1.head()).unwrap(),
std::str::from_utf8(read2.head()).unwrap()
);
let match1 = matcher.read_match(&mut read1);
let match2 = (!matcher.opts().color && match1) || matcher.read_match(&mut read2);
if match1 || match2 {
Some((read1, read2))
} else {
None
}
})
.flatten()
.fold(std::vec::Vec::new, |mut _matched_reads, (r1, r2)| {
_matched_reads.push(r1);
_matched_reads.push(r2);
_matched_reads
})
.flatten()
.collect();
let _lock = writer.lock.lock();
writer.tx.send(matched_reads).expect("Failed to send read");
}
fn setup() -> Opts {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
Opts::from_args()
}
#[cfg(test)]
pub mod tests {
use crate::*;
use fgoxide::io::Io;
use rstest::rstest;
use seq_io::fastq::{OwnedRecord, Record};
use tempfile::TempDir;
fn write_fastq(
temp_dir: &TempDir,
sequences_per_fastq: &Vec<Vec<&str>>,
file_extension: String,
) -> Vec<String> {
let mut fastq_paths = Vec::new();
for (fastq_index, fastq_sequences) in sequences_per_fastq.iter().enumerate() {
let name = format!("sample_{fastq_index}{file_extension}");
let fastq_path = temp_dir.path().join(name);
let io = Io::default();
let mut writer = io.new_writer(&fastq_path).unwrap();
for (num, seq) in fastq_sequences.iter().enumerate() {
let read = OwnedRecord {
head: format!("@{num}").as_bytes().to_vec(),
seq: seq.as_bytes().to_vec(),
qual: vec![b'X'; seq.len()],
};
fastq::write_to(&mut writer, &read.head, &read.seq, &read.qual)
.expect("failed writing read");
}
let path_as_string = fastq_path.as_path().display().to_string();
fastq_paths.push(path_as_string);
}
fastq_paths
}
fn write_pattern(temp_dir: &TempDir, pattern: &Vec<String>) -> PathBuf {
let io = Io::default();
let name = String::from("pattern.txt");
let pattern_path = temp_dir.path().join(name);
io.write_lines(&pattern_path, &*pattern).unwrap();
pattern_path
}
fn build_opts(
dir: &TempDir,
seqs: &Vec<Vec<&str>>,
regexp: &Vec<String>,
pattern_from_file: bool,
output: Option<PathBuf>,
compression: String,
) -> Opts {
let fq_path = write_fastq(&dir, &seqs, compression);
let (pattern_string, pattern_file) = {
if pattern_from_file {
(vec![], Some(write_pattern(&dir, ®exp)))
} else {
(regexp.to_vec(), None)
}
};
let return_opts = Opts {
threads: 4,
color: Color::Never,
count: {
if &output == &None {
true
} else {
false
}
},
regexp: pattern_string,
fixed_strings: false,
file: pattern_file,
invert_match: false,
decompress: false,
paired: false,
reverse_complement: false,
progress: true,
args: fq_path.to_vec(),
output: output,
};
return_opts
}
fn slurp_output(result_path: PathBuf) -> Vec<String> {
let mut return_seqs = vec![];
let mut reader = fastq::Reader::from_path(result_path).unwrap();
while let Some(record) = reader.next() {
let record = record.expect("Error reading record");
let seq = std::str::from_utf8(record.seq()).unwrap();
return_seqs.push(seq.to_owned());
}
return_seqs
}
#[rstest]
#[case(false, vec!["AA"], 1)] #[case(false, vec!["CCCG"], 0)] #[case(false, vec!["T"], 3)] #[case(false, vec!["^A"], 1)] #[case(false, vec!["T.....G"], 0)] #[case(false, vec!["G"], 4)] #[case(false, vec!["GGCC", "G..C"], 1)] #[case(false, vec!["Z", "A.....G"], 0)] #[case(false,vec!["^T", "AA"], 3)] #[case(true, vec!["AA"], 1)] #[case(true, vec!["CCCG"], 0)] #[case(true, vec!["CC"], 2)] #[case(true, vec!["^A"], 1)] #[case(true, vec!["T.....G"], 0)] #[case(true, vec!["G"], 3)] #[case(true, vec!["GGCC", "G..C"], 1)] #[case(true, vec!["Z", "A.....G"], 0)] #[case(true, vec!["^T", "AA"], 3)] fn test_reads_when_count_true(
#[case] paired: bool,
#[case] pattern: Vec<&str>,
#[case] expected: usize,
) {
let dir = TempDir::new().unwrap();
let seqs = vec![
vec!["AAAA", "TTTT"],
vec!["GGGG", "CCCC"],
vec!["TTCT", "CGCG"],
vec!["GGTT", "GGCC"],
];
let pattern = pattern.iter().map(|&s| s.to_owned()).collect::<Vec<_>>();
let mut opts = build_opts(&dir, &seqs, &pattern, true, None, String::from(".fq"));
opts.paired = paired;
let result = fqgrep_from_opts(&opts);
assert_eq!(result.unwrap(), expected);
}
#[rstest]
#[case(false, vec!["A"], vec!["AAAA", "ATAT", "TATA", "AAAT", "TTTA"], true)] #[case(false, vec!["A", "G"], vec!["AAAA", "ATAT", "TATA", "AAAT", "TTTA", "GGGG", "CGCG", "GCGC", "CCCG", "GGGC"], true)] #[case(false, vec!["^A"], vec!["AAAA", "ATAT", "AAAT"], true)] #[case(false, vec!["^A", "^G"], vec!["AAAA", "ATAT", "AAAT", "GGGG", "GCGC", "GGGC"], true)] #[case(true, vec!["AAAA"], vec!["AAAA", "CCCC"], true)] #[case(true, vec!["A", "G"], vec!["AAAA", "CCCC", "TTTT", "GGGG", "ATAT", "CGCG", "TATA", "GCGC", "AAAT", "CCCG", "TTTA", "GGGC"], true)]
#[case(true, vec!["A", "G"], vec!["AAAA", "GGGG", "TTTT", "CCCC", "CGCG", "ATAT", "GCGC", "TATA", "CCCG", "AAAT", "GGGC", "TTTA"], false)]
#[case(true, vec!["^AAAA"], vec!["AAAA", "CCCC"], true)] #[case(true, vec!["^AA", "^GG"], vec!["AAAA", "CCCC", "TTTT", "GGGG", "AAAT", "CCCG", "TTTA", "GGGC"], true)] #[case(true, vec!["^AA", "^GG"], vec!["AAAA", "GGGG", "TTTT", "CCCC", "TTTA", "CCCG", "AAAT", "GGGC"], false)] fn test_reads_when_count_false(
#[case] paired: bool,
#[case] pattern: Vec<&str>,
#[case] expected_seq: Vec<&str>,
#[case] expected_bool: bool,
) {
let dir = TempDir::new().unwrap();
let seqs = vec![
vec!["AAAA", "TTTT", "ATAT", "TATA", "AAAT", "TTTA"],
vec!["CCCC", "GGGG", "CGCG", "GCGC", "CCCG", "GGGC"],
];
let out_path = dir.path().join(String::from("output.fq"));
let result_path = &out_path.clone();
let pattern = pattern.iter().map(|&s| s.to_owned()).collect::<Vec<_>>();
let mut opts = build_opts(
&dir,
&seqs,
&pattern,
true,
Some(out_path),
String::from(".fq"),
);
opts.paired = paired;
let _result = fqgrep_from_opts(&opts);
let return_sequences = slurp_output(result_path.to_path_buf());
let sequence_match = expected_seq == return_sequences;
assert_eq!(sequence_match, expected_bool);
}
#[rstest]
#[case(false, false, false, 0)] #[case(false, false, true, 1)] #[case(false, true, false, 4)] #[case(false, true, true, 3)] #[case(true, false, false, 0)] #[case(true, false, true, 1)] #[case(true, true, false, 2)] #[case(true, true, true, 2)] fn test_reverse_complement_and_invert_match(
#[case] paired: bool,
#[case] invert_match: bool,
#[case] reverse_complement: bool,
#[case] expected: usize,
) {
let dir = TempDir::new().unwrap();
let seqs = vec![vec!["GGGG", "GGGG"], vec!["AAAA", "CCCC"]];
let pattern = vec![String::from("TTTT")];
let mut opts = build_opts(&dir, &seqs, &pattern, false, None, String::from(".fq"));
opts.paired = paired;
opts.invert_match = invert_match;
opts.reverse_complement = reverse_complement;
let result = fqgrep_from_opts(&opts);
assert_eq!(result.unwrap(), expected);
}
#[rstest]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: Fixed pattern must contain only DNA bases: .. [^] .. G"
)]
#[case(true, vec![String::from("^G")])] #[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: Fixed pattern must contain only DNA bases: .. [^] .. A"
)]
#[case(true, vec![String::from("^A"),String::from("AA")])] fn test_regexp_from_fixed_string_fails_with_regex(
#[case] fixed_strings: bool,
#[case] pattern: Vec<String>,
) {
let dir = TempDir::new().unwrap();
let seqs = vec![vec!["GGGG", "TTTT"], vec!["AAAA", "CCCC"]];
let mut opts = build_opts(&dir, &seqs, &pattern, true, None, String::from(".fq"));
opts.fixed_strings = fixed_strings;
let _result = fqgrep_from_opts(&opts);
_result.unwrap();
}
#[test]
#[should_panic(
expected = "Input files must be a multiple of two, or either a single file or standard input (assume interleaved) with --paired"
)]
fn test_paired_should_panic_with_three_records() {
let dir = TempDir::new().unwrap();
let seqs = vec![
vec!["GTCAGCTCGAGCATCAGCTACGCACT"],
vec!["AGTGCGTAGCTGATGCTCGAGCTGAC"],
vec!["GGGTCTGAATCCATGGAAAGCTATTG"],
];
let test_pattern = vec![String::from("A")];
let mut opts_test = build_opts(&dir, &seqs, &test_pattern, true, None, String::from(".fq"));
opts_test.paired = true;
let _num_matches = fqgrep_from_opts(&opts_test);
_num_matches.unwrap();
}
#[test]
fn test_regexp_matches_from_file_and_string() {
let dir = TempDir::new().unwrap();
let seqs = vec![
vec!["GTCAGCTCGAGCATCAGCTACGCACT"],
vec!["AGTGCGTAGCTGATGCTCGAGCTGAC"],
vec!["GGGTCTGAATCCATGGAAAGCTATTG"],
];
let test_pattern = vec![String::from("^G")];
let mut opts_test = build_opts(&dir, &seqs, &test_pattern, true, None, String::from(".fq"));
let result = fqgrep_from_opts(&opts_test);
assert_eq!(result.unwrap(), 2);
opts_test.regexp = test_pattern;
let result = fqgrep_from_opts(&opts_test);
assert_eq!(result.unwrap(), 2);
}
#[rstest]
#[case(String::from(".fq"), 3)]
#[case(String::from(".fastq"), 3)]
#[case(String::from(".fq.gz"), 3)]
#[case(String::from(".fq.bgz"), 3)]
fn test_fastq_compression(#[case] extension: String, #[case] expected: usize) {
let dir = TempDir::new().unwrap();
let seqs = vec![
vec!["GTCAG", "ACGT", "GGTG"],
vec!["AGTGCGTAGCTGATGCTCGAGCTGAC"],
vec!["GGGTCTGAATCCATGGAAAGCTATTG"],
];
let test_pattern = vec![String::from("^G")];
let opts = build_opts(&dir, &seqs, &test_pattern, true, None, extension);
let result = fqgrep_from_opts(&opts);
assert_eq!(result.unwrap(), expected);
}
#[rstest]
#[case(false, vec![String::from("*")], Some(101))] #[case(false, vec![String::from("^T")], Some(1))] #[case(true, vec![String::from("GTCAGC")], None)] #[case(true, vec![String::from("^T")], Some(2))] fn test_exit_code_catching(
#[case] fixed_strings: bool,
#[case] pattern: Vec<String>,
#[case] expected: Option<u8>,
) {
let dir = TempDir::new().unwrap();
let seqs = vec![vec!["GTCAGC"], vec!["AGTGCG"], vec!["GGGTCTG"]];
let mut opts = build_opts(&dir, &seqs, &pattern, true, None, String::from(".fq"));
opts.fixed_strings = fixed_strings;
assert_eq!(fqgrep(&opts), expected);
}
}