diff --git "a/RustBioGPT-train.txt" "b/RustBioGPT-train.txt" deleted file mode 100644--- "a/RustBioGPT-train.txt" +++ /dev/null @@ -1,15099 +0,0 @@ -use rand::prelude::*; - -/// A `Struct` for dealing with the randomised part of sub-sampling. -pub struct SubSampler { - /// Number of bases to sub-sample down to. - pub target_total_bases: u64, - /// Random seed to use for sub-sampling. If `None` is used, then the random number generator - /// will be seeded by the operating system. - pub seed: Option, -} - -impl SubSampler { - /// Returns a vector of indices for elements in `v`, but shuffled. - /// - /// # Note - /// - /// If the file has more than 4,294,967,296 reads, this function's behaviour is undefined. - /// - /// # Example - /// - /// ```rust - /// let v: Vec = vec![55, 1]; - /// let sampler = SubSampler { - /// target_total_bases: 100, - /// seed: None, - /// }; - /// let mut num_times_shuffled = 0; - /// let iterations = 500; - /// for _ in 0..iterations { - /// let idxs = sampler.shuffled_indices(&v); - /// if idxs == vec![1, 0] { - /// num_times_shuffled += 1; - /// } - /// } - /// // chances of shuffling the same way 100 times in a row is 3.054936363499605e-151 - /// assert!(num_times_shuffled > 0 && num_times_shuffled < iterations) - /// ``` - fn shuffled_indices(&self, v: &[T]) -> Vec { - let mut indices: Vec = (0..v.len() as u32).collect(); - let mut rng = match self.seed { - Some(s) => rand_pcg::Pcg64::seed_from_u64(s), - None => rand_pcg::Pcg64::seed_from_u64(random()), - }; - - indices.shuffle(&mut rng); - indices - } - - /// Sub-samples `lengths` to the desired `target_total_bases` specified in the `SubSampler` and - /// returns the indices for the reads that were selected. - /// - /// # Example - /// - /// ```rust - /// let v: Vec = vec![50, 50, 50]; - /// let sampler = SubSampler { - /// target_total_bases: 100, - /// seed: Some(1), - /// }; - /// let actual = sampler.indices(&v); - /// - /// assert_eq!(actual.len(), 3); - /// assert!(actual[1]); - /// assert!(actual[2]); - /// assert!(actual[3]); - /// ``` - pub fn indices(&self, lengths: &[u32]) -> (Vec, usize) { - let mut indices = self.shuffled_indices(lengths).into_iter(); - let mut to_keep: Vec = vec![false; lengths.len()]; - let mut total_bases_kept: u64 = 0; - - let mut nb_reads_to_keep = 0; - while total_bases_kept < self.target_total_bases { - let idx = match indices.next() { - Some(i) => i as usize, - None => break, - }; - to_keep[idx] = true; - total_bases_kept += u64::from(lengths[idx.to_owned()]); - nb_reads_to_keep += 1; - } - - (to_keep, nb_reads_to_keep) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shuffled_indices_for_empty_vector_returns_empty() { - let v: Vec = Vec::new(); - let sampler = SubSampler { - target_total_bases: 100, - seed: None, - }; - - let actual = sampler.shuffled_indices(&v); - - assert!(actual.is_empty()) - } - - #[test] - fn shuffled_indices_for_vector_len_one_returns_zero() { - let v: Vec = vec![55]; - let sampler = SubSampler { - target_total_bases: 100, - seed: None, - }; - - let actual = sampler.shuffled_indices(&v); - let expected: Vec = vec![0]; - - assert_eq!(actual, expected) - } - - #[test] - fn shuffled_indices_for_vector_len_two_does_shuffle() { - let v: Vec = vec![55, 1]; - let sampler = SubSampler { - target_total_bases: 100, - seed: None, - }; - - let mut num_times_shuffled = 0; - let iterations = 500; - for _ in 0..iterations { - let idxs = sampler.shuffled_indices(&v); - if idxs == vec![1, 0] { - num_times_shuffled += 1; - } - } - - // chances of shuffling the same way 100 times in a row is 3.054936363499605e-151 - assert!(num_times_shuffled > 0 && num_times_shuffled < iterations) - } - - #[test] - fn shuffled_indices_with_seed_produces_same_ordering() { - let v: Vec = vec![55, 1, 8]; - let sampler1 = SubSampler { - target_total_bases: 100, - seed: Some(1), - }; - - let sampler2 = SubSampler { - target_total_bases: 100, - seed: Some(1), - }; - let idxs1 = sampler1.shuffled_indices(&v); - let idxs2 = sampler2.shuffled_indices(&v); - - for i in 0..idxs1.len() { - assert_eq!(idxs1[i], idxs2[i]) - } - } - - #[test] - fn subsample_empty_lengths_returns_empty() { - let v: Vec = Vec::new(); - let sampler = SubSampler { - target_total_bases: 100, - seed: None, - }; - - let (_, nb_select) = sampler.indices(&v); - - assert_eq!(nb_select, 0) - } - - #[test] - fn subsample_one_length_target_zero_returns_empty() { - let v: Vec = Vec::new(); - let sampler = SubSampler { - target_total_bases: 0, - seed: None, - }; - - let (_, nb_select) = sampler.indices(&v); - - assert_eq!(nb_select, 0); - } - - #[test] - fn subsample_one_length_less_than_target_returns_zero() { - let v: Vec = vec![5]; - let sampler = SubSampler { - target_total_bases: 100, - seed: None, - }; - - let (actual, nb_select) = sampler.indices(&v); - - assert_eq!(nb_select, 1); - assert!(actual[0]) - } - - #[test] - fn subsample_one_length_greater_than_target_returns_zero() { - let v: Vec = vec![500]; - let sampler = SubSampler { - target_total_bases: 100, - seed: None, - }; - - let (actual, nb_select) = sampler.indices(&v); - - assert_eq!(nb_select, 1); - assert!(actual[0]) - } - - #[test] - fn subsample_three_lengths_sum_greater_than_target_returns_two() { - let v: Vec = vec![50, 50, 50]; - let sampler = SubSampler { - target_total_bases: 100, - seed: Some(1), - }; - - let (actual, nb_select) = sampler.indices(&v); - - assert_eq!(nb_select, 2); - assert!(!actual[0]); - assert!(actual[1]); - assert!(actual[2]); - } - - #[test] - fn subsample_three_lengths_sum_less_than_target_returns_three() { - let v: Vec = vec![5, 5, 5]; - let sampler = SubSampler { - target_total_bases: 100, - seed: None, - }; - - let (actual, _) = sampler.indices(&v); - let expected = vec![true; 3]; - - assert_eq!(actual, expected); - } - - #[test] - fn subsample_three_lengths_sum_equal_target_returns_three() { - let v: Vec = vec![25, 25, 50]; - let sampler = SubSampler { - target_total_bases: 100, - seed: None, - }; - - let (actual, _) = sampler.indices(&v); - let expected = vec![true; 3]; - - assert_eq!(actual, expected); - } - - #[test] - fn subsample_three_lengths_all_greater_than_target_returns_two() { - let v: Vec = vec![500, 500, 500]; - let sampler = SubSampler { - target_total_bases: 100, - seed: Some(1), - }; - - let (actual, nb_select) = sampler.indices(&v); - println!("{:?}", actual); - - assert_eq!(nb_select, 1); - assert!(!actual[0]); - assert!(!actual[1]); - assert!(actual[2]); - } -} -#![allow(clippy::redundant_clone)] // due to a structopt problem -use std::io::stdout; - -use anyhow::{Context, Result}; -use fern::colors::{Color, ColoredLevelConfig}; -use log::{debug, error, info}; -use structopt::StructOpt; - -pub use crate::cli::Cli; -pub use crate::fastx::Fastx; -pub use crate::subsampler::SubSampler; - -mod cli; -mod fastx; -mod subsampler; - -/// Sets up the logging based on whether you want verbose logging or not. If `verbose` is `false` -/// then info, warning, and error messages will be printed. If `verbose` is `true` then debug -/// messages will also be printed. -/// -/// # Errors -/// Will error if `fern` fails to apply the logging setup. -fn setup_logger(verbose: bool) -> Result<(), fern::InitError> { - let colors = ColoredLevelConfig::new() - .warn(Color::Yellow) - .debug(Color::Magenta) - .error(Color::Red) - .trace(Color::Green); - - let log_level = if verbose { - log::LevelFilter::Debug - } else { - log::LevelFilter::Info - }; - - fern::Dispatch::new() - .format(move |out, message, record| { - out.finish(format_args!( - "{}[{}][{}] {}", - chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), - record.target(), - colors.color(record.level()), - message - )) - }) - .level(log_level) - .chain(std::io::stderr()) - .apply()?; - Ok(()) -} - -fn main() -> Result<()> { - let args: Cli = Cli::from_args(); - setup_logger(args.verbose).context("Failed to setup the logger")?; - debug!("{:?}", args); - - args.validate_input_output_combination()?; - let is_illumina = args.input.len() == 2; - if is_illumina { - info!("Two input files given. Assuming paired Illumina...") - } - - let input_fastx = Fastx::from_path(&args.input[0]); - - let mut output_handle = match args.output.len() { - 0 => match args.output_type { - None => Box::new(stdout()), - Some(fmt) => niffler::basic::get_writer(Box::new(stdout()), fmt, args.compress_level)?, - }, - _ => { - let out_fastx = Fastx::from_path(&args.output[0]); - out_fastx - .create(args.compress_level, args.output_type) - .context("unable to create the first output file")? - } - }; - - let target_total_bases: u64 = args.genome_size * args.coverage; - info!( - "Target number of bases to subsample to is: {}", - target_total_bases - ); - - info!("Gathering read lengths..."); - let mut read_lengths = input_fastx - .read_lengths() - .context("unable to gather read lengths for the first input file")?; - - if is_illumina { - let second_input_fastx = Fastx::from_path(&args.input[1]); - let expected_num_reads = read_lengths.len(); - info!("Gathering read lengths for second input file..."); - let mate_lengths = second_input_fastx - .read_lengths() - .context("unable to gather read lengths for the second input file")?; - - if mate_lengths.len() != expected_num_reads { - error!("First input has {} reads, but the second has {} reads. Paired Illumina files are assumed to have the same number of reads. The results of this subsample may not be as expected now.", expected_num_reads, read_lengths.len()); - std::process::exit(1); - } else { - info!( - "Both input files have the same number of reads ({}) 👍", - expected_num_reads - ); - } - // add the paired read lengths to the existing lengths - for (i, len) in mate_lengths.iter().enumerate() { - read_lengths[i] += len; - } - } - info!("{} reads detected", read_lengths.len()); - - let subsampler = SubSampler { - target_total_bases, - seed: args.seed, - }; - - let (reads_to_keep, nb_reads_to_keep) = subsampler.indices(&read_lengths); - if is_illumina { - info!("Keeping {} reads from each input", nb_reads_to_keep); - } else { - info!("Keeping {} reads", nb_reads_to_keep); - } - debug!("Indices of reads being kept:\n{:?}", reads_to_keep); - - let mut total_kept_bases = - input_fastx.filter_reads_into(&reads_to_keep, nb_reads_to_keep, &mut output_handle)? as u64; - - // repeat the same process for the second input fastx (if illumina) - if is_illumina { - let second_input_fastx = Fastx::from_path(&args.input[1]); - let second_out_fastx = Fastx::from_path(&args.output[1]); - let mut second_output_handle = second_out_fastx - .create(args.compress_level, args.output_type) - .context("unable to create the second output file")?; - - total_kept_bases += second_input_fastx.filter_reads_into( - &reads_to_keep, - nb_reads_to_keep, - &mut second_output_handle, - )? as u64; - } - - let actual_covg = total_kept_bases / args.genome_size; - info!("Actual coverage of kept reads is {:.2}x", actual_covg); - - info!("Done 🎉"); - - Ok(()) -} -use crate::cli::CompressionExt; -use needletail::errors::ParseErrorKind::EmptyFile; -use needletail::parse_fastx_file; -use std::fs::File; -use std::io::{BufWriter, Write}; -use std::path::{Path, PathBuf}; -use thiserror::Error; - -/// A collection of custom errors relating to the working with files for this package. -#[derive(Error, Debug)] -pub enum FastxError { - /// Indicates that the file is not one of the allowed file types as specified by [`FileType`](#filetype). - #[error("File type of {0} is not fasta or fastq")] - UnknownFileType(String), - - /// Indicates that the specified input file could not be opened/read. - #[error("Read error")] - ReadError { - source: needletail::errors::ParseError, - }, - - /// Indicates that a sequence record could not be parsed. - #[error("Failed to parse record")] - ParseError { - source: needletail::errors::ParseError, - }, - - /// Indicates that the specified output file could not be created. - #[error("Output file could not be created")] - CreateError { source: std::io::Error }, - - /// Indicates and error trying to create the compressor - #[error(transparent)] - CompressOutputError(#[from] niffler::Error), - - /// Indicates that some indices we expected to find in the input file weren't found. - #[error("Some expected indices were not in the input file")] - IndicesNotFound, - - /// Indicates that writing to the output file failed. - #[error("Could not write to output file")] - WriteError { source: anyhow::Error }, -} - -/// A `Struct` used for seamlessly dealing with either compressed or uncompressed fasta/fastq files. -#[derive(Debug, PartialEq)] -pub struct Fastx { - /// The path for the file. - path: PathBuf, -} - -impl Fastx { - /// Create a `Fastx` object from a `std::path::Path`. - /// - /// # Example - /// - /// ```rust - /// let path = std::path::Path::new("input.fa.gz"); - /// let fastx = Fastx::from_path(path); - /// ``` - pub fn from_path(path: &Path) -> Self { - Fastx { - path: path.to_path_buf(), - } - } - /// Create the file associated with this `Fastx` object for writing. - /// - /// # Errors - /// If the file cannot be created then an `Err` containing a variant of [`FastxError`](#fastxerror) is - /// returned. - /// - /// # Example - /// - /// ```rust - /// let path = std::path::Path::new("output.fa"); - /// let fastx = Fastx{ path }; - /// { // this scoping means the file handle is closed afterwards. - /// let file_handle = fastx.create(6, None)?; - /// write!(file_handle, ">read1\nACGT\n")? - /// } - /// ``` - pub fn create( - &self, - compression_lvl: niffler::compression::Level, - compression_fmt: Option, - ) -> Result, FastxError> { - let file = File::create(&self.path).map_err(|source| FastxError::CreateError { source })?; - let file_handle = Box::new(BufWriter::new(file)); - let fmt = match compression_fmt { - None => niffler::Format::from_path(&self.path), - Some(f) => f, - }; - niffler::get_writer(file_handle, fmt, compression_lvl) - .map_err(FastxError::CompressOutputError) - } - - /// Returns a vector containing the lengths of all the reads in the file. - /// - /// # Errors - /// If the file cannot be opened or there is an issue parsing any records then an - /// `Err` containing a variant of [`FastxError`](#fastxerror) is returned. - /// - /// # Example - /// - /// ```rust - /// let text = "@read1\nACGT\n+\n!!!!\n@read2\nG\n+\n!"; - /// let mut file = tempfile::Builder::new().suffix(".fq").tempfile().unwrap(); - /// file.write_all(text.as_bytes()).unwrap(); - /// let fastx = Fastx{ file.path() }; - /// let actual = fastx.read_lengths().unwrap(); - /// let expected: Vec = vec![4, 1]; - /// assert_eq!(actual, expected) - /// ``` - pub fn read_lengths(&self) -> Result, FastxError> { - let mut read_lengths: Vec = vec![]; - let mut reader = match parse_fastx_file(&self.path) { - Ok(rdr) => rdr, - Err(e) if e.kind == EmptyFile => return Ok(read_lengths), - Err(source) => return Err(FastxError::ReadError { source }), - }; - - while let Some(record) = reader.next() { - match record { - Ok(rec) => read_lengths.push(rec.num_bases() as u32), - Err(err) => return Err(FastxError::ParseError { source: err }), - } - } - Ok(read_lengths) - } - - /// Writes reads, with indices contained within `reads_to_keep`, to the specified handle - /// `write_to`. - /// - /// # Errors - /// This function could raise an `Err` instance of [`FastxError`](#fastxerror) in the following - /// circumstances: - /// - If the file (of `self`) cannot be opened. - /// - If writing to `write_to` fails. - /// - If, after iterating through all reads in the file, there is still elements left in - /// `reads_to_keep`. *Note: in this case, this function still writes all reads where indices - /// were found in the file.* - /// - /// # Example - /// - /// ```rust - /// let text = "@read1\nACGT\n+\n!!!!\n@read2\nCCCC\n+\n$$$$\n"; - /// let mut input = tempfile::Builder::new().suffix(".fastq").tempfile().unwrap(); - /// input.write_all(text.as_bytes()).unwrap(); - /// let fastx = Fastx::from_path(input.path()).unwrap(); - /// let mut reads_to_keep: Vec = vec![false, true]); - /// let output = Builder::new().suffix(".fastq").tempfile().unwrap(); - /// let output_fastx = Fastx::from_path(output.path()).unwrap(); - /// { - /// let mut out_fh = output_fastx.create().unwrap(); - /// let filter_result = fastx.filter_reads_into(&mut reads_to_keep, 1, &mut out_fh); - /// assert!(filter_result.is_ok()); - /// } - /// let actual = std::fs::read_to_string(output).unwrap(); - /// let expected = "@read2\nCCCC\n+\n$$$$\n"; - /// assert_eq!(actual, expected) - /// ``` - pub fn filter_reads_into( - &self, - reads_to_keep: &[bool], - nb_reads_keep: usize, - write_to: &mut T, - ) -> Result { - let mut total_len = 0; - let mut reader = - parse_fastx_file(&self.path).map_err(|source| FastxError::ReadError { source })?; - let mut read_idx: usize = 0; - let mut nb_reads_written = 0; - - while let Some(record) = reader.next() { - match record { - Err(source) => return Err(FastxError::ParseError { source }), - Ok(rec) if reads_to_keep[read_idx] => { - total_len += rec.num_bases(); - rec.write(write_to, None) - .map_err(|err| FastxError::WriteError { - source: anyhow::Error::from(err), - })?; - nb_reads_written += 1; - if nb_reads_keep == nb_reads_written { - break; - } - } - Ok(_) => (), - } - - read_idx += 1; - } - - if nb_reads_written == nb_reads_keep { - Ok(total_len) - } else { - Err(FastxError::IndicesNotFound) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::any::Any; - use std::io::{Read, Write}; - use std::path::Path; - use tempfile::Builder; - - #[test] - fn fastx_from_fasta() { - let path = Path::new("data/my.fa"); - - let actual = Fastx::from_path(path); - let expected = Fastx { - path: path.to_path_buf(), - }; - - assert_eq!(actual, expected) - } - - #[test] - fn create_invalid_output_file_raises_error() { - let path = Path::new("invalid/out/path.fq"); - - let actual = Fastx::from_path(path) - .create(niffler::Level::Eight, None) - .err() - .unwrap(); - let expected = FastxError::CreateError { - source: std::io::Error::new( - std::io::ErrorKind::Other, - String::from("No such file or directory (os error 2)"), - ), - }; - - assert_eq!(actual.type_id(), expected.type_id()) - } - - #[test] - fn create_valid_output_file_and_can_write_to_it() { - let file = Builder::new().suffix(".fastq").tempfile().unwrap(); - let mut writer = Fastx::from_path(file.path()) - .create(niffler::Level::Eight, None) - .unwrap(); - - let actual = writer.write(b"foo\nbar"); - - assert!(actual.is_ok()) - } - - #[test] - fn create_valid_compressed_output_file_and_can_write_to_it() { - let file = Builder::new().suffix(".fastq.gz").tempfile().unwrap(); - let mut writer = Fastx::from_path(file.path()) - .create(niffler::Level::Four, None) - .unwrap(); - - let actual = writer.write(b"foo\nbar"); - - assert!(actual.is_ok()) - } - - #[test] - fn get_read_lengths_for_empty_fasta_returns_empty_vector() { - let text = ""; - let mut file = Builder::new().suffix(".fa").tempfile().unwrap(); - file.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(file.path()); - - let actual = fastx.read_lengths().unwrap(); - let expected: Vec = Vec::new(); - - assert_eq!(actual, expected) - } - - #[test] - fn get_read_lengths_for_fasta() { - let text = ">read1\nACGT\n>read2\nG"; - let mut file = Builder::new().suffix(".fa").tempfile().unwrap(); - file.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(file.path()); - - let actual = fastx.read_lengths().unwrap(); - let expected: Vec = vec![4, 1]; - - assert_eq!(actual, expected) - } - - #[test] - fn get_read_lengths_for_fastq() { - let text = "@read1\nACGT\n+\n!!!!\n@read2\nG\n+\n!"; - let mut file = Builder::new().suffix(".fq").tempfile().unwrap(); - file.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(file.path()); - - let actual = fastx.read_lengths().unwrap(); - let expected: Vec = vec![4, 1]; - - assert_eq!(actual, expected) - } - - #[test] - fn filter_reads_empty_indices_no_output() { - let text = "@read1\nACGT\n+\n!!!!"; - let mut input = Builder::new().suffix(".fastq").tempfile().unwrap(); - input.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(input.path()); - let reads_to_keep: Vec = vec![false]; - let output = Builder::new().suffix(".fastq").tempfile().unwrap(); - let output_fastx = Fastx::from_path(output.path()); - let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap(); - let filter_result = fastx.filter_reads_into(&reads_to_keep, 0, &mut out_fh); - - assert!(filter_result.is_ok()); - - let mut actual = String::new(); - output.into_file().read_to_string(&mut actual).unwrap(); - let expected = String::new(); - - assert_eq!(actual, expected) - } - - #[test] - fn filter_fastq_reads_one_index_matches_only_read() { - let text = "@read1\nACGT\n+\n!!!!\n"; - let mut input = Builder::new().suffix(".fastq").tempfile().unwrap(); - input.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(input.path()); - let reads_to_keep: Vec = vec![true]; - let output = Builder::new().suffix(".fastq").tempfile().unwrap(); - let output_fastx = Fastx::from_path(output.path()); - { - let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap(); - let filter_result = fastx.filter_reads_into(&reads_to_keep, 1, &mut out_fh); - assert!(filter_result.is_ok()); - } - - let actual = std::fs::read_to_string(output).unwrap(); - let expected = text; - - assert_eq!(actual, expected) - } - - #[test] - fn filter_fasta_reads_one_index_matches_only_read() { - let text = ">read1\nACGT\n"; - let mut input = Builder::new().suffix(".fa").tempfile().unwrap(); - input.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(input.path()); - let reads_to_keep: Vec = vec![true]; - let output = Builder::new().suffix(".fa").tempfile().unwrap(); - let output_fastx = Fastx::from_path(output.path()); - { - let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap(); - let filter_result = fastx.filter_reads_into(&reads_to_keep, 1, &mut out_fh); - assert!(filter_result.is_ok()); - } - - let actual = std::fs::read_to_string(output).unwrap(); - let expected = text; - - assert_eq!(actual, expected) - } - - #[test] - fn filter_fastq_reads_one_index_matches_one_of_two_reads() { - let text = "@read1\nACGT\n+\n!!!!\n@read2\nCCCC\n+\n$$$$\n"; - let mut input = Builder::new().suffix(".fastq").tempfile().unwrap(); - input.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(input.path()); - let reads_to_keep: Vec = vec![false, true]; - let output = Builder::new().suffix(".fastq").tempfile().unwrap(); - let output_fastx = Fastx::from_path(output.path()); - { - let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap(); - let filter_result = fastx.filter_reads_into(&reads_to_keep, 1, &mut out_fh); - assert!(filter_result.is_ok()); - } - - let actual = std::fs::read_to_string(output).unwrap(); - let expected = "@read2\nCCCC\n+\n$$$$\n"; - - assert_eq!(actual, expected) - } - - #[test] - fn filter_fastq_reads_two_indices_matches_first_and_last_reads() { - let text = "@read1\nACGT\n+\n!!!!\n@read2\nCCCC\n+\n$$$$\n@read3\nA\n+\n$\n"; - let mut input = Builder::new().suffix(".fastq").tempfile().unwrap(); - input.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(input.path()); - let reads_to_keep: Vec = vec![true, false, true]; - let output = Builder::new().suffix(".fastq").tempfile().unwrap(); - let output_fastx = Fastx::from_path(output.path()); - { - let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap(); - let filter_result = fastx.filter_reads_into(&reads_to_keep, 2, &mut out_fh); - assert!(filter_result.is_ok()); - } - - let actual = std::fs::read_to_string(output).unwrap(); - let expected = "@read1\nACGT\n+\n!!!!\n@read3\nA\n+\n$\n"; - - assert_eq!(actual, expected) - } - - #[test] - fn filter_fasta_reads_one_index_out_of_range() { - let text = ">read1 length=4\nACGT\n>read2\nCCCC\n"; - let mut input = Builder::new().suffix(".fa").tempfile().unwrap(); - input.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(input.path()); - let reads_to_keep: Vec = vec![true, false, true]; - let output = Builder::new().suffix(".fa").tempfile().unwrap(); - let output_fastx = Fastx::from_path(output.path()); - { - let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap(); - let filter_result = fastx.filter_reads_into(&reads_to_keep, 2, &mut out_fh); - assert!(filter_result.is_err()); - } - - let actual = std::fs::read_to_string(output).unwrap(); - let expected = ">read1 length=4\nACGT\n"; - - assert_eq!(actual, expected) - } - - #[test] - fn filter_fastq_reads_one_index_out_of_range() { - let text = "@read1 length=4\nACGT\n+\n!!!!\n@read2\nC\n+\n^\n"; - let mut input = Builder::new().suffix(".fq").tempfile().unwrap(); - input.write_all(text.as_bytes()).unwrap(); - let fastx = Fastx::from_path(input.path()); - let reads_to_keep: Vec = vec![true, false, true]; - let output = Builder::new().suffix(".fq").tempfile().unwrap(); - let output_fastx = Fastx::from_path(output.path()); - { - let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap(); - let filter_result = fastx.filter_reads_into(&reads_to_keep, 2, &mut out_fh); - assert!(filter_result.is_err()); - } - - let actual = std::fs::read_to_string(output).unwrap(); - let expected = "@read1 length=4\nACGT\n+\n!!!!\n"; - - assert_eq!(actual, expected) - } -} -use regex::Regex; -use std::ffi::{OsStr, OsString}; -use std::ops::{Div, Mul}; -use std::path::{Path, PathBuf}; -use std::str::FromStr; -use structopt::StructOpt; -use thiserror::Error; - -/// Randomly subsample reads to a specified coverage. -#[derive(Debug, StructOpt)] -#[structopt()] -pub struct Cli { - /// The fast{a,q} file(s) to subsample. - /// - /// For paired Illumina you may either pass this flag twice `-i r1.fq -i r2.fq` or give two - /// files consecutively `-i r1.fq r2.fq`. - #[structopt( - short = "i", - long = "input", - parse(try_from_os_str = check_path_exists), - multiple = true, - required = true - )] - pub input: Vec, - - /// Output filepath(s); stdout if not present. - /// - /// For paired Illumina you may either pass this flag twice `-o o1.fq -o o2.fq` or give two - /// files consecutively `-o o1.fq o2.fq`. NOTE: The order of the pairs is assumed to be the - /// same as that given for --input. This option is required for paired input. - #[structopt(short = "o", long = "output", parse(from_os_str), multiple = true)] - pub output: Vec, - - /// Genome size to calculate coverage with respect to. e.g., 4.3kb, 7Tb, 9000, 4.1MB - #[structopt(short = "g", long = "genome-size")] - pub genome_size: GenomeSize, - - /// The desired coverage to sub-sample the reads to. - #[structopt(short = "c", long = "coverage", value_name = "FLOAT")] - pub coverage: Coverage, - - /// Random seed to use. - #[structopt(short = "s", long = "seed", value_name = "INT")] - pub seed: Option, - - /// Switch on verbosity. - #[structopt(short)] - pub verbose: bool, - - /// u: uncompressed; b: Bzip2; g: Gzip; l: Lzma - /// - /// Rasusa will attempt to infer the output compression format automatically from the filename - /// extension. This option is used to override that. If writing to stdout, the default is - /// uncompressed - #[structopt(short = "O", long, value_name = "u|b|g|l", parse(try_from_str = parse_compression_format), possible_values = &["u", "b", "g", "l"], case_insensitive=true, hide_possible_values = true)] - pub output_type: Option, - - /// Compression level to use if compressing output - #[structopt(short = "l", long, parse(try_from_str = parse_level), default_value="6", value_name = "1-9")] - pub compress_level: niffler::Level, -} - -impl Cli { - /// Checks there is a valid and equal number of `--input` and `--output` arguments given. - /// - /// # Errors - /// A [`CliError::BadInputOutputCombination`](#clierror) is returned for the following: - /// - Either `--input` or `--output` are passed more than twice - /// - An unequal number of `--input` and `--output` are passed. The only exception to - /// this is if one `--input` and zero `--output` are passed, in which case, the output - /// will be sent to STDOUT. - pub fn validate_input_output_combination(&self) -> Result<(), CliError> { - let out_len = self.output.len(); - let in_len = self.input.len(); - - if in_len > 2 { - let msg = String::from("Got more than 2 files for input."); - return Err(CliError::BadInputOutputCombination(msg)); - } - if out_len > 2 { - let msg = String::from("Got more than 2 files for output."); - return Err(CliError::BadInputOutputCombination(msg)); - } - match (in_len as isize - out_len as isize) as isize { - diff if diff == 1 && in_len == 1 => Ok(()), - diff if diff != 0 => Err(CliError::BadInputOutputCombination(format!( - "Got {} --input but {} --output", - in_len, out_len - ))), - _ => Ok(()), - } - } -} - -/// A collection of custom errors relating to the command line interface for this package. -#[derive(Error, Debug, PartialEq)] -pub enum CliError { - /// Indicates that a string cannot be parsed into a [`MetricSuffix`](#metricsuffix). - #[error("{0} is not a valid metric suffix")] - InvalidMetricSuffix(String), - - /// Indicates that a string cannot be parsed into a [`GenomeSize`](#genomesize). - #[error("{0} is not a valid genome size. Valid forms include 4gb, 3000, 8.7Kb etc.")] - InvalidGenomeSizeString(String), - - /// Indicates that a string cannot be parsed into a [`Coverage`](#coverage). - #[error("{0} is not a valid coverage string. Coverage must be either an integer or a float and can end with an optional 'x' character")] - InvalidCoverageValue(String), - - /// Indicates that a string cannot be parsed into a [`CompressionFormat`](#compressionformat). - #[error("{0} is not a valid output format")] - InvalidCompression(String), - - /// Indicates a bad combination of input and output files was passed. - #[error("Bad combination of input and output files: {0}")] - BadInputOutputCombination(String), -} - -/// A metric suffix is a unit suffix used to indicate the multiples of (in this case) base pairs. -/// For instance, the metric suffix 'Kb' refers to kilobases. Therefore, 6.9kb means 6900 base pairs. -#[derive(PartialEq, Debug)] -enum MetricSuffix { - Base, - Kilo, - Mega, - Giga, - Tera, -} - -impl FromStr for MetricSuffix { - type Err = CliError; - - /// Parses a string into a `MetricSuffix`. - /// - /// # Example - /// ```rust - /// let s = "5.5mb"; - /// let metric_suffix = MetricSuffix::from_str(s); - /// - /// assert_eq!(metric_suffix, MetricSuffix::Mega) - /// ``` - fn from_str(suffix: &str) -> Result { - let suffix_lwr = suffix.to_lowercase(); - let metric_suffix = match suffix_lwr.as_str() { - s if "b".contains(s) => MetricSuffix::Base, - s if "kb".contains(s) => MetricSuffix::Kilo, - s if "mb".contains(s) => MetricSuffix::Mega, - s if "gb".contains(s) => MetricSuffix::Giga, - s if "tb".contains(s) => MetricSuffix::Tera, - _ => { - return Err(CliError::InvalidMetricSuffix(suffix.to_string())); - } - }; - Ok(metric_suffix) - } -} - -/// Allow for multiplying a `f64` by a `MetricSuffix`. -/// -/// # Example -/// -/// ```rust -/// let metric_suffix = MetricSuffix::Mega; -/// let x: f64 = 5.5; -/// -/// assert_eq!(x * metric_suffix, 5_500_000) -/// ``` -impl Mul for f64 { - type Output = Self; - - fn mul(self, rhs: MetricSuffix) -> Self::Output { - match rhs { - MetricSuffix::Base => self, - MetricSuffix::Kilo => self * 1_000.0, - MetricSuffix::Mega => self * 1_000_000.0, - MetricSuffix::Giga => self * 1_000_000_000.0, - MetricSuffix::Tera => self * 1_000_000_000_000.0, - } - } -} - -/// An object for collecting together methods for working with the genome size parameter for this -/// package. -#[derive(Debug, PartialOrd, PartialEq, Copy, Clone)] -pub struct GenomeSize(u64); - -/// Allow for comparison of a `u64` and a `GenomeSize`. -/// -/// # Example -/// -/// ```rust -/// assert!(GenomeSize(10) == 10) -/// ``` -impl PartialEq for GenomeSize { - fn eq(&self, other: &u64) -> bool { - self.0 == *other - } -} - -impl FromStr for GenomeSize { - type Err = CliError; - - /// Parses a string into a `GenomeSize`. - /// - /// # Example - /// ```rust - /// let s = "5.5mb"; - /// let genome_size = GenomeSize::from_str(s); - /// - /// assert_eq!(genome_size, GenomeSize(5_500_000)) - /// ``` - fn from_str(s: &str) -> Result { - let text = s.to_lowercase(); - let re = Regex::new(r"(?P[0-9]*\.?[0-9]+)(?P\w*)$").unwrap(); - let captures = match re.captures(text.as_str()) { - Some(cap) => cap, - None => { - return Err(CliError::InvalidGenomeSizeString(s.to_string())); - } - }; - let size = captures - .name("size") - .unwrap() - .as_str() - .parse::() - .unwrap(); - let metric_suffix = MetricSuffix::from_str(captures.name("sfx").unwrap().as_str())?; - - Ok(GenomeSize((size * metric_suffix) as u64)) - } -} - -/// Allow for multiplying a `GenomeSize` by a [`Coverage`](#coverage). -/// -/// # Example -/// -/// ```rust -/// let genome_size = GenomeSize(100); -/// let covg = Coverage(5); -/// -/// assert_eq!(genome_size * covg, 500) -/// ``` -impl Mul for GenomeSize { - type Output = u64; - - fn mul(self, rhs: Coverage) -> Self::Output { - (self.0 as f32 * rhs.0) as u64 - } -} - -/// Allow for dividing a `u64` by a `GenomeSize`. -/// -/// # Example -/// -/// ```rust -/// let x: u64 = 210; -/// let size = GenomeSize(200); -/// -/// let actual = x / size; -/// let expected = 1.05; -/// -/// assert_eq!(actual, expected) -/// ``` -impl Div for u64 { - type Output = f64; - - fn div(self, rhs: GenomeSize) -> Self::Output { - (self as f64) / (rhs.0 as f64) - } -} - -/// An object for collecting together methods for working with the coverage parameter for this -/// package. -#[derive(Debug, PartialOrd, PartialEq, Copy, Clone)] -pub struct Coverage(f32); - -/// Allow for comparison of a `f32` and a `Coverage`. -/// -/// # Example -/// -/// ```rust -/// assert!(Coverage(10) == 10.0) -/// ``` -impl PartialEq for Coverage { - fn eq(&self, other: &f32) -> bool { - self.0 == *other - } -} - -impl FromStr for Coverage { - type Err = CliError; - - /// Parses a string into a `Coverage`. - /// - /// # Example - /// ```rust - /// let s = "100x"; - /// let covg = Coverage::from_str(s); - /// - /// assert_eq!(covg, Coverage(100)) - /// ``` - fn from_str(s: &str) -> Result { - let re = Regex::new(r"^(?P[0-9]*\.?[0-9]+)(?i)x?$").unwrap(); - let captures = match re.captures(s) { - Some(cap) => cap, - None => { - return Err(CliError::InvalidCoverageValue(s.to_string())); - } - }; - Ok(Coverage( - captures - .name("covg") - .unwrap() - .as_str() - .parse::() - .unwrap(), - )) - } -} - -/// Allow for multiplying a `Coverage` by a [`GenomeSize`](#genomesize). -/// -/// # Example -/// -/// ```rust -/// let covg = Coverage(5); -/// let genome_size = GenomeSize(100); -/// -/// assert_eq!(covg * genome_size, 500) -/// ``` -impl Mul for Coverage { - type Output = u64; - - fn mul(self, rhs: GenomeSize) -> Self::Output { - (self.0 * (rhs.0 as f32)) as u64 - } -} - -pub trait CompressionExt { - fn from_path + ?Sized>(p: &S) -> Self; -} - -impl CompressionExt for niffler::compression::Format { - /// Attempts to infer the compression type from the file extension. If the extension is not - /// known, then Uncompressed is returned. - fn from_path + ?Sized>(p: &S) -> Self { - let path = Path::new(p); - match path.extension().map(|s| s.to_str()) { - Some(Some("gz")) => Self::Gzip, - Some(Some("bz") | Some("bz2")) => Self::Bzip, - Some(Some("lzma")) => Self::Lzma, - _ => Self::No, - } - } -} - -fn parse_compression_format(s: &str) -> Result { - match s { - "b" | "B" => Ok(niffler::Format::Bzip), - "g" | "G" => Ok(niffler::Format::Gzip), - "l" | "L" => Ok(niffler::Format::Lzma), - "u" | "U" => Ok(niffler::Format::No), - _ => Err(CliError::InvalidCompression(s.to_string())), - } -} -/// A utility function that allows the CLI to error if a path doesn't exist -fn check_path_exists + ?Sized>(s: &S) -> Result { - let path = PathBuf::from(s); - if path.exists() { - Ok(path) - } else { - Err(OsString::from(format!("{:?} does not exist", path))) - } -} - -/// A utility function to validate compression level is in allowed range -#[allow(clippy::redundant_clone)] -fn parse_level(s: &str) -> Result { - let lvl = match s.parse::() { - Ok(1) => niffler::Level::One, - Ok(2) => niffler::Level::Two, - Ok(3) => niffler::Level::Three, - Ok(4) => niffler::Level::Four, - Ok(5) => niffler::Level::Five, - Ok(6) => niffler::Level::Six, - Ok(7) => niffler::Level::Seven, - Ok(8) => niffler::Level::Eight, - Ok(9) => niffler::Level::Nine, - _ => return Err(format!("Compression level {} not in the range 1-9", s)), - }; - Ok(lvl) -} - -#[cfg(test)] -mod tests { - use super::*; - - const ERROR: f32 = f32::EPSILON; - - #[test] - fn no_args_given_raises_error() { - let passed_args = vec!["rasusa"]; - let args: Result = Cli::from_iter_safe(passed_args); - - let actual = args.unwrap_err().kind; - let expected = clap::ErrorKind::MissingRequiredArgument; - - assert_eq!(actual, expected) - } - - #[test] - fn no_input_file_given_raises_error() { - let passed_args = vec!["rasusa", "-c", "30", "-g", "3mb"]; - let args: Result = Cli::from_iter_safe(passed_args); - - let actual = args.unwrap_err().kind; - let expected = clap::ErrorKind::MissingRequiredArgument; - - assert_eq!(actual, expected) - } - - #[test] - fn no_coverage_given_raises_error() { - let passed_args = vec!["rasusa", "-i", "in.fq", "-g", "3mb"]; - let args: Result = Cli::from_iter_safe(passed_args); - - let actual = args.unwrap_err().kind; - let expected = clap::ErrorKind::MissingRequiredArgument; - - assert_eq!(actual, expected) - } - - #[test] - fn invalid_coverage_given_raises_error() { - let passed_args = vec!["rasusa", "-i", "in.fq", "-g", "3mb", "-c", "foo"]; - let args: Result = Cli::from_iter_safe(passed_args); - - let actual = args.unwrap_err().kind; - let expected = clap::ErrorKind::ValueValidation; - - assert_eq!(actual, expected) - } - - #[test] - fn no_genome_size_given_raises_error() { - let passed_args = vec!["rasusa", "-i", "in.fq", "-c", "5"]; - let args: Result = Cli::from_iter_safe(passed_args); - - let actual = args.unwrap_err().kind; - let expected = clap::ErrorKind::MissingRequiredArgument; - - assert_eq!(actual, expected) - } - - #[test] - fn invalid_genome_size_given_raises_error() { - let passed_args = vec!["rasusa", "-i", "in.fq", "-c", "5", "-g", "8jb"]; - let args: Result = Cli::from_iter_safe(passed_args); - - let actual = args.unwrap_err().kind; - let expected = clap::ErrorKind::ValueValidation; - - assert_eq!(actual, expected) - } - - #[test] - fn invalid_seed_given_raises_error() { - let passed_args = vec!["rasusa", "-i", "in.fq", "-c", "5", "-g", "8mb", "-s", "foo"]; - let args: Result = Cli::from_iter_safe(passed_args); - - let actual = args.unwrap_err().kind; - let expected = clap::ErrorKind::ValueValidation; - - assert_eq!(actual, expected) - } - - #[test] - fn all_valid_args_parsed_as_expected() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec![ - "rasusa", - "-i", - infile, - "-c", - "5", - "-g", - "8mb", - "-s", - "88", - "-o", - "my/output/file.fq", - ]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - assert_eq!(args.input[0], PathBuf::from_str(infile).unwrap()); - assert_eq!(args.coverage, Coverage(5.0)); - assert_eq!(args.genome_size, GenomeSize(8_000_000)); - assert_eq!(args.seed, Some(88)); - assert_eq!( - args.output[0], - PathBuf::from_str("my/output/file.fq").unwrap() - ) - } - - #[test] - fn all_valid_args_with_two_inputs_parsed_as_expected() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec![ - "rasusa", - "-i", - infile, - infile, - "-c", - "5", - "-g", - "8mb", - "-s", - "88", - "-o", - "my/output/file.fq", - ]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - let expected_input = vec![ - PathBuf::from_str(infile).unwrap(), - PathBuf::from_str(infile).unwrap(), - ]; - assert_eq!(args.input, expected_input); - assert_eq!(args.coverage, Coverage(5.0)); - assert_eq!(args.genome_size, GenomeSize(8_000_000)); - assert_eq!(args.seed, Some(88)); - assert_eq!( - args.output[0], - PathBuf::from_str("my/output/file.fq").unwrap() - ) - } - - #[test] - fn all_valid_args_with_two_inputs_using_flag_twice_parsed_as_expected() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec![ - "rasusa", - "-i", - infile, - "-i", - infile, - "-c", - "5", - "-g", - "8mb", - "-s", - "88", - "-o", - "my/output/file.fq", - ]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - let expected_input = vec![ - PathBuf::from_str(infile).unwrap(), - PathBuf::from_str(infile).unwrap(), - ]; - assert_eq!(args.input, expected_input); - assert_eq!(args.coverage, Coverage(5.0)); - assert_eq!(args.genome_size, GenomeSize(8_000_000)); - assert_eq!(args.seed, Some(88)); - assert_eq!( - args.output[0], - PathBuf::from_str("my/output/file.fq").unwrap() - ) - } - - #[test] - fn three_inputs_raises_error() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec![ - "rasusa", - "-i", - infile, - "-i", - infile, - "-i", - infile, - "-c", - "5", - "-g", - "8mb", - "-s", - "88", - "-o", - "my/output/file.fq", - ]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - let actual: CliError = args.validate_input_output_combination().unwrap_err(); - let expected = - CliError::BadInputOutputCombination(String::from("Got more than 2 files for input.")); - - assert_eq!(actual, expected) - } - - #[test] - fn three_outputs_raises_error() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec![ - "rasusa", - "-i", - infile, - "-i", - infile, - "-c", - "5", - "-g", - "8mb", - "-s", - "88", - "-o", - "my/output/file.fq", - "-o", - "out.fq", - "-o", - "out.fq", - ]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - let actual: CliError = args.validate_input_output_combination().unwrap_err(); - let expected = - CliError::BadInputOutputCombination(String::from("Got more than 2 files for output.")); - - assert_eq!(actual, expected) - } - - #[test] - fn one_input_no_output_is_ok() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec!["rasusa", "-i", infile, "-c", "5", "-g", "8mb", "-s", "88"]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - let actual = args.validate_input_output_combination(); - - assert!(actual.is_ok()) - } - - #[test] - fn two_inputs_one_output_raises_error() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec![ - "rasusa", "-i", infile, "-i", infile, "-c", "5", "-g", "8mb", "-s", "88", "-o", - "out.fq", - ]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - let actual: CliError = args.validate_input_output_combination().unwrap_err(); - let expected = - CliError::BadInputOutputCombination(String::from("Got 2 --input but 1 --output")); - - assert_eq!(actual, expected) - } - - #[test] - fn one_input_two_outputs_raises_error() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec![ - "rasusa", "-i", infile, "-c", "5", "-g", "8mb", "-s", "88", "-o", "out.fq", "-o", - "out.fq", - ]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - let actual: CliError = args.validate_input_output_combination().unwrap_err(); - let expected = - CliError::BadInputOutputCombination(String::from("Got 1 --input but 2 --output")); - - assert_eq!(actual, expected) - } - - #[test] - fn two_input_two_outputs_is_ok() { - let infile = "tests/cases/r1.fq.gz"; - let passed_args = vec![ - "rasusa", "-i", infile, "-i", infile, "-c", "5", "-g", "8mb", "-s", "88", "-o", - "out.fq", "-o", "out.fq", - ]; - let args = Cli::from_iter_safe(passed_args).unwrap(); - - let actual = args.validate_input_output_combination(); - - assert!(actual.is_ok()) - } - - #[test] - fn float_multiply_with_base_unit() { - let actual = 4.5 * MetricSuffix::Base; - let expected = 4.5; - - let diff = (actual.abs() - expected).abs(); - assert!(diff < f64::EPSILON) - } - - #[test] - fn integer_only_returns_integer() { - let actual = GenomeSize::from_str("6").unwrap(); - let expected = 6; - - assert_eq!(actual, expected); - } - - #[test] - fn float_only_returns_integer() { - let actual = GenomeSize::from_str("6.5").unwrap(); - let expected = 6; - - assert_eq!(actual, expected); - } - - #[test] - fn int_and_suffix_returns_multiplied_int() { - let actual = GenomeSize::from_str("5mb").unwrap(); - let expected = 5_000_000; - - assert_eq!(actual, expected); - } - - #[test] - fn float_and_suffix_returns_multiplied_float_as_int() { - let actual = GenomeSize::from_str("5.4kB").unwrap(); - let expected = 5_400; - - assert_eq!(actual, expected); - } - - #[test] - fn float_without_leading_int_and_suffix_returns_multiplied_float_as_int() { - let actual = GenomeSize::from_str(".77G").unwrap(); - let expected = 770_000_000; - - assert_eq!(actual, expected); - } - - #[test] - fn int_and_tera_suffix_returns_multiplied_int() { - let actual = GenomeSize::from_str("7TB").unwrap(); - let expected = 7_000_000_000_000; - - assert_eq!(actual, expected); - } - - #[test] - fn int_and_base_suffix_returns_int_without_scaling() { - let actual = GenomeSize::from_str("7B").unwrap(); - let expected = 7; - - assert_eq!(actual, expected); - } - - #[test] - fn invalid_suffix_returns_err() { - let genome_size = String::from(".77uB"); - let actual = GenomeSize::from_str(genome_size.as_str()).unwrap_err(); - let expected = CliError::InvalidMetricSuffix(String::from("ub")); - - assert_eq!(actual, expected); - } - - #[test] - fn empty_string_returns_error() { - let actual = GenomeSize::from_str("").unwrap_err(); - let expected = CliError::InvalidGenomeSizeString(String::from("")); - - assert_eq!(actual, expected); - } - - #[test] - fn suffix_with_no_size_returns_error() { - let actual = GenomeSize::from_str("gb"); - - assert!(actual.is_err()); - } - - #[test] - fn int_coverage_returns_float() { - let actual = Coverage::from_str("56").unwrap(); - let expected = 56.0; - - assert!((expected - actual.0).abs() < ERROR) - } - - #[test] - fn float_coverage_returns_float() { - let actual = Coverage::from_str("56.6").unwrap(); - let expected = 56.6; - - assert!((expected - actual.0).abs() < ERROR) - } - - #[test] - fn empty_coverage_returns_err() { - let coverage = String::from(""); - - let actual = Coverage::from_str(coverage.as_str()).unwrap_err(); - let expected = CliError::InvalidCoverageValue(coverage); - - assert_eq!(actual, expected) - } - - #[test] - fn non_number_coverage_returns_err() { - let coverage = String::from("foo"); - - let actual = Coverage::from_str(coverage.as_str()).unwrap_err(); - let expected = CliError::InvalidCoverageValue(coverage); - - assert_eq!(actual, expected) - } - - #[test] - fn zero_coverage_returns_zero() { - let actual = Coverage::from_str("0").unwrap(); - let expected = 0.0; - - assert!((expected - actual.0).abs() < ERROR) - } - - #[test] - fn int_ending_in_x_coverage_returns_float() { - let actual = Coverage::from_str("1X").unwrap(); - let expected = 1.0; - - assert!((expected - actual.0).abs() < ERROR) - } - - #[test] - fn float_ending_in_x_coverage_returns_float() { - let actual = Coverage::from_str("1.9X").unwrap(); - let expected = 1.9; - - assert!((expected - actual.0).abs() < ERROR) - } - - #[test] - fn mega_suffix_from_string() { - let actual = MetricSuffix::from_str("MB").unwrap(); - let expected = MetricSuffix::Mega; - - assert_eq!(actual, expected) - } - - #[test] - fn kilo_suffix_from_string() { - let actual = MetricSuffix::from_str("kB").unwrap(); - let expected = MetricSuffix::Kilo; - - assert_eq!(actual, expected) - } - - #[test] - fn giga_suffix_from_string() { - let actual = MetricSuffix::from_str("Gb").unwrap(); - let expected = MetricSuffix::Giga; - - assert_eq!(actual, expected) - } - - #[test] - fn tera_suffix_from_string() { - let actual = MetricSuffix::from_str("tb").unwrap(); - let expected = MetricSuffix::Tera; - - assert_eq!(actual, expected) - } - - #[test] - fn base_suffix_from_string() { - let actual = MetricSuffix::from_str("B").unwrap(); - let expected = MetricSuffix::Base; - - assert_eq!(actual, expected) - } - - #[test] - fn empty_string_is_base_metric_suffix() { - let suffix = String::from(""); - let actual = MetricSuffix::from_str(suffix.as_str()).unwrap(); - let expected = MetricSuffix::Base; - - assert_eq!(actual, expected) - } - - #[test] - fn invalid_suffix_raises_error() { - let suffix = String::from("ub"); - let actual = MetricSuffix::from_str(suffix.as_str()).unwrap_err(); - let expected = CliError::InvalidMetricSuffix(suffix); - - assert_eq!(actual, expected) - } - - #[test] - fn multiply_genome_size_by_coverage() { - let genome_size = GenomeSize::from_str("4.2kb").unwrap(); - let covg = Coverage::from_str("11.7866").unwrap(); - - let actual = genome_size * covg; - let expected: u64 = 49_503; - - assert_eq!(actual, expected) - } - - #[test] - fn multiply_coverage_by_genome_size() { - let genome_size = GenomeSize::from_str("4.2kb").unwrap(); - let covg = Coverage::from_str("11.7866").unwrap(); - - let actual = covg * genome_size; - let expected: u64 = 49_503; - - assert_eq!(actual, expected) - } - - #[test] - fn divide_u64_by_genome_size() { - let x: u64 = 210; - let size = GenomeSize(200); - - let actual = x / size; - let expected = 1.05; - - let diff = (actual.abs() - expected).abs(); - assert!(diff < f64::EPSILON) - } - - #[test] - fn compression_format_from_str() { - let mut s = "B"; - assert_eq!(parse_compression_format(s).unwrap(), niffler::Format::Bzip); - - s = "g"; - assert_eq!(parse_compression_format(s).unwrap(), niffler::Format::Gzip); - - s = "l"; - assert_eq!(parse_compression_format(s).unwrap(), niffler::Format::Lzma); - - s = "U"; - assert_eq!(parse_compression_format(s).unwrap(), niffler::Format::No); - - s = "a"; - assert_eq!( - parse_compression_format(s).unwrap_err(), - CliError::InvalidCompression(s.to_string()) - ); - } - - #[test] - fn test_in_compress_range() { - assert!(parse_level("1").is_ok()); - assert!(parse_level("9").is_ok()); - assert!(parse_level("0").is_err()); - assert!(parse_level("10").is_err()); - assert!(parse_level("f").is_err()); - assert!(parse_level("5.5").is_err()); - assert!(parse_level("-3").is_err()); - } - - #[test] - fn compression_format_from_path() { - assert_eq!(niffler::Format::from_path("foo.gz"), niffler::Format::Gzip); - assert_eq!( - niffler::Format::from_path(Path::new("foo.gz")), - niffler::Format::Gzip - ); - assert_eq!(niffler::Format::from_path("baz"), niffler::Format::No); - assert_eq!(niffler::Format::from_path("baz.fq"), niffler::Format::No); - assert_eq!( - niffler::Format::from_path("baz.fq.bz2"), - niffler::Format::Bzip - ); - assert_eq!( - niffler::Format::from_path("baz.fq.bz"), - niffler::Format::Bzip - ); - assert_eq!( - niffler::Format::from_path("baz.fq.lzma"), - niffler::Format::Lzma - ); - } -} -use assert_cmd::prelude::*; -// Add methods on commands -use predicates::prelude::*; -use std::process::Command; // Run programs // Used for writing assertions - -#[test] -fn input_file_doesnt_exist() -> Result<(), Box> { - let mut cmd = Command::main_binary()?; - cmd.args(vec!["-i", "file/doesnt/exist.fa", "-g", "5mb", "-c", "20"]); - cmd.assert() - .failure() - .stderr(predicate::str::contains("does not exist")); - - Ok(()) -} - -#[test] -fn output_file_in_nonexistant_dir() -> Result<(), Box> { - let mut cmd = Command::main_binary()?; - cmd.args(vec![ - "-i", - "tests/cases/file1.fq.gz", - "-g", - "5mb", - "-c", - "20", - "-o", - "dir/doesnt/exists/out.fq.gz", - ]); - cmd.assert() - .failure() - .stderr(predicate::str::contains("No such file")); - - Ok(()) -} - -#[test] -fn valid_inputs_raises_no_errors() -> Result<(), Box> { - let mut cmd = Command::main_binary()?; - cmd.args(vec![ - "-i", - "tests/cases/file1.fq.gz", - "-g", - "5mb", - "-c", - "20", - ]); - - cmd.assert().success(); - - Ok(()) -} - -#[test] -fn input_and_output_filetypes_different_raises_no_errors() -> Result<(), Box> -{ - let mut cmd = Command::main_binary()?; - cmd.args(vec![ - "-i", - "tests/cases/file1.fq.gz", - "-g", - "5mb", - "-c", - "20", - "-o", - "/tmp/out.fasta", - ]); - - cmd.assert().success(); - - Ok(()) -} - -#[test] -fn invalid_input_and_output_combination_raises_error() -> Result<(), Box> { - let mut cmd = Command::main_binary()?; - cmd.args(vec![ - "-i", - "tests/cases/file1.fq.gz", - "-g", - "5mb", - "-c", - "20", - "-o", - "/tmp/out.fasta", - "-o", - "/tmp/out2.fq", - ]); - - cmd.assert() - .failure() - .stderr(predicate::str::contains("Got 1 --input but 2 --output")); - - Ok(()) -} - -#[test] -fn unequal_number_of_reads_raises_error() -> Result<(), Box> { - let mut cmd = Command::main_binary()?; - cmd.args(vec![ - "-i", - "tests/cases/file1.fq.gz", - "tests/cases/r2.fq.gz", - "-g", - "5mb", - "-c", - "20", - "-o", - "/tmp/out.fq", - "-o", - "/tmp/out2.fq", - ]); - - cmd.assert().failure().stderr(predicate::str::contains( - "Illumina files are assumed to have the same number of reads", - )); - - Ok(()) -} - -#[test] -fn two_valid_illumina_inputs_suceeds() -> Result<(), Box> { - let mut cmd = Command::main_binary()?; - cmd.args(vec![ - "-i", - "tests/cases/r1.fq.gz", - "tests/cases/r2.fq.gz", - "-g", - "4", - "-c", - "2", - "-o", - "/tmp/out.fq", - "-o", - "/tmp/out2.fq", - ]); - - cmd.assert().success(); - - Ok(()) -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* std use */ -use std::clone::Clone; -use std::collections::{HashMap, HashSet}; - -/* crate use */ -use petgraph::graph::NodeIndex; - -/* project use */ -use crate::filter; -use crate::io; -use filter::Filter; - -// read_a strand read_a strand length -type LineType = (String, char, String, char, u64); -// read_a strand leng_a read_b strand len_b position len_containment -type ContainmentType = (String, char, u64, String, char, u64, u64, u64); - -type Graph = petgraph::Graph<(String, u64), LineType>; - -pub struct Gfa1 { - keep_internal: bool, - keep_containment: bool, - graph: Graph, - containments: HashMap<(String, u64), ContainmentType>, - test_containment: filter::Containment, - test_internalmatch: filter::InternalMatch, - node2index: HashMap<(String, u64), petgraph::graph::NodeIndex>, -} - -impl Gfa1 { - pub fn new(keep_internal: bool, keep_containment: bool, internal_threshold: f64) -> Self { - Gfa1 { - keep_internal, - keep_containment, - graph: Graph::new(), - containments: HashMap::new(), - test_containment: filter::Containment::new(internal_threshold), - test_internalmatch: filter::InternalMatch::new(internal_threshold), - node2index: HashMap::new(), - } - } - - pub fn add(&mut self, record: &dyn io::MappingRecord) { - if self.test_internalmatch.run(&*record) { - self.add_internalmatch(record); - } else if self.test_containment.run(&*record) { - self.add_containment(record); - } else { - self.add_dovetails(record); - } - } - - fn add_containment(&mut self, record: &dyn io::MappingRecord) { - if record.strand() == '+' { - if record.begin_a() <= record.begin_b() && record.len_to_end_a() < record.len_to_end_b() - { - // B contain A - self.containments.insert( - (record.read_a(), record.length_a()), - ( - record.read_b(), - '+', - record.length_b(), - record.read_a(), - '+', - record.length_a(), - record.begin_b(), - record.length(), - ), - ); - } else if record.begin_a() >= record.begin_b() - && record.len_to_end_a() > record.len_to_end_b() - { - // A contain B - self.containments.insert( - (record.read_b(), record.length_b()), - ( - record.read_a(), - '+', - record.length_a(), - record.read_b(), - '+', - record.length_b(), - record.begin_a(), - record.length(), - ), - ); - } else { - println!( - "Containment Record not managed {:?} {:?}", - record.read_a(), - record.read_b() - ); - } - } else if record.begin_a() <= record.len_to_end_b() - && record.len_to_end_a() < record.begin_b() - { - // B contain A - self.containments.insert( - (record.read_a(), record.length_a()), - ( - record.read_b(), - '+', - record.length_b(), - record.read_a(), - '-', - record.length_a(), - record.begin_b(), - record.length(), - ), - ); - } else if record.begin_a() >= record.len_to_end_b() - && record.len_to_end_a() > record.begin_b() - { - // A contain B - self.containments.insert( - (record.read_b(), record.length_b()), - ( - record.read_a(), - '+', - record.length_a(), - record.read_b(), - '-', - record.length_b(), - record.begin_a(), - record.length(), - ), - ); - } else { - println!( - "Containment Record not managed {:?} {:?}", - record.read_a(), - record.read_b() - ); - } - } - - fn add_internalmatch(&mut self, record: &dyn io::MappingRecord) { - if self.keep_internal { - self.add_dovetails(record); - } - } - - fn add_dovetails(&mut self, record: &dyn io::MappingRecord) { - let node_a = self.add_node((record.read_a(), record.length_a())); - let node_b = self.add_node((record.read_b(), record.length_b())); - - if record.strand() == '+' { - if record.begin_a() > record.begin_b() { - // A overlap B - self.add_edge( - node_a, - node_b, - (record.read_a(), '+', record.read_b(), '+', record.length()), - ); - } else { - // B overlap A - self.add_edge( - node_b, - node_a, - (record.read_b(), '+', record.read_a(), '+', record.length()), - ); - } - } else if record.begin_a() > record.len_to_end_a() { - if record.begin_a() > record.len_to_end_b() { - // A overlap B - self.add_edge( - node_a, - node_b, - (record.read_a(), '+', record.read_b(), '-', record.length()), - ); - } else { - // B overlap Af - self.add_edge( - node_b, - node_a, - (record.read_b(), '+', record.read_a(), '-', record.length()), - ); - } - } else if (record.length_a() - record.begin_a()) > record.end_b() { - // A overlap B - self.add_edge( - node_a, - node_b, - (record.read_a(), '-', record.read_b(), '+', record.length()), - ); - } else { - // B overlap A - self.add_edge( - node_b, - node_a, - (record.read_b(), '-', record.read_a(), '+', record.length()), - ); - } - } - - pub fn write(&mut self, writer: &mut W) { - if !self.keep_containment { - let remove_key: Vec<((String, u64), ContainmentType)> = - self.containments.drain().collect(); - for (key, _) in remove_key { - let index = self.add_node(key.clone()); - self.graph.remove_node(index); - } - } - - writer - .write_all(b"H\tVN:Z:1.0\n") - .expect("Error durring gfa1 write"); - - let mut writed = HashSet::new(); - for (read_a, _, len_a, read_b, _, len_b, _, _) in self.containments.values() { - if !writed.contains(&(read_a, len_a)) { - writer - .write_fmt(format_args!("S\t{}\t*\tLN:i:{}\n", read_a, len_a)) - .expect("Error durring gfa1 write"); - - writed.insert((read_a, len_a)); - } - - if !writed.contains(&(read_b, len_b)) { - writer - .write_fmt(format_args!("S\t{}\t*\tLN:i:{}\n", read_b, len_b)) - .expect("Error durring gfa1 write"); - writed.insert((read_b, len_b)); - } - } - - for node in self.graph.node_indices() { - if self.graph.neighbors_undirected(node).count() != 0 { - let segment = self.graph.node_weight(node).unwrap(); - if writed.contains(&(&segment.0, &segment.1)) { - continue; - } - - writer - .write_fmt(format_args!("S\t{}\t*\tLN:i:{}\n", segment.0, segment.1)) - .expect("Error durring gfa1 write"); - } - } - - for edge in self.graph.edge_references() { - writer - .write_fmt(format_args!( - "L\t{}\t{}\t{}\t{}\t{}M\n", - edge.weight().0, - edge.weight().1, - edge.weight().2, - edge.weight().3, - edge.weight().4 - )) - .expect("Error durring gfa1 write"); - } - - for value in self.containments.values() { - writer - .write_fmt(format_args!( - "C\t{}\t{}\t{}\t{}\t{}\t{}M\n", - value.0, value.1, value.3, value.4, value.6, value.7 - )) - .expect("Error durring gfa1 write"); - } - } - - fn add_node(&mut self, node: (String, u64)) -> petgraph::graph::NodeIndex { - let graph = &mut self.graph; - *self - .node2index - .entry(node) - .or_insert_with_key(|n| graph.add_node(n.clone())) - } - - fn add_edge(&mut self, node_a: NodeIndex, node_b: NodeIndex, new_edge: LineType) { - if let Some(e) = self.graph.find_edge(node_a, node_b) { - if self.graph.edge_weight(e).unwrap().4 < new_edge.4 { - self.graph.update_edge(node_a, node_b, new_edge); - } - } else { - self.graph.add_edge(node_a, node_b, new_edge); - } - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -pub mod gfa1; -pub use self::gfa1::Gfa1; -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* local use */ -use crate::io; - -/* standard use */ -use std::cmp::min; - -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct Record { - pub read_a: String, - pub length_a: u64, - pub begin_a: u64, - pub end_a: u64, - pub strand: char, - pub read_b: String, - pub length_b: u64, - pub begin_b: u64, - pub end_b: u64, - pub nb_match_base: u64, - pub nb_base: u64, - pub mapping_quality: u64, - pub sam_field: Vec, - pub position: (u64, u64), -} - -impl io::MappingRecord for Record { - fn read_a(&self) -> String { - self.read_a.clone() - } - - fn length_a(&self) -> u64 { - self.length_a - } - - fn begin_a(&self) -> u64 { - self.begin_a - } - - fn end_a(&self) -> u64 { - self.end_a - } - - fn strand(&self) -> char { - self.strand - } - - fn read_b(&self) -> String { - self.read_b.clone() - } - - fn length_b(&self) -> u64 { - self.length_b - } - - fn begin_b(&self) -> u64 { - self.begin_b - } - - fn end_b(&self) -> u64 { - self.end_b - } - - fn position(&self) -> (u64, u64) { - self.position - } - - fn set_position(&mut self, p: (u64, u64)) { - self.position = p; - } - - fn length(&self) -> u64 { - min(self.end_a - self.begin_a, self.end_b - self.begin_b) - } - - fn len_to_end_a(&self) -> u64 { - self.length_a - self.end_a - } - - fn len_to_end_b(&self) -> u64 { - self.length_b - self.end_b - } - - fn set_read_a(&mut self, new_name: String) { - self.read_a = new_name; - } - fn set_read_b(&mut self, new_name: String) { - self.read_b = new_name; - } -} - -type RecordInner = ( - String, - u64, - u64, - u64, - char, - String, - u64, - u64, - u64, - u64, - u64, - Vec, -); - -pub struct Records<'a, R: 'a + std::io::Read> { - inner: csv::DeserializeRecordsIter<'a, R, RecordInner>, -} - -impl<'a, R: std::io::Read> Iterator for Records<'a, R> { - type Item = csv::Result; - - fn next(&mut self) -> Option> { - let position = self.inner.reader().position().byte(); - self.inner.next().map(|res| { - res.map( - |( - read_a, - length_a, - begin_a, - end_a, - strand, - read_b, - length_b, - begin_b, - end_b, - nb_match_base, - nb_base, - mapping_quality_and_sam, - )| { - let mapping_quality = mapping_quality_and_sam[0].parse::().unwrap(); - - let sam_field = if mapping_quality_and_sam.len() > 1 { - mapping_quality_and_sam[1..].to_vec() - } else { - Vec::new() - }; - - let new_position = self.inner.reader().position().byte(); - Record { - read_a, - length_a, - begin_a, - end_a, - strand, - read_b, - length_b, - begin_b, - end_b, - nb_match_base, - nb_base, - mapping_quality, - sam_field, - position: (position, new_position), - } - }, - ) - }) - } -} - -pub struct Reader { - inner: csv::Reader, -} - -impl Reader { - pub fn new(reader: R) -> Self { - Reader { - inner: csv::ReaderBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .flexible(true) - .from_reader(reader), - } - } - - /// Iterate over all records. - pub fn records(&mut self) -> Records { - Records { - inner: self.inner.deserialize(), - } - } -} - -#[derive(Debug)] -pub struct Writer { - inner: csv::Writer, -} - -impl Writer { - /// Write to a given writer. - pub fn new(writer: W) -> Self { - Writer { - inner: csv::WriterBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .flexible(true) - .from_writer(writer), - } - } - - /// Write a given GFF record. - pub fn write(&mut self, record: &Record) -> csv::Result { - let buffer: Vec = Vec::new(); - let mut wrapper = csv::WriterBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .flexible(true) - .from_writer(buffer); - - wrapper.serialize(( - &record.read_a, - record.length_a, - record.begin_a, - record.end_a, - record.strand, - &record.read_b, - record.length_b, - record.begin_b, - record.end_b, - record.nb_match_base, - record.nb_base, - record.mapping_quality, - &record.sam_field, - ))?; - - let nb_bytes = wrapper.into_inner().unwrap().len() as u64; - - self.inner.serialize(( - &record.read_a, - record.length_a, - record.begin_a, - record.end_a, - record.strand, - &record.read_b, - record.length_b, - record.begin_b, - record.end_b, - record.nb_match_base, - record.nb_base, - record.mapping_quality, - &record.sam_field, - ))?; - - Ok(nb_bytes) - } -} - -#[cfg(test)] -mod test { - - use super::*; - - const PAF_FILE: &'static [u8] = b"1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255 -1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255 -"; - - const PAF_SAM_FIELD_FILE: &'static [u8] = - b"1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255\tam:I:5 -1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255\ttest:B:true\tam:I:5 -"; - - const READ_A: &'static [&str; 2] = &["1", "1"]; - const LENGTH_A: &'static [u64; 2] = &[12000, 12000]; - const BEGIN_A: &'static [u64; 2] = &[20, 5500]; - const END_A: &'static [u64; 2] = &[4500, 10000]; - const STRAND: &'static [char; 2] = &['-', '-']; - const READ_B: &'static [&str; 2] = &["2", "3"]; - const LENGTH_B: &'static [u64; 2] = &[10000, 10000]; - const BEGIN_B: &'static [u64; 2] = &[5500, 0]; - const END_B: &'static [u64; 2] = &[10000, 4500]; - const NB_MATCH_BASE: &'static [u64; 2] = &[4500, 4500]; - const NB_BASE: &'static [u64; 2] = &[4500, 4500]; - const MAPPING_QUALITY: &'static [u64; 2] = &[255, 255]; - - #[test] - fn read() { - let mut reader = Reader::new(PAF_FILE); - - let sam_field: [Vec; 2] = [Vec::new(), Vec::new()]; - - for (i, r) in reader.records().enumerate() { - let record = r.unwrap(); - - assert_eq!(record.read_a, READ_A[i]); - assert_eq!(record.length_a, LENGTH_A[i]); - assert_eq!(record.begin_a, BEGIN_A[i]); - assert_eq!(record.end_a, END_A[i]); - assert_eq!(record.strand, STRAND[i]); - assert_eq!(record.read_b, READ_B[i]); - assert_eq!(record.length_b, LENGTH_B[i]); - assert_eq!(record.begin_b, BEGIN_B[i]); - assert_eq!(record.end_b, END_B[i]); - assert_eq!(record.nb_match_base, NB_MATCH_BASE[i]); - assert_eq!(record.nb_base, NB_BASE[i]); - assert_eq!(record.mapping_quality, MAPPING_QUALITY[i]); - assert_eq!(record.sam_field, sam_field[i]); - } - } - - #[test] - fn read_sam_field() { - let mut reader = Reader::new(PAF_SAM_FIELD_FILE); - - let sam_field = &[vec!["am:I:5"], vec!["test:B:true", "am:I:5"]]; - - for (i, r) in reader.records().enumerate() { - let record = r.unwrap(); - - assert_eq!(record.read_a, READ_A[i]); - assert_eq!(record.length_a, LENGTH_A[i]); - assert_eq!(record.begin_a, BEGIN_A[i]); - assert_eq!(record.end_a, END_A[i]); - assert_eq!(record.strand, STRAND[i]); - assert_eq!(record.read_b, READ_B[i]); - assert_eq!(record.length_b, LENGTH_B[i]); - assert_eq!(record.begin_b, BEGIN_B[i]); - assert_eq!(record.end_b, END_B[i]); - assert_eq!(record.nb_match_base, NB_MATCH_BASE[i]); - assert_eq!(record.nb_base, NB_BASE[i]); - assert_eq!(record.mapping_quality, MAPPING_QUALITY[i]); - assert_eq!(record.sam_field, sam_field[i]); - } - } - - #[test] - fn write() { - let mut reader = Reader::new(PAF_FILE); - let mut writer = Writer::new(vec![]); - for r in reader.records() { - writer - .write(&r.ok().expect("Error reading record")) - .ok() - .expect("Error writing record"); - } - assert_eq!(writer.inner.into_inner().unwrap(), PAF_FILE); - } - - #[test] - fn write_sam_field() { - let mut reader = Reader::new(PAF_SAM_FIELD_FILE); - let mut writer = Writer::new(vec![]); - for r in reader.records() { - writer - .write(&r.ok().expect("Error reading record")) - .ok() - .expect("Error writing record"); - } - assert_eq!(writer.inner.into_inner().unwrap(), PAF_SAM_FIELD_FILE); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -pub mod gfa; -pub mod m4; -pub mod paf; - -pub trait MappingRecord { - fn read_a(&self) -> String; - fn length_a(&self) -> u64; - fn begin_a(&self) -> u64; - fn end_a(&self) -> u64; - fn strand(&self) -> char; - fn read_b(&self) -> String; - fn length_b(&self) -> u64; - fn begin_b(&self) -> u64; - fn end_b(&self) -> u64; - fn position(&self) -> (u64, u64); - fn set_position(&mut self, p: (u64, u64)); - - fn length(&self) -> u64; - - fn len_to_end_a(&self) -> u64; - fn len_to_end_b(&self) -> u64; - - fn set_read_a(&mut self, new_name: String); - fn set_read_b(&mut self, new_name: String); -} - -pub enum MappingFormat { - Paf, - M4, -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* local use */ -use crate::io; - -/* standard use */ -use std::cmp::min; - -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct Record { - pub read_a: String, - pub read_b: String, - pub error: f64, - pub shared_min_mers: u64, - pub strand_a: char, - pub begin_a: u64, - pub end_a: u64, - pub length_a: u64, - pub strand_b: char, - pub begin_b: u64, - pub end_b: u64, - pub length_b: u64, - pub position: (u64, u64), -} - -impl io::MappingRecord for Record { - fn read_a(&self) -> String { - self.read_a.clone() - } - - fn length_a(&self) -> u64 { - self.length_a - } - - fn begin_a(&self) -> u64 { - self.begin_a - } - - fn end_a(&self) -> u64 { - self.end_a - } - - fn strand(&self) -> char { - if self.strand_a == self.strand_b { - '+' - } else { - '-' - } - } - - fn read_b(&self) -> String { - self.read_b.clone() - } - - fn length_b(&self) -> u64 { - self.length_b - } - - fn begin_b(&self) -> u64 { - self.begin_b - } - - fn end_b(&self) -> u64 { - self.end_b - } - - fn position(&self) -> (u64, u64) { - self.position - } - - fn set_position(&mut self, p: (u64, u64)) { - self.position = p; - } - - fn length(&self) -> u64 { - min(self.end_a - self.begin_a, self.end_b - self.begin_b) - } - - fn len_to_end_a(&self) -> u64 { - self.length_a - self.end_a - } - fn len_to_end_b(&self) -> u64 { - self.length_b - self.end_b - } - - fn set_read_a(&mut self, new_name: String) { - self.read_a = new_name; - } - fn set_read_b(&mut self, new_name: String) { - self.read_b = new_name; - } -} - -type RecordInner = ( - String, - String, - f64, - u64, - char, - u64, - u64, - u64, - char, - u64, - u64, - u64, -); - -pub struct Records<'a, R: 'a + std::io::Read> { - inner: csv::DeserializeRecordsIter<'a, R, RecordInner>, -} - -impl<'a, R: std::io::Read> Iterator for Records<'a, R> { - type Item = csv::Result; - - fn next(&mut self) -> Option> { - let position = self.inner.reader().position().byte(); - self.inner.next().map(|res| { - res.map( - |( - read_a, - read_b, - error, - shared_min_mers, - strand_a, - begin_a, - end_a, - length_a, - strand_b, - begin_b, - end_b, - length_b, - )| { - let new_position = self.inner.reader().position().byte(); - - Record { - read_a, - read_b, - error, - shared_min_mers, - strand_a, - begin_a, - end_a, - length_a, - strand_b, - begin_b, - end_b, - length_b, - position: (position, new_position), - } - }, - ) - }) - } -} - -pub struct Reader { - inner: csv::Reader, -} - -impl Reader { - pub fn new(reader: R) -> Self { - Reader { - inner: csv::ReaderBuilder::new() - .delimiter(b' ') - .has_headers(false) - .flexible(true) - .from_reader(reader), - } - } - - /// Iterate over all records. - pub fn records(&mut self) -> Records { - Records { - inner: self.inner.deserialize(), - } - } -} - -#[derive(Debug)] -pub struct Writer { - inner: csv::Writer, -} - -impl Writer { - /// Write to a given writer. - pub fn new(writer: W) -> Self { - Writer { - inner: csv::WriterBuilder::new() - .delimiter(b' ') - .has_headers(false) - .flexible(true) - .from_writer(writer), - } - } - - /// Write a given Blasr m4 record. - pub fn write(&mut self, record: &Record) -> csv::Result { - let buffer: Vec = Vec::new(); - let mut wrapper = csv::WriterBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .flexible(true) - .from_writer(buffer); - - wrapper.serialize(( - &record.read_a, - &record.read_b, - record.error, - record.shared_min_mers, - record.strand_a, - record.begin_a, - record.end_a, - record.length_a, - record.strand_b, - record.begin_b, - record.end_b, - record.length_b, - ))?; - - let nb_bytes = wrapper.into_inner().unwrap().len() as u64; - - self.inner.serialize(( - &record.read_a, - &record.read_b, - record.error, - record.shared_min_mers, - record.strand_a, - record.begin_a, - record.end_a, - record.length_a, - record.strand_b, - record.begin_b, - record.end_b, - record.length_b, - ))?; - - Ok(nb_bytes) - } -} - -#[cfg(test)] -mod test { - - use super::*; - - const M4_FILE: &'static [u8] = b"1 2 0.1 2 0 100 450 1000 0 550 900 1000 -1 3 0.1 2 0 550 900 1000 0 100 450 1000 -"; - - const READ_A: &'static [&str; 2] = &["1", "1"]; - const READ_B: &'static [&str; 2] = &["2", "3"]; - const ERROR: &'static [f64; 2] = &[0.1, 0.1]; - const SHARED_MIN_MERS: &'static [u64; 2] = &[2, 2]; - const STRAND_A: &'static [char; 2] = &['0', '0']; - const STRAND_B: &'static [char; 2] = &['0', '0']; - const BEGIN_A: &'static [u64; 2] = &[100, 550]; - const END_A: &'static [u64; 2] = &[450, 900]; - const LENGTH_A: &'static [u64; 2] = &[1000, 1000]; - const BEGIN_B: &'static [u64; 2] = &[550, 100]; - const END_B: &'static [u64; 2] = &[900, 450]; - const LENGTH_B: &'static [u64; 2] = &[1000, 1000]; - - #[test] - fn read() { - let mut reader = Reader::new(M4_FILE); - - for (i, r) in reader.records().enumerate() { - let record = r.unwrap(); - - assert_eq!(record.read_a, READ_A[i]); - assert_eq!(record.read_b, READ_B[i]); - assert_eq!(record.error, ERROR[i]); - assert_eq!(record.shared_min_mers, SHARED_MIN_MERS[i]); - assert_eq!(record.strand_a, STRAND_A[i]); - assert_eq!(record.begin_a, BEGIN_A[i]); - assert_eq!(record.end_a, END_A[i]); - assert_eq!(record.length_a, LENGTH_A[i]); - assert_eq!(record.strand_b, STRAND_B[i]); - assert_eq!(record.begin_b, BEGIN_B[i]); - assert_eq!(record.end_b, END_B[i]); - assert_eq!(record.length_b, LENGTH_B[i]); - } - } - - #[test] - fn write() { - let mut reader = Reader::new(M4_FILE); - let mut writer = Writer::new(vec![]); - for r in reader.records() { - writer - .write(&r.ok().expect("Error reading record")) - .ok() - .expect("Error writing record"); - } - - assert_eq!(writer.inner.into_inner().unwrap(), M4_FILE); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* standard use */ -use std::io; -use std::io::{BufReader, BufWriter}; - -pub fn get_input(input_name: &str) -> (Box, niffler::compression::Format) { - match input_name { - "-" => niffler::get_reader(Box::new(BufReader::new(io::stdin()))) - .expect("File is probably empty"), - _ => niffler::from_path(input_name).expect("File is probably empty"), - } -} - -pub fn choose_compression( - input_compression: niffler::compression::Format, - compression_set: bool, - compression_value: &str, -) -> niffler::compression::Format { - if !compression_set { - return input_compression; - } - - match compression_value { - "gzip" => niffler::compression::Format::Gzip, - "bzip2" => niffler::compression::Format::Bzip, - "lzma" => niffler::compression::Format::Lzma, - _ => niffler::compression::Format::No, - } -} - -pub fn get_output(output_name: &str, format: niffler::compression::Format) -> Box { - match output_name { - "-" => niffler::get_writer( - Box::new(BufWriter::new(io::stdout())), - format, - niffler::compression::Level::One, - ) - .unwrap(), - _ => niffler::to_path(output_name, format, niffler::compression::Level::One).unwrap(), - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* project use */ -use crate::filter; -use crate::io; - -use crate::cli::Filters; - -pub struct Keep { - filters: Vec>, - internal_threshold: f64, -} - -impl Keep { - pub fn new( - internal_match: f64, - matches: &std::collections::HashMap, - ) -> Self { - let filters = Vec::new(); - let mut k = Keep { - filters, - internal_threshold: internal_match, - }; - - if let Some(keep) = matches.get("keep") { - k.generate(keep); - } - - k - } -} - -impl Filters for Keep { - fn pass(&self, r: &dyn io::MappingRecord) -> bool { - if self.filters.is_empty() { - true - } else { - self.filters.iter().all(|x| x.run(r)) - } - } - - fn internal_match(&self) -> f64 { - self.internal_threshold - } - - fn add_filter(&mut self, f: Box) { - self.filters.push(f); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* project use */ -use crate::filter; -use crate::io; - -use crate::cli::Filters; - -pub struct Drop { - filters: Vec>, - internal_threshold: f64, -} - -impl Drop { - pub fn new( - internal_match: f64, - matches: &std::collections::HashMap, - ) -> Self { - let filters = Vec::new(); - let mut d = Drop { - filters, - internal_threshold: internal_match, - }; - - if let Some(drop) = matches.get("drop") { - d.generate(drop); - } - - d - } -} - -impl Filters for Drop { - fn pass(&self, r: &dyn io::MappingRecord) -> bool { - if self.filters.is_empty() { - true - } else { - !self.filters.iter().any(|x| x.run(r)) - } - } - - fn internal_match(&self) -> f64 { - self.internal_threshold - } - - fn add_filter(&mut self, f: Box) { - self.filters.push(f); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* project use */ -use crate::generator; -use crate::io; - -pub struct Modifier { - modifiers: Vec>, -} - -impl Modifier { - pub fn new( - internal_match: f64, - matches: &std::collections::HashMap, - ) -> Self { - let mut modifiers: Vec> = Vec::new(); - - if let Some(m) = matches.get("rename") { - if m.is_present("input") { - modifiers.push(Box::new(generator::Renaming::new( - m.value_of("input").unwrap(), - true, - ))); - } else if m.is_present("output") { - modifiers.push(Box::new(generator::Renaming::new( - m.value_of("output").unwrap(), - false, - ))); - } - } - - if let Some(m) = matches.get("gfa") { - modifiers.push(Box::new(generator::Gfa1::new( - m.value_of("output").unwrap().to_string(), - m.is_present("internalmatch"), - m.is_present("containment"), - internal_match, - ))) - } - - Modifier { modifiers } - } - - pub fn pass(&mut self, r: &mut dyn io::MappingRecord) { - for m in self.modifiers.iter_mut() { - m.run(r); - } - } - - pub fn write(&mut self) { - for m in self.modifiers.iter_mut() { - m.write(); - } - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crates use */ -use clap::{App, Arg}; - -pub fn get_keep<'a>() -> App<'a> { - App::new("keep") - .setting(clap::AppSettings::AllowExternalSubcommands) - .about("fpa keep only mapping match this constraints") - .arg( - Arg::new("containment") - .short('c') - .long("containment") - .about("Keep only containment mapping"), - ) - .arg( - Arg::new("internalmatch") - .short('i') - .long("internalmatch") - .about("Keep only internal mapping"), - ) - .arg( - Arg::new("dovetail") - .short('d') - .long("dovetail") - .about("Keep only dovetail mapping"), - ) - .arg( - Arg::new("length_lower") - .short('l') - .long("length-lower") - .takes_value(true) - .about("Keep only mapping with length lower than value"), - ) - .arg( - Arg::new("length_upper") - .short('L') - .long("length-upper") - .takes_value(true) - .about("Keep only mapping with length upper than value"), - ) - .arg( - Arg::new("name_match") - .short('n') - .long("name-match") - .takes_value(true) - .about("Keep only mapping where one reads match with regex"), - ) - .arg( - Arg::new("same_name") - .short('m') - .long("same-name") - .about("Keep only mapping where reads have same name"), - ) - .arg( - Arg::new("sequence_length_lower") - .short('s') - .long("sequence-length-lower") - .takes_value(true) - .about("Keep only mapping where one reads have length lower than value"), - ) - .arg( - Arg::new("sequence_length_upper") - .short('S') - .long("sequence-length-upper") - .takes_value(true) - .about("Keep only mapping where one reads have length upper than value"), - ) -} - -pub fn get_drop<'a>() -> clap::App<'a> { - App::new("drop") - .setting(clap::AppSettings::AllowExternalSubcommands) - .about("fpa drop mapping match this constraints") - .arg( - Arg::new("containment") - .short('c') - .long("containment") - .about("Drop containment mapping"), - ) - .arg( - Arg::new("internalmatch") - .short('i') - .long("internalmatch") - .about("Drop internal mapping"), - ) - .arg( - Arg::new("dovetail") - .short('d') - .long("dovetail") - .about("Drop dovetail mapping"), - ) - .arg( - Arg::new("length_lower") - .short('l') - .long("length-lower") - .takes_value(true) - .about("Drop mapping with length lower than value"), - ) - .arg( - Arg::new("length_upper") - .short('L') - .long("length-upper") - .takes_value(true) - .about("Drop mapping with length upper than value"), - ) - .arg( - Arg::new("name_match") - .short('n') - .long("name-match") - .takes_value(true) - .about("Drop mapping where one reads match with regex"), - ) - .arg( - Arg::new("same_name") - .short('m') - .long("same-name") - .about("Drop mapping where reads have same name"), - ) - .arg( - Arg::new("sequence_length_lower") - .short('s') - .long("sequence-length-lower") - .takes_value(true) - .about("Drop mapping where one reads have length lower than value"), - ) - .arg( - Arg::new("sequence_length_upper") - .short('S') - .long("sequence-length-upper") - .takes_value(true) - .about("Drop mapping where one reads have length upper than value"), - ) -} - -pub fn get_rename<'a>() -> clap::App<'a> { - App::new("rename") - .setting(clap::AppSettings::AllowExternalSubcommands) - .about("fpa rename reads with name you chose or with incremental counter") - .arg( - Arg::new("input") - .short('i') - .long("input") - .takes_value(true) - .about("Rename reads with value in path passed as parameter"), - ) - .arg( - Arg::new("output") - .short('o') - .long("output") - .takes_value(true) - .about("Write rename table in path passed as parameter"), - ) -} - -pub fn get_index<'a>() -> clap::App<'a> { - App::new("index") - .setting(clap::AppSettings::AllowExternalSubcommands) - .about("fpa generate a index of mapping passing filter") - .arg( - Arg::new("filename") - .short('f') - .long("filename") - .takes_value(true) - .display_order(108) - .about("Write index of mapping passing filter in path passed as parameter"), - ) - .arg( - Arg::new("type") - .short('t') - .long("type") - .takes_value(true) - .default_value("both") - .possible_values(&["query", "target", "both"]) - .about( - "Type of index, only reference read when it's query, target or both of them", - ), - ) -} - -pub fn get_gfa<'a>() -> clap::App<'a> { - App::new("gfa") - .setting(clap::AppSettings::AllowExternalSubcommands) - .about("fpa generate a overlap graph in gfa1 format with mapping passing filter") - .arg( - Arg::new("output") - .short('o') - .long("output") - .required(true) - .takes_value(true) - .about( - "Write mapping passing filter in gfa1 graph format in path passed as parameter", - ), - ) - .arg( - Arg::new("containment") - .short('c') - .long("containment") - .about("Keep containment overlap"), - ) - .arg( - Arg::new("internalmatch") - .short('i') - .long("internalmatch") - .about("Keep internal match overlap"), - ) -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* project use */ -use crate::filter; -use crate::io; - -/* local use */ -pub mod subcommand; -pub use self::subcommand::*; - -pub mod drop; -pub use self::drop::Drop; - -pub mod keep; -pub use self::keep::Keep; - -pub mod modifier; -pub use self::modifier::*; - -/* crates use */ -use clap::{App, Arg, ArgMatches}; - -pub fn app<'a>() -> App<'a> { - App::new("fpa") - .version("0.5.1 Sandslash") - .author("Pierre Marijon ") - .about("fpa take long read mapping information and filter them") - .arg(Arg::new("input") - .short('i') - .long("input") - .default_value("-") - .about("Path to input file, use '-' for stdin") - ) - .arg(Arg::new("output") - .short('o') - .long("output") - .default_value("-") - .about("Path to output file, use '-' for stdout") - ) - - .arg(Arg::new("internal-match-threshold") - .takes_value(true) - .long("internal-threshold") - .default_value("0.8") - .about("A match is internal match if overhang length > match length * internal threshold this option set internal match") - ) - .arg(Arg::new("compression-out") - .short('z') - .takes_value(true) - .long("compression-out") - .possible_values(&["gzip", "bzip2", "lzma", "no"]) - .about("Output compression format, the input compression format is chosen by default") - ) - .arg(Arg::new("format") - .short('F') - .long("format") - .takes_value(true) - .about("Force the format used") - .possible_values(&["paf", "m4"]) - ) - .subcommand(subcommand::get_keep()) - .subcommand(subcommand::get_drop()) - .subcommand(subcommand::get_rename()) - .subcommand(subcommand::get_index()) - .subcommand(subcommand::get_gfa()) -} - -pub fn get_subcmd(app: &mut App) -> std::collections::HashMap { - let basic_cli = vec![ - "fpa".to_string(), - "-i".to_string(), - "foo".to_string(), - "-o".to_string(), - "bar".to_string(), - ]; - let mut sub2matches = std::collections::HashMap::new(); - - let mut cli: Vec = std::env::args().collect(); - loop { - /* parse cli */ - let matches = app - .try_get_matches_from_mut(cli) - .unwrap_or_else(|e| e.exit()); - - let (name, sub) = match matches.subcommand() { - Some((n, s)) => (n, s), - None => break, - }; - - sub2matches.insert(name.to_string(), sub.clone()); - - let (subname, subsub) = match sub.subcommand() { - Some((n, s)) => (n, s), - None => break, - }; - - if subsub.values_of("").is_none() { - break; - } - - /* rebuild a new cli*/ - cli = basic_cli.clone(); - cli.push(subname.to_string()); - cli.extend(subsub.values_of("").unwrap().map(|x| x.to_string())); - } - - sub2matches -} - -pub trait Filters { - fn pass(&self, r: &dyn io::MappingRecord) -> bool; - - fn internal_match(&self) -> f64; - - fn add_filter(&mut self, f: Box); - - fn generate(&mut self, m: &clap::ArgMatches) { - let internal_match = self.internal_match(); - if m.is_present("containment") { - self.add_filter(Box::new(filter::Containment::new(internal_match))); - } - - if m.is_present("internalmatch") { - self.add_filter(Box::new(filter::InternalMatch::new(internal_match))); - } - - if m.is_present("dovetail") { - self.add_filter(Box::new(filter::Dovetails::new(internal_match))); - } - - if let Some(length_lower) = m.value_of("length_lower") { - self.add_filter(Box::new(filter::Length::new( - length_lower.parse::().unwrap(), - std::cmp::Ordering::Less, - ))); - } - - if let Some(length_lower) = m.value_of("length_upper") { - self.add_filter(Box::new(filter::Length::new( - length_lower.parse::().unwrap(), - std::cmp::Ordering::Greater, - ))); - } - - if let Some(name_match) = m.value_of("name_match") { - self.add_filter(Box::new(filter::NameMatch::new(name_match))); - } - - if m.is_present("same_name") { - self.add_filter(Box::new(filter::SameName::new())); - } - - if let Some(sequence_length_lower) = m.value_of("sequence_length_lower") { - self.add_filter(Box::new(filter::SequenceLength::new( - sequence_length_lower.parse::().unwrap(), - std::cmp::Ordering::Less, - ))); - } - - if let Some(sequence_length_lower) = m.value_of("sequence_length_upper") { - self.add_filter(Box::new(filter::SequenceLength::new( - sequence_length_lower.parse::().unwrap(), - std::cmp::Ordering::Greater, - ))); - } - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -#[derive(Clone, Debug, PartialEq)] -pub enum WorkOnWichPart { - Query, - Target, - Both, -} - -impl From<&str> for WorkOnWichPart { - fn from(index_type: &str) -> Self { - match index_type { - "query" => WorkOnWichPart::Query, - "target" => WorkOnWichPart::Target, - "both" => WorkOnWichPart::Both, - _ => WorkOnWichPart::Both, - } - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* std use */ -use std::collections::HashMap; -use std::fs::File; -use std::path::Path; - -/* project use */ -use crate::generator; -use crate::io; - -pub struct Renaming { - file_rename_path: String, - rename_table: HashMap, - index: u64, - index_mode: bool, -} - -impl Renaming { - pub fn new(file_rename_path: &str, in_file: bool) -> Self { - if in_file { - if !Path::new(file_rename_path).exists() { - panic!("Rename file not exist") - } - - let mut table = HashMap::new(); - let mut reader = csv::ReaderBuilder::new() - .has_headers(false) - .from_reader(File::open(file_rename_path).unwrap()); - - for result in reader.records() { - let record = result.expect("Error during parse of renaming file"); - table.insert(record[0].to_string(), record[1].to_string()); - } - - Renaming { - file_rename_path: file_rename_path.to_string(), - rename_table: table, - index: 0, - index_mode: false, - } - } else { - Renaming { - file_rename_path: file_rename_path.to_string(), - rename_table: HashMap::new(), - index: 1, - index_mode: true, - } - } - } - - fn run_index(&self, r: &mut dyn io::MappingRecord) { - if self.rename_table.contains_key(&r.read_a()) { - let key = r.read_a(); - r.set_read_a(self.rename_table.get(&key).unwrap().to_string()); - } - - if self.rename_table.contains_key(&r.read_b()) { - let key = r.read_b(); - r.set_read_b(self.rename_table.get(&key).unwrap().to_string()); - } - } - - fn run_no_index(&mut self, r: &mut dyn io::MappingRecord) { - let mut key = r.read_a(); - if !self.rename_table.contains_key(&key) { - self.rename_table.insert(r.read_a(), self.index.to_string()); - self.index += 1; - } - - r.set_read_a(self.rename_table.get(&key).unwrap().to_string()); - - key = r.read_b(); - if !self.rename_table.contains_key(&key) { - self.rename_table.insert(r.read_b(), self.index.to_string()); - self.index += 1; - } - r.set_read_b(self.rename_table.get(&key).unwrap().to_string()); - } -} - -impl generator::Modifier for Renaming { - fn run(&mut self, r: &mut dyn io::MappingRecord) { - if self.index_mode { - self.run_no_index(r); - } else { - self.run_index(r); - } - } - - fn write(&mut self) { - if self.index != 0 { - let mut writer = csv::Writer::from_path(&self.file_rename_path) - .expect("Can't create file to write renaming file"); - - for (key, val) in &self.rename_table { - writer - .write_record(&[key, val]) - .expect("Error durring write renaming file"); - } - } - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -use crate::io; - -pub trait Modifier { - fn run(&mut self, r: &mut dyn io::MappingRecord); - - fn write(&mut self); -} - -pub mod renaming; -pub use self::renaming::Renaming; - -pub mod indexing; -pub use self::indexing::Indexing; - -pub mod gfa; -pub use self::gfa::Gfa1; -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* std use */ -use std::collections::HashMap; - -/* project use */ -use crate::generator; -use crate::io; -use crate::type_def::WorkOnWichPart; - -pub struct Indexing { - index_type: WorkOnWichPart, - file_index_path: String, - index_table: HashMap>, -} - -impl Indexing { - pub fn new(file_index_path: &str, index_type: &str) -> Self { - Indexing { - file_index_path: file_index_path.to_string(), - index_type: WorkOnWichPart::from(index_type), - index_table: HashMap::new(), - } - } - - pub fn empty() -> Self { - Indexing { - file_index_path: "".to_string(), - index_type: WorkOnWichPart::Both, - index_table: HashMap::new(), - } - } - - fn run_both(&mut self, r: &mut dyn io::MappingRecord) { - self.index_table - .entry(r.read_a()) - .or_insert_with(Vec::new) - .push(r.position()); - if r.read_a() != r.read_b() { - self.index_table - .entry(r.read_b()) - .or_insert_with(Vec::new) - .push(r.position()); - } - } - - fn run_query(&mut self, r: &mut dyn io::MappingRecord) { - self.index_table - .entry(r.read_a()) - .or_insert_with(Vec::new) - .push(r.position()); - } - - fn run_target(&mut self, r: &mut dyn io::MappingRecord) { - self.index_table - .entry(r.read_b()) - .or_insert_with(Vec::new) - .push(r.position()); - } -} - -impl generator::Modifier for Indexing { - fn run(&mut self, r: &mut dyn io::MappingRecord) { - if self.file_index_path.is_empty() { - return; - } - - match self.index_type { - WorkOnWichPart::Both => self.run_both(r), - WorkOnWichPart::Query => self.run_query(r), - WorkOnWichPart::Target => self.run_target(r), - } - } - - fn write(&mut self) { - if self.file_index_path.is_empty() { - return; - } - - let mut writer = csv::Writer::from_path(&self.file_index_path) - .expect("Can't create file to write index"); - - for (key, val) in &self.index_table { - let mut iterator = val.iter(); - let mut position = *iterator.next().unwrap(); - - let mut positions: Vec<(u64, u64)> = Vec::new(); - for v in iterator { - if v.0 - position.1 > 1 { - positions.push(position); - position = *v; - } else { - position.1 = v.1; - } - } - positions.push(position); - - let positions_str = positions - .iter() - .map(|x| x.0.to_string() + ":" + &x.1.to_string()) - .collect::>() - .join(";"); - writer - .write_record(&[key, &positions_str]) - .expect("Error durring write index file"); - } - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* std use */ - -/* crate use */ - -/* projet use */ -use crate::generator; -use crate::io; - -pub struct Gfa1 { - gfa_path: String, - gfa_object: io::gfa::Gfa1, -} - -impl Gfa1 { - pub fn new( - gfa_path: String, - keep_internal: bool, - keep_containment: bool, - internal_threshold: f64, - ) -> Self { - Gfa1 { - gfa_path, - gfa_object: io::gfa::Gfa1::new(keep_internal, keep_containment, internal_threshold), - } - } -} - -impl generator::Modifier for Gfa1 { - fn run(&mut self, r: &mut dyn io::MappingRecord) { - self.gfa_object.add(r); - } - - fn write(&mut self) { - let mut writer = std::io::BufWriter::new( - std::fs::File::create(&self.gfa_path).expect("Can't create gfa ou"), - ); - self.gfa_object.write(&mut writer); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* project use */ -use crate::filter; -use crate::io; - -/* standard use */ - -pub struct Dovetails { - internal_threshold: f64, -} - -impl Dovetails { - pub fn new(internal_threshold: f64) -> Self { - Dovetails { internal_threshold } - } -} - -impl filter::Filter for Dovetails { - fn run(&self, r: &dyn io::MappingRecord) -> bool { - !filter::InternalMatch::new(self.internal_threshold).run(r) - && !filter::Containment::new(self.internal_threshold).run(r) - } -} - -#[cfg(test)] -mod test { - - use super::*; - use filter::Filter; - - lazy_static! { - static ref RECORD: io::paf::Record = { - io::paf::Record { - read_a: "read_1".to_string(), - length_a: 20000, - begin_a: 15000, - end_a: 20000, - strand: '+', - read_b: "read_2".to_string(), - length_b: 20000, - begin_b: 0, - end_b: 15000, - nb_match_base: 500, - nb_base: 500, - mapping_quality: 255, - sam_field: Vec::new(), - position: (0, 50), - } - }; - } - - #[test] - fn positif() { - let nm = Dovetails::new(0.8); - - assert_eq!(nm.run(&*RECORD), true); - } - - #[test] - fn negatif() { - let nm = Dovetails::new(0.8); - - assert_ne!(nm.run(&*RECORD), false); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* project use */ -use crate::filter; -use crate::io; - -pub struct Length { - length_threshold: u64, - ordering: std::cmp::Ordering, -} - -impl Length { - pub fn new(length_threshold: u64, ord: std::cmp::Ordering) -> Self { - Length { - length_threshold, - ordering: ord, - } - } -} - -impl filter::Filter for Length { - fn run(&self, r: &dyn io::MappingRecord) -> bool { - r.length().cmp(&self.length_threshold) == self.ordering - } -} - -#[cfg(test)] -mod test { - - use super::*; - use filter::Filter; - - lazy_static! { - static ref RECORD: io::paf::Record = { - io::paf::Record { - read_a: "read_1".to_string(), - length_a: 5000, - begin_a: 0, - end_a: 5000, - strand: '+', - read_b: "read_2".to_string(), - length_b: 20000, - begin_b: 5000, - end_b: 10000, - nb_match_base: 500, - nb_base: 500, - mapping_quality: 255, - sam_field: Vec::new(), - position: (0, 50), - } - }; - } - - #[test] - fn positif() { - let mut nm = Length::new(5001, std::cmp::Ordering::Less); - - assert_eq!(nm.run(&*RECORD), true); - - nm = Length::new(5001, std::cmp::Ordering::Greater); - - assert_eq!(nm.run(&*RECORD), false); - } - - #[test] - fn negatif() { - let mut nm = Length::new(5001, std::cmp::Ordering::Less); - - assert_ne!(nm.run(&*RECORD), false); - - nm = Length::new(5001, std::cmp::Ordering::Greater); - - assert_ne!(nm.run(&*RECORD), true); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* project use */ -use crate::filter; -use crate::io; - -/* standard use */ - -pub struct NameMatch { - regex: regex::Regex, -} - -impl NameMatch { - pub fn new(regex: &str) -> Self { - NameMatch { - regex: regex::Regex::new(regex).expect("Error in regex build"), - } - } -} - -impl filter::Filter for NameMatch { - fn run(&self, r: &dyn io::MappingRecord) -> bool { - self.regex.is_match(&r.read_a()) || self.regex.is_match(&r.read_b()) - } -} - -#[cfg(test)] -mod test { - - use super::*; - use filter::Filter; - - lazy_static! { - static ref RECORD: io::paf::Record = { - io::paf::Record { - read_a: "read_1".to_string(), - length_a: 20000, - begin_a: 1, - end_a: 19999, - strand: '+', - read_b: "read_2".to_string(), - length_b: 20000, - begin_b: 1, - end_b: 19999, - nb_match_base: 500, - nb_base: 500, - mapping_quality: 255, - sam_field: Vec::new(), - position: (0, 50), - } - }; - } - - #[test] - fn positif() { - let nm = NameMatch::new("read_1"); - - assert_eq!(nm.run(&*RECORD), true); - } - - #[test] - fn negatif() { - let nm = NameMatch::new("read_1"); - - assert_ne!(nm.run(&*RECORD), false); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -use crate::io; - -pub trait Filter { - fn run(&self, r: &dyn io::MappingRecord) -> bool; -} - -pub mod length; -pub use self::length::Length; - -pub mod dovetails; -pub use self::dovetails::Dovetails; - -pub mod containment; -pub use self::containment::Containment; - -pub mod internalmatch; -pub use self::internalmatch::InternalMatch; - -pub mod samename; -pub use self::samename::SameName; - -pub mod namematch; -pub use self::namematch::NameMatch; - -pub mod sequence_length; -pub use self::sequence_length::SequenceLength; -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* project use */ -use crate::filter; -use crate::io; - -/* standard use */ -use std::cmp::{max, min}; - -pub struct InternalMatch { - internal_threshold: f64, -} - -impl InternalMatch { - pub fn new(internal_threshold: f64) -> Self { - InternalMatch { internal_threshold } - } -} - -impl filter::Filter for InternalMatch { - fn run(&self, r: &dyn io::MappingRecord) -> bool { - let overhang = if r.strand() == '+' { - min(r.begin_a(), r.begin_b()) + min(r.length_a() - r.end_a(), r.length_b() - r.end_b()) - } else { - min(r.begin_a(), r.length_b() - r.end_b()) + min(r.begin_b(), r.length_a() - r.end_a()) - }; - - let maplen = max(r.end_a() - r.begin_a(), r.end_b() - r.begin_b()); - - overhang > min(1000, (maplen as f64 * self.internal_threshold) as u64) - } -} - -#[cfg(test)] -mod test { - - use super::*; - use filter::Filter; - - lazy_static! { - static ref RECORD: io::paf::Record = { - io::paf::Record { - read_a: "read_1".to_string(), - length_a: 20000, - begin_a: 500, - end_a: 1000, - strand: '+', - read_b: "read_2".to_string(), - length_b: 20000, - begin_b: 5000, - end_b: 5500, - nb_match_base: 500, - nb_base: 500, - mapping_quality: 255, - sam_field: Vec::new(), - position: (0, 50), - } - }; - } - - #[test] - fn positif() { - let nm = InternalMatch::new(0.8); - - assert_eq!(nm.run(&*RECORD), true); - } - - #[test] - fn negatif() { - let nm = InternalMatch::new(0.8); - - assert_ne!(nm.run(&*RECORD), false); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* project use */ -use crate::filter; -use crate::io; - -/* standard use */ - -pub struct Containment { - internal_threshold: f64, -} - -impl Containment { - pub fn new(internal_threshold: f64) -> Self { - Containment { internal_threshold } - } -} - -impl filter::Filter for Containment { - fn run(&self, r: &dyn io::MappingRecord) -> bool { - if filter::InternalMatch::new(self.internal_threshold).run(r) { - return false; - } - - (r.strand() == '+' - && r.begin_a() <= r.begin_b() - && r.length_a() - r.end_a() < r.length_b() - r.end_b()) - || (r.strand() == '-' - && r.begin_a() <= r.length_b() - r.end_b() - && r.length_a() - r.end_a() < r.begin_b()) - || (r.strand() == '+' - && r.begin_a() >= r.begin_b() - && r.length_a() - r.end_a() > r.length_b() - r.end_b()) - || (r.strand() == '-' - && r.begin_a() >= r.length_b() - r.end_b() - && r.length_a() - r.end_a() > r.begin_b()) - } -} - -#[cfg(test)] -mod test { - - use super::*; - use filter::Filter; - - lazy_static! { - static ref RECORD: io::paf::Record = { - io::paf::Record { - read_a: "read_1".to_string(), - length_a: 5000, - begin_a: 0, - end_a: 5000, - strand: '+', - read_b: "read_2".to_string(), - length_b: 20000, - begin_b: 5000, - end_b: 10000, - nb_match_base: 500, - nb_base: 500, - mapping_quality: 255, - sam_field: Vec::new(), - position: (0, 50), - } - }; - } - - #[test] - fn positif() { - let nm = Containment::new(0.8); - - assert_eq!(nm.run(&*RECORD), true); - } - - #[test] - fn negatif() { - let nm = Containment::new(0.8); - - assert_ne!(nm.run(&*RECORD), false); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* project use */ -use crate::filter; -use crate::io; - -pub struct SequenceLength { - length_threshold: u64, - ordering: std::cmp::Ordering, -} - -impl SequenceLength { - pub fn new(length_threshold: u64, ord: std::cmp::Ordering) -> Self { - SequenceLength { - length_threshold, - ordering: ord, - } - } -} - -impl filter::Filter for SequenceLength { - fn run(&self, r: &dyn io::MappingRecord) -> bool { - r.length_a().cmp(&self.length_threshold) == self.ordering - || r.length_b().cmp(&self.length_threshold) == self.ordering - } -} - -#[cfg(test)] -mod test { - - use super::*; - use filter::Filter; - - lazy_static! { - static ref RECORD: io::paf::Record = { - io::paf::Record { - read_a: "read_1".to_string(), - length_a: 5000, - begin_a: 0, - end_a: 5000, - strand: '+', - read_b: "read_2".to_string(), - length_b: 20000, - begin_b: 5000, - end_b: 10000, - nb_match_base: 500, - nb_base: 500, - mapping_quality: 255, - sam_field: Vec::new(), - position: (0, 50), - } - }; - } - - #[test] - fn positif() { - let mut nm = SequenceLength::new(5001, std::cmp::Ordering::Less); - - assert_eq!(nm.run(&*RECORD), true); - - nm = SequenceLength::new(20001, std::cmp::Ordering::Greater); - - assert_eq!(nm.run(&*RECORD), false); - } - - #[test] - fn negatif() { - let mut nm = SequenceLength::new(5001, std::cmp::Ordering::Less); - - assert_ne!(nm.run(&*RECORD), false); - - nm = SequenceLength::new(20001, std::cmp::Ordering::Greater); - - assert_ne!(nm.run(&*RECORD), true); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/* project use */ -use crate::filter; -use crate::io; - -/* standard use */ - -pub struct SameName {} - -impl SameName { - pub fn new() -> Self { - SameName {} - } -} - -impl filter::Filter for SameName { - fn run(&self, r: &dyn io::MappingRecord) -> bool { - r.read_a() == r.read_b() - } -} - -#[cfg(test)] -mod test { - - use super::*; - use filter::Filter; - - lazy_static! { - static ref RECORD: io::paf::Record = { - io::paf::Record { - read_a: "read_1".to_string(), - length_a: 5000, - begin_a: 0, - end_a: 5000, - strand: '+', - read_b: "read_1".to_string(), - length_b: 20000, - begin_b: 5000, - end_b: 10000, - nb_match_base: 500, - nb_base: 500, - mapping_quality: 255, - sam_field: Vec::new(), - position: (0, 50), - } - }; - } - - #[test] - fn positif() { - let nm = SameName::new(); - - assert_eq!(nm.run(&*RECORD), true); - } - - #[test] - fn negatif() { - let nm = SameName::new(); - - assert_ne!(nm.run(&*RECORD), false); - } -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -#[macro_use] -extern crate serde_derive; - -#[cfg(test)] -#[macro_use] -extern crate lazy_static; - -/* project mod */ -mod cli; -mod file; -mod filter; -mod generator; -mod io; -mod type_def; - -use cli::Filters; -use generator::Modifier; -use io::MappingRecord; - -fn main() { - let mut app = cli::app(); - let matches = app - .try_get_matches_from_mut(std::env::args()) - .unwrap_or_else(|e| e.exit()); - - let subcmd = cli::get_subcmd(&mut app); - - /* Manage input and output file */ - let (input, compression) = file::get_input(matches.value_of("input").unwrap()); - - let format = if matches.is_present("format") { - match matches.value_of("format").unwrap() { - "paf" => io::MappingFormat::Paf, - "m4" => io::MappingFormat::M4, - _ => io::MappingFormat::Paf, - } - } else { - io::MappingFormat::Paf - }; - - let out_compression = file::choose_compression( - compression, - matches.is_present("compression-out"), - matches.value_of("compression-out").unwrap_or("no"), - ); - - let output: std::io::BufWriter> = std::io::BufWriter::new( - file::get_output(matches.value_of("output").unwrap(), out_compression), - ); - - let internal_match_threshold = matches - .value_of("internal-match-threshold") - .unwrap() - .parse::() - .unwrap(); - - match format { - io::MappingFormat::Paf => paf(input, output, internal_match_threshold, subcmd), - io::MappingFormat::M4 => m4(input, output, internal_match_threshold, subcmd), - } -} - -fn paf( - input: Box, - output: std::io::BufWriter>, - internal_match_threshold: f64, - subcmd: std::collections::HashMap, -) { - let mut writer = io::paf::Writer::new(output); - let mut reader = io::paf::Reader::new(input); - let drop = cli::Drop::new(internal_match_threshold, &subcmd); - let keep = cli::Keep::new(internal_match_threshold, &subcmd); - let mut modifier = cli::Modifier::new(internal_match_threshold, &subcmd); - - let mut index = if let Some(m) = subcmd.get("index") { - generator::Indexing::new(m.value_of("filename").unwrap(), m.value_of("type").unwrap()) - } else { - generator::Indexing::empty() - }; - - let mut position = 0; - for result in reader.records() { - let mut record = result.expect("Trouble during read of input mapping"); - - // keep - if !keep.pass(&record) { - continue; - } - - // drop - if !drop.pass(&record) { - continue; - } - - // modifier - modifier.pass(&mut record); - - let new_position = position - + writer - .write(&record) - .expect("Trouble during write of output"); - - record.set_position((position, new_position)); - - index.run(&mut record); - - position = new_position; - } - - // close modifier - modifier.write(); - - index.write(); -} - -fn m4( - input: Box, - output: std::io::BufWriter>, - internal_match_threshold: f64, - subcmd: std::collections::HashMap, -) { - let mut writer = io::m4::Writer::new(output); - let mut reader = io::m4::Reader::new(input); - let drop = cli::Drop::new(internal_match_threshold, &subcmd); - let keep = cli::Keep::new(internal_match_threshold, &subcmd); - let mut modifier = cli::Modifier::new(internal_match_threshold, &subcmd); - - let mut index = if let Some(m) = subcmd.get("index") { - generator::Indexing::new(m.value_of("filename").unwrap(), m.value_of("type").unwrap()) - } else { - generator::Indexing::empty() - }; - - let mut position = 0; - for result in reader.records() { - let mut record = result.expect("Trouble during read of input mapping"); - - // keep - if !keep.pass(&record) { - continue; - } - - // drop - if !drop.pass(&record) { - continue; - } - - // modifier - modifier.pass(&mut record); - - let new_position = position - + writer - .write(&record) - .expect("Trouble during write of output"); - - record.set_position((position, new_position)); - - index.run(&mut record); - - position = new_position; - } - - // close modifier - modifier.write(); - - index.write(); -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/// Yacrd use overlap between reads, to detect 'good' and 'bad' region, -/// a region with coverage over the threshold is 'good' others are 'bad'. -/// If read has a 'bad' region in middle this reads is mark as 'Chimeric'. -/// If the ratio of 'bad' region length on total read length is larger than threshold this reads is marked as 'Not_covered'. - -/// Yacrd can make some other actions: -/// - filter: for sequence or overlap file, record with reads marked as Chimeric or NotCovered isn't written in the output -/// - extract: for sequence or overlap file, record contains reads marked as Chimeric or NotCovered is written in the output -/// - split: for sequence file bad region in the middle of reads are removed, NotCovered read is removed -/// - scrubb: for sequence file all bad region are removed, NotCovered read is removed -#[derive(clap::Parser, Debug)] -#[clap( - version = "1.0.0 Magby", - author = "Pierre Marijon ", - name = "yacrd" -)] -pub struct Command { - /// path to input file overlap (.paf|.m4|.mhap) or yacrd report (.yacrd), format is autodetected and compression input is allowed (gz|bzip2|lzma) - #[clap(short = 'i', long = "input")] - pub input: String, - - /// path output file - #[clap(short = 'o', long = "output")] - pub output: String, - - /// number of thread use by yacrd, 0 mean all threads available, default 1 - #[clap(short = 't', long = "thread")] - pub threads: Option, - - /// if coverage reach this value region is marked as bad - #[clap(short = 'c', long = "coverage", default_value = "0")] - pub coverage: u64, - - /// if the ratio of bad region length on total length is lower than this value, read is marked as NotCovered - #[clap(short = 'n', long = "not-coverage", default_value = "0.8")] - pub not_coverage: f64, - - /// Control the size of the buffer used to read paf file - #[clap(long = "read-buffer-size", default_value = "8192")] - pub buffer_size: usize, - - /// yacrd switches to 'ondisk' mode which will reduce memory usage but increase computation time. The value passed as a parameter is used as a prefix for the temporary files created by yacrd. Be careful if the prefix contains path separators (`/` for unix or `\\` for windows) this folder will be deleted - #[clap(short = 'd', long = "ondisk")] - pub ondisk: Option, - - /// with the default value yacrd in 'ondisk' mode use around 1 GBytes, you can increase to reduce runtime but increase memory usage - #[clap(long = "ondisk-buffer-size", default_value = "64000000")] - pub ondisk_buffer_size: String, - - #[clap(subcommand)] - pub subcmd: Option, -} - -#[derive(clap::Parser, Debug)] -pub enum SubCommand { - /// All bad region of read is removed - #[clap()] - Scrubb(Scrubb), - - /// Record mark as chimeric or NotCovered is filter - #[clap()] - Filter(Filter), - - /// Record mark as chimeric or NotCovered is extract - #[clap()] - Extract(Extract), - - /// Record mark as chimeric or NotCovered is split - #[clap()] - Split(Split), -} - -#[derive(clap::Parser, Debug)] -pub struct Scrubb { - /// path to sequence input (fasta|fastq), compression is autodetected (none|gzip|bzip2|lzma) - #[clap(short = 'i', long = "input", required = true)] - pub input: String, - - /// path to output file, format and compression of input is preserved - #[clap(short = 'o', long = "output", required = true)] - pub output: String, -} - -#[derive(clap::Parser, Debug)] -pub struct Filter { - /// path to sequence input (fasta|fastq), compression is autodetected (none|gzip|bzip2|lzma) - #[clap(short = 'i', long = "input", required = true)] - pub input: String, - - /// path to output file, format and compression of input is preserved - #[clap(short = 'o', long = "output", required = true)] - pub output: String, -} - -#[derive(clap::Parser, Debug)] -pub struct Extract { - /// path to sequence input (fasta|fastq), compression is autodetected (none|gzip|bzip2|lzma) - #[clap(short = 'i', long = "input", required = true)] - pub input: String, - - /// path to output file, format and compression of input is preserved - #[clap(short = 'o', long = "output", required = true)] - pub output: String, -} - -#[derive(clap::Parser, Debug)] -pub struct Split { - /// path to sequence input (fasta|fastq), compression is autodetected (none|gzip|bzip2|lzma) - #[clap(short = 'i', long = "input", required = true)] - pub input: String, - - /// path to output file, format and compression of input is preserved - #[clap(short = 'o', long = "output", required = true)] - pub output: String, -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, bail, Context, Result}; -use log::error; - -/* local use */ -use crate::editor; -use crate::error; -use crate::stack; -use crate::util; - -pub fn scrubbing( - input_path: &str, - output_path: &str, - badregions: &mut dyn stack::BadPart, - not_covered: f64, - buffer_size: usize, -) -> Result<()> { - let (input, compression) = util::read_file(input_path, buffer_size)?; - let output = util::write_file(output_path, compression, buffer_size)?; - - match util::get_file_type(input_path) { - Some(util::FileType::Fasta) => fasta(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Fastq) => fastq(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Paf) => bail!(error::Error::CantRunOperationOnFile { - operation: "scrubbing".to_string(), - filetype: util::FileType::Paf, - filename: input_path.to_string() - }), - Some(util::FileType::M4) => bail!(error::Error::CantRunOperationOnFile { - operation: "scrubbing".to_string(), - filetype: util::FileType::M4, - filename: input_path.to_string() - }), - Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile { - operation: "scrubbing".to_string(), - filetype: util::FileType::Yacrd, - filename: input_path.to_string() - }), - None | Some(util::FileType::YacrdOverlap) => { - bail!(error::Error::UnableToDetectFileFormat { - filename: input_path.to_string() - }) - } - }; - - Ok(()) -} - -fn fasta( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(input)); - let mut writer = noodles::fasta::Writer::new(std::io::BufWriter::new(output)); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Fasta, - })?; - - let (badregion, length) = badregions.get_bad_part(record.name())?; - - let rtype = editor::type_of_read(*length, badregion, not_covered); - - if rtype == editor::ReadType::NotCovered { - continue; - } else if badregion.is_empty() { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fasta, - })?; - } else { - let mut poss = vec![0]; - for interval in badregion { - poss.push(interval.0); - poss.push(interval.1); - } - - if poss.last() != Some(&(*length as u32)) { - poss.push(*length as u32); - }; - - let iter = if poss[0] == 0 && poss[1] == 0 { - &poss[2..] - } else { - &poss[..] - }; - - for pos in iter.chunks_exact(2) { - if pos[0] as usize > record.sequence().len() - || pos[1] as usize > record.sequence().len() - { - error!("For read {} scrubb position is larger than read, it's strange check your data. For this read, this split position and next are ignore.", record.name()); - break; - } - - writer - .write_record(&noodles::fasta::Record::new( - noodles::fasta::record::Definition::new( - &format!("{}_{}_{}", record.name(), pos[0], pos[1]), - None, - ), - noodles::fasta::record::Sequence::from( - record.sequence().as_ref()[(pos[0] as usize)..(pos[1] as usize)] - .to_vec(), - ), - )) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fasta, - })?; - } - } - } - - Ok(()) -} - -fn fastq( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = noodles::fastq::Reader::new(std::io::BufReader::new(input)); - let mut writer = noodles::fastq::Writer::new(std::io::BufWriter::new(output)); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Fastq, - })?; - - let (badregion, length) = badregions.get_bad_part( - std::str::from_utf8(record.name())? - .split_ascii_whitespace() - .next() - .unwrap(), - )?; - - let rtype = editor::type_of_read(*length, badregion, not_covered); - - if rtype == editor::ReadType::NotCovered { - continue; - } else if badregion.is_empty() { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fastq, - })?; - } else { - let mut sequence_description = std::str::from_utf8(record.name())?.splitn(2, ' '); - let name = sequence_description.next().unwrap(); - let description = sequence_description.next(); - - let mut poss = vec![0]; - for interval in badregion { - poss.push(interval.0); - poss.push(interval.1); - } - - if poss.last() != Some(&(*length as u32)) { - poss.push(*length as u32); - }; - - let iter = if poss[0] == 0 && poss[1] == 0 { - &poss[2..] - } else { - &poss[..] - }; - - for pos in iter.chunks_exact(2) { - if pos[0] as usize > record.sequence().len() - || pos[1] as usize > record.sequence().len() - { - error!("For read {} scrubb position is larger than read, it's strange check your data. For this read, this split position and next are ignore.", name); - break; - } - - writer - .write_record(&noodles::fastq::Record::new( - match description { - Some(desc) => format!("{}_{}_{} {}", name, pos[0], pos[1], desc), - None => format!("{}_{}_{}", name, pos[0], pos[1]), - } - .as_bytes(), - record.sequence()[(pos[0] as usize)..(pos[1] as usize)].to_vec(), - record.quality_scores()[(pos[0] as usize)..(pos[1] as usize)].to_vec(), - )) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fasta, - })?; - } - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - use crate::stack::BadPart; - - use crate::reads2ovl; - use crate::reads2ovl::Reads2Ovl; - - const FASTA_FILE: &'static [u8] = b">1 -ACTGGGGGGACTGGGGGGACTG ->2 -ACTG ->3 -ACTG -"; - - const FASTA_FILE_SCRUBBED: &'static [u8] = b">1_0_4 -ACTG ->1_9_13 -ACTG ->1_18_22 -ACTG ->2 -ACTG ->3 -ACTG -"; - - #[test] - fn fasta_keep_begin_end() -> () { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 22); - ovlst.add_overlap("1".to_string(), (0, 4)).unwrap(); - ovlst.add_overlap("1".to_string(), (9, 13)).unwrap(); - ovlst.add_overlap("1".to_string(), (18, 22)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTA_FILE_SCRUBBED, &output[..]); - } - - const FASTA_FILE_SCRUBBED2: &'static [u8] = b">1_4_18 -GGGGGACTGGGGGG ->2 -ACTG ->3 -ACTG -"; - - #[test] - fn fasta_keep_middle() -> () { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 22); - ovlst.add_overlap("1".to_string(), (4, 18)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTA_FILE_SCRUBBED2, &output[..]); - } - - const FASTQ_FILE: &'static [u8] = b"@1 -ACTGGGGGGACTGGGGGGACTG -+ -?????????????????????? -@2 -ACTG -+ -???? -@3 -ACTG -+ -???? -"; - - const FASTQ_FILE_SCRUBBED: &'static [u8] = b"@1_0_4 -ACTG -+ -???? -@1_9_13 -ACTG -+ -???? -@1_18_22 -ACTG -+ -???? -@2 -ACTG -+ -???? -@3 -ACTG -+ -???? -"; - - #[test] - fn fastq_keep_begin_end() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 22); - ovlst.add_overlap("1".to_string(), (0, 4)).unwrap(); - ovlst.add_overlap("1".to_string(), (9, 13)).unwrap(); - ovlst.add_overlap("1".to_string(), (18, 22)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTQ_FILE_SCRUBBED, &output[..]); - } - - const FASTQ_FILE_SCRUBBED2: &[u8] = b"@1_4_18 -GGGGGACTGGGGGG -+ -?????????????? -@2 -ACTG -+ -???? -@3 -ACTG -+ -???? -"; - - #[test] - fn fastq_keep_middle() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 22); - ovlst.add_overlap("1".to_string(), (4, 18)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTQ_FILE_SCRUBBED2, &output[..]); - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, bail, Context, Result}; - -/* local use */ -use crate::editor; -use crate::error; -use crate::stack; -use crate::util; - -pub fn filter( - input_path: &str, - output_path: &str, - badregions: &mut dyn stack::BadPart, - not_covered: f64, - buffer_size: usize, -) -> Result<()> { - let (input, compression) = util::read_file(input_path, buffer_size)?; - let output = util::write_file(output_path, compression, buffer_size)?; - - match util::get_file_type(input_path) { - Some(util::FileType::Fasta) => fasta(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Fastq) => fastq(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Paf) => paf(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::M4) => m4(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile { - operation: "scrubbing".to_string(), - filetype: util::FileType::Yacrd, - filename: input_path.to_string() - }), - None | Some(util::FileType::YacrdOverlap) => { - bail!(error::Error::UnableToDetectFileFormat { - filename: input_path.to_string() - }) - } - } - - Ok(()) -} - -fn fasta( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(input)); - let mut writer = noodles::fasta::Writer::new(std::io::BufWriter::new(output)); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Fasta, - })?; - - let (badregion, length) = badregions.get_bad_part(record.name())?; - - let rtype = editor::type_of_read(*length, badregion, not_covered); - - if rtype == editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fasta, - })?; - } - } - - Ok(()) -} - -pub fn fastq( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = noodles::fastq::Reader::new(std::io::BufReader::new(input)); - let mut writer = noodles::fastq::Writer::new(std::io::BufWriter::new(output)); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Fastq, - })?; - - let (badregion, length) = badregions.get_bad_part( - std::str::from_utf8(record.name())? - .split_ascii_whitespace() - .next() - .unwrap(), - )?; - - let rtype = editor::type_of_read(*length, badregion, not_covered); - - if rtype == editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fastq, - })?; - } - } - - Ok(()) -} - -pub fn paf( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = csv::ReaderBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .from_reader(input); - let mut writer = csv::WriterBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .from_writer(output); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Paf, - })?; - - let id_a = record[0].to_string(); - let id_b = record[5].to_string(); - - let (badregion, length) = badregions.get_bad_part(&id_a)?; - let rtype_a = editor::type_of_read(*length, badregion, not_covered); - - let (badregion, length) = badregions.get_bad_part(&id_b)?; - let rtype_b = editor::type_of_read(*length, badregion, not_covered); - - if rtype_a == editor::ReadType::NotBad && rtype_b == editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Paf, - })?; - } - } - - Ok(()) -} - -pub fn m4( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = csv::ReaderBuilder::new() - .delimiter(b' ') - .has_headers(false) - .from_reader(input); - let mut writer = csv::WriterBuilder::new() - .delimiter(b' ') - .has_headers(false) - .from_writer(output); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::M4, - })?; - - let id_a = record[0].to_string(); - let id_b = record[1].to_string(); - - let (badregion, length) = badregions.get_bad_part(&id_a)?; - let rtype_a = editor::type_of_read(*length, badregion, not_covered); - - let (badregion, length) = badregions.get_bad_part(&id_b)?; - let rtype_b = editor::type_of_read(*length, badregion, not_covered); - - if rtype_a == editor::ReadType::NotBad && rtype_b == editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::M4, - })?; - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - use crate::stack::BadPart; - - use crate::reads2ovl; - use crate::reads2ovl::Reads2Ovl; - - const FASTA_FILE: &'static [u8] = b">1 -ACTG ->2 -ACTG ->3 -ACTG -"; - - const FASTA_FILE_FILTRED: &'static [u8] = b">2 -ACTG ->3 -ACTG -"; - - #[test] - fn fasta_file() -> () { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 1000); - ovlst.add_overlap("1".to_string(), (10, 490)).unwrap(); - ovlst.add_overlap("1".to_string(), (510, 1000)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTA_FILE_FILTRED, &output[..]); - } - - const FASTQ_FILE: &'static [u8] = b"@1 -ACTG -+ -???? -@2 -ACTG -+ -???? -@3 -ACTG -+ -???? -"; - - const FASTQ_FILE_FILTRED: &'static [u8] = b"@2 -ACTG -+ -???? -@3 -ACTG -+ -???? -"; - - #[test] - fn fastq_file() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 1000); - ovlst.add_overlap("1".to_string(), (10, 490)).unwrap(); - ovlst.add_overlap("1".to_string(), (510, 1000)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTQ_FILE_FILTRED, &output[..]); - } - - const PAF_FILE: &'static [u8] = b"1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255 -1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255 -"; - - const PAF_FILE_FILTRED: &'static [u8] = b""; - - #[test] - fn paf_file() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 1000); - ovlst.add_overlap("1".to_string(), (10, 490)).unwrap(); - ovlst.add_overlap("1".to_string(), (510, 1000)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - paf(PAF_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(PAF_FILE_FILTRED, &output[..]); - } - - const M4_FILE: &'static [u8] = b"1 2 0.1 2 0 100 450 1000 0 550 900 1000 -1 3 0.1 2 0 550 900 1000 0 100 450 1000 -"; - - const M4_FILE_FILTRED: &'static [u8] = b""; - - #[test] - fn m4_file() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 1000); - ovlst.add_overlap("1".to_string(), (10, 490)).unwrap(); - ovlst.add_overlap("1".to_string(), (510, 1000)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - m4(M4_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(M4_FILE_FILTRED, &output[..]); - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, bail, Context, Result}; - -/* local use */ -use crate::editor; -use crate::error; -use crate::stack; -use crate::util; - -pub fn extract( - input_path: &str, - output_path: &str, - badregions: &mut dyn stack::BadPart, - not_covered: f64, - buffer_size: usize, -) -> Result<()> { - let (input, compression) = util::read_file(input_path, buffer_size)?; - let output = util::write_file(output_path, compression, buffer_size)?; - - match util::get_file_type(input_path) { - Some(util::FileType::Fasta) => fasta(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Fastq) => fastq(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Paf) => paf(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::M4) => m4(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile { - operation: "scrubbing".to_string(), - filetype: util::FileType::Yacrd, - filename: input_path.to_string() - }), - None | Some(util::FileType::YacrdOverlap) => { - bail!(error::Error::UnableToDetectFileFormat { - filename: input_path.to_string() - }) - } - } - - Ok(()) -} - -fn fasta( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(input)); - let mut writer = noodles::fasta::Writer::new(std::io::BufWriter::new(output)); - - let records = reader.records(); - - for result in records { - println!("PROUT"); - - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Fasta, - })?; - - let (badregion, length) = badregions.get_bad_part(record.name())?; - - let rtype = editor::type_of_read(*length, badregion, not_covered); - - if rtype != editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fasta, - })?; - } - } - - Ok(()) -} - -fn fastq( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = noodles::fastq::Reader::new(std::io::BufReader::new(input)); - let mut writer = noodles::fastq::Writer::new(std::io::BufWriter::new(output)); - - let records = reader.records(); - - for result in records { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Fastq, - })?; - - let (badregion, length) = badregions.get_bad_part( - std::str::from_utf8(record.name())? - .split_ascii_whitespace() - .next() - .unwrap(), - )?; - - let rtype = editor::type_of_read(*length, badregion, not_covered); - - if rtype != editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fastq, - })?; - } - } - - Ok(()) -} - -fn paf( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = csv::ReaderBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .from_reader(input); - let mut writer = csv::WriterBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .from_writer(output); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Paf, - })?; - - let id_a = record[0].to_string(); - let id_b = record[5].to_string(); - - let (badregion, length) = badregions.get_bad_part(&id_a)?; - let rtype_a = editor::type_of_read(*length, badregion, not_covered); - - let (badregion, length) = badregions.get_bad_part(&id_b)?; - let rtype_b = editor::type_of_read(*length, badregion, not_covered); - - if rtype_a != editor::ReadType::NotBad || rtype_b != editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Paf, - })?; - } - } - - Ok(()) -} - -fn m4( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = csv::ReaderBuilder::new() - .delimiter(b' ') - .has_headers(false) - .from_reader(input); - let mut writer = csv::WriterBuilder::new() - .delimiter(b' ') - .has_headers(false) - .from_writer(output); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::M4, - })?; - - let id_a = record[0].to_string(); - let id_b = record[1].to_string(); - - let (badregion, length) = badregions.get_bad_part(&id_a)?; - let rtype_a = editor::type_of_read(*length, badregion, not_covered); - - let (badregion, length) = badregions.get_bad_part(&id_b)?; - let rtype_b = editor::type_of_read(*length, badregion, not_covered); - - if rtype_a != editor::ReadType::NotBad || rtype_b != editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::M4, - })?; - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - use crate::stack::BadPart; - - use crate::reads2ovl; - use crate::reads2ovl::Reads2Ovl; - - const FASTA_FILE: &'static [u8] = b">1 -ACTG ->2 -ACTG ->3 -ACTG -"; - - const FASTA_FILE_EXTRACTED: &'static [u8] = b">1 -ACTG -"; - - #[test] - fn fasta_file() -> () { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 1000); - ovlst.add_overlap("1".to_string(), (10, 490)).unwrap(); - ovlst.add_overlap("1".to_string(), (510, 1000)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTA_FILE_EXTRACTED, &output[..]); - } - - const FASTQ_FILE: &'static [u8] = b"@1 -ACTG -+ -???? -@2 -ACTG -+ -???? -@3 -ACTG -+ -???? -"; - - const FASTQ_FILE_EXTRACTED: &'static [u8] = b"@1 -ACTG -+ -???? -"; - - #[test] - fn fastq_file() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 1000); - ovlst.add_overlap("1".to_string(), (10, 490)).unwrap(); - ovlst.add_overlap("1".to_string(), (510, 1000)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTQ_FILE_EXTRACTED, &output[..]); - } - - const PAF_FILE: &'static [u8] = b"1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255 -1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255 -"; - - const PAF_FILE_EXTRACTED: &'static [u8] = - b"1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255 -1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255 -"; - - #[test] - fn paf_file() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 1000); - ovlst.add_overlap("1".to_string(), (10, 490)).unwrap(); - ovlst.add_overlap("1".to_string(), (510, 1000)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - paf(PAF_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(PAF_FILE_EXTRACTED, &output[..]); - } - - const M4_FILE: &'static [u8] = b"1 2 0.1 2 0 100 450 1000 0 550 900 1000 -1 3 0.1 2 0 550 900 1000 0 100 450 1000 -"; - - const M4_FILE_EXTRACTED: &'static [u8] = b"1 2 0.1 2 0 100 450 1000 0 550 900 1000 -1 3 0.1 2 0 550 900 1000 0 100 450 1000 -"; - - #[test] - fn m4_file() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 1000); - ovlst.add_overlap("1".to_string(), (10, 490)).unwrap(); - ovlst.add_overlap("1".to_string(), (510, 1000)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - m4(M4_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(M4_FILE_EXTRACTED, &output[..]); - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, bail, Context, Result}; -use log::error; - -/* local use */ -use crate::editor; -use crate::error; -use crate::stack; -use crate::util; - -pub fn split( - input_path: &str, - output_path: &str, - badregions: &mut dyn stack::BadPart, - not_covered: f64, - buffer_size: usize, -) -> Result<()> { - let (input, compression) = util::read_file(input_path, buffer_size)?; - let output = util::write_file(output_path, compression, buffer_size)?; - - match util::get_file_type(input_path) { - Some(util::FileType::Fasta) => fasta(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Fastq) => fastq(input, output, badregions, not_covered) - .with_context(|| anyhow!("Filename: {}", input_path.to_string()))?, - Some(util::FileType::Paf) => bail!(error::Error::CantRunOperationOnFile { - operation: "split".to_string(), - filetype: util::FileType::Paf, - filename: input_path.to_string() - }), - Some(util::FileType::M4) => bail!(error::Error::CantRunOperationOnFile { - operation: "split".to_string(), - filetype: util::FileType::M4, - filename: input_path.to_string() - }), - Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile { - operation: "split".to_string(), - filetype: util::FileType::Yacrd, - filename: input_path.to_string() - }), - None | Some(util::FileType::YacrdOverlap) => { - bail!(error::Error::UnableToDetectFileFormat { - filename: input_path.to_string() - }) - } - }; - - Ok(()) -} - -fn fasta( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(input)); - let mut writer = noodles::fasta::Writer::new(std::io::BufWriter::new(output)); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Fasta, - })?; - - let (badregion, length) = badregions.get_bad_part(record.name())?; - - let rtype = editor::type_of_read(*length, badregion, not_covered); - - if rtype == editor::ReadType::NotCovered { - continue; - } else if rtype == editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fasta, - })?; - } else { - let mut poss = vec![0]; - for interval in badregion { - if interval.0 == 0 || interval.1 == *length as u32 { - continue; - } - - poss.push(interval.0); - poss.push(interval.1); - } - poss.push(*length as u32); - - for pos in poss.chunks(2) { - if pos[0] as usize > record.sequence().len() - || pos[1] as usize > record.sequence().len() - { - error!("For read {} split position is larger than read, it's strange check your data. For this read, this split position and next are ignore.", record.name()); - break; - } - - writer - .write_record(&noodles::fasta::Record::new( - noodles::fasta::record::Definition::new( - &format!("{}_{}_{}", record.name(), pos[0], pos[1]), - None, - ), - noodles::fasta::record::Sequence::from( - record.sequence().as_ref()[(pos[0] as usize)..(pos[1] as usize)] - .to_vec(), - ), - )) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fasta, - })?; - } - } - } - - Ok(()) -} - -fn fastq( - input: R, - output: W, - badregions: &mut dyn stack::BadPart, - not_covered: f64, -) -> Result<()> -where - R: std::io::Read, - W: std::io::Write, -{ - let mut reader = noodles::fastq::Reader::new(std::io::BufReader::new(input)); - let mut writer = noodles::fastq::Writer::new(std::io::BufWriter::new(output)); - - for result in reader.records() { - let record = result.with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Fastq, - })?; - - let (badregion, length) = badregions.get_bad_part( - std::str::from_utf8(record.name())? - .split_ascii_whitespace() - .next() - .unwrap(), - )?; - - let rtype = editor::type_of_read(*length, badregion, not_covered); - - if rtype == editor::ReadType::NotCovered { - continue; - } else if rtype == editor::ReadType::NotBad { - writer - .write_record(&record) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fastq, - })?; - } else { - let mut sequence_description = std::str::from_utf8(record.name())?.splitn(2, ' '); - let name = sequence_description.next().unwrap(); - let description = sequence_description.next(); - - let mut poss = vec![0]; - for interval in badregion { - if interval.0 == 0 || interval.1 == *length as u32 { - continue; - } - - poss.push(interval.0); - poss.push(interval.1); - } - poss.push(*length as u32); - - for pos in poss.chunks(2) { - if pos[0] as usize > record.sequence().len() - || pos[1] as usize > record.sequence().len() - { - error!("For read {} split position is larger than read, it's strange check your data. For this read, this split position and next are ignore.", std::str::from_utf8(record.name())?); - break; - } - - writer - .write_record(&noodles::fastq::Record::new( - match description { - Some(desc) => format!("{}_{}_{} {}", name, pos[0], pos[1], desc), - None => format!("{}_{}_{}", name, pos[0], pos[1]), - } - .as_bytes(), - record.sequence()[(pos[0] as usize)..(pos[1] as usize)].to_vec(), - record.quality_scores()[(pos[0] as usize)..(pos[1] as usize)].to_vec(), - )) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Fasta, - })?; - } - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - use crate::stack::BadPart; - - use crate::reads2ovl; - use crate::reads2ovl::Reads2Ovl; - - const FASTA_FILE: &'static [u8] = b">1 -ACTGGGGGGACTGGGGGGACTG ->2 -ACTG ->3 -ACTG -"; - - const FASTA_FILE_SPLITED: &'static [u8] = b">1_0_13 -ACTGGGGGGACTG ->1_18_22 -ACTG ->2 -ACTG ->3 -ACTG -"; - - #[test] - fn fasta_file() -> () { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 22); - ovlst.add_overlap("1".to_string(), (9, 13)).unwrap(); - ovlst.add_overlap("1".to_string(), (18, 22)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTA_FILE_SPLITED, &output[..]); - } - - const FASTQ_FILE: &'static [u8] = b"@1 -ACTGGGGGGACTGGGGGGACTG -+ -?????????????????????? -@2 -ACTG -+ -???? -@3 -ACTG -+ -???? -"; - - const FASTQ_FILE_FILTRED: &'static [u8] = b"@1_0_13 -ACTGGGGGGACTG -+ -????????????? -@1_18_22 -ACTG -+ -???? -@2 -ACTG -+ -???? -@3 -ACTG -+ -???? -"; - - #[test] - fn fastq_file() { - let mut ovlst = reads2ovl::FullMemory::new(8192); - - ovlst.add_length("1".to_string(), 22); - ovlst.add_overlap("1".to_string(), (9, 13)).unwrap(); - ovlst.add_overlap("1".to_string(), (18, 22)).unwrap(); - - let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0); - - stack.compute_all_bad_part(); - - let mut output: Vec = Vec::new(); - fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap(); - - assert_eq!(FASTQ_FILE_FILTRED, &output[..]); - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* local mod */ -pub mod extract; -pub mod filter; -pub mod scrubbing; -pub mod split; - -/* stuff declare in submod need to be accessible from mod level */ -pub use self::extract::*; -pub use self::filter::*; -pub use self::scrubbing::*; -pub use self::split::*; - -/* crate use */ -use anyhow::{Context, Result}; - -/* local use */ -use crate::error; -use crate::util; - -#[derive(Debug, PartialEq)] -pub enum ReadType { - Chimeric, - NotCovered, - NotBad, -} - -impl Eq for ReadType {} - -impl ReadType { - pub fn as_str(&self) -> &'static str { - match self { - ReadType::Chimeric => "Chimeric", - ReadType::NotCovered => "NotCovered", - ReadType::NotBad => "NotBad", - } - } -} - -pub fn report( - read: &str, - length: usize, - badregions: &[(u32, u32)], - not_covered: f64, - out: &mut W, -) -> Result<()> -where - W: std::io::Write, -{ - let readtype = type_of_read(length, badregions, not_covered); - writeln!( - out, - "{}\t{}\t{}\t{}", - readtype.as_str(), - read, - length, - bad_region_format(badregions) - ) - .with_context(|| error::Error::WritingErrorNoFilename { - format: util::FileType::Yacrd, - }) -} - -pub fn type_of_read(length: usize, badregions: &[(u32, u32)], not_covered: f64) -> ReadType { - let bad_region_len = badregions.iter().fold(0, |acc, x| acc + (x.1 - x.0)); - - if bad_region_len as f64 / length as f64 > not_covered { - return ReadType::NotCovered; - } - - let mut middle_gap = badregions - .iter() - .filter(|x| x.0 != 0 && x.1 != length as u32); - if middle_gap.next().is_some() { - return ReadType::Chimeric; - } - - ReadType::NotBad -} - -fn bad_region_format(bads: &[(u32, u32)]) -> String { - bads.iter() - .map(|b| format!("{},{},{}", b.1 - b.0, b.0, b.1)) - .collect::>() - .join(";") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn read_type_assignation() { - let a = (vec![(0, 10), (990, 1000)], 1000); - let b = (vec![(0, 10), (90, 1000)], 1000); - let c = (vec![(0, 10), (490, 510), (990, 1000)], 1000); - let d = (vec![(990, 1000)], 1000); - let e = (vec![(0, 10)], 1000); - let f = (vec![(490, 510)], 1000); - - assert_eq!(ReadType::NotBad, type_of_read(a.1, &a.0, 0.8)); - assert_eq!(ReadType::NotCovered, type_of_read(b.1, &b.0, 0.8)); - assert_eq!(ReadType::Chimeric, type_of_read(c.1, &c.0, 0.8)); - assert_eq!(ReadType::NotBad, type_of_read(d.1, &d.0, 0.8)); - assert_eq!(ReadType::NotBad, type_of_read(e.1, &e.0, 0.8)); - assert_eq!(ReadType::Chimeric, type_of_read(f.1, &f.0, 0.8)); - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use clap::Parser; - -/* mod declaration*/ -mod cli; -mod editor; -mod error; -mod io; -mod reads2ovl; -mod stack; -mod util; - -fn main() -> Result<()> { - env_logger::init(); - - let params = cli::Command::parse(); - - /* Get bad region of reads */ - let mut reads2badregion: Box = - if Some(util::FileType::Yacrd) == util::get_file_type(¶ms.input) { - /* Read bad part from yacrd report */ - Box::new(stack::FromReport::new(¶ms.input)?) - } else { - /* Get bad part from overlap */ - let mut reads2ovl: Box = match params.ondisk.clone() { - Some(on_disk_path) => Box::new(reads2ovl::OnDisk::new( - on_disk_path, - util::str2u64(¶ms.ondisk_buffer_size)?, - params.buffer_size, - )), - None => Box::new(reads2ovl::FullMemory::new(params.buffer_size)), - }; - - reads2ovl.init(¶ms.input)?; - - Box::new(stack::FromOverlap::new(reads2ovl, params.coverage)) - }; - - /* Write report */ - let raw_out = Box::new(std::io::BufWriter::new( - std::fs::File::create(¶ms.output).with_context(|| error::Error::CantWriteFile { - filename: params.output.clone(), - })?, - )); - - let mut out = niffler::get_writer( - raw_out, - niffler::compression::Format::No, - niffler::compression::Level::One, - )?; - - rayon::ThreadPoolBuilder::new() - .num_threads(params.threads.unwrap_or(1usize)) - .build_global()?; - reads2badregion.compute_all_bad_part(); - - for read in reads2badregion.get_reads() { - let (bads, len) = reads2badregion.get_bad_part(&read)?; - editor::report(&read, *len, bads, params.not_coverage, &mut out) - .with_context(|| anyhow!("Filename: {}", ¶ms.output))?; - } - - /* Run post operation on read or overlap */ - match params.subcmd { - Some(cli::SubCommand::Scrubb(s)) => editor::scrubbing( - &s.input, - &s.output, - &mut *reads2badregion, - params.not_coverage, - params.buffer_size, - )?, - Some(cli::SubCommand::Filter(f)) => editor::filter( - &f.input, - &f.output, - &mut *reads2badregion, - params.not_coverage, - params.buffer_size, - )?, - Some(cli::SubCommand::Extract(e)) => editor::extract( - &e.input, - &e.output, - &mut *reads2badregion, - params.not_coverage, - params.buffer_size, - )?, - Some(cli::SubCommand::Split(s)) => editor::split( - &s.input, - &s.output, - &mut *reads2badregion, - params.not_coverage, - params.buffer_size, - )?, - None => (), - }; - - if let Some(on_disk_path) = params.ondisk { - let path = std::path::PathBuf::from(on_disk_path); - if path.is_dir() { - remove_dir_all::remove_dir_all(&path).with_context(|| anyhow!("We failed to remove file {:?}, yacrd finish analysis but temporary file isn't removed", path.clone()))?; - } - - if let Some(parent_path) = path.parent() { - if path.is_dir() { - remove_dir_all::remove_dir_all(parent_path).with_context(|| { - error::Error::PathDestruction { - path: parent_path.to_path_buf(), - } - })?; - } - } - } - - Ok(()) -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; - -/* local use */ -use crate::error; - -#[derive(Debug, PartialEq)] -pub enum FileType { - Fasta, - Fastq, - Yacrd, - Paf, - M4, - YacrdOverlap, -} - -pub fn get_file_type(filename: &str) -> Option { - if filename.contains(".m4") || filename.contains(".mhap") { - Some(FileType::M4) - } else if filename.contains(".paf") { - Some(FileType::Paf) - } else if filename.contains(".yacrd") { - Some(FileType::Yacrd) - } else if filename.contains(".fastq") || filename.contains(".fq") { - Some(FileType::Fastq) - } else if filename.contains(".fasta") || filename.contains(".fa") { - Some(FileType::Fasta) - } else if filename.contains(".yovl") { - Some(FileType::YacrdOverlap) - } else { - None - } -} - -pub fn read_file( - filename: &str, - buffer_size: usize, -) -> Result<(Box, niffler::compression::Format)> { - let raw_in = Box::new(std::io::BufReader::with_capacity( - buffer_size, - std::fs::File::open(filename).with_context(|| error::Error::CantReadFile { - filename: filename.to_string(), - })?, - )); - - niffler::get_reader(raw_in) - .with_context(|| anyhow!("Error in compression detection of file {}", filename)) -} - -pub fn write_file( - filename: &str, - compression: niffler::compression::Format, - buffer_size: usize, -) -> Result> { - let raw_out = Box::new(std::io::BufWriter::with_capacity( - buffer_size, - std::fs::File::create(filename).with_context(|| error::Error::CantWriteFile { - filename: filename.to_string(), - })?, - )); - - let output = niffler::get_writer(raw_out, compression, niffler::compression::Level::One)?; - - Ok(output) -} - -pub fn str2usize(val: &str) -> Result { - val.parse::().with_context(|| { - anyhow!( - "Error during parsing of number from string {:?} in usize", - val - ) - }) -} - -pub fn str2u32(val: &str) -> Result { - val.parse::().with_context(|| { - anyhow!( - "Error during parsing of number from string {:?} in u32", - val - ) - }) -} - -pub fn str2u64(val: &str) -> Result { - val.parse::().with_context(|| { - anyhow!( - "Error during parsing of number from string {:?} in u64", - val - ) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - mod str2usize { - use super::*; - - #[test] - fn failed() { - match str2usize("2,5") { - Err(e) => assert!(true, "Error message {:?}", e), - Ok(a) => assert!(false, "str2usize('2,5') return {}", a), - } - - match str2usize("2.5") { - Err(e) => assert!(true, "Error message {:?}", e), - Ok(a) => assert!(false, "str2usize('2.5') return {}", a), - } - } - - #[test] - fn succeeded() { - match str2usize("2") { - Ok(a) => assert!(true, "Value {}", a), - Err(e) => assert!(false, "str2usize('2') return {}", e), - } - } - } - - mod str2u32 { - use super::*; - - #[test] - fn failed() { - match str2u32("2,5") { - Err(e) => assert!(true, "Error message {:?}", e), - Ok(a) => assert!(false, "str2u32('2,5') return {}", a), - } - - match str2u32("2.5") { - Err(e) => assert!(true, "Error message {:?}", e), - Ok(a) => assert!(false, "str2u32('2.5') return {}", a), - } - } - - #[test] - fn succeeded() { - match str2u32("2") { - Ok(a) => assert!(true, "Value {}", a), - Err(e) => assert!(false, "str2u32('2') return {}", e), - } - } - } - - mod str2u64 { - use super::*; - - #[test] - fn failed() { - match str2u64("2,5") { - Err(e) => assert!(true, "Error message {:?}", e), - Ok(a) => assert!(false, "str2u64('2,5') return {}", a), - } - - match str2u64("2.5") { - Err(e) => assert!(true, "Error message {:?}", e), - Ok(a) => assert!(false, "str2u64('2.5') return {}", a), - } - } - - #[test] - fn succeeded() { - match str2u64("2") { - Ok(a) => assert!(true, "Value {}", a), - Err(e) => assert!(false, "str2u64('2') return {}", e), - } - } - } - - mod file_type { - use super::*; - - #[test] - fn m4() { - assert_eq!(Some(FileType::M4), get_file_type("test.m4")); - } - - #[test] - fn m4_with_other_ext() { - assert_eq!(Some(FileType::M4), get_file_type("test.m4.other_ext")); - } - - #[test] - fn m4_with_nopoint() { - assert_eq!(None, get_file_type("m4.other_ext")); - } - - #[test] - fn mhap() { - assert_eq!(Some(FileType::M4), get_file_type("test.mhap")); - } - - #[test] - fn mhap_with_other_ext() { - assert_eq!(Some(FileType::M4), get_file_type("test.mhap.other_ext")); - } - - #[test] - fn mhap_with_nopoint() { - assert_eq!(None, get_file_type("mhap.other_ext")); - } - - #[test] - fn paf() { - assert_eq!(Some(FileType::Paf), get_file_type("test.paf")); - } - - #[test] - fn paf_with_other_ext() { - assert_eq!(Some(FileType::Paf), get_file_type("test.paf.other_ext")); - } - - #[test] - fn paf_with_nopoint() { - assert_eq!(None, get_file_type("paf.other_ext")); - } - - #[test] - fn fasta() { - assert_eq!(Some(FileType::Fasta), get_file_type("test.fasta")); - } - - #[test] - fn fasta_with_other_ext() { - assert_eq!(Some(FileType::Fasta), get_file_type("test.fasta.other_ext")); - } - - #[test] - fn fasta_with_nopoint() { - assert_eq!(None, get_file_type("fasta.other_ext")); - } - - #[test] - fn fa() { - assert_eq!(Some(FileType::Fasta), get_file_type("test.fa")); - } - - #[test] - fn fa_with_other_ext() { - assert_eq!(Some(FileType::Fasta), get_file_type("test.fa.other_ext")); - } - - #[test] - fn fa_with_nopoint() { - assert_eq!(None, get_file_type("fa.other_ext")); - } - - #[test] - fn fastq() { - assert_eq!(Some(FileType::Fastq), get_file_type("test.fastq")); - } - - #[test] - fn fastq_with_other_ext() { - assert_eq!(Some(FileType::Fastq), get_file_type("test.fastq.other_ext")); - } - - #[test] - fn fastq_with_nopoint() { - assert_eq!(None, get_file_type("fastq.other_ext")); - } - - #[test] - fn fq() { - assert_eq!(Some(FileType::Fastq), get_file_type("test.fq")); - } - - #[test] - fn fq_with_other_ext() { - assert_eq!(Some(FileType::Fastq), get_file_type("test.fq.other_ext")); - } - - #[test] - fn fq_with_nopoint() { - assert_eq!(None, get_file_type("fq.other_ext")); - } - - #[test] - fn yacrd_overlap() { - assert_eq!(Some(FileType::YacrdOverlap), get_file_type("test.yovl")); - } - - #[test] - fn yacrd_overlap_with_other_ext() { - assert_eq!( - Some(FileType::YacrdOverlap), - get_file_type("test.yovl.other_ext") - ); - } - - #[test] - fn yacrd_overlap_with_nopoint() { - assert_eq!(None, get_file_type("yovl.other_ext")); - } - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, bail, Context, Result}; - -/* local mod */ -pub mod fullmemory; -pub mod ondisk; - -/* stuff declare in submod need to be accessible from mod level */ -pub use self::fullmemory::*; -pub use self::ondisk::*; - -/* std use */ -pub use self::fullmemory::*; - -/* local use */ -use crate::error; -use crate::io; -use crate::util; - -pub type MapReads2Ovl = rustc_hash::FxHashMap, usize)>; - -pub trait Reads2Ovl { - fn init(&mut self, filename: &str) -> Result<()> { - self.sub_init(filename) - } - - fn sub_init(&mut self, filename: &str) -> Result<()> { - let (input, _) = util::read_file(filename, self.read_buffer_size())?; - - match util::get_file_type(filename) { - Some(util::FileType::Paf) => self - .init_paf(input) - .with_context(|| anyhow!("Filename: {}", filename.to_string()))?, - Some(util::FileType::M4) => self - .init_m4(input) - .with_context(|| anyhow!("Filename: {}", filename.to_string()))?, - Some(util::FileType::Fasta) => bail!(error::Error::CantRunOperationOnFile { - operation: "overlap parsing".to_string(), - filetype: util::FileType::Fasta, - filename: filename.to_string() - }), - Some(util::FileType::Fastq) => bail!(error::Error::CantRunOperationOnFile { - operation: "overlap parsing".to_string(), - filetype: util::FileType::Fastq, - filename: filename.to_string() - }), - Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile { - operation: "overlap parsing".to_string(), - filetype: util::FileType::Yacrd, - filename: filename.to_string() - }), - None | Some(util::FileType::YacrdOverlap) => { - bail!(error::Error::UnableToDetectFileFormat { - filename: filename.to_string() - }) - } - } - - Ok(()) - } - - fn init_paf(&mut self, input: Box) -> Result<()> { - let mut reader = csv::ReaderBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .flexible(true) - .from_reader(input); - - let mut rec = csv::StringRecord::new(); - - while reader.read_record(&mut rec).unwrap() { - let record: io::PafRecord = - rec.deserialize(None) - .with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::Paf, - })?; - - let id_a = record.read_a.to_string(); - let id_b = record.read_b.to_string(); - - let len_a = record.length_a; - let len_b = record.length_b; - - let ovl_a = (record.begin_a, record.end_a); - let ovl_b = (record.begin_b, record.end_b); - - self.add_overlap_and_length(id_a, ovl_a, len_a)?; - self.add_overlap_and_length(id_b, ovl_b, len_b)?; - } - - Ok(()) - } - - fn init_m4(&mut self, input: Box) -> Result<()> { - let mut reader = csv::ReaderBuilder::new() - .delimiter(b' ') - .has_headers(false) - .flexible(true) - .from_reader(input); - - let mut rec = csv::StringRecord::new(); - - while reader.read_record(&mut rec).unwrap() { - let record: io::M4Record = - rec.deserialize(None) - .with_context(|| error::Error::ReadingErrorNoFilename { - format: util::FileType::M4, - })?; - - let id_a = record.read_a.to_string(); - let id_b = record.read_b.to_string(); - - let len_a = record.length_a; - let len_b = record.length_b; - - let ovl_a = (record.begin_a, record.end_a); - let ovl_b = (record.begin_b, record.end_b); - - self.add_overlap_and_length(id_a, ovl_a, len_a)?; - self.add_overlap_and_length(id_b, ovl_b, len_b)?; - } - - Ok(()) - } - - fn get_overlaps(&mut self, new: &mut MapReads2Ovl) -> bool; - - fn overlap(&self, id: &str) -> Result>; - fn length(&self, id: &str) -> usize; - - fn add_overlap(&mut self, id: String, ovl: (u32, u32)) -> Result<()>; - fn add_length(&mut self, id: String, ovl: usize); - - fn add_overlap_and_length(&mut self, id: String, ovl: (u32, u32), length: usize) -> Result<()>; - - fn get_reads(&self) -> rustc_hash::FxHashSet; - - fn read_buffer_size(&self) -> usize; -} - -#[cfg(test)] -mod tests { - use super::*; - - use std::io::Write; - - extern crate tempfile; - - const PAF_FILE: &'static [u8] = b"1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255 -1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255 -"; - - const M4_FILE: &'static [u8] = b"1 2 0.1 2 0 20 4500 12000 0 5500 10000 10000 -1 3 0.1 2 0 5500 10000 12000 0 0 4500 10000 -"; - - #[test] - fn paf() { - let mut paf = tempfile::Builder::new() - .suffix(".paf") - .tempfile() - .expect("Can't create tmpfile"); - - paf.as_file_mut() - .write_all(PAF_FILE) - .expect("Error durring write of paf in temp file"); - - let mut ovl = FullMemory::new(8192); - - ovl.init(paf.into_temp_path().to_str().unwrap()) - .expect("Error in overlap init"); - - assert_eq!( - ["1".to_string(), "2".to_string(), "3".to_string(),] - .iter() - .cloned() - .collect::>(), - ovl.get_reads() - ); - - assert_eq!(vec![(20, 4500), (5500, 10000)], ovl.overlap("1").unwrap()); - assert_eq!(vec![(5500, 10000)], ovl.overlap("2").unwrap()); - assert_eq!(vec![(0, 4500)], ovl.overlap("3").unwrap()); - } - - #[test] - fn m4() { - let mut m4 = tempfile::Builder::new() - .suffix(".m4") - .tempfile() - .expect("Can't create tmpfile"); - - m4.as_file_mut() - .write_all(M4_FILE) - .expect("Error durring write of m4 in temp file"); - - let mut ovl = FullMemory::new(8192); - - ovl.init(m4.into_temp_path().to_str().unwrap()) - .expect("Error in overlap init"); - - assert_eq!( - ["1".to_string(), "2".to_string(), "3".to_string(),] - .iter() - .cloned() - .collect::>(), - ovl.get_reads() - ); - - assert_eq!(vec![(20, 4500), (5500, 10000)], ovl.overlap("1").unwrap()); - assert_eq!(vec![(5500, 10000)], ovl.overlap("2").unwrap()); - assert_eq!(vec![(0, 4500)], ovl.overlap("3").unwrap()); - } -} -/* - Copyright (c) 2019 Pierre Marijon - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -/* crate use */ -use anyhow::Result; - -/* local use */ -use crate::reads2ovl; - -pub struct FullMemory { - reads2ovl: reads2ovl::MapReads2Ovl, - no_overlap: Vec<(u32, u32)>, - read_buffer_size: usize, -} - -impl FullMemory { - pub fn new(read_buffer_size: usize) -> Self { - FullMemory { - reads2ovl: rustc_hash::FxHashMap::default(), - no_overlap: Vec::new(), - read_buffer_size, - } - } -} - -impl reads2ovl::Reads2Ovl for FullMemory { - fn get_overlaps(&mut self, new: &mut reads2ovl::MapReads2Ovl) -> bool { - std::mem::swap(&mut self.reads2ovl, new); - - true - } - - fn overlap(&self, id: &str) -> Result> { - if let Some((vec, _)) = self.reads2ovl.get(&id.to_string()) { - Ok(vec.to_vec()) - } else { - Ok(self.no_overlap.to_vec()) - } - } - - fn length(&self, id: &str) -> usize { - if let Some((_, len)) = self.reads2ovl.get(&id.to_string()) { - *len - } else { - 0 - } - } - - fn add_overlap(&mut self, id: String, ovl: (u32, u32)) -> Result<()> { - self.reads2ovl - .entry(id) - .or_insert((Vec::new(), 0)) - .0 - .push(ovl); - - Ok(()) - } - - fn add_length(&mut self, id: String, length: usize) { - self.reads2ovl.entry(id).or_insert((Vec::new(), 0)).1 = length; - } - - fn add_overlap_and_length(&mut self, id: String, ovl: (u32, u32), length: usize) -> Result<()> { - if let Some(value) = self.reads2ovl.get_mut(&id) { - value.0.push(ovl); - } else { - self.reads2ovl.insert(id, (vec![ovl], length)); - } - - Ok(()) - } - - fn get_reads(&self) -> rustc_hash::FxHashSet { - self.reads2ovl.keys().map(|x| x.to_string()).collect() - } - - fn read_buffer_size(&self) -> usize { - self.read_buffer_size - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use log::info; - -/* local use */ -use crate::error; -use crate::reads2ovl; - -pub struct OnDisk { - reads2ovl: rustc_hash::FxHashMap>, - reads2len: rustc_hash::FxHashMap, - db: sled::Db, - number_of_value: u64, - buffer_size: u64, - read_buffer_size: usize, -} - -#[derive(Debug, Clone, serde::Deserialize)] -struct OnDiskRecord { - _begin: u32, - _end: u32, -} - -impl OnDisk { - pub fn new(on_disk_path: String, buffer_size: u64, read_buffer_size: usize) -> Self { - let path = std::path::PathBuf::from(on_disk_path.clone()); - - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent) - .with_context(|| error::Error::PathCreation { path }) - .unwrap(); - } - - let db = sled::Config::default() - .path(on_disk_path) - .open() - .with_context(|| error::Error::OnDiskOpen) - .unwrap(); - - OnDisk { - reads2ovl: rustc_hash::FxHashMap::default(), - reads2len: rustc_hash::FxHashMap::default(), - db, - number_of_value: 0, - buffer_size, - read_buffer_size, - } - } - - fn clean_buffer(&mut self) -> Result<()> { - info!( - "Clear cache, number of value in cache is {}", - self.number_of_value - ); - - let mut batch = sled::Batch::default(); - - for (key, vs) in self.reads2ovl.drain() { - let new_val: Vec<(u32, u32)> = match self - .db - .get(key.as_bytes()) - .with_context(|| error::Error::OnDiskReadDatabase)? - { - Some(x) => { - let mut orig: Vec<(u32, u32)> = bincode::deserialize(&x) - .with_context(|| error::Error::OnDiskDeserializeVec)?; - orig.extend(vs); - orig - } - None => vs.to_vec(), - }; - - batch.insert( - key.as_bytes(), - bincode::serialize(&new_val).with_context(|| error::Error::OnDiskSerializeVec)?, - ); - } - - self.db - .apply_batch(batch) - .with_context(|| error::Error::OnDiskBatchApplication)?; - - self.db - .flush() - .with_context(|| error::Error::OnDiskBatchApplication)?; - - self.number_of_value = 0; - - Ok(()) - } - - fn _overlap(&self, id: &str) -> Result> { - bincode::deserialize( - &self - .db - .get(id.as_bytes()) - .with_context(|| error::Error::OnDiskReadDatabase)? - .unwrap(), - ) - .with_context(|| error::Error::OnDiskDeserializeVec) - } -} - -impl reads2ovl::Reads2Ovl for OnDisk { - fn init(&mut self, filename: &str) -> Result<()> { - self.sub_init(filename)?; - - self.clean_buffer() - .with_context(|| anyhow!("Error durring creation of tempory file"))?; - self.number_of_value = 0; - - Ok(()) - } - - fn get_overlaps(&mut self, new: &mut reads2ovl::MapReads2Ovl) -> bool { - let mut tmp = rustc_hash::FxHashMap::default(); - - if self.reads2len.is_empty() { - std::mem::swap(&mut tmp, new); - return true; - } - - let mut remove_reads = Vec::with_capacity(self.buffer_size as usize); - - for (k, v) in self.reads2len.iter().take(self.buffer_size as usize) { - remove_reads.push(k.clone()); - tmp.insert(k.clone(), (self._overlap(k).unwrap(), *v)); - } - - for k in remove_reads { - self.reads2len.remove(&k); - } - - std::mem::swap(&mut tmp, new); - false - } - - fn overlap(&self, id: &str) -> Result> { - self._overlap(id) - } - - fn length(&self, id: &str) -> usize { - *self.reads2len.get(&id.to_string()).unwrap_or(&0) - } - - fn add_overlap(&mut self, id: String, ovl: (u32, u32)) -> Result<()> { - self.reads2ovl.entry(id).or_insert_with(Vec::new).push(ovl); - - self.number_of_value += 1; - - if self.number_of_value >= self.buffer_size { - self.clean_buffer()?; - } - - Ok(()) - } - - fn add_length(&mut self, id: String, length: usize) { - self.reads2len.entry(id).or_insert(length); - } - - fn add_overlap_and_length(&mut self, id: String, ovl: (u32, u32), length: usize) -> Result<()> { - self.add_length(id.clone(), length); - - self.add_overlap(id, ovl) - } - - fn get_reads(&self) -> rustc_hash::FxHashSet { - self.reads2len.keys().map(|x| x.to_string()).collect() - } - - fn read_buffer_size(&self) -> usize { - self.read_buffer_size - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* std use */ -use std::cmp::Reverse; - -/* crate use */ -use anyhow::{Context, Result}; -use rayon::prelude::*; - -/* local use */ -use crate::error; -use crate::reads2ovl; -use crate::util; - -pub trait BadPart { - fn compute_all_bad_part(&mut self); - - fn get_bad_part(&mut self, id: &str) -> Result<&(Vec<(u32, u32)>, usize)>; - - fn get_reads(&self) -> rustc_hash::FxHashSet; -} - -pub struct FromOverlap { - ovl: Box, - coverage: u64, - buffer: reads2ovl::MapReads2Ovl, - empty: (Vec<(u32, u32)>, usize), -} - -impl FromOverlap { - pub fn new(ovl: Box, coverage: u64) -> Self { - let empty = (Vec::new(), 0); - FromOverlap { - ovl, - coverage, - buffer: rustc_hash::FxHashMap::default(), - empty, - } - } - - fn compute_bad_part(mut ovls: Vec<(u32, u32)>, len: usize, coverage: usize) -> Vec<(u32, u32)> { - let mut gaps: Vec<(u32, u32)> = Vec::new(); - let mut stack: std::collections::BinaryHeap> = - std::collections::BinaryHeap::new(); - - ovls.sort_unstable(); - - let mut first_covered = 0; - let mut last_covered = 0; - - for interval in ovls { - while let Some(head) = stack.peek() { - if head.0 > interval.0 { - break; - } - - if stack.len() > coverage { - last_covered = head.0; - } - stack.pop(); - } - - if stack.len() <= coverage { - if last_covered != 0 { - gaps.push((last_covered, interval.0)); - } else { - first_covered = interval.0; - } - } - stack.push(Reverse(interval.1)); - } - - while stack.len() > coverage { - last_covered = stack - .peek() - .with_context(|| error::Error::NotReachableCode { - name: format!("{} {}", file!(), line!()), - }) - .unwrap() - .0; - if last_covered as usize >= len { - break; - } - stack.pop(); - } - - if first_covered != 0 { - gaps.insert(0, (0, first_covered)); - } - - if last_covered as usize != len { - gaps.push((last_covered, len as u32)); - } - - if gaps.is_empty() { - return gaps; - } - - /* clean overlapped bad region */ - let mut clean_gaps: Vec<(u32, u32)> = Vec::new(); - let mut begin = gaps[0].0; - let mut end = gaps[0].1; - for gaps in gaps.windows(2) { - let g1 = gaps[0]; - let g2 = gaps[1]; - - if g1.0 == g2.0 { - begin = g1.0; - end = g1.1.max(g2.1); - } else { - clean_gaps.push((begin, end)); - begin = g2.0; - end = g2.1; - } - } - clean_gaps.push((begin, end)); - - clean_gaps - } -} - -impl BadPart for FromOverlap { - fn compute_all_bad_part(&mut self) { - let mut new = rustc_hash::FxHashMap::default(); - - let coverage = self.coverage as usize; - - loop { - let finish = self.ovl.get_overlaps(&mut new); - - self.buffer.extend( - new.drain() - .par_bridge() - .map(|(k, v)| (k, (FromOverlap::compute_bad_part(v.0, v.1, coverage), v.1))) - .collect::(), - ); - - if finish { - break; - } - } - } - - fn get_bad_part(&mut self, id: &str) -> Result<&(Vec<(u32, u32)>, usize)> { - match self.buffer.get(id) { - Some(v) => Ok(v), - None => Ok(&self.empty), - } - } - - fn get_reads(&self) -> rustc_hash::FxHashSet { - self.buffer.keys().map(|x| x.to_string()).collect() - } -} - -pub struct FromReport { - buffer: reads2ovl::MapReads2Ovl, - empty: (Vec<(u32, u32)>, usize), -} - -impl FromReport { - pub fn new(input_path: &str) -> Result { - let input = - std::io::BufReader::new(std::fs::File::open(input_path).with_context(|| { - error::Error::CantReadFile { - filename: input_path.to_string(), - } - })?); - let mut reader = csv::ReaderBuilder::new() - .delimiter(b'\t') - .has_headers(false) - .from_reader(input); - - let mut buffer = rustc_hash::FxHashMap::default(); - for (line, record) in reader.records().enumerate() { - let result = record.with_context(|| error::Error::Reading { - filename: input_path.to_string(), - format: util::FileType::Fasta, - })?; - - let id = result[1].to_string(); - let len = util::str2usize(&result[2])?; - let bad_part = FromReport::parse_bad_string(&result[3]).with_context(|| { - error::Error::CorruptYacrdReport { - name: input_path.to_string(), - line, - } - })?; - - buffer.insert(id, (bad_part, len)); - } - - let empty = (Vec::new(), 0); - Ok(FromReport { buffer, empty }) - } - - fn parse_bad_string(bad_string: &str) -> Result> { - let mut ret = Vec::new(); - - if bad_string.is_empty() { - return Ok(ret); - } - - for sub in bad_string.split(';') { - let mut iter = sub.split(','); - iter.next(); - - ret.push(( - util::str2u32( - iter.next() - .with_context(|| error::Error::CorruptYacrdReportInPosition)?, - )?, - util::str2u32( - iter.next() - .with_context(|| error::Error::CorruptYacrdReportInPosition)?, - )?, - )); - } - - Ok(ret) - } -} - -impl BadPart for FromReport { - fn compute_all_bad_part(&mut self) {} - - fn get_bad_part(&mut self, id: &str) -> Result<&(Vec<(u32, u32)>, usize)> { - match self.buffer.get(id) { - Some(v) => Ok(v), - None => Ok(&self.empty), - } - } - - fn get_reads(&self) -> rustc_hash::FxHashSet { - self.buffer.keys().map(|x| x.to_string()).collect() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use std::io::Write; - - extern crate tempfile; - use self::tempfile::NamedTempFile; - - use reads2ovl::Reads2Ovl; - - #[test] - fn from_report() { - let mut report = NamedTempFile::new().expect("Can't create tmpfile"); - - writeln!( - report.as_file_mut(), - "NotBad SRR8494940.65223 2706 1131,0,1131;16,2690,2706 -NotCovered SRR8494940.141626 30116 326,0,326;27159,2957,30116 -Chimeric SRR8494940.91655 15691 151,0,151;4056,7213,11269;58,15633,15691" - ) - .expect("Error durring write of report in temp file"); - - let mut stack = FromReport::new(report.into_temp_path().to_str().unwrap()) - .expect("Error when create stack object"); - - assert_eq!( - [ - "SRR8494940.65223".to_string(), - "SRR8494940.141626".to_string(), - "SRR8494940.91655".to_string() - ] - .iter() - .cloned() - .collect::>(), - stack.get_reads() - ); - - assert_eq!( - &(vec![(0, 1131), (2690, 2706)], 2706), - stack.get_bad_part("SRR8494940.65223").unwrap() - ); - assert_eq!( - &(vec![(0, 326), (2957, 30116)], 30116), - stack.get_bad_part("SRR8494940.141626").unwrap() - ); - assert_eq!( - &(vec![(0, 151), (7213, 11269), (15633, 15691)], 15691), - stack.get_bad_part("SRR8494940.91655").unwrap() - ); - } - - #[test] - fn from_overlap() { - let mut ovl = reads2ovl::FullMemory::new(8192); - - ovl.add_overlap("A".to_string(), (10, 990)).unwrap(); - ovl.add_length("A".to_string(), 1000); - - ovl.add_overlap("B".to_string(), (10, 90)).unwrap(); - ovl.add_length("B".to_string(), 1000); - - ovl.add_overlap("C".to_string(), (10, 490)).unwrap(); - ovl.add_overlap("C".to_string(), (510, 990)).unwrap(); - ovl.add_length("C".to_string(), 1000); - - ovl.add_overlap("D".to_string(), (0, 990)).unwrap(); - ovl.add_length("D".to_string(), 1000); - - ovl.add_overlap("E".to_string(), (10, 1000)).unwrap(); - ovl.add_length("E".to_string(), 1000); - - ovl.add_overlap("F".to_string(), (0, 490)).unwrap(); - ovl.add_overlap("F".to_string(), (510, 1000)).unwrap(); - ovl.add_length("F".to_string(), 1000); - - let mut stack = FromOverlap::new(Box::new(ovl), 0); - - stack.compute_all_bad_part(); - - assert_eq!( - [ - "A".to_string(), - "B".to_string(), - "C".to_string(), - "D".to_string(), - "E".to_string(), - "F".to_string() - ] - .iter() - .cloned() - .collect::>(), - stack.get_reads() - ); - - assert_eq!( - &(vec![(0, 10), (990, 1000)], 1000), - stack.get_bad_part("A").unwrap() - ); - assert_eq!( - &(vec![(0, 10), (90, 1000)], 1000), - stack.get_bad_part("B").unwrap() - ); - assert_eq!( - &(vec![(0, 10), (490, 510), (990, 1000)], 1000), - stack.get_bad_part("C").unwrap() - ); - assert_eq!(&(vec![(990, 1000)], 1000), stack.get_bad_part("D").unwrap()); - assert_eq!(&(vec![(0, 10)], 1000), stack.get_bad_part("E").unwrap()); - assert_eq!(&(vec![(490, 510)], 1000), stack.get_bad_part("F").unwrap()); - } - - #[test] - fn coverage_upper_than_0() { - let mut ovl = reads2ovl::FullMemory::new(8192); - - ovl.add_length("A".to_string(), 1000); - - ovl.add_overlap("A".to_string(), (0, 425)).unwrap(); - ovl.add_overlap("A".to_string(), (0, 450)).unwrap(); - ovl.add_overlap("A".to_string(), (0, 475)).unwrap(); - - ovl.add_overlap("A".to_string(), (525, 1000)).unwrap(); - ovl.add_overlap("A".to_string(), (550, 1000)).unwrap(); - ovl.add_overlap("A".to_string(), (575, 1000)).unwrap(); - - let mut stack = FromOverlap::new(Box::new(ovl), 2); - - stack.compute_all_bad_part(); - - assert_eq!(&(vec![(425, 575)], 1000), stack.get_bad_part("A").unwrap()); - } - - #[test] - fn failled_correctly_on_corrupt_yacrd() { - let mut report = NamedTempFile::new().expect("Can't create tmpfile"); - - writeln!( - report.as_file_mut(), - "NotBad SRR8494940.65223 2706 1131,0,1131;16,2690,2706 -NotCovered SRR8494940.141626 30116 326,0,326;27159,2957,30116 -Chimeric SRR8494940.91655 15691 151,0,151;4056,7213,11269;58,156" - ) - .unwrap(); - - let stack = FromReport::new(report.into_temp_path().to_str().unwrap()); - - if !stack.is_err() { - assert!(false); - } - } - - #[test] - fn perfect_read_in_report() { - let mut report = NamedTempFile::new().expect("Can't create tmpfile"); - - writeln!(report.as_file_mut(), "NotBad perfect 2706 ") - .expect("Error durring write of report in temp file"); - - let mut stack = FromReport::new(report.into_temp_path().to_str().unwrap()) - .expect("Error when create stack object"); - - assert_eq!( - ["perfect".to_string()] - .iter() - .cloned() - .collect::>(), - stack.get_reads() - ); - - assert_eq!(&(vec![], 2706), stack.get_bad_part("perfect").unwrap()); - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use thiserror::Error; - -/* local use */ -use crate::util; - -#[derive(Debug, Error)] -pub enum Error { - #[error( - "Reading of the file '{filename:}' impossible, does it exist and can be read by the user?" - )] - CantReadFile { filename: String }, - - #[error("Creation/opening of the file '{filename:}' impossible, directory in path exist? can be written by the user?")] - CantWriteFile { filename: String }, - - #[error("Format detection for '{filename:}' file not possible, filename need to contains .fasta, .fa, .fastq, fq, .paf, .m4, .mhap or .yacrd")] - UnableToDetectFileFormat { filename: String }, - - #[error( - "This operation {operation:} can't be run on this type ({filetype:?}) of file {filename:}" - )] - CantRunOperationOnFile { - operation: String, - filetype: util::FileType, - filename: String, - }, - - #[error("Error durring reading of file {filename:} in format {format:?}")] - Reading { - filename: String, - format: util::FileType, - }, - - #[error("Error during reading a file in format {format:?}")] - ReadingErrorNoFilename { format: util::FileType }, - - #[error("Error during writing of file in format {format:?}")] - WritingErrorNoFilename { format: util::FileType }, - - #[error("Error during yacrd overlap path creation {path:?}")] - PathCreation { path: std::path::PathBuf }, - - #[error("Error during yacrd overlap path destruction {path:?}")] - PathDestruction { path: std::path::PathBuf }, - - #[error("If you get this error please contact the author with this message and command line you use: {name:?}")] - NotReachableCode { name: String }, - - #[error("Yacrd postion seems corrupt")] - CorruptYacrdReportInPosition, - - #[error("Your yacrd file {name} seems corrupt at line {line} you probably need to relaunch analisys with overlapping file")] - CorruptYacrdReport { name: String, line: usize }, - - #[error("Error durring open database")] - OnDiskOpen, - - #[error("Error durring read database")] - OnDiskReadDatabase, - - #[error("Error durring on disk deserialize vector")] - OnDiskDeserializeVec, - - #[error("Error durring on disk serialize vector")] - OnDiskSerializeVec, - - #[error("Error durring on disk batch application")] - OnDiskBatchApplication, -} -/* -Copyright (c) 2018 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -#[derive(Debug, Clone, serde::Deserialize)] -pub struct PafRecord<'a> { - pub read_a: &'a str, - pub length_a: usize, - pub begin_a: u32, - pub end_a: u32, - pub _strand: char, - pub read_b: &'a str, - pub length_b: usize, - pub begin_b: u32, - pub end_b: u32, -} - -#[derive(Debug, Clone, serde::Deserialize)] -pub struct M4Record<'a> { - pub read_a: &'a str, - pub read_b: &'a str, - pub _error: f64, - pub _shared_min: u64, - pub _strand_a: char, - pub begin_a: u32, - pub end_a: u32, - pub length_a: usize, - pub _strand_b: char, - pub begin_b: u32, - pub end_b: u32, - pub length_b: usize, -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* std use */ -use std::io::BufRead; -use std::io::Read; -use std::process::{Command, Stdio}; - -#[cfg(test)] -mod tests { - - use super::*; - - fn diff_unorder(truth_path: &str, result_path: &str) { - let truth_file = std::io::BufReader::new( - std::fs::File::open(truth_path).expect(&format!("Impossible to open {}", truth_path)), - ); - - let mut truth: std::collections::HashSet = std::collections::HashSet::new(); - - for res in truth_file.lines() { - let line = res.unwrap(); - truth.insert(line); - } - - let result_file = std::io::BufReader::new( - std::fs::File::open(result_path).expect(&format!("Impossible to open {}", result_path)), - ); - - let mut result: std::collections::HashSet = std::collections::HashSet::new(); - - for res in result_file.lines() { - let line = res.unwrap(); - result.insert(line); - } - - if truth != result { - panic!( - "Truth {} and result {} are different", - truth_path, result_path - ); - } - } - - fn diff(truth_path: &str, result_path: &str) { - let truth_file = std::io::BufReader::new( - std::fs::File::open(truth_path).expect(&format!("Impossible to open {}", truth_path)), - ); - - let mut truth: Vec = Vec::new(); - - for res in truth_file.lines() { - let line = res.unwrap(); - truth.push(line); - } - - let result_file = std::io::BufReader::new( - std::fs::File::open(result_path).expect(&format!("Impossible to open {}", result_path)), - ); - - let mut result: Vec = Vec::new(); - - for res in result_file.lines() { - let line = res.unwrap(); - result.push(line); - } - - if truth != result { - panic!( - "Truth {} and result {} are different", - truth_path, result_path - ); - } - } - - #[test] - fn detection() { - let mut child = Command::new("./target/debug/yacrd") - .args(&["-i", "tests/reads.paf", "-o", "tests/result.yacrd"]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create yacrd subprocess"); - - if !child.wait().expect("Error durring yacrd run").success() { - let mut stdout = String::new(); - let mut stderr = String::new(); - - child.stdout.unwrap().read_to_string(&mut stdout).unwrap(); - child.stderr.unwrap().read_to_string(&mut stderr).unwrap(); - - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); - panic!(); - } - - diff_unorder("tests/truth.yacrd", "tests/result.yacrd"); - } - - #[test] - fn detection_ondisk() { - if cfg!(windows) { - () - } else { - if std::path::Path::new("tests/ondisk").exists() { - std::fs::remove_dir_all(std::path::Path::new("tests/ondisk")) - .expect("We can't delete temporary directory of ondisk test"); - } - - std::fs::create_dir(std::path::Path::new("tests/ondisk")) - .expect("We can't create temporary directory for ondisk test"); - - let mut child = Command::new("./target/debug/yacrd") - .args(&[ - "-i", - "tests/reads.paf", - "-o", - "tests/result.ondisk.yacrd", - "-d", - "tests/ondisk", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create yacrd subprocess"); - - if !child.wait().expect("Error durring yacrd run").success() { - let mut stdout = String::new(); - let mut stderr = String::new(); - - child.stdout.unwrap().read_to_string(&mut stdout).unwrap(); - child.stderr.unwrap().read_to_string(&mut stderr).unwrap(); - - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); - panic!(); - } - - diff_unorder("tests/truth.yacrd", "tests/result.ondisk.yacrd"); - } - } - - #[test] - fn filter() { - let mut child = Command::new("./target/debug/yacrd") - .args(&[ - "-i", - "tests/reads.paf", - "-o", - "tests/result.filter.yacrd", - "filter", - "-i", - "tests/reads.fastq", - "-o", - "tests/reads.filter.fastq", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create yacrd subprocess"); - - if !child.wait().expect("Error durring yacrd run").success() { - let mut stdout = String::new(); - let mut stderr = String::new(); - - child.stdout.unwrap().read_to_string(&mut stdout).unwrap(); - child.stderr.unwrap().read_to_string(&mut stderr).unwrap(); - - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); - panic!(); - } - - diff_unorder("tests/truth.yacrd", "tests/result.filter.yacrd"); - diff("tests/truth.filter.fastq", "tests/reads.filter.fastq") - } - - #[test] - fn extract() { - let mut child = Command::new("./target/debug/yacrd") - .args(&[ - "-i", - "tests/reads.paf", - "-o", - "tests/result.extract.yacrd", - "extract", - "-i", - "tests/reads.fastq", - "-o", - "tests/reads.extract.fastq", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create yacrd subprocess"); - - if !child.wait().expect("Error durring yacrd run").success() { - let mut stdout = String::new(); - let mut stderr = String::new(); - - child.stdout.unwrap().read_to_string(&mut stdout).unwrap(); - child.stderr.unwrap().read_to_string(&mut stderr).unwrap(); - - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); - panic!(); - } - - diff_unorder("tests/truth.yacrd", "tests/result.extract.yacrd"); - diff("tests/truth.extract.fastq", "tests/reads.extract.fastq") - } - - #[test] - fn split() { - let mut child = Command::new("./target/debug/yacrd") - .args(&[ - "-i", - "tests/reads.paf", - "-o", - "tests/result.split.yacrd", - "split", - "-i", - "tests/reads.fastq", - "-o", - "tests/reads.split.fastq", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create yacrd subprocess"); - - if !child.wait().expect("Error durring yacrd run").success() { - let mut stdout = String::new(); - let mut stderr = String::new(); - - child.stdout.unwrap().read_to_string(&mut stdout).unwrap(); - child.stderr.unwrap().read_to_string(&mut stderr).unwrap(); - - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); - panic!(); - } - - diff_unorder("tests/truth.yacrd", "tests/result.split.yacrd"); - diff("tests/truth.split.fastq", "tests/reads.split.fastq") - } - - #[test] - fn scrubb() { - let mut child = Command::new("./target/debug/yacrd") - .args(&[ - "-i", - "tests/reads.paf", - "-o", - "tests/result.scrubb.yacrd", - "scrubb", - "-i", - "tests/reads.fastq", - "-o", - "tests/reads.scrubb.fastq", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create yacrd subprocess"); - - if !child.wait().expect("Error durring yacrd run").success() { - let mut stdout = String::new(); - let mut stderr = String::new(); - - child.stdout.unwrap().read_to_string(&mut stdout).unwrap(); - child.stderr.unwrap().read_to_string(&mut stderr).unwrap(); - - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); - panic!(); - } - - diff_unorder("tests/truth.yacrd", "tests/result.scrubb.yacrd"); - diff("tests/truth.scrubb.fastq", "tests/reads.scrubb.fastq") - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use log::Level; - -pub fn i82level(level: i8) -> Option { - match level { - std::i8::MIN..=0 => None, - 1 => Some(log::Level::Error), - 2 => Some(log::Level::Warn), - 3 => Some(log::Level::Info), - 4 => Some(log::Level::Debug), - 5..=std::i8::MAX => Some(log::Level::Trace), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn loglevel() { - assert_eq!(i82level(i8::MIN), None); - assert_eq!(i82level(-3), None); - assert_eq!(i82level(1), Some(log::Level::Error)); - assert_eq!(i82level(2), Some(log::Level::Warn)); - assert_eq!(i82level(3), Some(log::Level::Info)); - assert_eq!(i82level(4), Some(log::Level::Debug)); - assert_eq!(i82level(5), Some(log::Level::Trace)); - assert_eq!(i82level(i8::MAX), Some(log::Level::Trace)); - } -} -/* -Copyright (c) 2021 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use clap::Parser; - -use br::error::IO::*; -use br::error::*; -use br::*; - -#[derive(clap::Parser, Debug)] -#[clap( - version = "0.1", - author = "Pierre Marijon ", - about = "A version of br where memory usage depend on number of kmer not kmer length" -)] -pub struct Command { - /// fasta file to be correct - #[clap(short = 'i', long = "inputs")] - pub inputs: Vec, - - /// path where corrected read was write - #[clap(short = 'o', long = "outputs")] - pub outputs: Vec, - - /// use kmer present in fasta file as solid kmer and store them in HashSet - #[clap(short = 'S', long = "kmer-solid")] - pub kmer_solid: Vec, - - /// kmer length lower or equal to 32 - #[clap(short = 'k', long = "kmer")] - pub kmer_size: Option, - - /// correction method used, methods are applied in the order you specify, default value is 'one' - #[clap( - short = 'm', - long = "method", - possible_values = &["one", "two", "graph", "greedy", "gap_size"], - )] - pub methods: Option>, - - /// number of kmer need to be solid after one, greedy correction to validate it, default value is '2' - #[clap(short = 'c', long = "confirm")] - pub confirm: Option, - - /// number of base we use to try correct error, default value is '7' - #[clap(short = 'M', long = "max-search")] - pub max_search: Option, - - /// if this flag is set br correct only in forward orientation - #[clap(short = 'n', long = "not-two-side")] - pub two_side: bool, - - /// Number of thread use by br, 0 use all avaible core, default value 0 - #[clap(short = 't', long = "threads")] - pub threads: Option, - - /// Number of sequence record load in buffer, default 8192 - #[clap(short = 'b', long = "record_buffer")] - pub record_buffer: Option, - - /// verbosity level also control by environment variable BR_LOG if flag is set BR_LOG value is ignored - #[clap(short = 'v', long = "verbosity", parse(from_occurrences))] - pub verbosity: i8, -} - -#[cfg(not(tarpaulin_include))] -fn main() -> Result<()> { - let params = Command::parse(); - - let mut files = Vec::new(); - - for path in params.kmer_solid { - files.push(std::io::BufReader::new( - std::fs::File::open(&path) - .with_context(|| Error::IO(CantOpenFile)) - .with_context(|| anyhow!("File {:?}", path.clone()))?, - )); - } - - let solid: set::BoxKmerSet = Box::new(set::Hash::new( - files, - params.kmer_size.ok_or(Error::Cli(Cli::KmerSolidNeedK))?, - )); - - let confirm = params.confirm.unwrap_or(2); - let max_search = params.max_search.unwrap_or(7); - let record_buffer = params.record_buffer.unwrap_or(8192); - - let methods = br::build_methods(params.methods, &solid, confirm, max_search); - - br::run_correction( - ¶ms.inputs, - ¶ms.outputs, - methods, - params.two_side, - record_buffer, - )?; - - Ok(()) -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use clap::Parser; - -use br::error::Cli::*; -use br::error::*; -use br::*; - -#[derive(clap::Parser, Debug)] -#[clap( - version = "0.1", - author = "Pierre Marijon ", - about = "Br: Brutal rewrite a simple long read corrector based on kmer spectrum methode" -)] -pub struct Command { - /// solidity bitfield produce by pcon - #[clap(short = 's', long = "solidity")] - pub solidity: Option, - - /// kmer length if you didn't provide solidity path you must give a kmer length - #[clap(short = 'k', long = "kmer")] - pub kmer_size: Option, - - /// fasta file to be correct - #[clap(short = 'i', long = "inputs")] - pub inputs: Vec, - - /// path where corrected read was write - #[clap(short = 'o', long = "outputs")] - pub outputs: Vec, - - /// if you want choose the minimum abundance you can set this parameter - #[clap(short = 'a', long = "abundance")] - pub abundance: Option, - - /// Choose method to automaticly choose minimum abundance, format is {method}_{params}, method must be ['first-minimum', 'rarefaction', 'percent-most', 'percent-least'] params is a float between 0 to 1, default value is first-minimum_0.0, more information in pcon documentation - #[clap(short = 'A', long = "abundance-method")] - pub abundance_method: Option, - - /// correction method used, methods are applied in the order you specify, default value is 'one' - #[clap( - short = 'm', - long = "method", - possible_values = &["one", "two", "graph", "greedy", "gap_size"], - )] - pub methods: Option>, - - /// number of kmer need to be solid after one, greedy correction to validate it, default value is '2' - #[clap(short = 'c', long = "confirm")] - pub confirm: Option, - - /// number of base we use to try correct error, default value is '7' - #[clap(short = 'M', long = "max-search")] - pub max_search: Option, - - /// if this flag is set br correct only in forward orientation - #[clap(short = 'n', long = "not-two-side")] - pub two_side: bool, - - /// Number of thread use by br, 0 use all avaible core, default value 0 - #[clap(short = 't', long = "threads")] - pub threads: Option, - - /// Number of sequence record load in buffer, default 8192 - #[clap(short = 'b', long = "record_buffer")] - pub record_buffer: Option, - - /// verbosity level also control by environment variable BR_LOG if flag is set BR_LOG value is ignored - #[clap(short = 'v', long = "verbosity", parse(from_occurrences))] - pub verbosity: i8, -} - -#[cfg(not(tarpaulin_include))] -fn main() -> Result<()> { - let params = Command::parse(); - - if params.inputs.len() != params.outputs.len() { - return Err(anyhow!(Error::Cli(NotSameNumberOfInAndOut))); - } - - if let Some(level) = cli::i82level(params.verbosity) { - env_logger::builder() - .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis)) - .filter_level(level.to_level_filter()) - .init(); - } else { - env_logger::Builder::from_env("BR_LOG") - .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis)) - .init(); - } - - let confirm = params.confirm.unwrap_or(2); - let max_search = params.max_search.unwrap_or(7); - let record_buffer = params.record_buffer.unwrap_or(8192); - - if let Some(threads) = params.threads { - log::info!("Set number of threads to {}", threads); - - set_nb_threads(threads); - } - - let solid = if let Some(path) = params.solidity { - read_solidity(path)? - } else if let Some(kmer_size) = params.kmer_size { - let count = count_kmer(¶ms.inputs, kmer_size, record_buffer)?; - - let abundance_method = params.abundance_method.unwrap_or(AbundanceMethod { - method: pcon::spectrum::ThresholdMethod::FirstMinimum, - params: 0.0, - }); - - let threshold = params.abundance.unwrap_or(compute_abundance_threshold( - &count, - abundance_method, - std::io::stdout(), - )?); - - Box::new(set::Pcon::new(pcon::solid::Solid::from_counter( - &count, threshold, - ))) - } else { - anyhow::bail!(Error::Cli(NoSolidityNoKmer)); - }; - - let methods = br::build_methods(params.methods, &solid, confirm, max_search); - - br::run_correction( - ¶ms.inputs, - ¶ms.outputs, - methods, - params.two_side, - record_buffer, - )?; - - Ok(()) -} - -fn read_solidity<'a>(path: String) -> Result> { - let solidity_reader = std::io::BufReader::new( - std::fs::File::open(&path) - .with_context(|| Error::IO(IO::CantOpenFile)) - .with_context(|| anyhow!("File {:?}", path.clone()))?, - ); - - log::info!("Load solidity file"); - - Ok(Box::new(set::Pcon::new(pcon::solid::Solid::deserialize( - solidity_reader, - )?))) -} - -fn count_kmer( - inputs: &[String], - kmer_size: u8, - record_buffer_len: usize, -) -> Result { - let mut counter = pcon::counter::Counter::new(kmer_size); - - log::info!("Start count kmer from input"); - for input in inputs { - let fasta = std::io::BufReader::new( - std::fs::File::open(&input) - .with_context(|| Error::IO(IO::CantOpenFile)) - .with_context(|| anyhow!("File {:?}", input.clone()))?, - ); - - counter.count_fasta(fasta, record_buffer_len); - } - log::info!("End count kmer from input"); - - Ok(counter) -} - -fn compute_abundance_threshold( - count: &pcon::counter::Counter, - method: AbundanceMethod, - out: W, -) -> Result -where - W: std::io::Write, -{ - let spectrum = pcon::spectrum::Spectrum::from_counter(count); - - let abundance = spectrum - .get_threshold(method.method, method.params) - .ok_or(Error::CantComputeAbundance)?; - - spectrum - .write_histogram(out, Some(abundance)) - .with_context(|| anyhow!("Error durring write of kmer histograme"))?; - println!("If this curve seems bad or minimum abundance choose (marked by *) not apopriate set parameter -a"); - - Ok(abundance as u8) -} - -#[derive(Debug)] -pub struct AbundanceMethod { - pub method: pcon::spectrum::ThresholdMethod, - pub params: f64, -} - -impl std::str::FromStr for AbundanceMethod { - type Err = br::error::Cli; - - fn from_str(s: &str) -> Result { - let elements: Vec<&str> = s.split('_').collect(); - - if elements.len() > 2 { - Err(Cli::CantParseAbundanceMethod) - } else { - let method = match elements[0] { - "first-minimum" => pcon::spectrum::ThresholdMethod::FirstMinimum, - "rarefaction" => pcon::spectrum::ThresholdMethod::Rarefaction, - "percent-most" => pcon::spectrum::ThresholdMethod::PercentAtMost, - "percent-least" => pcon::spectrum::ThresholdMethod::PercentAtLeast, - _ => return Err(Cli::CantParseAbundanceMethod), - }; - - let params = if method == pcon::spectrum::ThresholdMethod::FirstMinimum { - 0.0 - } else if let Ok(p) = f64::from_str(elements[1]) { - if p > 0.0 && p < 1.0 { - p - } else { - return Err(Cli::CantParseAbundanceMethod); - } - } else { - return Err(Cli::CantParseAbundanceMethod); - }; - - Ok(AbundanceMethod { method, params }) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use std::str::FromStr; - - use std::io::Seek; - use std::io::Write; - - use rand::seq::SliceRandom; - use rand::{Rng, SeedableRng}; - - fn init() { - let _ = env_logger::builder() - .is_test(true) - .filter_level(log::LevelFilter::Trace) - .try_init(); - } - - fn generate_seq_file() -> tempfile::NamedTempFile { - let mut rng = rand::rngs::SmallRng::seed_from_u64(42); - - let nucs = [b'A', b'C', b'T', b'G']; - - let mut sequence = (0..1000) - .map(|_| *nucs.choose(&mut rng).unwrap()) - .collect::>(); - - let mut tmpfile = tempfile::NamedTempFile::new().unwrap(); - - writeln!( - tmpfile.as_file_mut(), - ">42\n{}", - std::str::from_utf8(&sequence).unwrap() - ) - .unwrap(); - - for _ in 0..25 { - for nuc in sequence.iter_mut() { - if rng.gen_ratio(2, 100) { - *nuc = *nucs.choose(&mut rng).unwrap(); - } - } - - writeln!( - tmpfile.as_file_mut(), - ">42\n{}", - std::str::from_utf8(&sequence).unwrap() - ) - .unwrap(); - } - - tmpfile.seek(std::io::SeekFrom::Start(0)).unwrap(); - - tmpfile - } - - static COUNT: &[u8] = &[ - 5, 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 5, 192, 88, 111, 210, 96, 140, 18, 100, 144, 140, 66, - 57, 202, 213, 210, 227, 251, 122, 209, 155, 149, 210, 99, 20, 10, 45, 45, 163, 21, 156, - 107, 68, 221, 3, 137, 17, 141, 154, 232, 18, 227, 139, 15, 186, 159, 224, 15, 94, 78, 76, - 83, 27, 34, 168, 118, 148, 79, 51, 105, 75, 153, 164, 57, 61, 52, 44, 92, 198, 11, 32, 67, - 54, 96, 145, 102, 241, 117, 12, 49, 47, 27, 207, 213, 54, 64, 2, 180, 143, 57, 9, 161, 101, - 12, 185, 36, 251, 126, 44, 132, 165, 125, 114, 154, 23, 35, 121, 156, 139, 119, 204, 206, - 161, 217, 58, 42, 106, 113, 224, 81, 128, 27, 6, 198, 78, 233, 104, 93, 85, 187, 130, 198, - 101, 7, 83, 206, 191, 7, 130, 237, 249, 135, 248, 43, 106, 209, 84, 52, 178, 239, 37, 164, - 94, 133, 67, 14, 110, 244, 91, 215, 151, 194, 158, 142, 101, 31, 121, 205, 4, 177, 95, 123, - 38, 187, 235, 233, 213, 146, 41, 81, 119, 52, 93, 236, 202, 35, 95, 82, 192, 246, 115, 201, - 129, 108, 211, 34, 114, 5, 95, 4, 95, 8, 134, 104, 93, 255, 85, 10, 196, 46, 179, 204, 159, - 124, 218, 139, 46, 203, 167, 84, 177, 81, 184, 34, 82, 187, 133, 114, 250, 58, 215, 185, - 176, 225, 30, 132, 237, 74, 125, 61, 17, 106, 78, 94, 55, 230, 76, 210, 234, 244, 90, 239, - 101, 184, 226, 169, 202, 122, 207, 151, 47, 194, 28, 74, 181, 217, 219, 51, 84, 94, 148, - 71, 84, 51, 237, 138, 228, 66, 117, 143, 193, 12, 101, 195, 31, 27, 238, 67, 210, 150, 244, - 181, 84, 0, 145, 165, 0, 106, 248, 28, 151, 31, 67, 27, 161, 176, 229, 125, 247, 92, 5, 47, - 33, 10, 63, 221, 20, 4, 70, 129, 42, 24, 213, 67, 202, 104, 176, 130, 216, 110, 186, 192, - 36, 197, 71, 250, 155, 77, 31, 136, 65, 95, 216, 170, 184, 96, 137, 147, 30, 149, 64, 197, - 5, 209, 12, 5, 222, 120, 96, 48, 209, 196, 251, 142, 201, 176, 103, 139, 165, 7, 16, 236, - 73, 133, 23, 206, 189, 170, 180, 136, 56, 220, 159, 80, 139, 138, 136, 195, 81, 251, 159, - 136, 179, 197, 119, 181, 109, 243, 6, 13, 200, 56, 77, 228, 137, 240, 43, 57, 42, 164, 19, - 14, 5, 246, 149, 250, 230, 182, 242, 159, 43, 136, 23, 148, 125, 242, 178, 181, 96, 84, 56, - 35, 26, 253, 241, 219, 77, 19, 54, 216, 250, 74, 127, 8, 92, 90, 242, 49, 196, 222, 243, - 67, 159, 11, 162, 220, 157, 134, 53, 220, 65, 216, 198, 19, 175, 254, 202, 208, 0, 2, 0, 0, - ]; - - #[test] - fn _count_kmer() { - init(); - - let file = generate_seq_file(); - - let path = file.path().to_str().unwrap().to_string(); - - let count = count_kmer(&[path], 5, 26).unwrap(); - - let mut output = std::io::Cursor::new(Vec::new()); - count.serialize(&mut output).unwrap(); - - assert_eq!(COUNT, output.into_inner()); - } - - #[test] - fn _compute_abundance_threshold() { - init(); - - let output = vec![]; - let count = pcon::counter::Counter::deserialize(COUNT).unwrap(); - - let abu_method = AbundanceMethod { - method: pcon::spectrum::ThresholdMethod::FirstMinimum, - params: 0.0, - }; - - assert_eq!( - 2, - compute_abundance_threshold(&count, abu_method, output).unwrap() - ); - } - - static SOLID: &[u8] = &[ - 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 77, 136, 193, 9, 0, 64, 8, 195, 94, 183, 255, 136, 55, - 134, 15, 145, 216, 10, 130, 208, 180, 52, 15, 40, 113, 147, 62, 223, 181, 248, 140, 93, - 161, 13, 1, 52, 40, 137, 69, 44, 65, 0, 0, 0, - ]; - - #[test] - fn _read_solidity() { - init(); - - let count = pcon::counter::Counter::deserialize(COUNT).unwrap(); - let compute = pcon::solid::Solid::from_counter(&count, 2); - - let mut compute_out = vec![]; - compute.serialize(&mut compute_out).unwrap(); - - assert_eq!(SOLID, compute_out.as_slice()); - - let mut tmpfile = tempfile::NamedTempFile::new().unwrap(); - - tmpfile.write_all(SOLID).unwrap(); - - let path = tmpfile.path().to_str().unwrap().to_string(); - - let read = read_solidity(path).unwrap(); - for kmer in 0..cocktail::kmer::get_kmer_space_size(5) { - assert_eq!(compute.get(kmer), read.get(kmer)); - } - } - - #[test] - fn abundance_method_parsing() { - init(); - - let tmp = AbundanceMethod::from_str("first-minimum").unwrap(); - assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::FirstMinimum); - assert_eq!(tmp.params, 0.0); - - let tmp = AbundanceMethod::from_str("rarefaction_0.5").unwrap(); - assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::Rarefaction); - assert_eq!(tmp.params, 0.5); - - let tmp = AbundanceMethod::from_str("percent-most_0.1").unwrap(); - assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::PercentAtMost); - assert_eq!(tmp.params, 0.1); - - let tmp = AbundanceMethod::from_str("percent-least_0.8").unwrap(); - assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::PercentAtLeast); - assert_eq!(tmp.params, 0.8); - - // First minimum params is always 0.0 - let tmp = AbundanceMethod::from_str("first-minimum_0.8").unwrap(); - assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::FirstMinimum); - assert_eq!(tmp.params, 0.0); - - // name not match - assert!(AbundanceMethod::from_str("aesxàyxauie_0.8").is_err()); - - // to many field - assert!(AbundanceMethod::from_str("first-minimum_0.8_aiue_auie").is_err()); - - // params to large - assert!(AbundanceMethod::from_str("rarefaction_34.8").is_err()); - - // params don't care - assert!(AbundanceMethod::from_str("first-minimum_42.42").is_ok()); - assert!(AbundanceMethod::from_str("first-minimum_auie").is_ok()); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -pub mod hash; -pub mod pcon; - -pub use self::hash::Hash; -pub use self::pcon::Pcon; - -pub trait KmerSet: Sync { - fn get(&self, kmer: u64) -> bool; - - fn k(&self) -> u8; -} - -pub type BoxKmerSet<'a> = Box; -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* local use */ -pub use crate::set::KmerSet; - -pub struct Hash { - set: rustc_hash::FxHashSet, - k: u8, -} - -impl Hash { - pub fn new(inputs: Vec, k: u8) -> Self - where - R: std::io::Read, - { - let mut set = rustc_hash::FxHashSet::default(); - - for input in inputs { - let mut records = bio::io::fasta::Reader::new(input).records(); - - while let Some(Ok(record)) = records.next() { - for cano in cocktail::tokenizer::Canonical::new(record.seq(), k) { - set.insert(cano); - } - } - } - - Self { set, k } - } -} - -impl KmerSet for Hash { - fn get(&self, kmer: u64) -> bool { - self.set.contains(&cocktail::kmer::canonical(kmer, self.k)) - } - - fn k(&self) -> u8 { - self.k - } -} - -#[cfg(test)] -mod tests { - use super::*; - - static FILE: &[u8] = b">1\nACGTGGGAATTGTGGCCACATCACGAGGTCCTGCGTATTGACGACTGTAAAGCGAGTGGCCGTGGAATTTCAAGCTCAATTAGCCGAACCAATCCGCCTA"; - - #[test] - fn canonical() { - let file = std::io::Cursor::new(FILE); - - let hash = Hash::new(vec![file], 11); - - let set: crate::set::BoxKmerSet = Box::new(hash); - - let mut records = bio::io::fasta::Reader::new(FILE).records(); - for cano in cocktail::tokenizer::Canonical::new(records.next().unwrap().unwrap().seq(), 11) - { - assert!(set.get(cano)) - } - } - - #[test] - fn forward() { - let file = std::io::Cursor::new(FILE); - - let hash = Hash::new(vec![file], 11); - - let set: crate::set::BoxKmerSet = Box::new(hash); - - let mut records = bio::io::fasta::Reader::new(FILE).records(); - for kmer in cocktail::tokenizer::Tokenizer::new(records.next().unwrap().unwrap().seq(), 11) - { - assert!(set.get(kmer)) - } - } - - #[test] - fn absence() { - let file = std::io::Cursor::new(FILE); - - let hash = Hash::new(vec![file], 11); - - let set: crate::set::BoxKmerSet = Box::new(hash); - - assert!(!set.get(0)); - } - - #[test] - fn k() { - let file = std::io::Cursor::new(FILE); - - let hash = Hash::new(vec![file], 11); - - let set: crate::set::BoxKmerSet = Box::new(hash); - - assert_eq!(set.k(), 11); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* local use */ -use crate::set::KmerSet; - -pub struct Pcon { - set: pcon::solid::Solid, -} - -impl Pcon { - pub fn new(set: pcon::solid::Solid) -> Self { - Pcon { set } - } -} - -impl KmerSet for Pcon { - fn get(&self, kmer: u64) -> bool { - self.set.get(kmer) - } - - fn k(&self) -> u8 { - self.set.k - } -} - -#[cfg(test)] -mod tests { - use super::*; - - static SEQ: &[u8] = b"ACGTGGGAATTGTGGCCACATCACGAGGTCCTGCGTATTGACGACTGTAAAGCGAGTGGCCGTGGAATTTCAAGCTCAATTAGCCGAACCAATCCGCCTA"; - - #[test] - fn canonical() { - let mut solid = pcon::solid::Solid::new(11); - for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) { - solid.set(cano, true); - } - - let set: crate::set::BoxKmerSet = Box::new(Pcon::new(solid)); - - for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) { - assert!(set.get(cano)) - } - } - - #[test] - fn forward() { - let mut solid = pcon::solid::Solid::new(11); - for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) { - solid.set(cano, true); - } - - let set: crate::set::BoxKmerSet = Box::new(Pcon::new(solid)); - - for kmer in cocktail::tokenizer::Tokenizer::new(SEQ, 11) { - assert!(set.get(kmer)) - } - } - - #[test] - fn absence() { - let mut solid = pcon::solid::Solid::new(11); - for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) { - solid.set(cano, true); - } - - let set: crate::set::BoxKmerSet = Box::new(Pcon::new(solid)); - - assert!(!set.get(0)); - } - - #[test] - fn k() { - let mut solid = pcon::solid::Solid::new(11); - for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) { - solid.set(cano, true); - } - - let set: crate::set::BoxKmerSet = Box::new(Pcon::new(solid)); - - assert_eq!(set.k(), 11); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use log::debug; - -/* local use */ -use crate::correct::*; - -pub struct GapSize<'a> { - valid_kmer: &'a set::BoxKmerSet<'a>, - graph: graph::Graph<'a>, - one: One<'a>, -} - -impl<'a> GapSize<'a> { - pub fn new(valid_kmer: &'a set::BoxKmerSet<'a>, c: u8) -> Self { - Self { - valid_kmer, - graph: graph::Graph::new(valid_kmer), - one: One::new(valid_kmer, c), - } - } - - pub fn ins_sub_correction(&self, kmer: u64, gap_size: usize) -> Option<(Vec, usize)> { - let mut alts = alt_nucs(self.valid_kmer, kmer); - - if alts.len() != 1 { - debug!("not one alts {:?}", alts); - return None; - } - - let mut corr = add_nuc_to_end(kmer >> 2, alts[0], self.k()); - let mut local_corr = vec![cocktail::kmer::bit2nuc(alts[0])]; - let mut viewed_kmer = rustc_hash::FxHashSet::default(); - viewed_kmer.insert(corr); - - for i in 0..gap_size { - alts = next_nucs(self.valid_kmer, corr); - - if alts.len() != 1 { - debug!( - "failled multiple successor {} {:?} i: {}", - cocktail::kmer::kmer2seq(corr, self.valid_kmer.k()), - alts, - i - ); - return None; - } - - corr = add_nuc_to_end(corr, alts[0], self.k()); - debug!( - "kmer {}", - cocktail::kmer::kmer2seq(corr, self.valid_kmer.k()) - ); - if viewed_kmer.contains(&corr) { - debug!( - "we view this kmer previously {}", - cocktail::kmer::kmer2seq(corr, self.k()) - ); - return None; - } - viewed_kmer.insert(corr); - - local_corr.push(cocktail::kmer::bit2nuc(alts[0])); - } - - let offset = local_corr.len(); - Some((local_corr, offset)) - } -} - -impl<'a> Corrector for GapSize<'a> { - fn valid_kmer(&self) -> &set::BoxKmerSet<'a> { - self.valid_kmer - } - - fn correct_error(&self, kmer: u64, seq: &[u8]) -> Option<(Vec, usize)> { - let (error_len, _first_correct_kmer) = error_len(seq, kmer, self.valid_kmer()); - - debug!("error_len {}", error_len); - match error_len.cmp(&(self.k() as usize)) { - std::cmp::Ordering::Less => self.graph.correct_error(kmer, seq), // we can avoid a second compute of error_len - std::cmp::Ordering::Equal => self.one.correct_error(kmer, seq), - std::cmp::Ordering::Greater => { - self.ins_sub_correction(kmer, error_len - self.k() as usize) - } - } - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - fn init() { - let _ = env_logger::builder() - .is_test(true) - .filter_level(log::LevelFilter::Trace) - .try_init(); - } - - #[test] - fn csc() { - init(); - - let refe = b"AGCGTATCTT"; - // ||||| ||||| - let read = b"AGCGTTTCTT"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = GapSize::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn cssc() { - init(); - - let refe = b"TCTCTAATCTTC"; - // ||||| ||||| - let read = b"TCTCTGGTCTTC"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = GapSize::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn csssc() { - init(); - - let refe = b"TCTCTAAATCTTC"; - // ||||| ||||| - let read = b"TCTCTGGGTCTTC"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = GapSize::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrect - } - - #[test] - fn cscsc() { - init(); - - let refe = b"GTGTGACTTACACCTCGTTGAGCACCCGATGTTGGTATAGTCCGAACAAC"; - // ||||| | ||||| - let read = b"GTGTGACTTACACCTCGTTGAGTAGCCGATGTTGGTATAGTCCGAACAAC"; - - println!("{}", String::from_utf8(refe.to_vec()).unwrap()); - println!("{}", String::from_utf8(read.to_vec()).unwrap()); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(11); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 11) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = GapSize::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn cdc() { - init(); - - let refe = b"GATACATGGACACTAGTATG"; - // |||||||||| - let read = b"GATACATGGAACTAGTATG"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = GapSize::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cddc() { - init(); - - let refe = b"CAAAGCATTTTT"; - // ||||| - let read = b"CAAAGTTTTT"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = GapSize::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cic() { - init(); - - let refe = b"GGATAACTCT"; - // ||||| - let read = b"GGATATACTCT"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = GapSize::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use log::debug; - -/* local use */ -use crate::correct::*; - -struct Score; - -impl bio::alignment::pairwise::MatchFunc for Score { - fn score(&self, a: u8, b: u8) -> i32 { - if a == b { - 1 - } else { - -1 - } - } -} - -pub struct Greedy<'a> { - valid_kmer: &'a set::BoxKmerSet<'a>, - max_search: u8, - nb_validate: u8, -} - -impl<'a> Greedy<'a> { - pub fn new(valid_kmer: &'a set::BoxKmerSet, max_search: u8, nb_validate: u8) -> Self { - Self { - valid_kmer, - max_search, - nb_validate, - } - } - - fn match_alignement(&self, before_seq: Vec, read: &[u8], corr: &[u8]) -> Option { - let mut r = before_seq.clone(); - r.extend_from_slice(read); - - let mut c = before_seq.clone(); - c.extend_from_slice(corr); - - let mut aligner = - bio::alignment::pairwise::Aligner::with_capacity(10, 10, -1, -1, Score {}); - let alignment = aligner.global(r.as_slice(), c.as_slice()); - - let mut offset = 0; - for ops in alignment.operations[before_seq.len()..].windows(2) { - match ops[0] { - bio::alignment::AlignmentOperation::Del => offset -= 1, - bio::alignment::AlignmentOperation::Ins => offset += 1, - _ => (), - } - - if ops[0] == bio::alignment::AlignmentOperation::Match && ops[0] == ops[1] { - let mut offset_corr = 0; - for op in alignment.operations.iter().rev() { - match op { - bio::alignment::AlignmentOperation::Del => offset_corr -= 1, - bio::alignment::AlignmentOperation::Ins => offset_corr += 1, - _ => break, - } - } - return Some(offset - offset_corr); - } - } - - None - } - - fn follow_graph(&self, mut kmer: u64) -> Option<(u8, u64)> { - let alts = next_nucs(self.valid_kmer(), kmer); - - if alts.len() != 1 { - debug!("failled branching node {:?}", alts); - return None; - } - - kmer = add_nuc_to_end(kmer, alts[0], self.k()); - - Some((cocktail::kmer::bit2nuc(alts[0]), kmer)) - } - - fn check_next_kmers(&self, mut kmer: u64, seq: &[u8]) -> bool { - if seq.len() < self.nb_validate as usize { - return false; - } - - for nuc in &seq[..self.nb_validate as usize] { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(*nuc), self.k()); - if !self.valid_kmer.get(kmer) { - return false; - } - } - - true - } -} - -impl<'a> Corrector for Greedy<'a> { - fn k(&self) -> u8 { - self.valid_kmer.k() - } - - fn valid_kmer(&self) -> &set::BoxKmerSet { - self.valid_kmer - } - - fn correct_error(&self, mut kmer: u64, seq: &[u8]) -> Option<(Vec, usize)> { - let alts = alt_nucs(self.valid_kmer(), kmer); - if alts.len() != 1 { - debug!("failled multiple successor {:?}", alts); - return None; - } - - let mut viewed_kmer = rustc_hash::FxHashSet::default(); - - let mut local_corr = Vec::new(); - let before_seq = cocktail::kmer::kmer2seq(kmer >> 2, self.k() - 1) - .as_bytes() - .to_vec(); - - kmer = add_nuc_to_end(kmer >> 2, alts[0], self.k()); - - local_corr.push(cocktail::kmer::bit2nuc(alts[0])); - viewed_kmer.insert(kmer); - - for i in 0..(self.max_search as usize) { - if let Some((base, new_kmer)) = self.follow_graph(kmer) { - local_corr.push(base); - kmer = new_kmer; - } - - if viewed_kmer.contains(&kmer) { - debug!("we view this kmer previously"); - return None; - } - viewed_kmer.insert(kmer); - - if seq.len() < i as usize { - return None; - } - - if let Some(off) = self.match_alignement(before_seq.clone(), &seq[..i], &local_corr) { - if self.check_next_kmers(kmer, &seq[i..]) { - let offset: usize = (local_corr.len() as i64 + off) as usize; - return Some((local_corr, offset)); - } - } - } - - None - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - static K: u8 = 11; - static REFE: &[u8] = b"TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG"; - - fn init() { - let _ = env_logger::builder() - .is_test(true) - .filter_level(log::LevelFilter::Trace) - .try_init(); - } - - fn get_solid() -> pcon::solid::Solid { - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(K); - - for kmer in cocktail::tokenizer::Tokenizer::new(REFE, K) { - data.set(kmer, true); - } - - data - } - - #[test] - fn branching_path_csc() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // |||||||||||||||||||||||| ||||||||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACATTTCACTGCCCGATACGCAGATGAAAGAGG"; - - let mut data = get_solid(); - - data.set(cocktail::kmer::seq2bit(b"CACATTTCGCG"), true); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn branching_path_cdc() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // ||||||||||||||||||||||||////////////////////////// - let read = b"TAAGGCGCGTCCCGCACACATTTCCTGCCCGATACGCAGATGAAAGAGG"; - - let mut data = get_solid(); - - data.set(cocktail::kmer::seq2bit(b"CACATTTCGCG"), true); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn branching_path_cic() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // ||||||||||||||||||||||||\\\\\\\\\\\\\\\\\\\\\\\\\\ - let read = b"TAAGGCGCGTCCCGCACACATTTCAGCTGCCCGATACGCAGATGAAAGAGG"; - - let mut data = get_solid(); - - data.set(cocktail::kmer::seq2bit(b"CACACATTTCT"), true); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn csc() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // |||||||||||||||||||||||| ||||||||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACATTTCACTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn cssc() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // ||||||||||||||||||||||| ||||||||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACATTTGACTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn csssc() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // ||||||||||||||||||||||| |||||||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACATTTGATTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn cscsc() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // ||||||||||||||||||||||| |||||||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACATTTGATTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - #[ignore] - fn cdc() { - init(); - - // TTTCGCTGCCCG - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // ||||||||||||||||||||||||////////////////////////// - let read = b"TAAGGCGCGTCCCGCACACATTTCCTGCCCGATACGCAGATGAAAGAGG"; - // TTTCCTGCCCG - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - #[ignore] - fn cddc() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // |||||||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACATCGCTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - #[ignore] - fn cdddc() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // |||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACACGCTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn cic() { - init(); - - // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG - // ||||||||||||||||||||||||\\\\\\\\\\\\\\\\\\\\\\\\\\\ - let read = b"TAAGGCGCGTCCCGCACACATTTCAGCTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn ciic() { - init(); - - // TAAGGCGCGTCCCGCACACATTTC--GCTGCCCGATACGCAGATGAAAGAGG - // |||||||||||||||||||||||| |||||||||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACATTTCAAGCTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } - - #[test] - fn ciiic() { - init(); - - // TAAGGCGCGTCCCGCACACATTTC---GCTGCCCGATACGCAGATGAAAGAGG - // |||||||||||||||||||||||| |||||||||||||||||||||||||| - let read = b"TAAGGCGCGTCCCGCACACATTTCAAAGCTGCCCGATACGCAGATGAAAGAGG"; - - let data = get_solid(); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Greedy::new(&set, 7, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection - } -} -/* crate use */ -use log::debug; -use strum::IntoEnumIterator; - -/* crate use */ -use crate::correct::*; -use crate::set; - -/////////////////////////////////////////// -// Generic Trait for correction scenario // -/////////////////////////////////////////// -pub trait Scenario: std::fmt::Debug + Copy { - fn init(&self, c: usize, k: u8) -> Self; - - fn c(&self) -> usize; - - fn apply(&self, valid_kmer: &set::BoxKmerSet, kmer: u64, seq: &[u8]) -> Option<(u64, usize)>; - - fn correct(&self, valid_kmer: &set::BoxKmerSet, kmer: u64, _seq: &[u8]) -> (Vec, usize); - - fn get_score(&self, valid_kmer: &set::BoxKmerSet, ori: u64, seq: &[u8]) -> usize { - if let Some((mut kmer, offset)) = self.apply(valid_kmer, ori, seq) { - if !valid_kmer.get(kmer) { - return 0; - } - - if offset + self.c() > seq.len() { - return 0; - } - - let mut score = 0; - - for nuc in &seq[offset..offset + self.c()] { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(*nuc), valid_kmer.k()); - - if valid_kmer.get(kmer) { - score += 1 - } else { - break; - } - } - - score - } else { - 0 - } - } - - fn one_more(&self, valid_kmer: &set::BoxKmerSet, mut kmer: u64, seq: &[u8]) -> bool { - // Get correction - let (corr, offset) = self.correct(valid_kmer, kmer, seq); - - // Can we read one base more - if seq.len() > self.c() + offset + 1 { - kmer >>= 2; - // Apply correction on kmer - corr.iter().for_each(|nuc| { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(*nuc), valid_kmer.k()) - }); - - // Apply base previously check - seq[offset..(offset + self.c() + 1)].iter().for_each(|nuc| { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(*nuc), valid_kmer.k()) - }); - - valid_kmer.get(kmer) - } else { - false - } - } -} - -////////////////////////////////////////// -// Exsist use scenario to correct error // -////////////////////////////////////////// -pub struct Exist<'a, S> -where - S: Scenario + IntoEnumIterator, -{ - valid_kmer: &'a set::BoxKmerSet<'a>, - c: u8, - _phantom: std::marker::PhantomData<&'a S>, -} - -impl<'a, S> Exist<'a, S> -where - S: Scenario + IntoEnumIterator, -{ - pub fn new(valid_kmer: &'a set::BoxKmerSet, c: u8) -> Self { - Self { - valid_kmer, - c, - _phantom: std::marker::PhantomData, - } - } - - fn get_scenarii(&self, kmer: u64, seq: &[u8]) -> Vec { - let mut scenarii: Vec = Vec::new(); - - for mut scenario in S::iter() { - scenario = scenario.init(self.c as usize, self.valid_kmer.k()); - - if scenario.get_score(self.valid_kmer, kmer, seq) == self.c as usize { - scenarii.push(scenario) - } - } - - scenarii - } -} - -impl<'a, S> Corrector for Exist<'a, S> -where - S: Scenario + IntoEnumIterator, -{ - fn valid_kmer(&self) -> &set::BoxKmerSet { - self.valid_kmer - } - - fn correct_error(&self, kmer: u64, seq: &[u8]) -> Option<(Vec, usize)> { - let alts = alt_nucs(self.valid_kmer, kmer); - - if alts.len() != 1 { - debug!("not one alts {:?}", alts); - return None; - } - debug!("one alts {:?}", alts); - - let corr = add_nuc_to_end(kmer >> 2, alts[0], self.k()); - let mut scenarii = self.get_scenarii(corr, seq); - - if scenarii.is_empty() { - debug!("no scenario"); - None - } else if scenarii.len() == 1 { - debug!("one {:?}", scenarii); - Some(scenarii[0].correct(self.valid_kmer, corr, seq)) - } else { - debug!("multiple {:?}", scenarii); - scenarii.retain(|x| x.one_more(self.valid_kmer, corr, seq)); - debug!("multiple {:?}", scenarii); - - if scenarii.len() == 1 { - Some(scenarii[0].correct(self.valid_kmer, corr, seq)) - } else { - None - } - } - } -} - -pub mod one; -pub mod two; -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use strum_macros::EnumIter; - -/* crate use */ -use crate::correct::exist::{Exist, Scenario}; -use crate::correct::*; -use crate::set; - -//////////////////////////////////// -// Scenario for correct two error // -//////////////////////////////////// -#[derive(Debug, EnumIter, Clone, Copy)] -pub enum ScenarioTwo { - II(usize, u8), - IS(usize, u8), - SS(usize, u8), - SD(usize, u8), - DD(usize, u8), - - ICI(usize, u8), - ICS(usize, u8), - ICD(usize, u8), - SCI(usize, u8), - SCS(usize, u8), - SCD(usize, u8), - DCI(usize, u8), - DCD(usize, u8), -} - -impl Scenario for ScenarioTwo { - fn init(&self, c: usize, k: u8) -> Self { - match self { - ScenarioTwo::II(_, _) => ScenarioTwo::II(c, k), - ScenarioTwo::IS(_, _) => ScenarioTwo::IS(c, k), - ScenarioTwo::SS(_, _) => ScenarioTwo::SS(c, k), - ScenarioTwo::SD(_, _) => ScenarioTwo::SD(c, k), - ScenarioTwo::DD(_, _) => ScenarioTwo::DD(c, k), - ScenarioTwo::ICI(_, _) => ScenarioTwo::ICI(c, k), - ScenarioTwo::ICS(_, _) => ScenarioTwo::ICS(c, k), - ScenarioTwo::ICD(_, _) => ScenarioTwo::ICD(c, k), - ScenarioTwo::SCI(_, _) => ScenarioTwo::SCI(c, k), - ScenarioTwo::SCS(_, _) => ScenarioTwo::SCS(c, k), - ScenarioTwo::SCD(_, _) => ScenarioTwo::SCD(c, k), - ScenarioTwo::DCI(_, _) => ScenarioTwo::DCI(c, k), - ScenarioTwo::DCD(_, _) => ScenarioTwo::DCD(c, k), - } - } - - fn c(&self) -> usize { - match self { - ScenarioTwo::II(c, _) => *c, - ScenarioTwo::IS(c, _) => *c, - ScenarioTwo::SS(c, _) => *c, - ScenarioTwo::SD(c, _) => *c, - ScenarioTwo::DD(c, _) => *c, - ScenarioTwo::ICI(c, _) => *c, - ScenarioTwo::ICS(c, _) => *c, - ScenarioTwo::ICD(c, _) => *c, - ScenarioTwo::SCI(c, _) => *c, - ScenarioTwo::SCS(c, _) => *c, - ScenarioTwo::SCD(c, _) => *c, - ScenarioTwo::DCI(c, _) => *c, - ScenarioTwo::DCD(c, _) => *c, - } - } - - fn apply( - &self, - valid_kmer: &set::BoxKmerSet, - mut kmer: u64, - seq: &[u8], - ) -> Option<(u64, usize)> { - match self { - ScenarioTwo::II(_, _) => Some((kmer, 3)), // kmer not change check from base 3 - ScenarioTwo::IS(_, _) => Some((kmer, 2)), // kmer not change check from base 2 - ScenarioTwo::SS(_, k) => { - if seq.len() < 2 { - None - } else { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k); - if valid_kmer.get(kmer) { - None - } else { - let alts = alt_nucs(valid_kmer, kmer); - if alts.len() != 1 { - None - } else { - Some((add_nuc_to_end(kmer >> 2, alts[0], *k), 2)) - } - } - } - } - ScenarioTwo::SD(_, k) => { - if seq.is_empty() { - None - } else { - let alts = alt_nucs(valid_kmer, kmer << 2); - if alts.len() != 1 { - None - } else { - Some((add_nuc_to_end(kmer, alts[0], *k), 1)) - } - } - } - ScenarioTwo::DD(_, k) => { - let alts = alt_nucs(valid_kmer, kmer << 2); - if alts.len() != 1 { - None - } else { - Some((add_nuc_to_end(kmer, alts[0], *k), 0)) - } - } - ScenarioTwo::ICI(_, k) => { - // If seq is to short we can't apply - if seq.len() < 4 { - None - } else { - let corr = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[3]), *k); // If kmer with thrid base is valid is an ICI - - if valid_kmer.get(corr) { - Some((corr, 4)) - } else { - None - } - } - } - ScenarioTwo::ICS(_, k) => { - // If seq is to short we can't apply - if seq.len() < 4 { - None - } else { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k); - if valid_kmer.get(kmer) { - None - } else { - let alts = alt_nucs(valid_kmer, kmer); - if alts.len() != 1 { - None - } else { - Some((add_nuc_to_end(kmer >> 2, alts[0], *k), 3)) - } - } - } - } - ScenarioTwo::ICD(_, k) => { - // If seq is to short we can't apply - if seq.len() < 4 { - None - } else { - let second = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[2]), *k); - - let alts = alt_nucs(valid_kmer, second << 2); - if alts.len() != 1 { - None - } else { - Some((add_nuc_to_end(second, alts[0], *k), 3)) - } - } - } - ScenarioTwo::SCI(_, k) => { - if seq.len() < 4 { - None - } else { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k); - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[3]), *k); - - Some((kmer, 4)) - } - } - ScenarioTwo::SCS(_, k) => { - if seq.len() < 3 { - None - } else { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k); - if valid_kmer.get(kmer) { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[2]), *k); - - if !valid_kmer.get(kmer) { - let alts = alt_nucs(valid_kmer, kmer); - - if alts.len() == 1 { - Some((add_nuc_to_end(kmer >> 2, alts[0], *k), 3)) - } else { - None - } - } else { - None - } - } else { - None - } - } - } - ScenarioTwo::SCD(_, k) => { - if seq.len() < 2 { - None - } else { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k); - - let alts = alt_nucs(valid_kmer, kmer << 2); - - if alts.len() != 1 { - None - } else { - Some((add_nuc_to_end(kmer, alts[0], *k), 2)) - } - } - } - ScenarioTwo::DCI(_, k) => { - if seq.len() < 4 { - None - } else { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k); - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[3]), *k); - - Some((kmer, 4)) - } - } - ScenarioTwo::DCD(_, k) => { - if seq.len() < 2 { - None - } else { - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[0]), *k); - - let alts = alt_nucs(valid_kmer, kmer << 2); - if alts.len() != 1 { - None - } else { - Some((add_nuc_to_end(kmer, alts[0], *k), 1)) - } - } - } - } - } - - fn correct(&self, valid_kmer: &set::BoxKmerSet, kmer: u64, seq: &[u8]) -> (Vec, usize) { - match self { - ScenarioTwo::II(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 2), - ScenarioTwo::IS(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 2), - ScenarioTwo::SS(_, _) | ScenarioTwo::SD(_, _) | ScenarioTwo::DD(_, _) => { - let (corr, offset) = self - .apply(valid_kmer, kmer, seq) - .expect("we can't failled her"); - - ( - vec![ - cocktail::kmer::bit2nuc((corr & 0b1100) >> 2), - cocktail::kmer::bit2nuc(corr & 0b11), - ], - offset, - ) - } - ScenarioTwo::ICI(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 3), - ScenarioTwo::ICD(_, _) => { - let (corr, offset) = self - .apply(valid_kmer, kmer, seq) - .expect("we can't failled her"); - - ( - vec![ - cocktail::kmer::bit2nuc((corr & 0b1100) >> 2), - cocktail::kmer::bit2nuc(corr & 0b11), - ], - offset - 1, - ) - } - ScenarioTwo::ICS(_, _) => { - let (corr, offset) = self - .apply(valid_kmer, kmer, seq) - .expect("we can't failled her"); - - ( - vec![ - cocktail::kmer::bit2nuc((corr & 0b1100) >> 2), - cocktail::kmer::bit2nuc(corr & 0b11), - ], - offset + 1, - ) - } - ScenarioTwo::SCI(_, _) - | ScenarioTwo::SCS(_, _) - | ScenarioTwo::SCD(_, _) - | ScenarioTwo::DCD(_, _) => { - let (corr, offset) = self - .apply(valid_kmer, kmer, seq) - .expect("we can't failled her"); - - ( - vec![ - cocktail::kmer::bit2nuc((corr & 0b110000) >> 4), - cocktail::kmer::bit2nuc((corr & 0b1100) >> 2), - cocktail::kmer::bit2nuc(corr & 0b11), - ], - offset, - ) - } - /* ScenarioTwo::DCD => { - None - }, - */ - _ => (vec![], 1), - } - } -} - -pub type Two<'a> = Exist<'a, ScenarioTwo>; - -#[cfg(test)] -mod tests { - - use super::*; - - use crate::correct::Corrector; - - fn init() { - let _ = env_logger::builder() - .is_test(true) - .filter_level(log::LevelFilter::Trace) - .try_init(); - } - - fn filter<'a>(ori: &[u8]) -> Vec { - ori.iter() - .cloned() - .filter(|x| *x != b'-') - .collect::>() - } - - #[test] - fn short() { - init(); - - let refe = filter(b"CTGGTGCACTACCGGATAGG"); - // |||||| | - let read = filter(b"-------ACTACCTG"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(read, corrector.correct(&read).as_slice()); // test correction work - } - - #[test] - fn ciic() { - init(); - - let refe = filter(b"GATACATGGA--CACTAGTATG"); - // |||||||||| |||||||||| - let read = filter(b"GATACATGGATTCACTAGTATG"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cisc() { - init(); - - let refe = filter(b"GATACATGGA-CACTAGTATG"); - // |||||||||| ||||||||| - let read = filter(b"GATACATGGATGACTAGTATG"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cssc() { - init(); - - let refe = b"TCGTTATTCGGTGGACTCCT"; - // |||||||||| |||||||| - let read = b"TCGTTATTCGAAGGACTCCT"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn csdc() { - init(); - - let refe = b"AACAGCTGAATCTACCATTG"; - // |||||||||| ///////// - let read = b"AACAGCTGAAGTACCATTG"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn cddc() { - init(); - - let refe = b"TGCCGTAGGCCATTGCGGCT"; - // |||||||||| |||||||| - let read = b"TGCCGTAGGC--TTGCGGCT"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(refe, corrector.correct(&filter(read)).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn cicic() { - init(); - - let refe = filter(b"ATAGTAACGG-A-CACACTT"); - // |||||||||| | ||||||| - let read = filter(b"ATAGTAACGGAAGCACACTT"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 3); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cicsc() { - init(); - - let refe = filter(b"GAGCCCAGAG-CGATATTCT"); - // |||||||||| | ||||||| - let read = filter(b"GAGCCCAGAGACTATATTCT"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cicdc() { - init(); - - let refe = filter(b"TCGAAAGCAT-GGGTACGTT"); - // |||||||||| | ||||||| - let read = filter(b"TCGAAAGCATAG-GTACGTT"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cscic() { - init(); - - let refe = filter(b"AAGGATGCATCG-ACTCAAG"); - // |||||||||| | ||||||| - let read = filter(b"AAGGATGCATGGAACTCAAG"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cscsc() { - init(); - - let refe = filter(b"ACACGTGCGCTTGGAGGTAC"); - // |||||||||| | ||||||| - let read = filter(b"ACACGTGCGCATCGAGGTAC"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cscdc() { - init(); - - let refe = filter(b"TATGCTCTGCGTAATCATAG"); - // |||||||||| | ||||||| - let read = filter(b"TATGCTCTGCAT-ATCATAG"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cdcic() { - init(); - - let refe = filter(b"GCTTCGTGATAG-TACGCTT"); - // |||||||||| | ||||||| - let read = filter(b"GCTTCGTGAT-GATACGCTT"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cdcsc() { - init(); - - let refe = filter(b"GGACCTGATCACGTCAATTA"); - // |||||||||| | ||||||| - let read = filter(b"GGACCTGATC-CCTCAATTA"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } - - #[test] - fn cdcdc() { - init(); - - let refe = filter(b"GGAATACGTGCGTTGGGTAA"); - // |||||||||| | ||||||| - let read = filter(b"GGAATACGTG-G-TGGGTAA"); - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Two::new(&set, 2); - - assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work - assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use strum_macros::EnumIter; - -/* crate use */ -use crate::correct::exist::{Exist, Scenario}; -use crate::set; - -//////////////////////////////////// -// Scenario for correct one error // -//////////////////////////////////// -#[derive(Debug, EnumIter, Clone, Copy)] -pub enum ScenarioOne { - I(usize, u8), - S(usize, u8), - D(usize, u8), -} - -impl Scenario for ScenarioOne { - fn init(&self, c: usize, k: u8) -> Self { - match self { - ScenarioOne::I(_, _) => ScenarioOne::I(c, k), - ScenarioOne::S(_, _) => ScenarioOne::S(c, k), - ScenarioOne::D(_, _) => ScenarioOne::D(c, k), - } - } - - fn c(&self) -> usize { - match self { - ScenarioOne::I(c, _) => *c, - ScenarioOne::S(c, _) => *c, - ScenarioOne::D(c, _) => *c, - } - } - - fn apply(&self, _valid_kmer: &set::BoxKmerSet, kmer: u64, _seq: &[u8]) -> Option<(u64, usize)> { - match self { - ScenarioOne::I(_, _) => Some((kmer, 2)), - ScenarioOne::S(_, _) => Some((kmer, 1)), - ScenarioOne::D(_, _) => Some((kmer, 0)), - } - } - - fn correct(&self, _valid_kmer: &set::BoxKmerSet, kmer: u64, _seq: &[u8]) -> (Vec, usize) { - match self { - ScenarioOne::I(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 2), - ScenarioOne::S(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 1), - ScenarioOne::D(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 0), - } - } -} - -pub type One<'a> = Exist<'a, ScenarioOne>; - -#[cfg(test)] -mod tests { - - use super::*; - use crate::correct::Corrector; - - fn init() { - let _ = env_logger::builder() - .is_test(true) - .filter_level(log::LevelFilter::Trace) - .try_init(); - } - - fn filter<'a>(ori: &[u8]) -> Vec { - ori.iter() - .cloned() - .filter(|x| *x != b'-') - .collect::>() - } - - #[test] - fn csc() { - init(); - - let refe = b"ACTGACGAC"; - let read = b"ACTGATGAC"; - - let mut data = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn csc_relaxe() { - init(); - - let refe = b"ACTGACCACT"; - let read = b"ACTGATCACT"; - let conf = b"ACTGACAC"; - - let mut data = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - for kmer in cocktail::tokenizer::Tokenizer::new(conf, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cssc() { - init(); - - let refe = b"ACTGACGAG"; - let read = b"ACTGATAAG"; - - let mut data = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // don't correct - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cic() { - init(); - - let refe = filter(b"ACTGA-CGAC"); - let read = filter(b"ACTGATCGAC"); - - let mut data = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(refe, corrector.correct(&read).as_slice()); - assert_eq!(refe, corrector.correct(&refe).as_slice()); - } - - #[test] - fn cic_relaxe() { - init(); - - // GCGTAC-G - // AGCGTAC - // GTACTTG - let refe = filter(b"GAGCGTAC-GTTGGAT"); - let read = filter(b"GAGCGTACTGTTGGAT"); - let conf = b"GCGTACGTGA"; - - let mut data = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) { - data.set(kmer, true); - } - - for kmer in cocktail::tokenizer::Tokenizer::new(conf, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(refe, corrector.correct(&read).as_slice()); - assert_eq!(refe, corrector.correct(&refe).as_slice()); - } - - #[test] - fn ciic() { - init(); - - let refe = b"ACTGACGA"; - let read = b"ACTGATTCGA"; - - let mut data = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // don't correct - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cdc() { - init(); - - let refe = b"ACTGACGACCC"; - let read = b"ACTGAGACCC"; - - let mut data = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cdc_relaxe() { - init(); - - let refe = b"GAGCGTACGTTGGAT"; - let read = b"GAGCGTAGTTGGAT"; - let conf = b"GCGTACTT"; - - let mut data = pcon::solid::Solid::new(7); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 7) { - data.set(kmer, true); - } - - for kmer in cocktail::tokenizer::Tokenizer::new(conf, 7) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(refe, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cddc() { - init(); - - let refe = b"ACTGACGAG"; - let read = b"ACTGAAG"; - - let mut data = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = One::new(&set, 2); - - assert_eq!(read, corrector.correct(read).as_slice()); // don't correct - assert_eq!(refe, corrector.correct(refe).as_slice()); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* local use */ -use crate::set; - -const MASK_LOOKUP: [u64; 32] = { - let mut lookup = [0; 32]; - - let mut k = 1; - while k < 32 { - lookup[k] = (1 << (2 * k)) - 1; - - k += 1; - } - - lookup -}; - -#[inline(always)] -pub(crate) fn mask(k: u8) -> u64 { - MASK_LOOKUP[k as usize] -} - -pub trait Corrector { - fn valid_kmer(&self) -> &set::BoxKmerSet; - - fn correct_error(&self, kmer: u64, seq: &[u8]) -> Option<(Vec, usize)>; - - fn k(&self) -> u8 { - self.valid_kmer().k() - } - - fn correct(&self, seq: &[u8]) -> Vec { - let mut correct: Vec = Vec::with_capacity(seq.len()); - - if seq.len() < self.k() as usize { - return seq.to_vec(); - } - - let mut i = self.k() as usize; - let mut kmer = cocktail::kmer::seq2bit(&seq[0..i]); - - for n in &seq[0..i] { - correct.push(*n); - } - - let mut previous = self.valid_kmer().get(kmer); - while i < seq.len() { - let nuc = seq[i]; - - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(nuc), self.k()); - - if !self.valid_kmer().get(kmer) && previous { - if let Some((local_correct, offset)) = self.correct_error(kmer, &seq[i..]) { - kmer >>= 2; - - for nuc in local_correct { - kmer = add_nuc_to_end( - kmer, - cocktail::kmer::nuc2bit(nuc), - self.valid_kmer().k(), - ); - correct.push(nuc); - } - - log::debug!("error at position {} cor", i); - - previous = true; - i += offset; - } else { - correct.push(nuc); - - log::debug!("error at position {} not", i); - - i += 1; - previous = false; - } - } else { - previous = self.valid_kmer().get(kmer); - correct.push(nuc); - - i += 1; - } - } - - correct - } -} - -pub(crate) fn add_nuc_to_end(kmer: u64, nuc: u64, k: u8) -> u64 { - ((kmer << 2) & mask(k)) ^ nuc -} - -pub(crate) fn alt_nucs(valid_kmer: &set::BoxKmerSet, ori: u64) -> Vec { - next_nucs(valid_kmer, ori >> 2) -} - -pub(crate) fn next_nucs(valid_kmer: &set::BoxKmerSet, kmer: u64) -> Vec { - let mut correct_nuc: Vec = Vec::with_capacity(4); - - for alt_nuc in 0..4 { - if valid_kmer.get(add_nuc_to_end(kmer, alt_nuc, valid_kmer.k())) { - correct_nuc.push(alt_nuc); - } - } - - correct_nuc -} - -pub(crate) fn error_len( - subseq: &[u8], - mut kmer: u64, - valid_kmer: &set::BoxKmerSet, -) -> (usize, u64) { - let mut j = 0; - - loop { - j += 1; - - if j >= subseq.len() { - break; - } - - kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(subseq[j]), valid_kmer.k()); - - if valid_kmer.get(kmer) { - break; - } - } - - (j, kmer) -} - -pub mod exist; -pub mod gap_size; -pub mod graph; -pub mod greedy; - -pub use exist::one::One; -pub use exist::two::Two; -pub use gap_size::GapSize; -pub use graph::Graph; -pub use greedy::Greedy; - -#[cfg(test)] -mod tests { - - use super::*; - - #[test] - fn found_alt_kmer() { - let mut data = pcon::solid::Solid::new(5); - data.set(cocktail::kmer::seq2bit(b"ACTGA"), true); - data.set(cocktail::kmer::seq2bit(b"ACTGT"), true); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let kmer = cocktail::kmer::seq2bit(b"ACTGC"); - - assert_eq!(alt_nucs(&set, kmer), vec![0, 2]); - } -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use log::debug; - -/* local use */ -use crate::correct::*; - -pub struct Graph<'a> { - valid_kmer: &'a set::BoxKmerSet<'a>, -} - -impl<'a> Graph<'a> { - pub fn new(valid_kmer: &'a set::BoxKmerSet<'a>) -> Self { - Self { valid_kmer } - } -} - -impl<'a> Corrector for Graph<'a> { - fn valid_kmer(&self) -> &set::BoxKmerSet { - self.valid_kmer - } - - fn correct_error(&self, mut kmer: u64, seq: &[u8]) -> Option<(Vec, usize)> { - let (error_len, first_correct_kmer) = error_len(seq, kmer, self.valid_kmer()); - - let mut viewed_kmer = rustc_hash::FxHashSet::default(); - - let mut local_corr = Vec::new(); - - let alts = alt_nucs(self.valid_kmer(), kmer); - if alts.len() != 1 { - debug!("failed multiple successor {:?}", alts); - return None; - } - - kmer = add_nuc_to_end(kmer >> 2, alts[0], self.k()); - local_corr.push(cocktail::kmer::bit2nuc(alts[0])); - viewed_kmer.insert(kmer); - - while self.valid_kmer().get(kmer) { - let alts = next_nucs(self.valid_kmer(), kmer); - - if alts.len() != 1 { - debug!("failed branching node {:?}", alts); - return None; - } - - kmer = add_nuc_to_end(kmer, alts[0], self.k()); - - if viewed_kmer.contains(&kmer) { - debug!("we view this kmer previously"); - return None; - } - viewed_kmer.insert(kmer); - - local_corr.push(cocktail::kmer::bit2nuc(alts[0])); - - if kmer == first_correct_kmer { - break; - } - } - - Some((local_corr, error_len + 1)) - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - fn init() { - let _ = env_logger::builder() - .is_test(true) - .filter_level(log::LevelFilter::Trace) - .try_init(); - } - - #[test] - fn branching_path_csc() { - init(); - - let refe = b"TCTTTATTTTC"; - // ||||| ||||| - let read = b"TCTTTGTTTTC"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - data.set(cocktail::kmer::seq2bit(b"TTTTT"), true); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn branching_path_cdc() { - init(); - - let refe = b"GATACATGGACACTAGTATG"; - // |||||||||| - let read = b"GATACATGGAACTAGTATG"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - data.set(cocktail::kmer::seq2bit(b"GGACT"), true); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(read, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn branching_path_cic() { - init(); - - let refe = b"GATACATGGACACTAGTATG"; - // |||||||||| - let read = b"GATACATGGATCACTAGTATG"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - data.set(cocktail::kmer::seq2bit(b"GGACT"), true); - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(read, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn csc() { - init(); - - let refe = b"TCTTTATTTTC"; - // ||||| ||||| - let read = b"TCTTTGTTTTC"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn cssc() { - init(); - - let refe = b"TCTCTAATCTTC"; - // ||||| ||||| - let read = b"TCTCTGGTCTTC"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn csssc() { - init(); - - let refe = b"TCTCTAAATCTTC"; - // ||||| ||||| - let read = b"TCTCTGGGTCTTC"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrect - } - - #[test] - fn cscsc() { - init(); - - let refe = b"TCTTTACATTTTT"; - // ||||| | ||||| - let read = b"TCTTTGCGTTTTT"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn cdc() { - init(); - - let refe = b"GATACATGGACACTAGTATG"; - // |||||||||| - let read = b"GATACATGGAACTAGTATG"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(refe, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cddc() { - init(); - - let refe = b"CAAAGCATTTTT"; - // ||||| - let read = b"CAAAGTTTTT"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(refe, corrector.correct(read).as_slice()); - assert_eq!(refe, corrector.correct(refe).as_slice()); - } - - #[test] - fn cic() { - init(); - - let refe = b"GATACATGGACACTAGTATG"; - // |||||||||| - let read = b"GATACATGGATCACTAGTATG"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } - - #[test] - fn ciic() { - init(); - - let refe = b"GATACATGGACACTAGTATG"; - // |||||||||| - let read = b"GATACATGGATTCACTAGTATG"; - - let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5); - - for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) { - data.set(kmer, true); - } - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(data)); - - let corrector = Graph::new(&set); - - assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work - assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* local mod */ -pub mod cli; -pub mod correct; -pub mod error; -pub mod set; - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use rayon::iter::ParallelBridge; -use rayon::prelude::*; - -/* local use */ -use error::IO::*; -use error::*; - -pub fn run_correction<'a>( - inputs: &[String], - outputs: &[String], - methods: Vec>, - two_side: bool, - record_buffer_len: usize, -) -> Result<()> { - for (input, output) in inputs.iter().zip(outputs) { - log::info!("Read file {} write in {}", input, output); - - let reader = bio::io::fasta::Reader::new(std::io::BufReader::new( - std::fs::File::open(input) - .with_context(|| error::Error::IO(CantOpenFile)) - .with_context(|| anyhow!("File {}", input.clone()))?, - )); - - let mut write = bio::io::fasta::Writer::new(std::io::BufWriter::new( - std::fs::File::create(&output) - .with_context(|| error::Error::IO(CantCreateFile)) - .with_context(|| anyhow!("File {}", output.clone()))?, - )); - - let mut iter = reader.records(); - let mut records = Vec::with_capacity(record_buffer_len); - let mut corrected: Vec; - - let mut end = false; - loop { - for _ in 0..record_buffer_len { - if let Some(Ok(record)) = iter.next() { - records.push(record); - } else { - end = true; - break; - } - } - - log::info!("Buffer len: {}", records.len()); - - corrected = records - .drain(..) - .par_bridge() - .map(|record| { - log::debug!("begin correct read {} {}", record.id(), record.seq().len()); - - let seq = record.seq(); - - let mut correct = seq.to_vec(); - methods - .iter() - .for_each(|x| correct = x.correct(correct.as_slice())); - - if !two_side { - correct.reverse(); - methods - .iter() - .for_each(|x| correct = x.correct(correct.as_slice())); - - correct.reverse(); - } - - log::debug!("end correct read {}", record.id()); - bio::io::fasta::Record::with_attrs(record.id(), record.desc(), &correct) - }) - .collect(); - - for corr in corrected { - write - .write_record(&corr) - .with_context(|| Error::IO(IO::ErrorDurringWrite)) - .with_context(|| anyhow!("File {}", output.clone()))? - } - - records.clear(); - - if end { - break; - } - } - } - - Ok(()) -} - -pub fn build_methods<'a>( - params: Option>, - solid: &'a set::BoxKmerSet, - confirm: u8, - max_search: u8, -) -> Vec> { - let mut methods: Vec> = Vec::new(); - - if let Some(ms) = params { - for method in ms { - match &method[..] { - "one" => methods.push(Box::new(correct::One::new(solid, confirm))), - "two" => methods.push(Box::new(correct::Two::new(solid, confirm))), - "graph" => methods.push(Box::new(correct::Graph::new(solid))), - "greedy" => { - methods.push(Box::new(correct::Greedy::new(solid, max_search, confirm))) - } - "gap_size" => methods.push(Box::new(correct::GapSize::new(solid, confirm))), - _ => unreachable!(), - } - } - } else { - methods.push(Box::new(correct::One::new(solid, confirm))); - } - - methods -} - -/// Set the number of threads use by count step -pub fn set_nb_threads(nb_threads: usize) { - rayon::ThreadPoolBuilder::new() - .num_threads(nb_threads) - .build_global() - .unwrap(); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn methods_list() { - // Not perfect test - - let set: set::BoxKmerSet = Box::new(set::Pcon::new(pcon::solid::Solid::new(5))); - let mut methods = build_methods(None, &set, 2, 5); - - assert_eq!(methods.len(), 1); - - methods = build_methods(Some(vec!["one".to_string(), "two".to_string()]), &set, 2, 5); - - assert_eq!(methods.len(), 2); - - methods = build_methods( - Some(vec![ - "one".to_string(), - "two".to_string(), - "graph".to_string(), - "greedy".to_string(), - "gap_size".to_string(), - "gap_size".to_string(), - ]), - &set, - 2, - 5, - ); - - assert_eq!(methods.len(), 6); - } - - #[test] - #[should_panic] - fn methods_unreachable() { - let set: set::BoxKmerSet = Box::new(set::Pcon::new(pcon::solid::Solid::new(5))); - let _ = build_methods(Some(vec!["oe".to_string(), "tw".to_string()]), &set, 2, 5); - } - - #[test] - fn change_number_of_thread() { - set_nb_threads(16); - assert_eq!(rayon::current_num_threads(), 16); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use thiserror::Error; - -/// All error produce by Pcon -#[derive(Debug, Error)] -pub enum Error { - /// See enum [Cli] - #[error(transparent)] - Cli(#[from] Cli), - - /// See enum [IO] - #[error(transparent)] - IO(#[from] IO), - - #[error("Can't compute minimal abundance")] - CantComputeAbundance, -} - -/// Error emmit durring Cli parsing -#[derive(Debug, Error)] -pub enum Cli { - /// Number of inputs and outputs must be the same - #[error("Kmer size must be odd")] - NotSameNumberOfInAndOut, - - #[error("You must provide a solidity path '-s', a kmer solid path '-S' or a kmer length '-k'")] - NoSolidityNoKmer, - - #[error("If you provide kmer solid path '-S' you must provide a kmer length '-k'")] - KmerSolidNeedK, - - #[error("Abundance method threshold can't be parse")] - CantParseAbundanceMethod, -} - -/// Error emmit when pcon try to work with file -#[repr(C)] -#[derive(Debug, Error)] -pub enum IO { - /// We can't create file. In C binding it's equal to 0 - #[error("We can't create file")] - CantCreateFile, - - /// We can't open file. In C binding it's equal to 1 - #[error("We can't open file")] - CantOpenFile, - - /// Error durring write in file. In C binding it's equal to 2 - #[error("Error durring write")] - ErrorDurringWrite, - - /// Error durring read file. In C binding it's equal to 3 - #[error("Error durring read")] - ErrorDurringRead, - - /// No error, this exist only for C binding it's the value of a new error pointer - #[error("Isn't error if you see this please contact the author with this message and a description of what you do with pcon")] - NoError, -} -#[cfg(test)] -mod tests { - use std::io::Read; - use std::process::{Command, Stdio}; - - fn run_finish(mut child: std::process::Child) -> bool { - if !child.wait().expect("Error durring br run").success() { - let mut stdout = String::new(); - let mut stderr = String::new(); - - child.stdout.unwrap().read_to_string(&mut stdout).unwrap(); - child.stderr.unwrap().read_to_string(&mut stderr).unwrap(); - - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); - - false - } else { - true - } - } - - #[test] - fn count() { - let child = Command::new("./target/debug/br") - .args(&[ - "-i", - "tests/data/raw.fasta", - "-o", - "tests/data/corr.fasta", - "-k", - "11", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create br subprocess"); - - assert!(run_finish(child)); - } - - #[test] - fn solid() { - let child = Command::new("./target/debug/br") - .args(&[ - "-i", - "tests/data/raw.fasta", - "-o", - "tests/data/corr.fasta", - "-s", - "tests/data/raw.k11.a2.solid", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create br subprocess"); - - assert!(run_finish(child)); - } - - #[test] - fn no_count_no_solid() { - let child = Command::new("./target/debug/br") - .args(&["-i", "tests/data/raw.fasta", "-o", "tests/data/corr.fasta"]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create br subprocess"); - - assert!(!run_finish(child)); - } -} -#[cfg(test)] -mod tests { - use std::io::Read; - use std::process::{Command, Stdio}; - - fn run_finish(mut child: std::process::Child) -> bool { - if !child.wait().expect("Error durring br run").success() { - let mut stdout = String::new(); - let mut stderr = String::new(); - - child.stdout.unwrap().read_to_string(&mut stdout).unwrap(); - child.stderr.unwrap().read_to_string(&mut stderr).unwrap(); - - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); - - false - } else { - true - } - } - - #[test] - fn run() { - let child = Command::new("./target/debug/br_large") - .args(&[ - "-i", - "tests/data/raw.fasta", - "-o", - "tests/data/corr.fasta", - "-S", - "tests/data/raw.k31.fasta", - "-k", - "31", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create br subprocess"); - - assert!(run_finish(child)); - } - - #[test] - fn no_kmer_size() { - let child = Command::new("./target/debug/br_large") - .args(&[ - "-i", - "tests/data/raw.fasta", - "-o", - "tests/data/corr.fasta", - "-S", - "tests/data/raw.k31.fasta", - ]) - .stderr(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("Couldn't create br subprocess"); - - assert!(!run_finish(child)); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; - -/* local use */ -use crate::error::IO::*; -use crate::error::*; -use crate::*; - -pub fn count(params: cli::SubCommandCount) -> Result<()> { - let params = cli::check_count_param(params)?; - - let record_buffer = if let Some(len) = params.record_buffer { - len - } else { - 8192 - }; - - log::info!("Start of count structure initialization"); - let mut counter = counter::Counter::new(params.kmer); - log::info!("End of count structure initialization"); - - for input in params.inputs.iter() { - log::info!("Start of kmer count of the file {}", input); - let reader = niffler::get_reader(Box::new( - std::fs::File::open(input) - .with_context(|| Error::IO(CantOpenFile)) - .with_context(|| anyhow!("File {}", input.clone()))?, - )) - .with_context(|| anyhow!("File {}", input.clone()))? - .0; - - counter.count_fasta(reader, record_buffer); - - log::info!("End of kmer count of the file {}", &input); - } - - dump::dump_worker( - counter, - params.output, - params.csv, - params.solid, - params.spectrum, - params.abundance, - ); - - Ok(()) -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* project mod declaration */ -pub mod cli; -pub mod error; - -pub mod count; -pub mod counter; -pub mod dump; -pub mod solid; -pub mod spectrum; -pub mod static_counter; - -pub mod binding; - -/// Set the number of threads use by pcon -pub fn set_nb_threads(nb_threads: usize) { - rayon::ThreadPoolBuilder::new() - .num_threads(nb_threads) - .build_global() - .unwrap(); -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{Context, Result}; -use rayon::prelude::*; - -/* local use */ -use crate::error::IO::*; -use crate::error::*; -use crate::*; - -/// Based on Kmergenie we assume kmer spectrum is a mixture of Pareto law and some Gaussians law -/// Erroneous kmer follow Pareto law, Gaussians law represente true and repetitive kmer -/// We use this property to found the threshold to remove many Erroneous kmer and keep Many True kmer -#[derive(Debug, PartialEq)] -pub enum ThresholdMethod { - /// The first local minimum match with the intersection of Pareto and Gaussians - FirstMinimum, - - /// More we remove kmer less we remove Erroneous kmer when remove less than n percent view before - Rarefaction, - - /// Remove at most n percent of total kmer - PercentAtMost, - - /// Remove at least n percent of total kmer - PercentAtLeast, -} - -/// A struct to represent kmer spectrum and usefull corresponding function -pub struct Spectrum { - data: Box<[u64]>, -} - -impl Spectrum { - pub fn from_counter(counter: &counter::Counter) -> Self { - let counts = unsafe { - &(*(counter.get_raw_count() as *const [counter::AtoCount] as *const [counter::Count])) - }; - - let data = counts - .par_chunks(counts.len() / rayon::current_num_threads()) - .map(|chunk| { - let mut d: Box<[u64]> = vec![0u64; 256].into_boxed_slice(); - - for count in chunk.iter() { - d[*count as usize] = d[*count as usize].saturating_add(1); - } - - d - }) - .reduce( - || vec![0u64; 256].into_boxed_slice(), - |a, b| { - let mut d = Vec::with_capacity(256); - - for x in a.iter().zip(b.iter()) { - d.push(x.0.saturating_add(*x.1)); - } - - d.into_boxed_slice() - }, - ); - - Self { data } - } - - pub fn get_threshold(&self, method: ThresholdMethod, params: f64) -> Option { - match method { - ThresholdMethod::FirstMinimum => self.first_minimum(), - ThresholdMethod::Rarefaction => self.rarefaction(params), - ThresholdMethod::PercentAtMost => self.percent_at_most(params), - ThresholdMethod::PercentAtLeast => self.percent_at_least(params), - } - } - - fn first_minimum(&self) -> Option { - for (i, d) in self.data.windows(2).enumerate() { - if d[1] > d[0] { - return Some(i as u8); - } - } - - None - } - - fn rarefaction(&self, limit: f64) -> Option { - let mut cumulative_sum = 0; - - for (index, value) in self.data.iter().enumerate() { - cumulative_sum += index as u64 * value; - - if (*value as f64 / cumulative_sum as f64) < limit { - return Some(index as u8); - } - } - - None - } - - fn percent_at_most(&self, percent: f64) -> Option { - self.percent_at_least(percent).map(|x| x - 1) - } - - fn percent_at_least(&self, percent: f64) -> Option { - let total: u64 = self - .data - .iter() - .enumerate() - .map(|(index, value)| index as u64 * value) - .sum(); - - let mut cumulative_sum = 0; - for (index, value) in self.data.iter().enumerate() { - cumulative_sum += index as u64 * value; - - if (cumulative_sum as f64 / total as f64) > percent { - return Some(index as u8); - } - } - - None - } - - #[allow(dead_code)] - pub(crate) fn get_raw_histogram(&self) -> &[u64] { - &self.data - } - - pub fn write_csv(&self, mut writer: W) -> Result<()> - where - W: std::io::Write, - { - for (i, nb) in self.data.iter().enumerate() { - writeln!(writer, "{},{}", i, nb).with_context(|| Error::IO(ErrorDurringWrite))?; - } - - Ok(()) - } - - pub fn write_histogram(&self, mut out: W, point: Option) -> std::io::Result<()> - where - W: std::io::Write, - { - // Draw kmer spectrum in console - let shape = get_shape(); - - let factor = (*self.data.iter().max().unwrap() as f64).log(10.0) / shape.1 as f64; - - let normalized: Box<[f64]> = self - .data - .iter() - .map(|y| { - if *y == 0 { - 0.0 - } else { - (*y as f64).log(10.0) / factor - } - }) - .collect(); - - for h in (1..=shape.1).rev() { - for w in 0..shape.0 { - if normalized[w] >= h as f64 { - let delta = normalized[w] - h as f64; - if delta > 1.0 { - write!(out, "\u{258c}")?; - } else if delta > 0.5 { - write!(out, "\u{2596}")?; - } else { - write!(out, " ")?; - } - } else { - write!(out, " ")?; - } - } - - writeln!(out)?; - } - - let mut last_line = vec![b' '; shape.0]; - for x in (0..shape.0).step_by(5) { - last_line[x] = b'5' - } - last_line[0] = b'0'; - if let Some(pos) = point { - if (pos as usize) < last_line.len() { - last_line[pos as usize] = b'*'; - } - } - - writeln!(out, "{}", std::str::from_utf8(&last_line).unwrap())?; - - Ok(()) - } -} - -#[allow(dead_code)] -fn term_size() -> (usize, usize) { - match term_size::dimensions() { - Some((w, h)) => (w, h), - None => (80, 24), - } -} - -#[cfg(test)] -fn get_shape() -> (usize, usize) { - (256, 48) -} - -#[cfg(not(test))] -fn get_shape() -> (usize, usize) { - let term_size = term_size(); - - ( - core::cmp::min(256, term_size.0), - core::cmp::min(48, term_size.1), - ) -} - -#[cfg(test)] -mod tests { - - use super::*; - - lazy_static::lazy_static! { - static ref COUNTER: crate::counter::Counter = { - let mut counter = crate::counter::Counter::new(5); - - for i in 0..cocktail::kmer::get_kmer_space_size(5) { - counter.inc(i); - } - - counter.inc(0); - - counter - }; - } - - #[test] - fn from_counter() { - let spectrum = Spectrum::from_counter(&COUNTER); - - assert_eq!( - spectrum.get_raw_histogram(), - &[ - 0, 0, 511, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0 - ] - ); - } - - static SPECTRUM: [u64; 256] = [ - 992273316, 64106898, 6792586, 1065818, 220444, 62400, 36748, 54062, 100806, 178868, 287058, - 424184, 568742, 705680, 805332, 871544, 874546, 827252, 744428, 636722, 523488, 418036, - 320506, 237956, 170642, 118046, 77290, 48320, 30500, 21096, 15632, 12758, 11838, 10888, - 10402, 9872, 9018, 7960, 7236, 6304, 5276, 4524, 3714, 3056, 2628, 2018, 1578, 1256, 1036, - 906, 708, 716, 592, 476, 540, 520, 446, 388, 316, 264, 258, 200, 230, 172, 164, 184, 154, - 162, 126, 124, 126, 156, 152, 98, 116, 108, 134, 116, 88, 124, 96, 94, 96, 72, 52, 56, 68, - 50, 54, 66, 54, 28, 44, 48, 30, 42, 48, 32, 38, 34, 44, 30, 32, 28, 18, 34, 20, 28, 26, 28, - 28, 32, 22, 16, 10, 26, 8, 26, 14, 14, 30, 6, 32, 38, 26, 26, 16, 30, 20, 38, 20, 22, 22, - 28, 14, 16, 20, 20, 20, 10, 12, 14, 12, 10, 18, 16, 16, 12, 18, 2, 14, 6, 12, 8, 0, 6, 2, - 4, 2, 0, 0, 2, 4, 2, 2, 6, 6, 0, 0, 2, 0, 2, 4, 0, 2, 2, 6, 2, 0, 0, 0, 2, 2, 2, 2, 2, 0, - 2, 2, 0, 2, 2, 0, 2, 2, 2, 0, 0, 2, 4, 2, 0, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 2, - 0, 0, 2, 2, 2, 2, 4, 0, 2, 4, 4, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 4, 2, 0, 2, 0, 0, 0, 2, - 0, 4, 2, 0, 4, 2, 0, 0, 284, - ]; - - #[test] - fn first_local_min() { - let spectrum = Spectrum { - data: Box::new(SPECTRUM), - }; - - assert_eq!( - spectrum.get_threshold(ThresholdMethod::FirstMinimum, 0.1), - Some(6) - ); - } - - #[test] - fn failled_first_local_min() { - let tmp = (0..256).map(|_| 1).collect::>(); - - let spectrum = Spectrum { data: tmp }; - - assert_eq!( - spectrum.get_threshold(ThresholdMethod::FirstMinimum, 0.1), - None - ); - } - - #[test] - fn rarefaction() { - let spectrum = Spectrum { - data: Box::new(SPECTRUM), - }; - - assert_eq!( - spectrum.get_threshold(ThresholdMethod::Rarefaction, 0.1), - Some(2) - ); - } - - #[test] - fn failled_rarefaction() { - let tmp = (0..256).map(|_| 1).collect::>(); - - let spectrum = Spectrum { data: tmp }; - - assert_eq!( - spectrum.get_threshold(ThresholdMethod::FirstMinimum, 0.00001), - None - ); - } - - #[test] - fn test_draw_hist() { - let spectrum = Spectrum { - data: Box::new(SPECTRUM), - }; - - let mut output = vec![]; - spectrum.write_histogram(&mut output, Some(6)).unwrap(); - - let good_output = " -▖ -▌ -▌ -▌ -▌ -▌ -▌▖ -▌▌ -▌▌ -▌▌ -▌▌ -▌▌ -▌▌▌ -▌▌▌ -▌▌▌ -▌▌▌ -▌▌▌▌ ▖▖▖▖ -▌▌▌▌ ▖▌▌▌▌▌▌▖▖ -▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▖ ▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌ ▖▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ -▌▌▌▌▌▖ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ -▌▌▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ ▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖ ▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖▌▖▖ ▖▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▖▌▌ ▌▖▖▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ ▖ ▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▖▖ ▖▖ ▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▌▖▌▌▌▌▌▌▖▌▖ ▌ ▖▖▖▖▌ ▖ ▖ ▖ ▌▌▖▖ ▖ ▌ ▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▖▌▌▌▌▌▌ ▌ ▌ ▌ ▌▌▌▌ ▌▖▌▖▌▌▌ ▖▖▖ ▖ ▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▌ ▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▖▌▖ ▌▌▌▖▌ ▌ ▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▌ ▌▖ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌���▌▌▌▌▌ ▌▌▌▌ ▌ ▌▌ ▌ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▌▌▌▌ ▌ ▌ ▌ ▌▌ ▌ ▌ ▌ ▌ ▌▌ ▌ ▌ ▌ ▌ -▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▌▌▌ ▌▖▌▖ ▖▌▖▖▌▌ ▖ ▖▌ ▖▖▌▖ ▖▖▖▖▖ ▖▖ ▖▖ ▖▖▖ ▖▌▖ ▖ ▖▖▖ ▖▖▖▖▖ ▖ ▖▖▖▖▌ ▖▌▌ ▖ ▖▖ ▌▖ ▖ ▖ ▌▖ ▌▖ ▌ -0 5* 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 -"; - - assert_eq!(good_output, std::str::from_utf8(&output).unwrap()); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use cocktail::*; - -/* local use */ -use crate::error::IO::*; -use crate::error::*; -use crate::*; - -pub fn dump(params: cli::SubCommandDump) -> Result<()> { - let params = cli::check_dump_param(params)?; - - log::info!("Start of read of count"); - let reader = std::fs::File::open(¶ms.input) - .with_context(|| Error::IO(CantOpenFile)) - .with_context(|| anyhow!("File {}", params.input.clone()))?; - - let counter = counter::Counter::deserialize(reader) - .with_context(|| Error::IO(ErrorDurringRead)) - .with_context(|| anyhow!("File {}", params.input.clone()))?; - - log::info!("End of read of count"); - - dump_worker( - counter, - params.bin, - params.csv, - params.solid, - params.spectrum, - params.abundance, - ); - - Ok(()) -} - -pub(crate) fn dump_worker( - counter: counter::Counter, - bin_path: Option, - csv_path: Option, - solid_path: Option, - spectrum_path: Option, - abundance: counter::Count, -) { - rayon::scope(|s| { - s.spawn(|_| { - if let Some(output) = bin_path.clone() { - log::info!("Start of dump count data in binary"); - let writer = std::io::BufWriter::new( - std::fs::File::create(&output) - .with_context(|| Error::IO(CantCreateFile)) - .with_context(|| anyhow!("File {}", output.clone())) - .unwrap(), - ); - - counter - .serialize(writer) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("In file {}", output.clone())) - .unwrap(); - - log::info!("End of dump count data in binary"); - } - }); - - s.spawn(|_| { - if let Some(output) = csv_path.clone() { - log::info!("Start of dump count data in csv"); - - let writer = std::io::BufWriter::new( - std::fs::File::create(&output) - .with_context(|| Error::IO(CantOpenFile)) - .with_context(|| anyhow!("File {}", output.clone())) - .unwrap(), - ); - - csv(writer, &counter, abundance) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("File {} in csv format", output)) - .unwrap(); - - log::info!("End of dump count data in csv"); - } - }); - - s.spawn(|_| { - if let Some(output) = solid_path.clone() { - log::info!("Start of dump count data in solid format"); - - let writer = std::io::BufWriter::new( - std::fs::File::create(&output) - .with_context(|| Error::IO(CantOpenFile)) - .with_context(|| anyhow!("File {}", output.clone())) - .unwrap(), - ); - - solid(writer, &counter, abundance) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("File {} in solid format", output)) - .unwrap(); - - log::info!("End of dump count data in solid format"); - } - }); - - s.spawn(|_| { - if let Some(output) = spectrum_path.clone() { - log::info!("Start of dump count data in spectrum"); - - let writer = std::io::BufWriter::new( - std::fs::File::create(&output) - .with_context(|| Error::IO(CantOpenFile)) - .with_context(|| anyhow!("File {}", output.clone())) - .unwrap(), - ); - - spectrum(writer, &counter) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("File {} in spectrum format", output)) - .unwrap(); - - log::info!("End of dump count data in spectrum"); - } - }); - }); -} - -/// Write in the given instance of io::Write the count in `counter` in binary format. -pub fn binary(writer: W, counter: &counter::Counter) -> Result<()> -where - W: std::io::Write, -{ - counter - .serialize(writer) - .with_context(|| Error::IO(ErrorDurringWrite))?; - - Ok(()) -} - -/// Write in the given instance of io::Write the count in `counter` in csv format. -/// Only count upper than `abundance` is write. -pub fn csv(mut writer: W, counter: &counter::Counter, abundance: counter::Count) -> Result<()> -where - W: std::io::Write, -{ - let counts = unsafe { - &(*(counter.get_raw_count() as *const [counter::AtoCount] as *const [counter::Count])) - }; - - for (hash, value) in counts.iter().enumerate() { - let kmer = if cocktail::kmer::parity_even(hash as u64) { - kmer::kmer2seq((hash as u64) << 1, counter.k) - } else { - kmer::kmer2seq(((hash as u64) << 1) ^ 0b1, counter.k) - }; - - if value > &abundance { - writeln!(writer, "{},{}", kmer, value).with_context(|| Error::IO(ErrorDurringWrite))?; - } - } - - Ok(()) -} - -/// Serialize in the given instance of io::Write an instance of [solid::Solid] build from counts in `counter` upper than `abundance`. -pub fn solid(writer: W, counter: &counter::Counter, abundance: counter::Count) -> Result<()> -where - W: std::io::Write, -{ - let solid = solid::Solid::from_counter(counter, abundance); - - solid - .serialize(writer) - .with_context(|| Error::IO(ErrorDurringWrite))?; - - Ok(()) -} - -/// Write in the given instance of io::Write the kmer spectrum from counts in `counter` -pub fn spectrum(writer: W, counter: &counter::Counter) -> Result<()> -where - W: std::io::Write, -{ - let spectrum = spectrum::Spectrum::from_counter(counter); - - spectrum - .write_csv(writer) - .with_context(|| Error::IO(ErrorDurringWrite))?; - - Ok(()) -} - -#[cfg(test)] -mod tests { - lazy_static::lazy_static! { - static ref COUNTER: crate::counter::Counter = { - let mut counter = crate::counter::Counter::new(5); - - for i in 0..cocktail::kmer::get_kmer_space_size(5) { - counter.inc(i); - } - - counter.inc(0); - - counter - }; - } - - const CSV_ABUNDANCE_MIN_1: &[u8] = &[ - 65, 65, 65, 65, 65, 44, 51, 10, 65, 65, 65, 65, 71, 44, 50, 10, 65, 65, 65, 67, 67, 44, 50, - 10, 65, 65, 65, 67, 84, 44, 50, 10, 65, 65, 65, 84, 67, 44, 50, 10, 65, 65, 65, 84, 84, 44, - 50, 10, 65, 65, 65, 71, 65, 44, 50, 10, 65, 65, 65, 71, 71, 44, 50, 10, 65, 65, 67, 65, 67, - 44, 50, 10, 65, 65, 67, 65, 84, 44, 50, 10, 65, 65, 67, 67, 65, 44, 50, 10, 65, 65, 67, 67, - 71, 44, 50, 10, 65, 65, 67, 84, 65, 44, 50, 10, 65, 65, 67, 84, 71, 44, 50, 10, 65, 65, 67, - 71, 67, 44, 50, 10, 65, 65, 67, 71, 84, 44, 50, 10, 65, 65, 84, 65, 67, 44, 50, 10, 65, 65, - 84, 65, 84, 44, 50, 10, 65, 65, 84, 67, 65, 44, 50, 10, 65, 65, 84, 67, 71, 44, 50, 10, 65, - 65, 84, 84, 65, 44, 50, 10, 65, 65, 84, 84, 71, 44, 50, 10, 65, 65, 84, 71, 67, 44, 50, 10, - 65, 65, 84, 71, 84, 44, 50, 10, 65, 65, 71, 65, 65, 44, 50, 10, 65, 65, 71, 65, 71, 44, 50, - 10, 65, 65, 71, 67, 67, 44, 50, 10, 65, 65, 71, 67, 84, 44, 50, 10, 65, 65, 71, 84, 67, 44, - 50, 10, 65, 65, 71, 84, 84, 44, 50, 10, 65, 65, 71, 71, 65, 44, 50, 10, 65, 65, 71, 71, 71, - 44, 50, 10, 65, 67, 65, 65, 67, 44, 50, 10, 65, 67, 65, 65, 84, 44, 50, 10, 65, 67, 65, 67, - 65, 44, 50, 10, 65, 67, 65, 67, 71, 44, 50, 10, 65, 67, 65, 84, 65, 44, 50, 10, 65, 67, 65, - 84, 71, 44, 50, 10, 65, 67, 65, 71, 67, 44, 50, 10, 65, 67, 65, 71, 84, 44, 50, 10, 65, 67, - 67, 65, 65, 44, 50, 10, 65, 67, 67, 65, 71, 44, 50, 10, 65, 67, 67, 67, 67, 44, 50, 10, 65, - 67, 67, 67, 84, 44, 50, 10, 65, 67, 67, 84, 67, 44, 50, 10, 65, 67, 67, 84, 84, 44, 50, 10, - 65, 67, 67, 71, 65, 44, 50, 10, 65, 67, 67, 71, 71, 44, 50, 10, 65, 67, 84, 65, 65, 44, 50, - 10, 65, 67, 84, 65, 71, 44, 50, 10, 65, 67, 84, 67, 67, 44, 50, 10, 65, 67, 84, 67, 84, 44, - 50, 10, 65, 67, 84, 84, 67, 44, 50, 10, 65, 67, 84, 84, 84, 44, 50, 10, 65, 67, 84, 71, 65, - 44, 50, 10, 65, 67, 84, 71, 71, 44, 50, 10, 65, 67, 71, 65, 67, 44, 50, 10, 65, 67, 71, 65, - 84, 44, 50, 10, 65, 67, 71, 67, 65, 44, 50, 10, 65, 67, 71, 67, 71, 44, 50, 10, 65, 67, 71, - 84, 65, 44, 50, 10, 65, 67, 71, 84, 71, 44, 50, 10, 65, 67, 71, 71, 67, 44, 50, 10, 65, 67, - 71, 71, 84, 44, 50, 10, 65, 84, 65, 65, 67, 44, 50, 10, 65, 84, 65, 65, 84, 44, 50, 10, 65, - 84, 65, 67, 65, 44, 50, 10, 65, 84, 65, 67, 71, 44, 50, 10, 65, 84, 65, 84, 65, 44, 50, 10, - 65, 84, 65, 84, 71, 44, 50, 10, 65, 84, 65, 71, 67, 44, 50, 10, 65, 84, 65, 71, 84, 44, 50, - 10, 65, 84, 67, 65, 65, 44, 50, 10, 65, 84, 67, 65, 71, 44, 50, 10, 65, 84, 67, 67, 67, 44, - 50, 10, 65, 84, 67, 67, 84, 44, 50, 10, 65, 84, 67, 84, 67, 44, 50, 10, 65, 84, 67, 84, 84, - 44, 50, 10, 65, 84, 67, 71, 65, 44, 50, 10, 65, 84, 67, 71, 71, 44, 50, 10, 65, 84, 84, 65, - 65, 44, 50, 10, 65, 84, 84, 65, 71, 44, 50, 10, 65, 84, 84, 67, 67, 44, 50, 10, 65, 84, 84, - 67, 84, 44, 50, 10, 65, 84, 84, 84, 67, 44, 50, 10, 65, 84, 84, 84, 84, 44, 50, 10, 65, 84, - 84, 71, 65, 44, 50, 10, 65, 84, 84, 71, 71, 44, 50, 10, 65, 84, 71, 65, 67, 44, 50, 10, 65, - 84, 71, 65, 84, 44, 50, 10, 65, 84, 71, 67, 65, 44, 50, 10, 65, 84, 71, 67, 71, 44, 50, 10, - 65, 84, 71, 84, 65, 44, 50, 10, 65, 84, 71, 84, 71, 44, 50, 10, 65, 84, 71, 71, 67, 44, 50, - 10, 65, 84, 71, 71, 84, 44, 50, 10, 65, 71, 65, 65, 65, 44, 50, 10, 65, 71, 65, 65, 71, 44, - 50, 10, 65, 71, 65, 67, 67, 44, 50, 10, 65, 71, 65, 67, 84, 44, 50, 10, 65, 71, 65, 84, 67, - 44, 50, 10, 65, 71, 65, 84, 84, 44, 50, 10, 65, 71, 65, 71, 65, 44, 50, 10, 65, 71, 65, 71, - 71, 44, 50, 10, 65, 71, 67, 65, 67, 44, 50, 10, 65, 71, 67, 65, 84, 44, 50, 10, 65, 71, 67, - 67, 65, 44, 50, 10, 65, 71, 67, 67, 71, 44, 50, 10, 65, 71, 67, 84, 65, 44, 50, 10, 65, 71, - 67, 84, 71, 44, 50, 10, 65, 71, 67, 71, 67, 44, 50, 10, 65, 71, 67, 71, 84, 44, 50, 10, 65, - 71, 84, 65, 67, 44, 50, 10, 65, 71, 84, 65, 84, 44, 50, 10, 65, 71, 84, 67, 65, 44, 50, 10, - 65, 71, 84, 67, 71, 44, 50, 10, 65, 71, 84, 84, 65, 44, 50, 10, 65, 71, 84, 84, 71, 44, 50, - 10, 65, 71, 84, 71, 67, 44, 50, 10, 65, 71, 84, 71, 84, 44, 50, 10, 65, 71, 71, 65, 65, 44, - 50, 10, 65, 71, 71, 65, 71, 44, 50, 10, 65, 71, 71, 67, 67, 44, 50, 10, 65, 71, 71, 67, 84, - 44, 50, 10, 65, 71, 71, 84, 67, 44, 50, 10, 65, 71, 71, 84, 84, 44, 50, 10, 65, 71, 71, 71, - 65, 44, 50, 10, 65, 71, 71, 71, 71, 44, 50, 10, 67, 65, 65, 65, 67, 44, 50, 10, 67, 65, 65, - 65, 84, 44, 50, 10, 67, 65, 65, 67, 65, 44, 50, 10, 67, 65, 65, 67, 71, 44, 50, 10, 67, 65, - 65, 84, 65, 44, 50, 10, 67, 65, 65, 84, 71, 44, 50, 10, 67, 65, 65, 71, 67, 44, 50, 10, 67, - 65, 65, 71, 84, 44, 50, 10, 67, 65, 67, 65, 65, 44, 50, 10, 67, 65, 67, 65, 71, 44, 50, 10, - 67, 65, 67, 67, 67, 44, 50, 10, 67, 65, 67, 67, 84, 44, 50, 10, 67, 65, 67, 84, 67, 44, 50, - 10, 67, 65, 67, 84, 84, 44, 50, 10, 67, 65, 67, 71, 65, 44, 50, 10, 67, 65, 67, 71, 71, 44, - 50, 10, 67, 65, 84, 65, 65, 44, 50, 10, 67, 65, 84, 65, 71, 44, 50, 10, 67, 65, 84, 67, 67, - 44, 50, 10, 67, 65, 84, 67, 84, 44, 50, 10, 67, 65, 84, 84, 67, 44, 50, 10, 67, 65, 84, 84, - 84, 44, 50, 10, 67, 65, 84, 71, 65, 44, 50, 10, 67, 65, 84, 71, 71, 44, 50, 10, 67, 65, 71, - 65, 67, 44, 50, 10, 67, 65, 71, 65, 84, 44, 50, 10, 67, 65, 71, 67, 65, 44, 50, 10, 67, 65, - 71, 67, 71, 44, 50, 10, 67, 65, 71, 84, 65, 44, 50, 10, 67, 65, 71, 84, 71, 44, 50, 10, 67, - 65, 71, 71, 67, 44, 50, 10, 67, 65, 71, 71, 84, 44, 50, 10, 67, 67, 65, 65, 65, 44, 50, 10, - 67, 67, 65, 65, 71, 44, 50, 10, 67, 67, 65, 67, 67, 44, 50, 10, 67, 67, 65, 67, 84, 44, 50, - 10, 67, 67, 65, 84, 67, 44, 50, 10, 67, 67, 65, 84, 84, 44, 50, 10, 67, 67, 65, 71, 65, 44, - 50, 10, 67, 67, 65, 71, 71, 44, 50, 10, 67, 67, 67, 65, 67, 44, 50, 10, 67, 67, 67, 65, 84, - 44, 50, 10, 67, 67, 67, 67, 65, 44, 50, 10, 67, 67, 67, 67, 71, 44, 50, 10, 67, 67, 67, 84, - 65, 44, 50, 10, 67, 67, 67, 84, 71, 44, 50, 10, 67, 67, 67, 71, 67, 44, 50, 10, 67, 67, 67, - 71, 84, 44, 50, 10, 67, 67, 84, 65, 67, 44, 50, 10, 67, 67, 84, 65, 84, 44, 50, 10, 67, 67, - 84, 67, 65, 44, 50, 10, 67, 67, 84, 67, 71, 44, 50, 10, 67, 67, 84, 84, 65, 44, 50, 10, 67, - 67, 84, 84, 71, 44, 50, 10, 67, 67, 84, 71, 67, 44, 50, 10, 67, 67, 84, 71, 84, 44, 50, 10, - 67, 67, 71, 65, 65, 44, 50, 10, 67, 67, 71, 65, 71, 44, 50, 10, 67, 67, 71, 67, 67, 44, 50, - 10, 67, 67, 71, 67, 84, 44, 50, 10, 67, 67, 71, 84, 67, 44, 50, 10, 67, 67, 71, 84, 84, 44, - 50, 10, 67, 67, 71, 71, 65, 44, 50, 10, 67, 67, 71, 71, 71, 44, 50, 10, 67, 84, 65, 65, 65, - 44, 50, 10, 67, 84, 65, 65, 71, 44, 50, 10, 67, 84, 65, 67, 67, 44, 50, 10, 67, 84, 65, 67, - 84, 44, 50, 10, 67, 84, 65, 84, 67, 44, 50, 10, 67, 84, 65, 84, 84, 44, 50, 10, 67, 84, 65, - 71, 65, 44, 50, 10, 67, 84, 65, 71, 71, 44, 50, 10, 67, 84, 67, 65, 67, 44, 50, 10, 67, 84, - 67, 65, 84, 44, 50, 10, 67, 84, 67, 67, 65, 44, 50, 10, 67, 84, 67, 67, 71, 44, 50, 10, 67, - 84, 67, 84, 65, 44, 50, 10, 67, 84, 67, 84, 71, 44, 50, 10, 67, 84, 67, 71, 67, 44, 50, 10, - 67, 84, 67, 71, 84, 44, 50, 10, 67, 84, 84, 65, 67, 44, 50, 10, 67, 84, 84, 65, 84, 44, 50, - 10, 67, 84, 84, 67, 65, 44, 50, 10, 67, 84, 84, 67, 71, 44, 50, 10, 67, 84, 84, 84, 65, 44, - 50, 10, 67, 84, 84, 84, 71, 44, 50, 10, 67, 84, 84, 71, 67, 44, 50, 10, 67, 84, 84, 71, 84, - 44, 50, 10, 67, 84, 71, 65, 65, 44, 50, 10, 67, 84, 71, 65, 71, 44, 50, 10, 67, 84, 71, 67, - 67, 44, 50, 10, 67, 84, 71, 67, 84, 44, 50, 10, 67, 84, 71, 84, 67, 44, 50, 10, 67, 84, 71, - 84, 84, 44, 50, 10, 67, 84, 71, 71, 65, 44, 50, 10, 67, 84, 71, 71, 71, 44, 50, 10, 67, 71, - 65, 65, 67, 44, 50, 10, 67, 71, 65, 65, 84, 44, 50, 10, 67, 71, 65, 67, 65, 44, 50, 10, 67, - 71, 65, 67, 71, 44, 50, 10, 67, 71, 65, 84, 65, 44, 50, 10, 67, 71, 65, 84, 71, 44, 50, 10, - 67, 71, 65, 71, 67, 44, 50, 10, 67, 71, 65, 71, 84, 44, 50, 10, 67, 71, 67, 65, 65, 44, 50, - 10, 67, 71, 67, 65, 71, 44, 50, 10, 67, 71, 67, 67, 67, 44, 50, 10, 67, 71, 67, 67, 84, 44, - 50, 10, 67, 71, 67, 84, 67, 44, 50, 10, 67, 71, 67, 84, 84, 44, 50, 10, 67, 71, 67, 71, 65, - 44, 50, 10, 67, 71, 67, 71, 71, 44, 50, 10, 67, 71, 84, 65, 65, 44, 50, 10, 67, 71, 84, 65, - 71, 44, 50, 10, 67, 71, 84, 67, 67, 44, 50, 10, 67, 71, 84, 67, 84, 44, 50, 10, 67, 71, 84, - 84, 67, 44, 50, 10, 67, 71, 84, 84, 84, 44, 50, 10, 67, 71, 84, 71, 65, 44, 50, 10, 67, 71, - 84, 71, 71, 44, 50, 10, 67, 71, 71, 65, 67, 44, 50, 10, 67, 71, 71, 65, 84, 44, 50, 10, 67, - 71, 71, 67, 65, 44, 50, 10, 67, 71, 71, 67, 71, 44, 50, 10, 67, 71, 71, 84, 65, 44, 50, 10, - 67, 71, 71, 84, 71, 44, 50, 10, 67, 71, 71, 71, 67, 44, 50, 10, 67, 71, 71, 71, 84, 44, 50, - 10, 84, 65, 65, 65, 67, 44, 50, 10, 84, 65, 65, 65, 84, 44, 50, 10, 84, 65, 65, 67, 65, 44, - 50, 10, 84, 65, 65, 67, 71, 44, 50, 10, 84, 65, 65, 84, 65, 44, 50, 10, 84, 65, 65, 84, 71, - 44, 50, 10, 84, 65, 65, 71, 67, 44, 50, 10, 84, 65, 65, 71, 84, 44, 50, 10, 84, 65, 67, 65, - 65, 44, 50, 10, 84, 65, 67, 65, 71, 44, 50, 10, 84, 65, 67, 67, 67, 44, 50, 10, 84, 65, 67, - 67, 84, 44, 50, 10, 84, 65, 67, 84, 67, 44, 50, 10, 84, 65, 67, 84, 84, 44, 50, 10, 84, 65, - 67, 71, 65, 44, 50, 10, 84, 65, 67, 71, 71, 44, 50, 10, 84, 65, 84, 65, 65, 44, 50, 10, 84, - 65, 84, 65, 71, 44, 50, 10, 84, 65, 84, 67, 67, 44, 50, 10, 84, 65, 84, 67, 84, 44, 50, 10, - 84, 65, 84, 84, 67, 44, 50, 10, 84, 65, 84, 84, 84, 44, 50, 10, 84, 65, 84, 71, 65, 44, 50, - 10, 84, 65, 84, 71, 71, 44, 50, 10, 84, 65, 71, 65, 67, 44, 50, 10, 84, 65, 71, 65, 84, 44, - 50, 10, 84, 65, 71, 67, 65, 44, 50, 10, 84, 65, 71, 67, 71, 44, 50, 10, 84, 65, 71, 84, 65, - 44, 50, 10, 84, 65, 71, 84, 71, 44, 50, 10, 84, 65, 71, 71, 67, 44, 50, 10, 84, 65, 71, 71, - 84, 44, 50, 10, 84, 67, 65, 65, 65, 44, 50, 10, 84, 67, 65, 65, 71, 44, 50, 10, 84, 67, 65, - 67, 67, 44, 50, 10, 84, 67, 65, 67, 84, 44, 50, 10, 84, 67, 65, 84, 67, 44, 50, 10, 84, 67, - 65, 84, 84, 44, 50, 10, 84, 67, 65, 71, 65, 44, 50, 10, 84, 67, 65, 71, 71, 44, 50, 10, 84, - 67, 67, 65, 67, 44, 50, 10, 84, 67, 67, 65, 84, 44, 50, 10, 84, 67, 67, 67, 65, 44, 50, 10, - 84, 67, 67, 67, 71, 44, 50, 10, 84, 67, 67, 84, 65, 44, 50, 10, 84, 67, 67, 84, 71, 44, 50, - 10, 84, 67, 67, 71, 67, 44, 50, 10, 84, 67, 67, 71, 84, 44, 50, 10, 84, 67, 84, 65, 67, 44, - 50, 10, 84, 67, 84, 65, 84, 44, 50, 10, 84, 67, 84, 67, 65, 44, 50, 10, 84, 67, 84, 67, 71, - 44, 50, 10, 84, 67, 84, 84, 65, 44, 50, 10, 84, 67, 84, 84, 71, 44, 50, 10, 84, 67, 84, 71, - 67, 44, 50, 10, 84, 67, 84, 71, 84, 44, 50, 10, 84, 67, 71, 65, 65, 44, 50, 10, 84, 67, 71, - 65, 71, 44, 50, 10, 84, 67, 71, 67, 67, 44, 50, 10, 84, 67, 71, 67, 84, 44, 50, 10, 84, 67, - 71, 84, 67, 44, 50, 10, 84, 67, 71, 84, 84, 44, 50, 10, 84, 67, 71, 71, 65, 44, 50, 10, 84, - 67, 71, 71, 71, 44, 50, 10, 84, 84, 65, 65, 65, 44, 50, 10, 84, 84, 65, 65, 71, 44, 50, 10, - 84, 84, 65, 67, 67, 44, 50, 10, 84, 84, 65, 67, 84, 44, 50, 10, 84, 84, 65, 84, 67, 44, 50, - 10, 84, 84, 65, 84, 84, 44, 50, 10, 84, 84, 65, 71, 65, 44, 50, 10, 84, 84, 65, 71, 71, 44, - 50, 10, 84, 84, 67, 65, 67, 44, 50, 10, 84, 84, 67, 65, 84, 44, 50, 10, 84, 84, 67, 67, 65, - 44, 50, 10, 84, 84, 67, 67, 71, 44, 50, 10, 84, 84, 67, 84, 65, 44, 50, 10, 84, 84, 67, 84, - 71, 44, 50, 10, 84, 84, 67, 71, 67, 44, 50, 10, 84, 84, 67, 71, 84, 44, 50, 10, 84, 84, 84, - 65, 67, 44, 50, 10, 84, 84, 84, 65, 84, 44, 50, 10, 84, 84, 84, 67, 65, 44, 50, 10, 84, 84, - 84, 67, 71, 44, 50, 10, 84, 84, 84, 84, 65, 44, 50, 10, 84, 84, 84, 84, 71, 44, 50, 10, 84, - 84, 84, 71, 67, 44, 50, 10, 84, 84, 84, 71, 84, 44, 50, 10, 84, 84, 71, 65, 65, 44, 50, 10, - 84, 84, 71, 65, 71, 44, 50, 10, 84, 84, 71, 67, 67, 44, 50, 10, 84, 84, 71, 67, 84, 44, 50, - 10, 84, 84, 71, 84, 67, 44, 50, 10, 84, 84, 71, 84, 84, 44, 50, 10, 84, 84, 71, 71, 65, 44, - 50, 10, 84, 84, 71, 71, 71, 44, 50, 10, 84, 71, 65, 65, 67, 44, 50, 10, 84, 71, 65, 65, 84, - 44, 50, 10, 84, 71, 65, 67, 65, 44, 50, 10, 84, 71, 65, 67, 71, 44, 50, 10, 84, 71, 65, 84, - 65, 44, 50, 10, 84, 71, 65, 84, 71, 44, 50, 10, 84, 71, 65, 71, 67, 44, 50, 10, 84, 71, 65, - 71, 84, 44, 50, 10, 84, 71, 67, 65, 65, 44, 50, 10, 84, 71, 67, 65, 71, 44, 50, 10, 84, 71, - 67, 67, 67, 44, 50, 10, 84, 71, 67, 67, 84, 44, 50, 10, 84, 71, 67, 84, 67, 44, 50, 10, 84, - 71, 67, 84, 84, 44, 50, 10, 84, 71, 67, 71, 65, 44, 50, 10, 84, 71, 67, 71, 71, 44, 50, 10, - 84, 71, 84, 65, 65, 44, 50, 10, 84, 71, 84, 65, 71, 44, 50, 10, 84, 71, 84, 67, 67, 44, 50, - 10, 84, 71, 84, 67, 84, 44, 50, 10, 84, 71, 84, 84, 67, 44, 50, 10, 84, 71, 84, 84, 84, 44, - 50, 10, 84, 71, 84, 71, 65, 44, 50, 10, 84, 71, 84, 71, 71, 44, 50, 10, 84, 71, 71, 65, 67, - 44, 50, 10, 84, 71, 71, 65, 84, 44, 50, 10, 84, 71, 71, 67, 65, 44, 50, 10, 84, 71, 71, 67, - 71, 44, 50, 10, 84, 71, 71, 84, 65, 44, 50, 10, 84, 71, 71, 84, 71, 44, 50, 10, 84, 71, 71, - 71, 67, 44, 50, 10, 84, 71, 71, 71, 84, 44, 50, 10, 71, 65, 65, 65, 65, 44, 50, 10, 71, 65, - 65, 65, 71, 44, 50, 10, 71, 65, 65, 67, 67, 44, 50, 10, 71, 65, 65, 67, 84, 44, 50, 10, 71, - 65, 65, 84, 67, 44, 50, 10, 71, 65, 65, 84, 84, 44, 50, 10, 71, 65, 65, 71, 65, 44, 50, 10, - 71, 65, 65, 71, 71, 44, 50, 10, 71, 65, 67, 65, 67, 44, 50, 10, 71, 65, 67, 65, 84, 44, 50, - 10, 71, 65, 67, 67, 65, 44, 50, 10, 71, 65, 67, 67, 71, 44, 50, 10, 71, 65, 67, 84, 65, 44, - 50, 10, 71, 65, 67, 84, 71, 44, 50, 10, 71, 65, 67, 71, 67, 44, 50, 10, 71, 65, 67, 71, 84, - 44, 50, 10, 71, 65, 84, 65, 67, 44, 50, 10, 71, 65, 84, 65, 84, 44, 50, 10, 71, 65, 84, 67, - 65, 44, 50, 10, 71, 65, 84, 67, 71, 44, 50, 10, 71, 65, 84, 84, 65, 44, 50, 10, 71, 65, 84, - 84, 71, 44, 50, 10, 71, 65, 84, 71, 67, 44, 50, 10, 71, 65, 84, 71, 84, 44, 50, 10, 71, 65, - 71, 65, 65, 44, 50, 10, 71, 65, 71, 65, 71, 44, 50, 10, 71, 65, 71, 67, 67, 44, 50, 10, 71, - 65, 71, 67, 84, 44, 50, 10, 71, 65, 71, 84, 67, 44, 50, 10, 71, 65, 71, 84, 84, 44, 50, 10, - 71, 65, 71, 71, 65, 44, 50, 10, 71, 65, 71, 71, 71, 44, 50, 10, 71, 67, 65, 65, 67, 44, 50, - 10, 71, 67, 65, 65, 84, 44, 50, 10, 71, 67, 65, 67, 65, 44, 50, 10, 71, 67, 65, 67, 71, 44, - 50, 10, 71, 67, 65, 84, 65, 44, 50, 10, 71, 67, 65, 84, 71, 44, 50, 10, 71, 67, 65, 71, 67, - 44, 50, 10, 71, 67, 65, 71, 84, 44, 50, 10, 71, 67, 67, 65, 65, 44, 50, 10, 71, 67, 67, 65, - 71, 44, 50, 10, 71, 67, 67, 67, 67, 44, 50, 10, 71, 67, 67, 67, 84, 44, 50, 10, 71, 67, 67, - 84, 67, 44, 50, 10, 71, 67, 67, 84, 84, 44, 50, 10, 71, 67, 67, 71, 65, 44, 50, 10, 71, 67, - 67, 71, 71, 44, 50, 10, 71, 67, 84, 65, 65, 44, 50, 10, 71, 67, 84, 65, 71, 44, 50, 10, 71, - 67, 84, 67, 67, 44, 50, 10, 71, 67, 84, 67, 84, 44, 50, 10, 71, 67, 84, 84, 67, 44, 50, 10, - 71, 67, 84, 84, 84, 44, 50, 10, 71, 67, 84, 71, 65, 44, 50, 10, 71, 67, 84, 71, 71, 44, 50, - 10, 71, 67, 71, 65, 67, 44, 50, 10, 71, 67, 71, 65, 84, 44, 50, 10, 71, 67, 71, 67, 65, 44, - 50, 10, 71, 67, 71, 67, 71, 44, 50, 10, 71, 67, 71, 84, 65, 44, 50, 10, 71, 67, 71, 84, 71, - 44, 50, 10, 71, 67, 71, 71, 67, 44, 50, 10, 71, 67, 71, 71, 84, 44, 50, 10, 71, 84, 65, 65, - 67, 44, 50, 10, 71, 84, 65, 65, 84, 44, 50, 10, 71, 84, 65, 67, 65, 44, 50, 10, 71, 84, 65, - 67, 71, 44, 50, 10, 71, 84, 65, 84, 65, 44, 50, 10, 71, 84, 65, 84, 71, 44, 50, 10, 71, 84, - 65, 71, 67, 44, 50, 10, 71, 84, 65, 71, 84, 44, 50, 10, 71, 84, 67, 65, 65, 44, 50, 10, 71, - 84, 67, 65, 71, 44, 50, 10, 71, 84, 67, 67, 67, 44, 50, 10, 71, 84, 67, 67, 84, 44, 50, 10, - 71, 84, 67, 84, 67, 44, 50, 10, 71, 84, 67, 84, 84, 44, 50, 10, 71, 84, 67, 71, 65, 44, 50, - 10, 71, 84, 67, 71, 71, 44, 50, 10, 71, 84, 84, 65, 65, 44, 50, 10, 71, 84, 84, 65, 71, 44, - 50, 10, 71, 84, 84, 67, 67, 44, 50, 10, 71, 84, 84, 67, 84, 44, 50, 10, 71, 84, 84, 84, 67, - 44, 50, 10, 71, 84, 84, 84, 84, 44, 50, 10, 71, 84, 84, 71, 65, 44, 50, 10, 71, 84, 84, 71, - 71, 44, 50, 10, 71, 84, 71, 65, 67, 44, 50, 10, 71, 84, 71, 65, 84, 44, 50, 10, 71, 84, 71, - 67, 65, 44, 50, 10, 71, 84, 71, 67, 71, 44, 50, 10, 71, 84, 71, 84, 65, 44, 50, 10, 71, 84, - 71, 84, 71, 44, 50, 10, 71, 84, 71, 71, 67, 44, 50, 10, 71, 84, 71, 71, 84, 44, 50, 10, 71, - 71, 65, 65, 65, 44, 50, 10, 71, 71, 65, 65, 71, 44, 50, 10, 71, 71, 65, 67, 67, 44, 50, 10, - 71, 71, 65, 67, 84, 44, 50, 10, 71, 71, 65, 84, 67, 44, 50, 10, 71, 71, 65, 84, 84, 44, 50, - 10, 71, 71, 65, 71, 65, 44, 50, 10, 71, 71, 65, 71, 71, 44, 50, 10, 71, 71, 67, 65, 67, 44, - 50, 10, 71, 71, 67, 65, 84, 44, 50, 10, 71, 71, 67, 67, 65, 44, 50, 10, 71, 71, 67, 67, 71, - 44, 50, 10, 71, 71, 67, 84, 65, 44, 50, 10, 71, 71, 67, 84, 71, 44, 50, 10, 71, 71, 67, 71, - 67, 44, 50, 10, 71, 71, 67, 71, 84, 44, 50, 10, 71, 71, 84, 65, 67, 44, 50, 10, 71, 71, 84, - 65, 84, 44, 50, 10, 71, 71, 84, 67, 65, 44, 50, 10, 71, 71, 84, 67, 71, 44, 50, 10, 71, 71, - 84, 84, 65, 44, 50, 10, 71, 71, 84, 84, 71, 44, 50, 10, 71, 71, 84, 71, 67, 44, 50, 10, 71, - 71, 84, 71, 84, 44, 50, 10, 71, 71, 71, 65, 65, 44, 50, 10, 71, 71, 71, 65, 71, 44, 50, 10, - 71, 71, 71, 67, 67, 44, 50, 10, 71, 71, 71, 67, 84, 44, 50, 10, 71, 71, 71, 84, 67, 44, 50, - 10, 71, 71, 71, 84, 84, 44, 50, 10, 71, 71, 71, 71, 65, 44, 50, 10, 71, 71, 71, 71, 71, 44, - 50, 10, - ]; - - const CSV_ABUNDANCE_MIN_2: &[u8] = &[65, 65, 65, 65, 65, 44, 51, 10]; - - #[test] - fn csv() { - let mut outfile = Vec::new(); - let counter = &*COUNTER; - - crate::dump::csv(&mut outfile, counter, 1).unwrap(); - assert_eq!(&outfile[..], &CSV_ABUNDANCE_MIN_1[..]); - - outfile.clear(); - - crate::dump::csv(&mut outfile, counter, 2).unwrap(); - assert_eq!(&outfile[..], &CSV_ABUNDANCE_MIN_2[..]); - } - - const SOLID_ABUNDANCE_MIN_1: &[u8] = &[ - 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 165, 192, 49, 1, 0, 0, 0, 64, 176, 75, 255, 200, 132, - 48, 156, 2, 70, 0, 241, 137, 65, 0, 0, 0, - ]; - - const SOLID_ABUNDANCE_MIN_2: &[u8] = &[ - 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 165, 192, 49, 1, 0, 0, 0, 130, 48, 61, 232, 95, 153, 16, - 140, 175, 17, 95, 201, 40, 124, 65, 0, 0, 0, - ]; - - #[test] - fn solid() { - let mut outfile = Vec::new(); - let counter = &*COUNTER; - - crate::dump::solid(&mut outfile, counter, 1).unwrap(); - assert_eq!(&outfile[..], &SOLID_ABUNDANCE_MIN_1[..]); - - outfile.clear(); - - crate::dump::solid(&mut outfile, counter, 2).unwrap(); - assert_eq!(&outfile[..], &SOLID_ABUNDANCE_MIN_2[..]); - } - - const SPECTRUM_ABUNDANCE_MIN_1: &[u8] = &[ - 48, 44, 48, 10, 49, 44, 48, 10, 50, 44, 53, 49, 49, 10, 51, 44, 49, 10, 52, 44, 48, 10, 53, - 44, 48, 10, 54, 44, 48, 10, 55, 44, 48, 10, 56, 44, 48, 10, 57, 44, 48, 10, 49, 48, 44, 48, - 10, 49, 49, 44, 48, 10, 49, 50, 44, 48, 10, 49, 51, 44, 48, 10, 49, 52, 44, 48, 10, 49, 53, - 44, 48, 10, 49, 54, 44, 48, 10, 49, 55, 44, 48, 10, 49, 56, 44, 48, 10, 49, 57, 44, 48, 10, - 50, 48, 44, 48, 10, 50, 49, 44, 48, 10, 50, 50, 44, 48, 10, 50, 51, 44, 48, 10, 50, 52, 44, - 48, 10, 50, 53, 44, 48, 10, 50, 54, 44, 48, 10, 50, 55, 44, 48, 10, 50, 56, 44, 48, 10, 50, - 57, 44, 48, 10, 51, 48, 44, 48, 10, 51, 49, 44, 48, 10, 51, 50, 44, 48, 10, 51, 51, 44, 48, - 10, 51, 52, 44, 48, 10, 51, 53, 44, 48, 10, 51, 54, 44, 48, 10, 51, 55, 44, 48, 10, 51, 56, - 44, 48, 10, 51, 57, 44, 48, 10, 52, 48, 44, 48, 10, 52, 49, 44, 48, 10, 52, 50, 44, 48, 10, - 52, 51, 44, 48, 10, 52, 52, 44, 48, 10, 52, 53, 44, 48, 10, 52, 54, 44, 48, 10, 52, 55, 44, - 48, 10, 52, 56, 44, 48, 10, 52, 57, 44, 48, 10, 53, 48, 44, 48, 10, 53, 49, 44, 48, 10, 53, - 50, 44, 48, 10, 53, 51, 44, 48, 10, 53, 52, 44, 48, 10, 53, 53, 44, 48, 10, 53, 54, 44, 48, - 10, 53, 55, 44, 48, 10, 53, 56, 44, 48, 10, 53, 57, 44, 48, 10, 54, 48, 44, 48, 10, 54, 49, - 44, 48, 10, 54, 50, 44, 48, 10, 54, 51, 44, 48, 10, 54, 52, 44, 48, 10, 54, 53, 44, 48, 10, - 54, 54, 44, 48, 10, 54, 55, 44, 48, 10, 54, 56, 44, 48, 10, 54, 57, 44, 48, 10, 55, 48, 44, - 48, 10, 55, 49, 44, 48, 10, 55, 50, 44, 48, 10, 55, 51, 44, 48, 10, 55, 52, 44, 48, 10, 55, - 53, 44, 48, 10, 55, 54, 44, 48, 10, 55, 55, 44, 48, 10, 55, 56, 44, 48, 10, 55, 57, 44, 48, - 10, 56, 48, 44, 48, 10, 56, 49, 44, 48, 10, 56, 50, 44, 48, 10, 56, 51, 44, 48, 10, 56, 52, - 44, 48, 10, 56, 53, 44, 48, 10, 56, 54, 44, 48, 10, 56, 55, 44, 48, 10, 56, 56, 44, 48, 10, - 56, 57, 44, 48, 10, 57, 48, 44, 48, 10, 57, 49, 44, 48, 10, 57, 50, 44, 48, 10, 57, 51, 44, - 48, 10, 57, 52, 44, 48, 10, 57, 53, 44, 48, 10, 57, 54, 44, 48, 10, 57, 55, 44, 48, 10, 57, - 56, 44, 48, 10, 57, 57, 44, 48, 10, 49, 48, 48, 44, 48, 10, 49, 48, 49, 44, 48, 10, 49, 48, - 50, 44, 48, 10, 49, 48, 51, 44, 48, 10, 49, 48, 52, 44, 48, 10, 49, 48, 53, 44, 48, 10, 49, - 48, 54, 44, 48, 10, 49, 48, 55, 44, 48, 10, 49, 48, 56, 44, 48, 10, 49, 48, 57, 44, 48, 10, - 49, 49, 48, 44, 48, 10, 49, 49, 49, 44, 48, 10, 49, 49, 50, 44, 48, 10, 49, 49, 51, 44, 48, - 10, 49, 49, 52, 44, 48, 10, 49, 49, 53, 44, 48, 10, 49, 49, 54, 44, 48, 10, 49, 49, 55, 44, - 48, 10, 49, 49, 56, 44, 48, 10, 49, 49, 57, 44, 48, 10, 49, 50, 48, 44, 48, 10, 49, 50, 49, - 44, 48, 10, 49, 50, 50, 44, 48, 10, 49, 50, 51, 44, 48, 10, 49, 50, 52, 44, 48, 10, 49, 50, - 53, 44, 48, 10, 49, 50, 54, 44, 48, 10, 49, 50, 55, 44, 48, 10, 49, 50, 56, 44, 48, 10, 49, - 50, 57, 44, 48, 10, 49, 51, 48, 44, 48, 10, 49, 51, 49, 44, 48, 10, 49, 51, 50, 44, 48, 10, - 49, 51, 51, 44, 48, 10, 49, 51, 52, 44, 48, 10, 49, 51, 53, 44, 48, 10, 49, 51, 54, 44, 48, - 10, 49, 51, 55, 44, 48, 10, 49, 51, 56, 44, 48, 10, 49, 51, 57, 44, 48, 10, 49, 52, 48, 44, - 48, 10, 49, 52, 49, 44, 48, 10, 49, 52, 50, 44, 48, 10, 49, 52, 51, 44, 48, 10, 49, 52, 52, - 44, 48, 10, 49, 52, 53, 44, 48, 10, 49, 52, 54, 44, 48, 10, 49, 52, 55, 44, 48, 10, 49, 52, - 56, 44, 48, 10, 49, 52, 57, 44, 48, 10, 49, 53, 48, 44, 48, 10, 49, 53, 49, 44, 48, 10, 49, - 53, 50, 44, 48, 10, 49, 53, 51, 44, 48, 10, 49, 53, 52, 44, 48, 10, 49, 53, 53, 44, 48, 10, - 49, 53, 54, 44, 48, 10, 49, 53, 55, 44, 48, 10, 49, 53, 56, 44, 48, 10, 49, 53, 57, 44, 48, - 10, 49, 54, 48, 44, 48, 10, 49, 54, 49, 44, 48, 10, 49, 54, 50, 44, 48, 10, 49, 54, 51, 44, - 48, 10, 49, 54, 52, 44, 48, 10, 49, 54, 53, 44, 48, 10, 49, 54, 54, 44, 48, 10, 49, 54, 55, - 44, 48, 10, 49, 54, 56, 44, 48, 10, 49, 54, 57, 44, 48, 10, 49, 55, 48, 44, 48, 10, 49, 55, - 49, 44, 48, 10, 49, 55, 50, 44, 48, 10, 49, 55, 51, 44, 48, 10, 49, 55, 52, 44, 48, 10, 49, - 55, 53, 44, 48, 10, 49, 55, 54, 44, 48, 10, 49, 55, 55, 44, 48, 10, 49, 55, 56, 44, 48, 10, - 49, 55, 57, 44, 48, 10, 49, 56, 48, 44, 48, 10, 49, 56, 49, 44, 48, 10, 49, 56, 50, 44, 48, - 10, 49, 56, 51, 44, 48, 10, 49, 56, 52, 44, 48, 10, 49, 56, 53, 44, 48, 10, 49, 56, 54, 44, - 48, 10, 49, 56, 55, 44, 48, 10, 49, 56, 56, 44, 48, 10, 49, 56, 57, 44, 48, 10, 49, 57, 48, - 44, 48, 10, 49, 57, 49, 44, 48, 10, 49, 57, 50, 44, 48, 10, 49, 57, 51, 44, 48, 10, 49, 57, - 52, 44, 48, 10, 49, 57, 53, 44, 48, 10, 49, 57, 54, 44, 48, 10, 49, 57, 55, 44, 48, 10, 49, - 57, 56, 44, 48, 10, 49, 57, 57, 44, 48, 10, 50, 48, 48, 44, 48, 10, 50, 48, 49, 44, 48, 10, - 50, 48, 50, 44, 48, 10, 50, 48, 51, 44, 48, 10, 50, 48, 52, 44, 48, 10, 50, 48, 53, 44, 48, - 10, 50, 48, 54, 44, 48, 10, 50, 48, 55, 44, 48, 10, 50, 48, 56, 44, 48, 10, 50, 48, 57, 44, - 48, 10, 50, 49, 48, 44, 48, 10, 50, 49, 49, 44, 48, 10, 50, 49, 50, 44, 48, 10, 50, 49, 51, - 44, 48, 10, 50, 49, 52, 44, 48, 10, 50, 49, 53, 44, 48, 10, 50, 49, 54, 44, 48, 10, 50, 49, - 55, 44, 48, 10, 50, 49, 56, 44, 48, 10, 50, 49, 57, 44, 48, 10, 50, 50, 48, 44, 48, 10, 50, - 50, 49, 44, 48, 10, 50, 50, 50, 44, 48, 10, 50, 50, 51, 44, 48, 10, 50, 50, 52, 44, 48, 10, - 50, 50, 53, 44, 48, 10, 50, 50, 54, 44, 48, 10, 50, 50, 55, 44, 48, 10, 50, 50, 56, 44, 48, - 10, 50, 50, 57, 44, 48, 10, 50, 51, 48, 44, 48, 10, 50, 51, 49, 44, 48, 10, 50, 51, 50, 44, - 48, 10, 50, 51, 51, 44, 48, 10, 50, 51, 52, 44, 48, 10, 50, 51, 53, 44, 48, 10, 50, 51, 54, - 44, 48, 10, 50, 51, 55, 44, 48, 10, 50, 51, 56, 44, 48, 10, 50, 51, 57, 44, 48, 10, 50, 52, - 48, 44, 48, 10, 50, 52, 49, 44, 48, 10, 50, 52, 50, 44, 48, 10, 50, 52, 51, 44, 48, 10, 50, - 52, 52, 44, 48, 10, 50, 52, 53, 44, 48, 10, 50, 52, 54, 44, 48, 10, 50, 52, 55, 44, 48, 10, - 50, 52, 56, 44, 48, 10, 50, 52, 57, 44, 48, 10, 50, 53, 48, 44, 48, 10, 50, 53, 49, 44, 48, - 10, 50, 53, 50, 44, 48, 10, 50, 53, 51, 44, 48, 10, 50, 53, 52, 44, 48, 10, 50, 53, 53, 44, - 48, 10, - ]; - - #[test] - fn spectrum() { - let mut outfile = Vec::new(); - let counter = &*COUNTER; - - crate::dump::spectrum(&mut outfile, counter).unwrap(); - - assert_eq!(&outfile[..], &SPECTRUM_ABUNDANCE_MIN_1[..]); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use thiserror::Error; - -/// All error produce by Pcon -#[derive(Debug, Error)] -pub enum Error { - /// See enum [Cli] - #[error(transparent)] - Cli(#[from] Cli), - - /// See enum [IO] - #[error(transparent)] - IO(#[from] IO), -} - -/// Error emmit durring Cli parsing -#[derive(Debug, Error)] -pub enum Cli { - /// For efficient computation of canonical the kmer size must be odd - #[error("Kmer size must be odd")] - KMustBeOdd, - - /// Kmer is store 2bit form on 64bit we can't manage larger kmer - #[error("Kmer size must be lower than 32")] - KMustBeLower32, - - /// You must set at least one dump option csv, solid, spectrum - #[error("You must set at least one dump option csv, solid, spectrum")] - ADumpOptionMustBeSet, -} - -/// Error emmit when pcon try to work with file -#[repr(C)] -#[derive(Debug, Error)] -pub enum IO { - /// We can't create file. In C binding it's equal to 0 - #[error("We can't create file")] - CantCreateFile, - - /// We can't open file. In C binding it's equal to 1 - #[error("We can't open file")] - CantOpenFile, - - /// Error durring write in file. In C binding it's equal to 2 - #[error("Error durring write")] - ErrorDurringWrite, - - /// Error durring read file. In C binding it's equal to 3 - #[error("Error durring read")] - ErrorDurringRead, - - /// No error, this exist only for C binding it's the value of a new error pointer - #[error("Isn't error if you see this please contact the author with this message and a description of what you do with pcon")] - NoError, -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* std use */ -use std::io::Read; -use std::io::Write; -use std::sync::atomic; - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use byteorder::{ReadBytesExt, WriteBytesExt}; -use rayon::prelude::*; - -/* local use */ -use crate::error::IO::*; -use crate::error::*; - -pub type AtoCount = atomic::AtomicU8; -pub type Count = u8; - -/// A counter of kmer based on cocktail crate 2bit conversion, canonicalisation and hashing. -/// If kmer occure more than 256 other occurence are ignored -pub struct Counter { - pub k: u8, - count: Box<[AtoCount]>, -} - -impl Counter { - /// Create a new Counter for kmer size equal to k, record_buffer_len control the number of record read in same time - pub fn new(k: u8) -> Self { - let tmp = vec![0u8; cocktail::kmer::get_hash_space_size(k) as usize]; - - Self { - k, - count: unsafe { - std::mem::transmute::, Box<[AtoCount]>>(tmp.into_boxed_slice()) - }, - } - } - - /// Read the given an instance of io::Read as a fasta format and count kmer init - pub fn count_fasta(&mut self, fasta: R, record_buffer_len: usize) - where - R: std::io::Read, - { - let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(fasta)); - - let mut iter = reader.records(); - let mut records = Vec::with_capacity(record_buffer_len); - - let mut end = false; - while !end { - for i in 0..record_buffer_len { - if let Some(Ok(record)) = iter.next() { - records.push(record); - } else { - end = true; - records.truncate(i); - break; - } - } - - log::info!("Buffer len: {}", records.len()); - - records.par_iter().for_each(|record| { - if record.sequence().len() >= self.k as usize { - let tokenizer = - cocktail::tokenizer::Canonical::new(record.sequence().as_ref(), self.k); - - for canonical in tokenizer { - Counter::inc_canonic_ato(&self.count, canonical); - } - } - }); - - records.clear() - } - } - - /// Increase the counter of a kmer - pub fn inc(&mut self, kmer: u64) { - self.inc_canonic(cocktail::kmer::canonical(kmer, self.k)); - } - - /// Increase the counter of a canonical kmer - pub fn inc_canonic(&self, canonical: u64) { - Counter::inc_canonic_ato(&self.count, canonical); - } - - fn inc_canonic_ato(count: &[AtoCount], canonical: u64) { - let hash = (canonical >> 1) as usize; - - if count[hash].load(std::sync::atomic::Ordering::SeqCst) != std::u8::MAX { - count[hash].fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } - } - - /// Get the counter of a kmer - pub fn get(&self, kmer: u64) -> Count { - self.get_canonic(cocktail::kmer::canonical(kmer, self.k)) - } - - /// Get the counter of a canonical kmer - pub fn get_canonic(&self, canonical: u64) -> Count { - let hash = (canonical >> 1) as usize; - - self.count[hash].load(atomic::Ordering::SeqCst) - } - - pub(crate) fn get_raw_count(&self) -> &[AtoCount] { - &self.count - } - - /// Serialize counter in given [std::io::Write] - pub fn serialize(&self, w: W) -> Result<()> - where - W: std::io::Write, - { - let mut writer = w; - let count = unsafe { &*(&self.count as *const Box<[AtoCount]> as *const Box<[Count]>) }; - - writer - .write_u8(self.k) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("Error durring serialize counter"))?; - - for b in count - .par_chunks(2usize.pow(25)) - .map(|in_buffer| { - let mut out_buffer = Vec::new(); - - { - let mut writer = - flate2::write::GzEncoder::new(&mut out_buffer, flate2::Compression::fast()); - - writer - .write_all(in_buffer) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("Error durring serialize counter"))?; - } - - Ok(out_buffer) - }) - .collect::>>>() - { - let buf = b?; - - writer - .write_all(&buf) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("Error durring serialize counter"))?; - } - - Ok(()) - } - - /// Deserialize counter for given [std::io::Read] - pub fn deserialize(r: R) -> Result - where - R: std::io::Read, - { - let mut reader = r; - - let k = reader - .read_u8() - .with_context(|| Error::IO(ErrorDurringRead)) - .with_context(|| anyhow!("Error durring deserialize counter"))?; - - let mut deflate = flate2::read::MultiGzDecoder::new(reader); - let mut tmp = vec![0u8; cocktail::kmer::get_hash_space_size(k) as usize].into_boxed_slice(); - - deflate - .read_exact(&mut tmp) - .with_context(|| Error::IO(ErrorDurringRead)) - .with_context(|| anyhow!("Error durring deserialize counter"))?; - - Ok(Self { - k, - count: unsafe { std::mem::transmute::, Box<[AtoCount]>>(tmp) }, - }) - } - - /// Convert a counter in a StaticCounter - pub fn into_static(self) -> crate::static_counter::StaticCounter { - crate::static_counter::StaticCounter { - k: self.k, - count: unsafe { std::mem::transmute::, Box<[Count]>>(self.count) }, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - const FASTA_FILE: &[u8] = b">random_seq 0 -GTTCTGCAAATTAGAACAGACAATACACTGGCAGGCGTTGCGTTGGGGGAGATCTTCCGTAACGAGCCGGCATTTGTAAGAAAGAGATTTCGAGTAAATG ->random_seq 1 -AGGATAGAAGCTTAAGTACAAGATAATTCCCATAGAGGAAGGGTGGTATTACAGTGCCGCCTGTTGAAAGCCCCAATCCCGCTTCAATTGTTGAGCTCAG -"; - - const FASTA_COUNT: &[u8] = &[ - 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 2, 2, 1, 0, 1, 1, 1, 2, 0, 0, - 0, 1, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, - 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, - 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 2, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, - 0, 0, 1, 0, 0, 0, 0, 2, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, - 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, - 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 0, 1, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 2, 1, 0, 0, 1, 1, - 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, - 0, 0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 1, 0, 1, 0, 0, 0, - 0, 1, 2, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 2, 1, 0, 0, 1, 1, 0, 2, 0, 0, 0, 0, 0, 0, 2, 0, - 1, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 1, - 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 1, 0, 1, 0, 0, 0, - 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 2, 1, 0, 0, 0, 0, 1, 0, 0, 1, - 0, 2, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, - 1, 1, - ]; - - #[test] - fn count_fasta() { - let mut counter = crate::counter::Counter::new(5); - - counter.count_fasta(FASTA_FILE, 1); - - unsafe { - assert_eq!( - std::mem::transmute::<&[AtoCount], &[Count]>(counter.get_raw_count()), - &FASTA_COUNT[..] - ); - } - } - - const FASTQ_FILE: &[u8] = b"@random_seq 0 -CCAGTAGCTTGGTGTACCGACGCTGTAGAGTTACAGTCTCGCGTGGATATAAGCTACTATCGACAGCAGGGTACGTTGTGAGTAATCTAACGTCATCTCT -+ -X-Ee--b`x6h6Yy,c7S`p_C*K~SAgs;LFManA`-oLL6!Pgi>`X'P~6np^M1jQ+xQc9.ZCTEn+Yy?5r+b|ta=EyHil%Z}>>(%y\\=IC -@random_seq 1 -TCAAATTGGCCGCCGCACAGTGAACCCGGAACTAAACAAGCACCGCACCGTTTGGTACACTTGAACACCGTATAAATTCATGGTGTTTATAAGCCAATGG -+ - - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -use crate::error; -use error::*; - -use crate::counter; -use crate::dump; -use crate::solid; - -/* Helper */ -fn cstr2string(c_path: *const std::os::raw::c_char) -> String { - unsafe { String::from_utf8_unchecked(std::ffi::CStr::from_ptr(c_path).to_bytes().to_owned()) } -} - -fn reader_from_c_path( - c_path: *const std::os::raw::c_char, -) -> Result>, error::IO> { - let path = cstr2string(c_path); - - let file = match std::fs::File::open(&path) { - Ok(f) => f, - Err(_) => return Err(IO::CantOpenFile), - }; - - let niffler = match niffler::get_reader(Box::new(file)) { - Ok(f) => f, - Err(_) => return Err(IO::ErrorDurringRead), - }; - - Ok(std::io::BufReader::new(niffler.0)) -} - -fn writer_from_c_path( - c_path: *const std::os::raw::c_char, -) -> Result>, error::IO> { - let path = cstr2string(c_path); - - let file = match std::fs::File::create(&path) { - Ok(f) => f, - Err(_) => return Err(IO::CantOpenFile), - }; - - Ok(std::io::BufWriter::new(Box::new(file))) -} - -/* Error section */ -/// Create a new pcon io error it's init to no error, see [error::IO]. In python corresponding string error is emit. -#[no_mangle] -pub extern "C" fn pcon_error_new() -> *mut error::IO { - Box::into_raw(Box::new(error::IO::NoError)) -} - -/// Free a pcon io error -/// -/// # Safety -/// It's safe -#[no_mangle] -pub unsafe extern "C" fn pcon_error_free(error: *mut error::IO) { - if error.is_null() { - return; - } - - let boxed = Box::from_raw(error); - - drop(boxed); -} - -/* Counter section */ -/// Create a new Counter. In python binding Counter is an object, new is the default constructor. -/// See [counter::Counter::new]. -#[no_mangle] -pub extern "C" fn pcon_counter_new(k: u8) -> *mut counter::Counter { - Box::into_raw(Box::new(counter::Counter::new(k))) -} - -/// Free a Counter. In Python use del on Counter object. -/// -/// # Safety -/// It's safe -#[no_mangle] -pub unsafe extern "C" fn pcon_counter_free(counter: *mut counter::Counter) { - if counter.is_null() { - return; - } - - let boxed = Box::from_raw(counter); - - drop(boxed); -} - -/// Perform count of kmer in fasta file in path, this file can be compress in gzip, bzip2, xz. -/// You must check value of `io_error` is equal to NoError before use `counter`. -/// -/// In Python it's count_fasta method of Counter object. -/// See [counter::Counter::count_fasta]. -#[no_mangle] -pub extern "C" fn pcon_counter_count_fasta( - counter: &mut counter::Counter, - c_path: *const std::os::raw::c_char, - read_buffer_len: usize, - io_error: &mut error::IO, -) { - let reader = reader_from_c_path(c_path); - - match reader { - Ok(r) => counter.count_fasta(r, read_buffer_len), - Err(e) => *io_error = e, - } -} - -/// Increase the count of `kmer` -/// -/// In Python it's inc method of Counter object. -/// See [counter::Counter::inc]. -#[no_mangle] -pub extern "C" fn pcon_counter_inc(counter: &mut counter::Counter, kmer: u64) { - counter.inc(kmer); -} - -/// Increase the count of a canonical `kmer` -/// -/// In Python it's inc_canonic method of Counter object. -/// See [counter::Counter::inc_canonic]. -#[no_mangle] -pub extern "C" fn pcon_counter_inc_canonic(counter: &mut counter::Counter, kmer: u64) { - counter.inc_canonic(kmer); -} - -/// Get the count of value `kmer` -/// -/// In Python it's get method of Counter object. -/// See [counter::Counter::get]. -#[no_mangle] -pub extern "C" fn pcon_counter_get(counter: &counter::Counter, kmer: u64) -> counter::Count { - counter.get(kmer) -} - -/// Get the count of value a canonical `kmer` -/// -/// In Python it's get_canonic method of Counter object. -/// See [counter::Counter::get_canonic]. -#[no_mangle] -pub extern "C" fn pcon_counter_get_canonic( - counter: &counter::Counter, - kmer: u64, -) -> counter::Count { - counter.get_canonic(kmer) -} - -/// Serialize Counter in path of file -/// You must check value of `io_error` is equal to NoError before use `counter` -/// -/// In Python it's serialize method of Counter object. -/// See [counter::Counter::serialize]. -#[no_mangle] -pub extern "C" fn pcon_serialize_counter( - counter: &counter::Counter, - c_path: *const std::os::raw::c_char, - io_error: &mut error::IO, -) { - let writer = writer_from_c_path(c_path); - - match writer { - Ok(w) => match counter.serialize(w) { - Ok(_) => (), - Err(_) => *io_error = IO::ErrorDurringWrite, - }, - Err(e) => *io_error = e, - } -} - -/// Deserialize Counter from `c_path` in `counter` -/// You must check value of `io_error` is equal to NoError before use `counter` -/// -/// In Python it's deserialize class method of Counter. -/// See [counter::Counter::deserialize]. -#[no_mangle] -pub extern "C" fn pcon_deserialize_counter( - counter: &mut counter::Counter, - c_path: *const std::os::raw::c_char, - io_error: &mut error::IO, -) { - let reader = reader_from_c_path(c_path); - - match reader { - Ok(r) => match counter::Counter::deserialize(r) { - Ok(c) => *counter = c, - Err(_) => *io_error = IO::ErrorDurringRead, - }, - Err(e) => *io_error = e, - } -} - -/* solid section */ -/// Create a new Solid. In python binding Solid is an object, new is the default constructor. -/// See [solid::Solid::new] -#[no_mangle] -pub extern "C" fn pcon_solid_new(k: u8) -> *mut solid::Solid { - Box::into_raw(Box::new(solid::Solid::new(k))) -} - -/// Create a new Solid from value in Counter -/// In python binding, this is a Solid class method from_counter. -/// See [solid::Solid::from_counter]. -#[no_mangle] -pub extern "C" fn pcon_solid_from_counter( - counter: &counter::Counter, - abundance: counter::Count, -) -> *mut solid::Solid { - Box::into_raw(Box::new(solid::Solid::from_counter(counter, abundance))) -} - -/// Free a Solid. In Python use del on Solid object. -/// -/// # Safety -/// It's safe -#[no_mangle] -pub unsafe extern "C" fn pcon_solid_free(solid: *mut solid::Solid) { - if solid.is_null() { - return; - } - - let boxed = Box::from_raw(solid); - - drop(boxed); -} - -/// Set the solidity status of `kmer` to `value` -/// -/// In Python it's set method of Solid object. -/// See [solid::Solid::set]. -#[no_mangle] -pub extern "C" fn pcon_solid_set(solid: &mut solid::Solid, kmer: u64, value: bool) { - solid.set(kmer, value); -} - -/// Set the solidity status of a canonical `kmer` to `value` -/// -/// In Python it's set_canonic method of Solid object. -/// See [solid::Solid::set_canonic]. -#[no_mangle] -pub extern "C" fn pcon_solid_set_canonic(solid: &mut solid::Solid, kmer: u64, value: bool) { - solid.set_canonic(kmer, value); -} - -/// Get the solidity status of `kmer` -/// -/// In Python it's get method of Solid object. -/// See [solid::Solid::get]. -#[no_mangle] -pub extern "C" fn pcon_solid_get(solid: &mut solid::Solid, kmer: u64) -> bool { - solid.get(kmer) -} - -/// Get the solidity status of a canonical `kmer` -/// -/// In Python it's get_canonic method of Solid object. -/// See [solid::Solid::get_canonic]. -#[no_mangle] -pub extern "C" fn pcon_solid_get_canonic(solid: &mut solid::Solid, kmer: u64) -> bool { - solid.get_canonic(kmer) -} - -/// Serialize Solid in path of file -/// You must check value of `io_error` is equal to NoError before use `solid` -/// -/// In Python it's serialize method of Solid object. -/// See [solid::Solid::serialize]. -#[no_mangle] -pub extern "C" fn pcon_serialize_solid( - solid: &solid::Solid, - c_path: *const std::os::raw::c_char, - io_error: &mut error::IO, -) { - let writer = writer_from_c_path(c_path); - - match writer { - Ok(w) => match solid.serialize(w) { - Ok(_) => (), - Err(_) => *io_error = IO::ErrorDurringWrite, - }, - Err(e) => *io_error = e, - } -} - -/// Deserialize Solid from `c_path` in `counter` -/// You must check value of `io_error` is equal to NoError before use `solid` -/// -/// In Python it's deserialize class method of solid. -/// See [solid::Solid::deserialize]. -#[no_mangle] -pub extern "C" fn pcon_deserialize_solid( - solid: &mut solid::Solid, - c_path: *const std::os::raw::c_char, - io_error: &mut error::IO, -) { - let reader = reader_from_c_path(c_path); - - match reader { - Ok(r) => match solid::Solid::deserialize(r) { - Ok(s) => *solid = s, - Err(_) => *io_error = IO::ErrorDurringRead, - }, - Err(e) => *io_error = e, - } -} - -/* Dump section */ -/// See [dump::csv]. -/// You must check value of `io_error` is equal to NoError to be sure no problem occure durring write -/// -/// In Python it's csv function of dump module. -#[no_mangle] -pub extern "C" fn pcon_dump_csv( - counter: &counter::Counter, - abundance: counter::Count, - c_path: *const std::os::raw::c_char, - io_error: &mut error::IO, -) { - let writer = writer_from_c_path(c_path); - - match writer { - Ok(w) => match dump::csv(w, counter, abundance) { - Ok(_) => (), - Err(_) => *io_error = IO::ErrorDurringWrite, - }, - Err(e) => *io_error = e, - } -} - -/// See [dump::solid()]. -/// You must check value of `io_error` is equal to NoError to be sure no problem occure durring write -/// -/// In Python it's solid function of dump module. -#[no_mangle] -pub extern "C" fn pcon_dump_solid( - counter: &counter::Counter, - abundance: counter::Count, - c_path: *const std::os::raw::c_char, - io_error: &mut error::IO, -) { - let writer = writer_from_c_path(c_path); - - match writer { - Ok(w) => match dump::solid(w, counter, abundance) { - Ok(_) => (), - Err(_) => *io_error = IO::ErrorDurringWrite, - }, - Err(e) => *io_error = e, - } -} - -/// See [dump::spectrum]. -/// You must check value of `io_error` is equal to NoError to be sure no problem occure durring write -/// -/// In Python it's spectrum function of dump module. -#[no_mangle] -pub extern "C" fn pcon_dump_spectrum( - counter: &counter::Counter, - c_path: *const std::os::raw::c_char, - io_error: &mut error::IO, -) { - let writer = writer_from_c_path(c_path); - - match writer { - Ok(w) => match dump::spectrum(w, counter) { - Ok(_) => (), - Err(_) => *io_error = IO::ErrorDurringWrite, - }, - Err(e) => *io_error = e, - } -} - -/// See [set_count_nb_threads] -#[no_mangle] -pub extern "C" fn pcon_set_nb_threads(nb_threads: usize) { - crate::set_nb_threads(nb_threads); -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::Result; -use clap::Parser; - -use pcon::*; - -fn main() -> Result<()> { - let params = cli::Command::parse(); - - if let Some(level) = cli::i82level(params.verbosity) { - env_logger::builder() - .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis)) - .filter_level(level.to_level_filter()) - .init(); - } else { - env_logger::Builder::from_env("PCON_LOG") - .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis)) - .init(); - } - - if let Some(threads) = params.threads { - log::info!("Set number of threads to {}", threads); - - set_nb_threads(threads); - } - - match params.subcmd { - cli::SubCommand::Count(params) => count::count(params), - cli::SubCommand::Dump(params) => dump::dump(params), - } -} -/* std use */ -use std::io::Read; - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use byteorder::ReadBytesExt; - -/* local use */ -use crate::counter; -use crate::error::IO::*; -use crate::error::*; - -/// A struct to get a fast access to count -pub struct StaticCounter { - pub k: u8, - pub(crate) count: Box<[u8]>, -} - -impl StaticCounter { - /// Deserialize counter for given [std::io::Read] - pub fn deserialize(r: R) -> Result - where - R: std::io::Read, - { - let mut reader = r; - - let k = reader - .read_u8() - .with_context(|| Error::IO(ErrorDurringRead)) - .with_context(|| anyhow!("Error durring deserialize counter"))?; - - let mut deflate = flate2::read::MultiGzDecoder::new(reader); - let mut tmp = vec![0u8; cocktail::kmer::get_hash_space_size(k) as usize].into_boxed_slice(); - - deflate - .read_exact(&mut tmp) - .with_context(|| Error::IO(ErrorDurringRead)) - .with_context(|| anyhow!("Error durring deserialize counter"))?; - - Ok(Self { k, count: tmp }) - } - - /// Get the counter of a kmer - pub fn get(&self, kmer: u64) -> counter::Count { - self.get_canonic(cocktail::kmer::canonical(kmer, self.k)) - } - - /// Get the counter of a canonical kmer - pub fn get_canonic(&self, canonical: u64) -> counter::Count { - let hash = (canonical >> 1) as usize; - - self.count[hash] - } - - pub(crate) fn get_raw_count(&self) -> &[counter::Count] { - &self.count - } -} - -#[cfg(test)] -mod tests { - const FASTA_FILE: &[u8] = b">random_seq 0 -GTTCTGCAAATTAGAACAGACAATACACTGGCAGGCGTTGCGTTGGGGGAGATCTTCCGTAACGAGCCGGCATTTGTAAGAAAGAGATTTCGAGTAAATG ->random_seq 1 -AGGATAGAAGCTTAAGTACAAGATAATTCCCATAGAGGAAGGGTGGTATTACAGTGCCGCCTGTTGAAAGCCCCAATCCCGCTTCAATTGTTGAGCTCAG -"; - - const FASTA_COUNT: &[u8] = &[ - 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 2, 2, 1, 0, 1, 1, 1, 2, 0, 0, - 0, 1, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, - 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, - 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 2, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, - 0, 0, 1, 0, 0, 0, 0, 2, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, - 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, - 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 0, 1, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 2, 1, 0, 0, 1, 1, - 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, - 0, 0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 1, 0, 1, 0, 0, 0, - 0, 1, 2, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 2, 1, 0, 0, 1, 1, 0, 2, 0, 0, 0, 0, 0, 0, 2, 0, - 1, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 1, - 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 1, 0, 1, 0, 0, 0, - 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 2, 1, 0, 0, 0, 0, 1, 0, 0, 1, - 0, 2, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, - 1, 1, - ]; - - #[test] - fn count_fasta() { - let mut counter = crate::counter::Counter::new(5); - - counter.count_fasta(FASTA_FILE, 1); - let static_count = counter.into_static(); - - assert_eq!(static_count.get_raw_count(), &FASTA_COUNT[..]); - } - - lazy_static::lazy_static! { - static ref COUNTER: crate::static_counter::StaticCounter = { - let mut counter = crate::counter::Counter::new(5); - - for i in 0..cocktail::kmer::get_kmer_space_size(5) { - counter.inc(i); - } - - counter.into_static() - }; - } - - const ALLKMERSEEONE: &[u8] = &[ - 5, 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 237, 208, 1, 9, 0, 0, 0, 128, 32, 232, 255, 232, 134, - 148, 19, 100, 233, 1, 1, 118, 18, 53, 208, 0, 2, 0, 0, - ]; - - #[test] - fn deserialize() { - let counter = - crate::static_counter::StaticCounter::deserialize(&ALLKMERSEEONE[..]).unwrap(); - - assert_eq!(counter.k, COUNTER.k); - - for (a, b) in counter - .get_raw_count() - .iter() - .zip(COUNTER.get_raw_count().iter()) - { - assert_eq!(a, b); - } - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -#[derive(clap::Parser, Debug)] -#[clap(version = "0.1", author = "Pierre Marijon ")] -/// Prompt COuNter is short kmer counter -pub struct Command { - #[clap(subcommand)] - pub subcmd: SubCommand, - - #[clap(short = 't', long = "threads")] - /// Number of thread use by pcon to count, 0 use all avaible core, default value 0 - pub threads: Option, - - #[clap(short = 'v', long = "verbosity", parse(from_occurrences))] - /// verbosity level also control by environment variable PCON_LOG if flag is set PCON_LOG value is ignored - pub verbosity: i8, -} - -#[derive(clap::Parser, Debug)] -pub enum SubCommand { - Count(SubCommandCount), - Dump(SubCommandDump), -} - -#[derive(clap::Parser, Debug)] -/// Perform kmer count -pub struct SubCommandCount { - #[clap(short = 'k', long = "kmer-size")] - /// Size of kmer - pub kmer: u8, - - #[clap(short = 'i', long = "inputs")] - /// Path to inputs - pub inputs: Vec, - - #[clap(short = 'o', long = "output")] - /// "Path where count are store in binary format" - pub output: Option, - - #[clap(short = 'b', long = "record_buffer")] - /// Number of sequence record load in buffer, default 8192 - pub record_buffer: Option, - - #[clap(short = 'a', long = "abundance", default_value = "0")] - /// Minimal abundance - pub abundance: crate::counter::Count, - - #[clap(short = 'c', long = "csv")] - /// Path where count is write in csv - pub csv: Option, - - #[clap(short = 's', long = "solid")] - /// Path where count is write in solid format - pub solid: Option, - - #[clap(short = 'S', long = "spectrum")] - /// Path where kmer spectrum is write - pub spectrum: Option, -} - -#[derive(clap::Parser, Debug)] -/// Convert count in usable format -pub struct SubCommandDump { - #[clap(short = 'i', long = "input", help = "Path to count file")] - pub input: String, - - #[clap(short = 'a', long = "abundance", default_value = "0")] - /// Minimal abundance - pub abundance: crate::counter::Count, - - #[clap(short = 'c', long = "csv")] - /// Path where count is write in csv - pub csv: Option, - - #[clap(short = 's', long = "solid")] - /// Path where count is write in solid format - pub solid: Option, - - #[clap(short = 'S', long = "spectrum")] - /// Path where kmer spectrum is write - pub spectrum: Option, - - #[clap(short = 'b', long = "bin")] - /// Path where count is write in bin - pub bin: Option, -} - -use crate::error::{Cli, Error}; -use Cli::*; - -pub fn check_count_param(params: SubCommandCount) -> Result { - if (params.kmer & 1) == 0 { - return Err(Error::Cli(KMustBeOdd)); - } - - if params.kmer > 32 { - return Err(Error::Cli(KMustBeLower32)); - } - - Ok(params) -} - -pub fn check_dump_param(params: SubCommandDump) -> Result { - if ![¶ms.csv, ¶ms.solid, ¶ms.spectrum, ¶ms.bin] - .iter() - .any(|x| x.is_some()) - { - return Err(Error::Cli(ADumpOptionMustBeSet)); - } - - Ok(params) -} - -pub fn i82level(level: i8) -> Option { - match level { - std::i8::MIN..=0 => None, - 1 => Some(log::Level::Error), - 2 => Some(log::Level::Warn), - 3 => Some(log::Level::Info), - 4 => Some(log::Level::Debug), - 5..=std::i8::MAX => Some(log::Level::Trace), - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use bitvec::prelude::*; -use byteorder::{ReadBytesExt, WriteBytesExt}; - -/* local use */ -use crate::error::IO::*; -use crate::error::*; -use crate::*; - -/// A struct to store if a kmer is Solid or not. Only kmer with abundance upper than a threshold is solid -pub struct Solid { - pub k: u8, - solid: BitBox, -} - -impl Solid { - /// Create a new Solid for kmer size equal to `k` - pub fn new(k: u8) -> Self { - Self { - k, - solid: bitbox![u8, Lsb0; 0; cocktail::kmer::get_hash_space_size(k) as usize], - } - } - - /// Create a new Solid with count in `counter` only kmer upper than `abundance` are solid - pub fn from_counter(counter: &counter::Counter, abundance: counter::Count) -> Self { - let counts = unsafe { - &(*(counter.get_raw_count() as *const [counter::AtoCount] as *const [counter::Count])) - }; - - let mut solid = bitbox![u8, Lsb0; 0; counts.len()]; - - unsafe { - for (index, count) in (*(counter.get_raw_count() as *const [counter::AtoCount] - as *const [counter::Count])) - .iter() - .enumerate() - { - if *count > abundance { - solid.set(index, true); - } - } - } - - Self { - k: counter.k, - solid, - } - } - - /// Solidity status of `kmer` is set to `value` - pub fn set(&mut self, kmer: u64, value: bool) { - self.set_canonic(cocktail::kmer::canonical(kmer, self.k), value); - } - - /// Solidity status of a canonical`kmer` is set to `value` - pub fn set_canonic(&mut self, canonical: u64, value: bool) { - let hash = (canonical >> 1) as usize; - - if let Some(mut v) = self.solid.get_mut(hash) { - *v = value; - } - } - - /// Get the solidity status of `kmer` - pub fn get(&self, kmer: u64) -> bool { - self.get_canonic(cocktail::kmer::canonical(kmer, self.k)) - } - - /// Get the solidity status of a canonical `kmer` - pub fn get_canonic(&self, canonical: u64) -> bool { - let hash = (canonical >> 1) as usize; - - self.solid[hash] - } - - #[allow(dead_code)] - pub(crate) fn get_raw_solid(&self) -> &BitBox { - &self.solid - } - - /// Serialize counter in given [std::io::Write] - pub fn serialize(&self, w: W) -> Result<()> - where - W: std::io::Write, - { - let mut writer = niffler::get_writer( - Box::new(w), - niffler::compression::Format::Gzip, - niffler::compression::Level::One, - )?; - - writer - .write_u8(self.k) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("Error durring serialize solid"))?; - - writer - .write_all(self.solid.as_raw_slice()) - .with_context(|| Error::IO(ErrorDurringWrite)) - .with_context(|| anyhow!("Error durring serialize solid"))?; - - Ok(()) - } - - /// Deserialize counter for given [std::io::Read] - pub fn deserialize(r: R) -> Result - where - R: std::io::Read, - { - let mut reader = niffler::get_reader(Box::new(r))?.0; - - let k = reader - .read_u8() - .with_context(|| Error::IO(ErrorDurringRead)) - .with_context(|| anyhow!("Error durring deserialize solid"))?; - - // >> 3 <-> divide by 8 - let mut tmp = - vec![0u8; (cocktail::kmer::get_hash_space_size(k) >> 3) as usize].into_boxed_slice(); - - reader - .read_exact(&mut tmp) - .with_context(|| Error::IO(ErrorDurringRead)) - .with_context(|| anyhow!("Error durring deserialize solid"))?; - - Ok(Self { - k, - solid: BitBox::from_boxed_slice(tmp), - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - const FASTA_FILE: &[u8] = b">random_seq 0 -GTTCTGCAAATTAGAACAGACAATACACTGGCAGGCGTTGCGTTGGGGGAGATCTTCCGTAACGAGCCGGCATTTGTAAGAAAGAGATTTCGAGTAAATG ->random_seq 1 -AGGATAGAAGCTTAAGTACAAGATAATTCCCATAGAGGAAGGGTGGTATTACAGTGCCGCCTGTTGAAAGCCCCAATCCCGCTTCAATTGTTGAGCTCAG -"; - - fn get_solid() -> solid::Solid { - let mut counter = crate::counter::Counter::new(5); - - counter.count_fasta(FASTA_FILE, 1); - - solid::Solid::from_counter(&counter, 0) - } - - const SOLID: &[u8] = &[ - 112, 64, 113, 143, 130, 8, 128, 4, 6, 60, 214, 0, 243, 8, 193, 1, 30, 4, 34, 97, 4, 70, - 192, 12, 16, 144, 133, 38, 192, 41, 1, 4, 218, 179, 140, 0, 0, 140, 242, 35, 90, 56, 205, - 179, 64, 3, 25, 20, 226, 0, 32, 76, 1, 134, 48, 64, 7, 0, 200, 144, 98, 131, 2, 203, - ]; - - #[test] - fn presence() { - let solid = get_solid(); - - assert_eq!(solid.get_raw_solid().as_raw_slice(), SOLID); - } - - const SOLID_SET: &[u8] = &[ - 112, 64, 113, 143, 130, 8, 128, 4, 6, 52, 214, 0, 243, 8, 193, 1, 30, 4, 2, 97, 4, 70, 192, - 12, 16, 144, 133, 36, 192, 41, 1, 4, 218, 179, 140, 0, 0, 140, 242, 35, 90, 56, 205, 179, - 64, 3, 25, 20, 226, 0, 32, 76, 1, 134, 48, 64, 7, 0, 192, 144, 98, 131, 2, 203, - ]; - - #[test] - fn set_value() { - let mut solid = get_solid(); - - solid.set(cocktail::kmer::seq2bit(b"GTTCT"), false); - solid.set(cocktail::kmer::seq2bit(b"AAATG"), false); - solid.set(cocktail::kmer::seq2bit(b"AGGAT"), false); - solid.set(cocktail::kmer::seq2bit(b"CTCAG"), false); - - assert_eq!(solid.get_raw_solid().as_raw_slice(), SOLID_SET); - } - - const FASTA_SOLID: &[u8] = &[ - 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 1, 65, 0, 190, 255, 5, 112, 64, 113, 143, 130, 8, 128, - 4, 6, 60, 214, 0, 243, 8, 193, 1, 30, 4, 34, 97, 4, 70, 192, 12, 16, 144, 133, 38, 192, 41, - 1, 4, 218, 179, 140, 0, 0, 140, 242, 35, 90, 56, 205, 179, 64, 3, 25, 20, 226, 0, 32, 76, - 1, 134, 48, 64, 7, 0, 200, 144, 98, 131, 2, 203, 186, 210, 139, 120, 65, 0, 0, 0, - ]; - - #[test] - fn serialize() { - let mut outfile = Vec::new(); - - let solid = get_solid(); - solid.serialize(&mut outfile).unwrap(); - - assert_eq!(&outfile[..], &FASTA_SOLID[..]); - } - - #[test] - fn deserialize() { - let solid = crate::solid::Solid::deserialize(&FASTA_SOLID[..]).unwrap(); - - assert_eq!(solid.k, 5); - assert_eq!(solid.get_raw_solid().as_raw_slice(), SOLID); - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::{anyhow, Context, Result}; -use log::Level; - -/* local use */ -use crate::error::*; - -#[derive(clap::Parser, Debug)] -#[clap( - version = "0.1", - author = "Pierre Marijon ", - about = "KMRF: Kmer based Read Filter" -)] -pub struct Command { - /// solidity bitfield produce by pcon - #[clap(short = 's', long = "solidity")] - pub solidity: Option, - - /// fasta file to be correct - #[clap(short = 'i', long = "inputs")] - pub inputs: Vec, - - /// path where corrected read was write - #[clap(short = 'o', long = "outputs")] - pub outputs: Vec, - - /// if you want choose the minimum abundance you can set this parameter - #[clap(short = 'a', long = "abundance")] - pub abundance: Option, - - /// if a ratio of correct kmer on all kmer is lower than this threshold read is filter out, default 0.8 - #[clap(short = 'r', long = "ratio")] - pub ratio: Option, - - /// if a read have length lower than this threshold read is filter out, default 1000 - #[clap(short = 'l', long = "min-length")] - pub length: Option, - - /// kmer length if you didn't provide solidity path you must give a kmer length - #[clap(short = 'k', long = "kmer")] - pub kmer: Option, - - /// Number of thread use by br, 0 use all avaible core, default value 0 - #[clap(short = 't', long = "threads")] - pub threads: Option, - - /// Number of sequence record load in buffer, default 8192 - #[clap(short = 'b', long = "record_buffer")] - pub record_buffer: Option, - - /// verbosity level also control by environment variable BR_LOG if flag is set BR_LOG value is ignored - #[clap(short = 'v', long = "verbosity", parse(from_occurrences))] - pub verbosity: i8, -} - -pub fn i82level(level: i8) -> Option { - match level { - std::i8::MIN..=0 => None, - 1 => Some(log::Level::Error), - 2 => Some(log::Level::Warn), - 3 => Some(log::Level::Info), - 4 => Some(log::Level::Debug), - 5..=std::i8::MAX => Some(log::Level::Trace), - } -} - -pub fn read_or_compute_solidity( - solidity_path: Option, - kmer: Option, - inputs: &[String], - record_buffer_len: usize, - abundance: Option, -) -> Result { - if let Some(solidity_path) = solidity_path { - let solidity_reader = std::io::BufReader::new( - std::fs::File::open(&solidity_path) - .with_context(|| Error::CantOpenFile) - .with_context(|| anyhow!("File {:?}", solidity_path.clone()))?, - ); - - log::info!("Load solidity file"); - Ok(pcon::solid::Solid::deserialize(solidity_reader)?) - } else if let Some(kmer) = kmer { - let mut counter = pcon::counter::Counter::new(kmer); - - log::info!("Start count kmer from input"); - for input in inputs { - let fasta = std::io::BufReader::new( - std::fs::File::open(&input) - .with_context(|| Error::CantOpenFile) - .with_context(|| anyhow!("File {:?}", input.clone()))?, - ); - - counter.count_fasta(fasta, record_buffer_len); - } - log::info!("End count kmer from input"); - - log::info!("Start build spectrum from count"); - let spectrum = pcon::spectrum::Spectrum::from_counter(&counter); - log::info!("End build spectrum from count"); - - let abun = if let Some(a) = abundance { - a - } else { - log::info!("Start search threshold"); - let abundance = spectrum - .get_threshold(pcon::spectrum::ThresholdMethod::FirstMinimum, 0.0) - .ok_or(Error::CantComputeAbundance)?; - - spectrum - .write_histogram(std::io::stdout(), Some(abundance)) - .with_context(|| anyhow!("Error durring write of kmer histograme"))?; - println!("If this curve seems bad or minimum abundance choose (marked by *) not apopriate set parameter -a"); - log::info!("End search threshold"); - abundance as u8 - }; - - Ok(pcon::solid::Solid::from_counter(&counter, abun)) - } else { - Err(anyhow!(Error::NoSolidityNoKmer)) - } -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use thiserror::Error; - -/// All error produce by Pcon -#[derive(Debug, Error)] -pub enum Error { - /// We can't create file. In C binding it's equal to 0 - #[error("We can't create file")] - CantCreateFile, - - /// We can't open file. In C binding it's equal to 1 - #[error("We can't open file")] - CantOpenFile, - - /// Error durring write in file. In C binding it's equal to 2 - #[error("Error durring write")] - ErrorDurringWrite, - - /// Error durring read file. In C binding it's equal to 3 - #[error("Error durring read")] - ErrorDurringRead, - - #[error("You must provide a solidity path '-s' or a kmer length '-k'")] - NoSolidityNoKmer, - - #[error("Can't compute minimal abundance")] - CantComputeAbundance, - - /// No error, this exist only for C binding it's the value of a new error pointer - #[error("Isn't error if you see this please contact the author with this message and a description of what you do with pcon")] - NoError, -} -/* -Copyright (c) 2019 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* crate use */ -use anyhow::Result; -use clap::Parser; - -use kmrf::*; - -fn main() -> Result<()> { - let params = cli::Command::parse(); - - if let Some(level) = cli::i82level(params.verbosity) { - env_logger::builder() - .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis)) - .filter_level(level.to_level_filter()) - .init(); - } else { - env_logger::Builder::from_env("KMRF_LOG") - .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis)) - .init(); - } - - let ratio = if let Some(val) = params.ratio { - val - } else { - 0.9 - }; - - let length = if let Some(val) = params.length { - val - } else { - 1000 - }; - - if let Some(threads) = params.threads { - log::info!("Set number of threads to {}", threads); - - set_nb_threads(threads); - } - - let record_buffer = if let Some(len) = params.record_buffer { - len - } else { - 8192 - }; - - let solid = cli::read_or_compute_solidity( - params.solidity, - params.kmer, - ¶ms.inputs, - record_buffer, - params.abundance, - )?; - - kmrf::run_filter( - params.inputs, - params.outputs, - solid, - ratio, - length, - record_buffer, - )?; - - Ok(()) -} -/* -Copyright (c) 2020 Pierre Marijon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - */ - -/* local mod */ -pub mod cli; -pub mod error; - -/* crates use */ -use anyhow::{anyhow, Context, Result}; -use rayon::iter::ParallelBridge; -use rayon::prelude::*; - -/* local use */ -use error::*; - -pub fn run_filter( - inputs: Vec, - outputs: Vec, - solid: pcon::solid::Solid, - ratio: f64, - length: usize, - record_buffer_len: usize, -) -> Result<()> { - for (input, output) in inputs.iter().zip(outputs) { - log::info!("Start filter {} write in {}", input, output); - - let mut reader = std::fs::File::open(input) - .with_context(|| Error::CantOpenFile) - .with_context(|| anyhow!("File {}", input.clone())) - .map(std::io::BufReader::new) - .map(noodles::fasta::Reader::new)?; - - let mut writer = std::fs::File::create(&output) - .with_context(|| Error::CantCreateFile) - .with_context(|| anyhow!("File {}", output.clone())) - .map(std::io::BufWriter::new) - .map(noodles::fasta::Writer::new)?; - - let mut iter = reader.records(); - let mut records = Vec::with_capacity(record_buffer_len); - - let mut end = false; - loop { - for _ in 0..record_buffer_len { - if let Some(Ok(record)) = iter.next() { - records.push(record); - } else { - end = true; - break; - } - } - - log::info!("Buffer len: {}", records.len()); - - let keeped: Vec<_> = records - .drain(..) - .par_bridge() - .filter_map(|record| { - let l = record.sequence().len(); - if l < length || l < solid.k as usize { - return None; - } - - let mut nb_kmer = 0; - let mut nb_valid = 0; - - for cano in - cocktail::tokenizer::Canonical::new(record.sequence().as_ref(), solid.k) - { - nb_kmer += 1; - - if solid.get_canonic(cano) { - nb_valid += 1; - } - } - - let r = (nb_valid as f64) / (nb_kmer as f64); - - if r >= ratio { - Some(record) - } else { - None - } - }) - .collect(); - - for record in keeped { - writer - .write_record(&record) - .with_context(|| Error::ErrorDurringWrite) - .with_context(|| anyhow!("File {}", output.clone()))? - } - - records.clear(); - - if end { - break; - } - } - log::info!("End filter file {} write in {}", input, output); - } - - Ok(()) -} - -/// Set the number of threads use by count step -pub fn set_nb_threads(nb_threads: usize) { - rayon::ThreadPoolBuilder::new() - .num_threads(nb_threads) - .build_global() - .unwrap(); -}