-
Notifications
You must be signed in to change notification settings - Fork 3
Feat/introduce revcomp #201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| use clap::Parser; | ||
|
|
||
| use super::{InputBinseq, Mate, OutputBinseq}; | ||
|
|
||
| /// Reverse complement the sequences in a BINSEQ file. | ||
| #[derive(Parser, Debug)] | ||
| pub struct RevcompCommand { | ||
| #[clap(flatten)] | ||
| pub input: InputBinseq, | ||
|
|
||
| #[clap(flatten)] | ||
| pub output: OutputBinseq, | ||
|
|
||
| /// Which mate(s) to reverse complement | ||
| /// | ||
| /// Only relevant for paired BINSEQ files. Defaults to reverse | ||
| /// complementing both mates; ignored (with a warning) on single-end | ||
| /// files. | ||
| /// | ||
| /// Note: `-m` is already used by `--mode` (BINSEQ output format), so | ||
| /// this flag uses `-M` instead. | ||
| #[clap(short = 'M', long, default_value = "both")] | ||
| pub mate: Mate, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,227 @@ | ||
| mod processor; | ||
|
|
||
| use anyhow::Result; | ||
| use binseq::{bq, cbq, vbq, BinseqReader, BinseqWriterBuilder, ParallelReader}; | ||
| use log::{info, warn}; | ||
|
|
||
| use crate::cli::{BinseqMode, Mate, RevcompCommand}; | ||
| use processor::RevCompProcessor; | ||
|
|
||
| /// Builds a writer that mirrors the input file's own header/configuration, | ||
| /// since reverse complementing changes sequence content but not schema. | ||
| fn get_builder(args: &RevcompCommand) -> Result<BinseqWriterBuilder> { | ||
| let builder = match args.input.mode()? { | ||
| BinseqMode::Bq => { | ||
| let reader = bq::MmapReader::new(args.input.path())?; | ||
| BinseqWriterBuilder::from_bq_header(reader.header()) | ||
| } | ||
| BinseqMode::Vbq => { | ||
| let reader = vbq::MmapReader::new(args.input.path())?; | ||
| BinseqWriterBuilder::from_vbq_header(reader.header()) | ||
| } | ||
| BinseqMode::Cbq => { | ||
| let reader = cbq::MmapReader::new(args.input.path())?; | ||
| BinseqWriterBuilder::from_cbq_header(reader.header()) | ||
| } | ||
| }; | ||
| Ok(builder) | ||
| } | ||
|
|
||
| pub fn run(args: &RevcompCommand) -> Result<()> { | ||
| let reader = BinseqReader::new(args.input.path())?; | ||
| if !reader.is_paired() && args.mate != Mate::Both { | ||
| warn!("Ignoring `--mate/-M` flag as only single channel found in file"); | ||
| } | ||
|
|
||
| let builder = get_builder(args)?; | ||
| let ohandle = args.output.as_writer()?; | ||
| let writer = builder.build(ohandle)?; | ||
| let mut processor = RevCompProcessor::new(writer, args.mate)?; | ||
|
|
||
| if let Some(mut span) = args.input.span { | ||
| let num_records = reader.num_records()?; | ||
| reader.process_parallel_range( | ||
| processor.clone(), | ||
| args.output.threads(), | ||
| span.get_range(num_records)?, | ||
| )?; | ||
| } else { | ||
| reader.process_parallel(processor.clone(), args.output.threads())?; | ||
| } | ||
| processor.finish()?; | ||
|
|
||
| info!( | ||
| "Wrote {} reverse complemented records", | ||
| processor.get_global_record_count() | ||
| ); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use anyhow::Result; | ||
| use clap::Parser; | ||
| use itertools::iproduct; | ||
| use tempfile::NamedTempFile; | ||
|
|
||
| use crate::cli::BinseqMode; | ||
| use crate::testutils::{count_binseq, write_fastx, DEFAULT_NUM_RECORDS}; | ||
|
|
||
| fn encode(in_path: &std::path::Path, out_path: &std::path::Path) -> Result<()> { | ||
| let cmd = crate::cli::EncodeCommand::try_parse_from([ | ||
| "encode", | ||
| in_path.to_str().unwrap(), | ||
| "-o", | ||
| out_path.to_str().unwrap(), | ||
| ])?; | ||
| crate::commands::encode::run(&cmd) | ||
| } | ||
|
|
||
| fn decode_to_fasta(bq_path: &std::path::Path, out_path: &std::path::Path) -> Result<()> { | ||
| let cmd = crate::cli::DecodeCommand::try_parse_from([ | ||
| "decode", | ||
| bq_path.to_str().unwrap(), | ||
| "-o", | ||
| out_path.to_str().unwrap(), | ||
| "-f", | ||
| "a", | ||
| ])?; | ||
| crate::commands::decode::run(&cmd) | ||
| } | ||
|
|
||
| fn revcomp( | ||
| in_path: &std::path::Path, | ||
| out_path: &std::path::Path, | ||
| extra: &[&str], | ||
| ) -> Result<()> { | ||
| let mut cmd_args = vec![ | ||
| "revcomp".to_string(), | ||
| in_path.to_str().unwrap().to_string(), | ||
| "-o".to_string(), | ||
| out_path.to_str().unwrap().to_string(), | ||
| ]; | ||
| cmd_args.extend(extra.iter().map(std::string::ToString::to_string)); | ||
| let cmd = crate::cli::RevcompCommand::try_parse_from(cmd_args)?; | ||
| super::run(&cmd) | ||
| } | ||
|
|
||
| fn reverse_complement_str(seq: &str) -> String { | ||
| seq.chars() | ||
| .rev() | ||
| .map(|c| match c { | ||
| 'A' => 'T', | ||
| 'C' => 'G', | ||
| 'G' => 'C', | ||
| 'T' => 'A', | ||
| other => other, | ||
| }) | ||
| .collect() | ||
| } | ||
|
|
||
| /// Extracts just the sequence lines from a FASTA file, sorted, so | ||
| /// comparisons are insensitive to reordering from parallel processing. | ||
| fn sorted_sequences(path: &std::path::Path) -> Result<Vec<String>> { | ||
| let content = std::fs::read_to_string(path)?; | ||
| let mut seqs: Vec<String> = content | ||
| .lines() | ||
| .filter(|l| !l.starts_with('>')) | ||
| .map(std::string::ToString::to_string) | ||
| .collect(); | ||
| seqs.sort_unstable(); | ||
| Ok(seqs) | ||
| } | ||
|
|
||
| /// Round-tripping revcomp twice must recover the original sequences. | ||
| #[test] | ||
| fn test_revcomp_double_application_is_identity() -> Result<()> { | ||
| for mode in BinseqMode::enum_iter() { | ||
| let in_tmp = write_fastx().call()?; | ||
| let bq_tmp = NamedTempFile::with_suffix(mode.extension())?; | ||
| encode(in_tmp.path(), bq_tmp.path())?; | ||
|
|
||
| let rc_once = NamedTempFile::with_suffix(mode.extension())?; | ||
| revcomp(bq_tmp.path(), rc_once.path(), &[])?; | ||
|
|
||
| let rc_twice = NamedTempFile::with_suffix(mode.extension())?; | ||
| revcomp(rc_once.path(), rc_twice.path(), &[])?; | ||
|
|
||
| let original_fa = NamedTempFile::with_suffix(".fasta")?; | ||
| decode_to_fasta(bq_tmp.path(), original_fa.path())?; | ||
| let roundtrip_fa = NamedTempFile::with_suffix(".fasta")?; | ||
| decode_to_fasta(rc_twice.path(), roundtrip_fa.path())?; | ||
|
|
||
| assert_eq!( | ||
| sorted_sequences(original_fa.path())?, | ||
| sorted_sequences(roundtrip_fa.path())?, | ||
| "double revcomp should be identity for {mode:?}" | ||
| ); | ||
|
|
||
| assert_eq!( | ||
| count_binseq(rc_once.path())?, | ||
| DEFAULT_NUM_RECORDS, | ||
| "revcomp record count wrong for {mode:?}" | ||
| ); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Reverse complementing a known sequence should produce the expected result. | ||
| #[test] | ||
| fn test_revcomp_known_sequence() -> Result<()> { | ||
| let seq = "ACGTACGTGATTACAACGTACGT"; | ||
| let in_tmp = NamedTempFile::with_suffix(".fastq")?; | ||
| { | ||
| use std::io::Write as _; | ||
| let mut f = std::fs::File::create(in_tmp.path())?; | ||
| writeln!(f, "@read1")?; | ||
| writeln!(f, "{seq}")?; | ||
| writeln!(f, "+")?; | ||
| writeln!(f, "{}", "I".repeat(seq.len()))?; | ||
| } | ||
| let bq_tmp = NamedTempFile::with_suffix(".cbq")?; | ||
| encode(in_tmp.path(), bq_tmp.path())?; | ||
|
|
||
| let rc_tmp = NamedTempFile::with_suffix(".cbq")?; | ||
| revcomp(bq_tmp.path(), rc_tmp.path(), &[])?; | ||
|
|
||
| let out_fa = NamedTempFile::with_suffix(".fasta")?; | ||
| decode_to_fasta(rc_tmp.path(), out_fa.path())?; | ||
|
|
||
| let content = std::fs::read_to_string(out_fa.path())?; | ||
| assert!( | ||
| content.contains(&reverse_complement_str(seq)), | ||
| "expected reverse complement of {seq} in output: {content}" | ||
| ); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| /// With `-M 1`/`-M 2`, only the targeted mate should be reverse complemented. | ||
| #[test] | ||
| fn test_revcomp_paired_single_mate() -> Result<()> { | ||
| for (mode, mate_flag) in iproduct!(BinseqMode::enum_iter(), ["1", "2"]) { | ||
| let r1 = write_fastx().call()?; | ||
| let r2 = write_fastx().call()?; | ||
| let bq_tmp = NamedTempFile::with_suffix(mode.extension())?; | ||
| let cmd = crate::cli::EncodeCommand::try_parse_from([ | ||
| "encode", | ||
| r1.path().to_str().unwrap(), | ||
| r2.path().to_str().unwrap(), | ||
| "-o", | ||
| bq_tmp.path().to_str().unwrap(), | ||
| ])?; | ||
| crate::commands::encode::run(&cmd)?; | ||
|
|
||
| let rc_tmp = NamedTempFile::with_suffix(mode.extension())?; | ||
| revcomp(bq_tmp.path(), rc_tmp.path(), &["-M", mate_flag])?; | ||
|
|
||
| assert_eq!( | ||
| count_binseq(rc_tmp.path())?, | ||
| DEFAULT_NUM_RECORDS, | ||
| "revcomp single-mate record count wrong for {mode:?} mate={mate_flag}" | ||
| ); | ||
| } | ||
| Ok(()) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a single-end file is processed and the user specifies a specific mate (e.g.,
-M 2), a warning is logged stating that the--mate/-Mflag is ignored. However, the code still passesargs.mate(which isMate::Two) toRevCompProcessor. Inprocess_record,rc_primaryis computed asmatches!(self.mate, Mate::One | Mate::Both). Sinceself.mateisMate::Two,rc_primaryevaluates tofalse, and the single channel is left untouched (not reverse complemented). This contradicts the warning and results in silent incorrect behavior.To fix this, we should override the
matevariable toMate::Bothwhen the file is single-end so that the single channel is actually reverse complemented as warned.