diff --git "a/RustBioGPT-train.csv" "b/RustBioGPT-train.csv" new file mode 100644--- /dev/null +++ "b/RustBioGPT-train.csv" @@ -0,0 +1,78 @@ +"repo_name","path","content","license" +"kmrf","./kmrf/src/cli.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse log::Level;\n\n/* local use */\nuse crate::error::*;\n\n#[derive(clap::Parser, Debug)]\n#[clap(\n version = '0.1',\n author = 'Pierre Marijon ',\n about = 'KMRF: Kmer based Read Filter'\n)]\npub struct Command {\n /// solidity bitfield produce by pcon\n #[clap(short = 's', long = 'solidity')]\n pub solidity: Option,\n\n /// fasta file to be correct\n #[clap(short = 'i', long = 'inputs')]\n pub inputs: Vec,\n\n /// path where corrected read was write\n #[clap(short = 'o', long = 'outputs')]\n pub outputs: Vec,\n\n /// if you want choose the minimum abundance you can set this parameter\n #[clap(short = 'a', long = 'abundance')]\n pub abundance: Option,\n\n /// if a ratio of correct kmer on all kmer is lower than this threshold read is filter out, default 0.8\n #[clap(short = 'r', long = 'ratio')]\n pub ratio: Option,\n\n /// if a read have length lower than this threshold read is filter out, default 1000\n #[clap(short = 'l', long = 'min-length')]\n pub length: Option,\n\n /// kmer length if you didn't provide solidity path you must give a kmer length\n #[clap(short = 'k', long = 'kmer')]\n pub kmer: Option,\n\n /// Number of thread use by br, 0 use all avaible core, default value 0\n #[clap(short = 't', long = 'threads')]\n pub threads: Option,\n\n /// Number of sequence record load in buffer, default 8192\n #[clap(short = 'b', long = 'record_buffer')]\n pub record_buffer: Option,\n\n /// verbosity level also control by environment variable BR_LOG if flag is set BR_LOG value is ignored\n #[clap(short = 'v', long = 'verbosity', parse(from_occurrences))]\n pub verbosity: i8,\n}\n\npub fn i82level(level: i8) -> Option {\n match level {\n std::i8::MIN..=0 => None,\n 1 => Some(log::Level::Error),\n 2 => Some(log::Level::Warn),\n 3 => Some(log::Level::Info),\n 4 => Some(log::Level::Debug),\n 5..=std::i8::MAX => Some(log::Level::Trace),\n }\n}\n\npub fn read_or_compute_solidity(\n solidity_path: Option,\n kmer: Option,\n inputs: &[String],\n record_buffer_len: usize,\n abundance: Option,\n) -> Result {\n if let Some(solidity_path) = solidity_path {\n let solidity_reader = std::io::BufReader::new(\n std::fs::File::open(&solidity_path)\n .with_context(|| Error::CantOpenFile)\n .with_context(|| anyhow!('File {:?}', solidity_path.clone()))?,\n );\n\n log::info!('Load solidity file');\n Ok(pcon::solid::Solid::deserialize(solidity_reader)?)\n } else if let Some(kmer) = kmer {\n let mut counter = pcon::counter::Counter::new(kmer);\n\n log::info!('Start count kmer from input');\n for input in inputs {\n let fasta = std::io::BufReader::new(\n std::fs::File::open(&input)\n .with_context(|| Error::CantOpenFile)\n .with_context(|| anyhow!('File {:?}', input.clone()))?,\n );\n\n counter.count_fasta(fasta, record_buffer_len);\n }\n log::info!('End count kmer from input');\n\n log::info!('Start build spectrum from count');\n let spectrum = pcon::spectrum::Spectrum::from_counter(&counter);\n log::info!('End build spectrum from count');\n\n let abun = if let Some(a) = abundance {\n a\n } else {\n log::info!('Start search threshold');\n let abundance = spectrum\n .get_threshold(pcon::spectrum::ThresholdMethod::FirstMinimum, 0.0)\n .ok_or(Error::CantComputeAbundance)?;\n\n spectrum\n .write_histogram(std::io::stdout(), Some(abundance))\n .with_context(|| anyhow!('Error durring write of kmer histograme'))?;\n println!('If this curve seems bad or minimum abundance choose (marked by *) not apopriate set parameter -a');\n log::info!('End search threshold');\n abundance as u8\n };\n\n Ok(pcon::solid::Solid::from_counter(&counter, abun))\n } else {\n Err(anyhow!(Error::NoSolidityNoKmer))\n }\n}\n","mit" +"kmrf","./kmrf/src/error.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse thiserror::Error;\n\n/// All error produce by Pcon\n#[derive(Debug, Error)]\npub enum Error {\n /// We can't create file. In C binding it's equal to 0\n #[error('We can't create file')]\n CantCreateFile,\n\n /// We can't open file. In C binding it's equal to 1\n #[error('We can't open file')]\n CantOpenFile,\n\n /// Error durring write in file. In C binding it's equal to 2\n #[error('Error durring write')]\n ErrorDurringWrite,\n\n /// Error durring read file. In C binding it's equal to 3\n #[error('Error durring read')]\n ErrorDurringRead,\n\n #[error('You must provide a solidity path '-s' or a kmer length '-k'')]\n NoSolidityNoKmer,\n\n #[error('Can't compute minimal abundance')]\n CantComputeAbundance,\n\n /// No error, this exist only for C binding it's the value of a new error pointer\n #[error('Isn't error if you see this please contact the author with this message and a description of what you do with pcon')]\n NoError,\n}\n","mit" +"kmrf","./kmrf/src/lib.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* local mod */\npub mod cli;\npub mod error;\n\n/* crates use */\nuse anyhow::{anyhow, Context, Result};\nuse rayon::iter::ParallelBridge;\nuse rayon::prelude::*;\n\n/* local use */\nuse error::*;\n\npub fn run_filter(\n inputs: Vec,\n outputs: Vec,\n solid: pcon::solid::Solid,\n ratio: f64,\n length: usize,\n record_buffer_len: usize,\n) -> Result<()> {\n for (input, output) in inputs.iter().zip(outputs) {\n log::info!('Start filter {} write in {}', input, output);\n\n let mut reader = std::fs::File::open(input)\n .with_context(|| Error::CantOpenFile)\n .with_context(|| anyhow!('File {}', input.clone()))\n .map(std::io::BufReader::new)\n .map(noodles::fasta::Reader::new)?;\n\n let mut writer = std::fs::File::create(&output)\n .with_context(|| Error::CantCreateFile)\n .with_context(|| anyhow!('File {}', output.clone()))\n .map(std::io::BufWriter::new)\n .map(noodles::fasta::Writer::new)?;\n\n let mut iter = reader.records();\n let mut records = Vec::with_capacity(record_buffer_len);\n\n let mut end = false;\n loop {\n for _ in 0..record_buffer_len {\n if let Some(Ok(record)) = iter.next() {\n records.push(record);\n } else {\n end = true;\n break;\n }\n }\n\n log::info!('Buffer len: {}', records.len());\n\n let keeped: Vec<_> = records\n .drain(..)\n .par_bridge()\n .filter_map(|record| {\n let l = record.sequence().len();\n if l < length || l < solid.k as usize {\n return None;\n }\n\n let mut nb_kmer = 0;\n let mut nb_valid = 0;\n\n for cano in\n cocktail::tokenizer::Canonical::new(record.sequence().as_ref(), solid.k)\n {\n nb_kmer += 1;\n\n if solid.get_canonic(cano) {\n nb_valid += 1;\n }\n }\n\n let r = (nb_valid as f64) / (nb_kmer as f64);\n\n if r >= ratio {\n Some(record)\n } else {\n None\n }\n })\n .collect();\n\n for record in keeped {\n writer\n .write_record(&record)\n .with_context(|| Error::ErrorDurringWrite)\n .with_context(|| anyhow!('File {}', output.clone()))?\n }\n\n records.clear();\n\n if end {\n break;\n }\n }\n log::info!('End filter file {} write in {}', input, output);\n }\n\n Ok(())\n}\n\n/// Set the number of threads use by count step\npub fn set_nb_threads(nb_threads: usize) {\n rayon::ThreadPoolBuilder::new()\n .num_threads(nb_threads)\n .build_global()\n .unwrap();\n}\n","mit" +"kmrf","./kmrf/src/main.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::Result;\nuse clap::Parser;\n\nuse kmrf::*;\n\nfn main() -> Result<()> {\n let params = cli::Command::parse();\n\n if let Some(level) = cli::i82level(params.verbosity) {\n env_logger::builder()\n .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis))\n .filter_level(level.to_level_filter())\n .init();\n } else {\n env_logger::Builder::from_env('KMRF_LOG')\n .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis))\n .init();\n }\n\n let ratio = if let Some(val) = params.ratio {\n val\n } else {\n 0.9\n };\n\n let length = if let Some(val) = params.length {\n val\n } else {\n 1000\n };\n\n if let Some(threads) = params.threads {\n log::info!('Set number of threads to {}', threads);\n\n set_nb_threads(threads);\n }\n\n let record_buffer = if let Some(len) = params.record_buffer {\n len\n } else {\n 8192\n };\n\n let solid = cli::read_or_compute_solidity(\n params.solidity,\n params.kmer,\n ¶ms.inputs,\n record_buffer,\n params.abundance,\n )?;\n\n kmrf::run_filter(\n params.inputs,\n params.outputs,\n solid,\n ratio,\n length,\n record_buffer,\n )?;\n\n Ok(())\n}\n","mit" +"yacrd","./yacrd/tests/run.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* std use */\nuse std::io::BufRead;\nuse std::io::Read;\nuse std::process::{Command, Stdio};\n\n#[cfg(test)]\nmod tests {\n\n use super::*;\n\n fn diff_unorder(truth_path: &str, result_path: &str) {\n let truth_file = std::io::BufReader::new(\n std::fs::File::open(truth_path).expect(&format!('Impossible to open {}', truth_path)),\n );\n\n let mut truth: std::collections::HashSet = std::collections::HashSet::new();\n\n for res in truth_file.lines() {\n let line = res.unwrap();\n truth.insert(line);\n }\n\n let result_file = std::io::BufReader::new(\n std::fs::File::open(result_path).expect(&format!('Impossible to open {}', result_path)),\n );\n\n let mut result: std::collections::HashSet = std::collections::HashSet::new();\n\n for res in result_file.lines() {\n let line = res.unwrap();\n result.insert(line);\n }\n\n if truth != result {\n panic!(\n 'Truth {} and result {} are different',\n truth_path, result_path\n );\n }\n }\n\n fn diff(truth_path: &str, result_path: &str) {\n let truth_file = std::io::BufReader::new(\n std::fs::File::open(truth_path).expect(&format!('Impossible to open {}', truth_path)),\n );\n\n let mut truth: Vec = Vec::new();\n\n for res in truth_file.lines() {\n let line = res.unwrap();\n truth.push(line);\n }\n\n let result_file = std::io::BufReader::new(\n std::fs::File::open(result_path).expect(&format!('Impossible to open {}', result_path)),\n );\n\n let mut result: Vec = Vec::new();\n\n for res in result_file.lines() {\n let line = res.unwrap();\n result.push(line);\n }\n\n if truth != result {\n panic!(\n 'Truth {} and result {} are different',\n truth_path, result_path\n );\n }\n }\n\n #[test]\n fn detection() {\n let mut child = Command::new('./target/debug/yacrd')\n .args(&['-i', 'tests/reads.paf', '-o', 'tests/result.yacrd'])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create yacrd subprocess');\n\n if !child.wait().expect('Error durring yacrd run').success() {\n let mut stdout = String::new();\n let mut stderr = String::new();\n\n child.stdout.unwrap().read_to_string(&mut stdout).unwrap();\n child.stderr.unwrap().read_to_string(&mut stderr).unwrap();\n\n println!('stdout: {}', stdout);\n println!('stderr: {}', stderr);\n panic!();\n }\n\n diff_unorder('tests/truth.yacrd', 'tests/result.yacrd');\n }\n\n #[test]\n fn detection_ondisk() {\n if cfg!(windows) {\n ()\n } else {\n if std::path::Path::new('tests/ondisk').exists() {\n std::fs::remove_dir_all(std::path::Path::new('tests/ondisk'))\n .expect('We can't delete temporary directory of ondisk test');\n }\n\n std::fs::create_dir(std::path::Path::new('tests/ondisk'))\n .expect('We can't create temporary directory for ondisk test');\n\n let mut child = Command::new('./target/debug/yacrd')\n .args(&[\n '-i',\n 'tests/reads.paf',\n '-o',\n 'tests/result.ondisk.yacrd',\n '-d',\n 'tests/ondisk',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create yacrd subprocess');\n\n if !child.wait().expect('Error durring yacrd run').success() {\n let mut stdout = String::new();\n let mut stderr = String::new();\n\n child.stdout.unwrap().read_to_string(&mut stdout).unwrap();\n child.stderr.unwrap().read_to_string(&mut stderr).unwrap();\n\n println!('stdout: {}', stdout);\n println!('stderr: {}', stderr);\n panic!();\n }\n\n diff_unorder('tests/truth.yacrd', 'tests/result.ondisk.yacrd');\n }\n }\n\n #[test]\n fn filter() {\n let mut child = Command::new('./target/debug/yacrd')\n .args(&[\n '-i',\n 'tests/reads.paf',\n '-o',\n 'tests/result.filter.yacrd',\n 'filter',\n '-i',\n 'tests/reads.fastq',\n '-o',\n 'tests/reads.filter.fastq',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create yacrd subprocess');\n\n if !child.wait().expect('Error durring yacrd run').success() {\n let mut stdout = String::new();\n let mut stderr = String::new();\n\n child.stdout.unwrap().read_to_string(&mut stdout).unwrap();\n child.stderr.unwrap().read_to_string(&mut stderr).unwrap();\n\n println!('stdout: {}', stdout);\n println!('stderr: {}', stderr);\n panic!();\n }\n\n diff_unorder('tests/truth.yacrd', 'tests/result.filter.yacrd');\n diff('tests/truth.filter.fastq', 'tests/reads.filter.fastq')\n }\n\n #[test]\n fn extract() {\n let mut child = Command::new('./target/debug/yacrd')\n .args(&[\n '-i',\n 'tests/reads.paf',\n '-o',\n 'tests/result.extract.yacrd',\n 'extract',\n '-i',\n 'tests/reads.fastq',\n '-o',\n 'tests/reads.extract.fastq',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create yacrd subprocess');\n\n if !child.wait().expect('Error durring yacrd run').success() {\n let mut stdout = String::new();\n let mut stderr = String::new();\n\n child.stdout.unwrap().read_to_string(&mut stdout).unwrap();\n child.stderr.unwrap().read_to_string(&mut stderr).unwrap();\n\n println!('stdout: {}', stdout);\n println!('stderr: {}', stderr);\n panic!();\n }\n\n diff_unorder('tests/truth.yacrd', 'tests/result.extract.yacrd');\n diff('tests/truth.extract.fastq', 'tests/reads.extract.fastq')\n }\n\n #[test]\n fn split() {\n let mut child = Command::new('./target/debug/yacrd')\n .args(&[\n '-i',\n 'tests/reads.paf',\n '-o',\n 'tests/result.split.yacrd',\n 'split',\n '-i',\n 'tests/reads.fastq',\n '-o',\n 'tests/reads.split.fastq',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create yacrd subprocess');\n\n if !child.wait().expect('Error durring yacrd run').success() {\n let mut stdout = String::new();\n let mut stderr = String::new();\n\n child.stdout.unwrap().read_to_string(&mut stdout).unwrap();\n child.stderr.unwrap().read_to_string(&mut stderr).unwrap();\n\n println!('stdout: {}', stdout);\n println!('stderr: {}', stderr);\n panic!();\n }\n\n diff_unorder('tests/truth.yacrd', 'tests/result.split.yacrd');\n diff('tests/truth.split.fastq', 'tests/reads.split.fastq')\n }\n\n #[test]\n fn scrubb() {\n let mut child = Command::new('./target/debug/yacrd')\n .args(&[\n '-i',\n 'tests/reads.paf',\n '-o',\n 'tests/result.scrubb.yacrd',\n 'scrubb',\n '-i',\n 'tests/reads.fastq',\n '-o',\n 'tests/reads.scrubb.fastq',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create yacrd subprocess');\n\n if !child.wait().expect('Error durring yacrd run').success() {\n let mut stdout = String::new();\n let mut stderr = String::new();\n\n child.stdout.unwrap().read_to_string(&mut stdout).unwrap();\n child.stderr.unwrap().read_to_string(&mut stderr).unwrap();\n\n println!('stdout: {}', stdout);\n println!('stderr: {}', stderr);\n panic!();\n }\n\n diff_unorder('tests/truth.yacrd', 'tests/result.scrubb.yacrd');\n diff('tests/truth.scrubb.fastq', 'tests/reads.scrubb.fastq')\n }\n}\n","mit" +"yacrd","./yacrd/src/reads2ovl/fullmemory.rs","/*\n Copyright (c) 2019 Pierre Marijon \n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the 'Software'), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n/* crate use */\nuse anyhow::Result;\n\n/* local use */\nuse crate::reads2ovl;\n\npub struct FullMemory {\n reads2ovl: reads2ovl::MapReads2Ovl,\n no_overlap: Vec<(u32, u32)>,\n read_buffer_size: usize,\n}\n\nimpl FullMemory {\n pub fn new(read_buffer_size: usize) -> Self {\n FullMemory {\n reads2ovl: rustc_hash::FxHashMap::default(),\n no_overlap: Vec::new(),\n read_buffer_size,\n }\n }\n}\n\nimpl reads2ovl::Reads2Ovl for FullMemory {\n fn get_overlaps(&mut self, new: &mut reads2ovl::MapReads2Ovl) -> bool {\n std::mem::swap(&mut self.reads2ovl, new);\n\n true\n }\n\n fn overlap(&self, id: &str) -> Result> {\n if let Some((vec, _)) = self.reads2ovl.get(&id.to_string()) {\n Ok(vec.to_vec())\n } else {\n Ok(self.no_overlap.to_vec())\n }\n }\n\n fn length(&self, id: &str) -> usize {\n if let Some((_, len)) = self.reads2ovl.get(&id.to_string()) {\n *len\n } else {\n 0\n }\n }\n\n fn add_overlap(&mut self, id: String, ovl: (u32, u32)) -> Result<()> {\n self.reads2ovl\n .entry(id)\n .or_insert((Vec::new(), 0))\n .0\n .push(ovl);\n\n Ok(())\n }\n\n fn add_length(&mut self, id: String, length: usize) {\n self.reads2ovl.entry(id).or_insert((Vec::new(), 0)).1 = length;\n }\n\n fn add_overlap_and_length(&mut self, id: String, ovl: (u32, u32), length: usize) -> Result<()> {\n if let Some(value) = self.reads2ovl.get_mut(&id) {\n value.0.push(ovl);\n } else {\n self.reads2ovl.insert(id, (vec![ovl], length));\n }\n\n Ok(())\n }\n\n fn get_reads(&self) -> rustc_hash::FxHashSet {\n self.reads2ovl.keys().map(|x| x.to_string()).collect()\n }\n\n fn read_buffer_size(&self) -> usize {\n self.read_buffer_size\n }\n}\n","mit" +"yacrd","./yacrd/src/reads2ovl/mod.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, bail, Context, Result};\n\n/* local mod */\npub mod fullmemory;\npub mod ondisk;\n\n/* stuff declare in submod need to be accessible from mod level */\npub use self::fullmemory::*;\npub use self::ondisk::*;\n\n/* std use */\npub use self::fullmemory::*;\n\n/* local use */\nuse crate::error;\nuse crate::io;\nuse crate::util;\n\npub type MapReads2Ovl = rustc_hash::FxHashMap, usize)>;\n\npub trait Reads2Ovl {\n fn init(&mut self, filename: &str) -> Result<()> {\n self.sub_init(filename)\n }\n\n fn sub_init(&mut self, filename: &str) -> Result<()> {\n let (input, _) = util::read_file(filename, self.read_buffer_size())?;\n\n match util::get_file_type(filename) {\n Some(util::FileType::Paf) => self\n .init_paf(input)\n .with_context(|| anyhow!('Filename: {}', filename.to_string()))?,\n Some(util::FileType::M4) => self\n .init_m4(input)\n .with_context(|| anyhow!('Filename: {}', filename.to_string()))?,\n Some(util::FileType::Fasta) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'overlap parsing'.to_string(),\n filetype: util::FileType::Fasta,\n filename: filename.to_string()\n }),\n Some(util::FileType::Fastq) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'overlap parsing'.to_string(),\n filetype: util::FileType::Fastq,\n filename: filename.to_string()\n }),\n Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'overlap parsing'.to_string(),\n filetype: util::FileType::Yacrd,\n filename: filename.to_string()\n }),\n None | Some(util::FileType::YacrdOverlap) => {\n bail!(error::Error::UnableToDetectFileFormat {\n filename: filename.to_string()\n })\n }\n }\n\n Ok(())\n }\n\n fn init_paf(&mut self, input: Box) -> Result<()> {\n let mut reader = csv::ReaderBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .flexible(true)\n .from_reader(input);\n\n let mut rec = csv::StringRecord::new();\n\n while reader.read_record(&mut rec).unwrap() {\n let record: io::PafRecord =\n rec.deserialize(None)\n .with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Paf,\n })?;\n\n let id_a = record.read_a.to_string();\n let id_b = record.read_b.to_string();\n\n let len_a = record.length_a;\n let len_b = record.length_b;\n\n let ovl_a = (record.begin_a, record.end_a);\n let ovl_b = (record.begin_b, record.end_b);\n\n self.add_overlap_and_length(id_a, ovl_a, len_a)?;\n self.add_overlap_and_length(id_b, ovl_b, len_b)?;\n }\n\n Ok(())\n }\n\n fn init_m4(&mut self, input: Box) -> Result<()> {\n let mut reader = csv::ReaderBuilder::new()\n .delimiter(b' ')\n .has_headers(false)\n .flexible(true)\n .from_reader(input);\n\n let mut rec = csv::StringRecord::new();\n\n while reader.read_record(&mut rec).unwrap() {\n let record: io::M4Record =\n rec.deserialize(None)\n .with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::M4,\n })?;\n\n let id_a = record.read_a.to_string();\n let id_b = record.read_b.to_string();\n\n let len_a = record.length_a;\n let len_b = record.length_b;\n\n let ovl_a = (record.begin_a, record.end_a);\n let ovl_b = (record.begin_b, record.end_b);\n\n self.add_overlap_and_length(id_a, ovl_a, len_a)?;\n self.add_overlap_and_length(id_b, ovl_b, len_b)?;\n }\n\n Ok(())\n }\n\n fn get_overlaps(&mut self, new: &mut MapReads2Ovl) -> bool;\n\n fn overlap(&self, id: &str) -> Result>;\n fn length(&self, id: &str) -> usize;\n\n fn add_overlap(&mut self, id: String, ovl: (u32, u32)) -> Result<()>;\n fn add_length(&mut self, id: String, ovl: usize);\n\n fn add_overlap_and_length(&mut self, id: String, ovl: (u32, u32), length: usize) -> Result<()>;\n\n fn get_reads(&self) -> rustc_hash::FxHashSet;\n\n fn read_buffer_size(&self) -> usize;\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use std::io::Write;\n\n extern crate tempfile;\n\n const PAF_FILE: &'static [u8] = b'1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255\n1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255\n';\n\n const M4_FILE: &'static [u8] = b'1 2 0.1 2 0 20 4500 12000 0 5500 10000 10000\n1 3 0.1 2 0 5500 10000 12000 0 0 4500 10000\n';\n\n #[test]\n fn paf() {\n let mut paf = tempfile::Builder::new()\n .suffix('.paf')\n .tempfile()\n .expect('Can't create tmpfile');\n\n paf.as_file_mut()\n .write_all(PAF_FILE)\n .expect('Error durring write of paf in temp file');\n\n let mut ovl = FullMemory::new(8192);\n\n ovl.init(paf.into_temp_path().to_str().unwrap())\n .expect('Error in overlap init');\n\n assert_eq!(\n ['1'.to_string(), '2'.to_string(), '3'.to_string(),]\n .iter()\n .cloned()\n .collect::>(),\n ovl.get_reads()\n );\n\n assert_eq!(vec![(20, 4500), (5500, 10000)], ovl.overlap('1').unwrap());\n assert_eq!(vec![(5500, 10000)], ovl.overlap('2').unwrap());\n assert_eq!(vec![(0, 4500)], ovl.overlap('3').unwrap());\n }\n\n #[test]\n fn m4() {\n let mut m4 = tempfile::Builder::new()\n .suffix('.m4')\n .tempfile()\n .expect('Can't create tmpfile');\n\n m4.as_file_mut()\n .write_all(M4_FILE)\n .expect('Error durring write of m4 in temp file');\n\n let mut ovl = FullMemory::new(8192);\n\n ovl.init(m4.into_temp_path().to_str().unwrap())\n .expect('Error in overlap init');\n\n assert_eq!(\n ['1'.to_string(), '2'.to_string(), '3'.to_string(),]\n .iter()\n .cloned()\n .collect::>(),\n ovl.get_reads()\n );\n\n assert_eq!(vec![(20, 4500), (5500, 10000)], ovl.overlap('1').unwrap());\n assert_eq!(vec![(5500, 10000)], ovl.overlap('2').unwrap());\n assert_eq!(vec![(0, 4500)], ovl.overlap('3').unwrap());\n }\n}\n","mit" +"yacrd","./yacrd/src/reads2ovl/ondisk.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse log::info;\n\n/* local use */\nuse crate::error;\nuse crate::reads2ovl;\n\npub struct OnDisk {\n reads2ovl: rustc_hash::FxHashMap>,\n reads2len: rustc_hash::FxHashMap,\n db: sled::Db,\n number_of_value: u64,\n buffer_size: u64,\n read_buffer_size: usize,\n}\n\n#[derive(Debug, Clone, serde::Deserialize)]\nstruct OnDiskRecord {\n _begin: u32,\n _end: u32,\n}\n\nimpl OnDisk {\n pub fn new(on_disk_path: String, buffer_size: u64, read_buffer_size: usize) -> Self {\n let path = std::path::PathBuf::from(on_disk_path.clone());\n\n if let Some(parent) = path.parent() {\n std::fs::create_dir_all(parent)\n .with_context(|| error::Error::PathCreation { path })\n .unwrap();\n }\n\n let db = sled::Config::default()\n .path(on_disk_path)\n .open()\n .with_context(|| error::Error::OnDiskOpen)\n .unwrap();\n\n OnDisk {\n reads2ovl: rustc_hash::FxHashMap::default(),\n reads2len: rustc_hash::FxHashMap::default(),\n db,\n number_of_value: 0,\n buffer_size,\n read_buffer_size,\n }\n }\n\n fn clean_buffer(&mut self) -> Result<()> {\n info!(\n 'Clear cache, number of value in cache is {}',\n self.number_of_value\n );\n\n let mut batch = sled::Batch::default();\n\n for (key, vs) in self.reads2ovl.drain() {\n let new_val: Vec<(u32, u32)> = match self\n .db\n .get(key.as_bytes())\n .with_context(|| error::Error::OnDiskReadDatabase)?\n {\n Some(x) => {\n let mut orig: Vec<(u32, u32)> = bincode::deserialize(&x)\n .with_context(|| error::Error::OnDiskDeserializeVec)?;\n orig.extend(vs);\n orig\n }\n None => vs.to_vec(),\n };\n\n batch.insert(\n key.as_bytes(),\n bincode::serialize(&new_val).with_context(|| error::Error::OnDiskSerializeVec)?,\n );\n }\n\n self.db\n .apply_batch(batch)\n .with_context(|| error::Error::OnDiskBatchApplication)?;\n\n self.db\n .flush()\n .with_context(|| error::Error::OnDiskBatchApplication)?;\n\n self.number_of_value = 0;\n\n Ok(())\n }\n\n fn _overlap(&self, id: &str) -> Result> {\n bincode::deserialize(\n &self\n .db\n .get(id.as_bytes())\n .with_context(|| error::Error::OnDiskReadDatabase)?\n .unwrap(),\n )\n .with_context(|| error::Error::OnDiskDeserializeVec)\n }\n}\n\nimpl reads2ovl::Reads2Ovl for OnDisk {\n fn init(&mut self, filename: &str) -> Result<()> {\n self.sub_init(filename)?;\n\n self.clean_buffer()\n .with_context(|| anyhow!('Error durring creation of tempory file'))?;\n self.number_of_value = 0;\n\n Ok(())\n }\n\n fn get_overlaps(&mut self, new: &mut reads2ovl::MapReads2Ovl) -> bool {\n let mut tmp = rustc_hash::FxHashMap::default();\n\n if self.reads2len.is_empty() {\n std::mem::swap(&mut tmp, new);\n return true;\n }\n\n let mut remove_reads = Vec::with_capacity(self.buffer_size as usize);\n\n for (k, v) in self.reads2len.iter().take(self.buffer_size as usize) {\n remove_reads.push(k.clone());\n tmp.insert(k.clone(), (self._overlap(k).unwrap(), *v));\n }\n\n for k in remove_reads {\n self.reads2len.remove(&k);\n }\n\n std::mem::swap(&mut tmp, new);\n false\n }\n\n fn overlap(&self, id: &str) -> Result> {\n self._overlap(id)\n }\n\n fn length(&self, id: &str) -> usize {\n *self.reads2len.get(&id.to_string()).unwrap_or(&0)\n }\n\n fn add_overlap(&mut self, id: String, ovl: (u32, u32)) -> Result<()> {\n self.reads2ovl.entry(id).or_insert_with(Vec::new).push(ovl);\n\n self.number_of_value += 1;\n\n if self.number_of_value >= self.buffer_size {\n self.clean_buffer()?;\n }\n\n Ok(())\n }\n\n fn add_length(&mut self, id: String, length: usize) {\n self.reads2len.entry(id).or_insert(length);\n }\n\n fn add_overlap_and_length(&mut self, id: String, ovl: (u32, u32), length: usize) -> Result<()> {\n self.add_length(id.clone(), length);\n\n self.add_overlap(id, ovl)\n }\n\n fn get_reads(&self) -> rustc_hash::FxHashSet {\n self.reads2len.keys().map(|x| x.to_string()).collect()\n }\n\n fn read_buffer_size(&self) -> usize {\n self.read_buffer_size\n }\n}\n","mit" +"yacrd","./yacrd/src/stack.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* std use */\nuse std::cmp::Reverse;\n\n/* crate use */\nuse anyhow::{Context, Result};\nuse rayon::prelude::*;\n\n/* local use */\nuse crate::error;\nuse crate::reads2ovl;\nuse crate::util;\n\npub trait BadPart {\n fn compute_all_bad_part(&mut self);\n\n fn get_bad_part(&mut self, id: &str) -> Result<&(Vec<(u32, u32)>, usize)>;\n\n fn get_reads(&self) -> rustc_hash::FxHashSet;\n}\n\npub struct FromOverlap {\n ovl: Box,\n coverage: u64,\n buffer: reads2ovl::MapReads2Ovl,\n empty: (Vec<(u32, u32)>, usize),\n}\n\nimpl FromOverlap {\n pub fn new(ovl: Box, coverage: u64) -> Self {\n let empty = (Vec::new(), 0);\n FromOverlap {\n ovl,\n coverage,\n buffer: rustc_hash::FxHashMap::default(),\n empty,\n }\n }\n\n fn compute_bad_part(mut ovls: Vec<(u32, u32)>, len: usize, coverage: usize) -> Vec<(u32, u32)> {\n let mut gaps: Vec<(u32, u32)> = Vec::new();\n let mut stack: std::collections::BinaryHeap> =\n std::collections::BinaryHeap::new();\n\n ovls.sort_unstable();\n\n let mut first_covered = 0;\n let mut last_covered = 0;\n\n for interval in ovls {\n while let Some(head) = stack.peek() {\n if head.0 > interval.0 {\n break;\n }\n\n if stack.len() > coverage {\n last_covered = head.0;\n }\n stack.pop();\n }\n\n if stack.len() <= coverage {\n if last_covered != 0 {\n gaps.push((last_covered, interval.0));\n } else {\n first_covered = interval.0;\n }\n }\n stack.push(Reverse(interval.1));\n }\n\n while stack.len() > coverage {\n last_covered = stack\n .peek()\n .with_context(|| error::Error::NotReachableCode {\n name: format!('{} {}', file!(), line!()),\n })\n .unwrap()\n .0;\n if last_covered as usize >= len {\n break;\n }\n stack.pop();\n }\n\n if first_covered != 0 {\n gaps.insert(0, (0, first_covered));\n }\n\n if last_covered as usize != len {\n gaps.push((last_covered, len as u32));\n }\n\n if gaps.is_empty() {\n return gaps;\n }\n\n /* clean overlapped bad region */\n let mut clean_gaps: Vec<(u32, u32)> = Vec::new();\n let mut begin = gaps[0].0;\n let mut end = gaps[0].1;\n for gaps in gaps.windows(2) {\n let g1 = gaps[0];\n let g2 = gaps[1];\n\n if g1.0 == g2.0 {\n begin = g1.0;\n end = g1.1.max(g2.1);\n } else {\n clean_gaps.push((begin, end));\n begin = g2.0;\n end = g2.1;\n }\n }\n clean_gaps.push((begin, end));\n\n clean_gaps\n }\n}\n\nimpl BadPart for FromOverlap {\n fn compute_all_bad_part(&mut self) {\n let mut new = rustc_hash::FxHashMap::default();\n\n let coverage = self.coverage as usize;\n\n loop {\n let finish = self.ovl.get_overlaps(&mut new);\n\n self.buffer.extend(\n new.drain()\n .par_bridge()\n .map(|(k, v)| (k, (FromOverlap::compute_bad_part(v.0, v.1, coverage), v.1)))\n .collect::(),\n );\n\n if finish {\n break;\n }\n }\n }\n\n fn get_bad_part(&mut self, id: &str) -> Result<&(Vec<(u32, u32)>, usize)> {\n match self.buffer.get(id) {\n Some(v) => Ok(v),\n None => Ok(&self.empty),\n }\n }\n\n fn get_reads(&self) -> rustc_hash::FxHashSet {\n self.buffer.keys().map(|x| x.to_string()).collect()\n }\n}\n\npub struct FromReport {\n buffer: reads2ovl::MapReads2Ovl,\n empty: (Vec<(u32, u32)>, usize),\n}\n\nimpl FromReport {\n pub fn new(input_path: &str) -> Result {\n let input =\n std::io::BufReader::new(std::fs::File::open(input_path).with_context(|| {\n error::Error::CantReadFile {\n filename: input_path.to_string(),\n }\n })?);\n let mut reader = csv::ReaderBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .from_reader(input);\n\n let mut buffer = rustc_hash::FxHashMap::default();\n for (line, record) in reader.records().enumerate() {\n let result = record.with_context(|| error::Error::Reading {\n filename: input_path.to_string(),\n format: util::FileType::Fasta,\n })?;\n\n let id = result[1].to_string();\n let len = util::str2usize(&result[2])?;\n let bad_part = FromReport::parse_bad_string(&result[3]).with_context(|| {\n error::Error::CorruptYacrdReport {\n name: input_path.to_string(),\n line,\n }\n })?;\n\n buffer.insert(id, (bad_part, len));\n }\n\n let empty = (Vec::new(), 0);\n Ok(FromReport { buffer, empty })\n }\n\n fn parse_bad_string(bad_string: &str) -> Result> {\n let mut ret = Vec::new();\n\n if bad_string.is_empty() {\n return Ok(ret);\n }\n\n for sub in bad_string.split(';') {\n let mut iter = sub.split(',');\n iter.next();\n\n ret.push((\n util::str2u32(\n iter.next()\n .with_context(|| error::Error::CorruptYacrdReportInPosition)?,\n )?,\n util::str2u32(\n iter.next()\n .with_context(|| error::Error::CorruptYacrdReportInPosition)?,\n )?,\n ));\n }\n\n Ok(ret)\n }\n}\n\nimpl BadPart for FromReport {\n fn compute_all_bad_part(&mut self) {}\n\n fn get_bad_part(&mut self, id: &str) -> Result<&(Vec<(u32, u32)>, usize)> {\n match self.buffer.get(id) {\n Some(v) => Ok(v),\n None => Ok(&self.empty),\n }\n }\n\n fn get_reads(&self) -> rustc_hash::FxHashSet {\n self.buffer.keys().map(|x| x.to_string()).collect()\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use std::io::Write;\n\n extern crate tempfile;\n use self::tempfile::NamedTempFile;\n\n use reads2ovl::Reads2Ovl;\n\n #[test]\n fn from_report() {\n let mut report = NamedTempFile::new().expect('Can't create tmpfile');\n\n writeln!(\n report.as_file_mut(),\n 'NotBad SRR8494940.65223 2706 1131,0,1131;16,2690,2706\nNotCovered SRR8494940.141626 30116 326,0,326;27159,2957,30116\nChimeric SRR8494940.91655 15691 151,0,151;4056,7213,11269;58,15633,15691'\n )\n .expect('Error durring write of report in temp file');\n\n let mut stack = FromReport::new(report.into_temp_path().to_str().unwrap())\n .expect('Error when create stack object');\n\n assert_eq!(\n [\n 'SRR8494940.65223'.to_string(),\n 'SRR8494940.141626'.to_string(),\n 'SRR8494940.91655'.to_string()\n ]\n .iter()\n .cloned()\n .collect::>(),\n stack.get_reads()\n );\n\n assert_eq!(\n &(vec![(0, 1131), (2690, 2706)], 2706),\n stack.get_bad_part('SRR8494940.65223').unwrap()\n );\n assert_eq!(\n &(vec![(0, 326), (2957, 30116)], 30116),\n stack.get_bad_part('SRR8494940.141626').unwrap()\n );\n assert_eq!(\n &(vec![(0, 151), (7213, 11269), (15633, 15691)], 15691),\n stack.get_bad_part('SRR8494940.91655').unwrap()\n );\n }\n\n #[test]\n fn from_overlap() {\n let mut ovl = reads2ovl::FullMemory::new(8192);\n\n ovl.add_overlap('A'.to_string(), (10, 990)).unwrap();\n ovl.add_length('A'.to_string(), 1000);\n\n ovl.add_overlap('B'.to_string(), (10, 90)).unwrap();\n ovl.add_length('B'.to_string(), 1000);\n\n ovl.add_overlap('C'.to_string(), (10, 490)).unwrap();\n ovl.add_overlap('C'.to_string(), (510, 990)).unwrap();\n ovl.add_length('C'.to_string(), 1000);\n\n ovl.add_overlap('D'.to_string(), (0, 990)).unwrap();\n ovl.add_length('D'.to_string(), 1000);\n\n ovl.add_overlap('E'.to_string(), (10, 1000)).unwrap();\n ovl.add_length('E'.to_string(), 1000);\n\n ovl.add_overlap('F'.to_string(), (0, 490)).unwrap();\n ovl.add_overlap('F'.to_string(), (510, 1000)).unwrap();\n ovl.add_length('F'.to_string(), 1000);\n\n let mut stack = FromOverlap::new(Box::new(ovl), 0);\n\n stack.compute_all_bad_part();\n\n assert_eq!(\n [\n 'A'.to_string(),\n 'B'.to_string(),\n 'C'.to_string(),\n 'D'.to_string(),\n 'E'.to_string(),\n 'F'.to_string()\n ]\n .iter()\n .cloned()\n .collect::>(),\n stack.get_reads()\n );\n\n assert_eq!(\n &(vec![(0, 10), (990, 1000)], 1000),\n stack.get_bad_part('A').unwrap()\n );\n assert_eq!(\n &(vec![(0, 10), (90, 1000)], 1000),\n stack.get_bad_part('B').unwrap()\n );\n assert_eq!(\n &(vec![(0, 10), (490, 510), (990, 1000)], 1000),\n stack.get_bad_part('C').unwrap()\n );\n assert_eq!(&(vec![(990, 1000)], 1000), stack.get_bad_part('D').unwrap());\n assert_eq!(&(vec![(0, 10)], 1000), stack.get_bad_part('E').unwrap());\n assert_eq!(&(vec![(490, 510)], 1000), stack.get_bad_part('F').unwrap());\n }\n\n #[test]\n fn coverage_upper_than_0() {\n let mut ovl = reads2ovl::FullMemory::new(8192);\n\n ovl.add_length('A'.to_string(), 1000);\n\n ovl.add_overlap('A'.to_string(), (0, 425)).unwrap();\n ovl.add_overlap('A'.to_string(), (0, 450)).unwrap();\n ovl.add_overlap('A'.to_string(), (0, 475)).unwrap();\n\n ovl.add_overlap('A'.to_string(), (525, 1000)).unwrap();\n ovl.add_overlap('A'.to_string(), (550, 1000)).unwrap();\n ovl.add_overlap('A'.to_string(), (575, 1000)).unwrap();\n\n let mut stack = FromOverlap::new(Box::new(ovl), 2);\n\n stack.compute_all_bad_part();\n\n assert_eq!(&(vec![(425, 575)], 1000), stack.get_bad_part('A').unwrap());\n }\n\n #[test]\n fn failled_correctly_on_corrupt_yacrd() {\n let mut report = NamedTempFile::new().expect('Can't create tmpfile');\n\n writeln!(\n report.as_file_mut(),\n 'NotBad SRR8494940.65223 2706 1131,0,1131;16,2690,2706\nNotCovered SRR8494940.141626 30116 326,0,326;27159,2957,30116\nChimeric SRR8494940.91655 15691 151,0,151;4056,7213,11269;58,156'\n )\n .unwrap();\n\n let stack = FromReport::new(report.into_temp_path().to_str().unwrap());\n\n if !stack.is_err() {\n assert!(false);\n }\n }\n\n #[test]\n fn perfect_read_in_report() {\n let mut report = NamedTempFile::new().expect('Can't create tmpfile');\n\n writeln!(report.as_file_mut(), 'NotBad perfect 2706 ')\n .expect('Error durring write of report in temp file');\n\n let mut stack = FromReport::new(report.into_temp_path().to_str().unwrap())\n .expect('Error when create stack object');\n\n assert_eq!(\n ['perfect'.to_string()]\n .iter()\n .cloned()\n .collect::>(),\n stack.get_reads()\n );\n\n assert_eq!(&(vec![], 2706), stack.get_bad_part('perfect').unwrap());\n }\n}\n","mit" +"yacrd","./yacrd/src/cli.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/// Yacrd use overlap between reads, to detect 'good' and 'bad' region,\n/// a region with coverage over the threshold is 'good' others are 'bad'.\n/// If read has a 'bad' region in middle this reads is mark as 'Chimeric'.\n/// If the ratio of 'bad' region length on total read length is larger than threshold this reads is marked as 'Not_covered'.\n\n/// Yacrd can make some other actions:\n/// - filter: for sequence or overlap file, record with reads marked as Chimeric or NotCovered isn't written in the output\n/// - extract: for sequence or overlap file, record contains reads marked as Chimeric or NotCovered is written in the output\n/// - split: for sequence file bad region in the middle of reads are removed, NotCovered read is removed\n/// - scrubb: for sequence file all bad region are removed, NotCovered read is removed\n#[derive(clap::Parser, Debug)]\n#[clap(\n version = '1.0.0 Magby',\n author = 'Pierre Marijon ',\n name = 'yacrd'\n)]\npub struct Command {\n /// path to input file overlap (.paf|.m4|.mhap) or yacrd report (.yacrd), format is autodetected and compression input is allowed (gz|bzip2|lzma)\n #[clap(short = 'i', long = 'input')]\n pub input: String,\n\n /// path output file\n #[clap(short = 'o', long = 'output')]\n pub output: String,\n\n /// number of thread use by yacrd, 0 mean all threads available, default 1\n #[clap(short = 't', long = 'thread')]\n pub threads: Option,\n\n /// if coverage reach this value region is marked as bad\n #[clap(short = 'c', long = 'coverage', default_value = '0')]\n pub coverage: u64,\n\n /// if the ratio of bad region length on total length is lower than this value, read is marked as NotCovered\n #[clap(short = 'n', long = 'not-coverage', default_value = '0.8')]\n pub not_coverage: f64,\n\n /// Control the size of the buffer used to read paf file\n #[clap(long = 'read-buffer-size', default_value = '8192')]\n pub buffer_size: usize,\n\n /// 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\n #[clap(short = 'd', long = 'ondisk')]\n pub ondisk: Option,\n\n /// with the default value yacrd in 'ondisk' mode use around 1 GBytes, you can increase to reduce runtime but increase memory usage\n #[clap(long = 'ondisk-buffer-size', default_value = '64000000')]\n pub ondisk_buffer_size: String,\n\n #[clap(subcommand)]\n pub subcmd: Option,\n}\n\n#[derive(clap::Parser, Debug)]\npub enum SubCommand {\n /// All bad region of read is removed\n #[clap()]\n Scrubb(Scrubb),\n\n /// Record mark as chimeric or NotCovered is filter\n #[clap()]\n Filter(Filter),\n\n /// Record mark as chimeric or NotCovered is extract\n #[clap()]\n Extract(Extract),\n\n /// Record mark as chimeric or NotCovered is split\n #[clap()]\n Split(Split),\n}\n\n#[derive(clap::Parser, Debug)]\npub struct Scrubb {\n /// path to sequence input (fasta|fastq), compression is autodetected (none|gzip|bzip2|lzma)\n #[clap(short = 'i', long = 'input', required = true)]\n pub input: String,\n\n /// path to output file, format and compression of input is preserved\n #[clap(short = 'o', long = 'output', required = true)]\n pub output: String,\n}\n\n#[derive(clap::Parser, Debug)]\npub struct Filter {\n /// path to sequence input (fasta|fastq), compression is autodetected (none|gzip|bzip2|lzma)\n #[clap(short = 'i', long = 'input', required = true)]\n pub input: String,\n\n /// path to output file, format and compression of input is preserved\n #[clap(short = 'o', long = 'output', required = true)]\n pub output: String,\n}\n\n#[derive(clap::Parser, Debug)]\npub struct Extract {\n /// path to sequence input (fasta|fastq), compression is autodetected (none|gzip|bzip2|lzma)\n #[clap(short = 'i', long = 'input', required = true)]\n pub input: String,\n\n /// path to output file, format and compression of input is preserved\n #[clap(short = 'o', long = 'output', required = true)]\n pub output: String,\n}\n\n#[derive(clap::Parser, Debug)]\npub struct Split {\n /// path to sequence input (fasta|fastq), compression is autodetected (none|gzip|bzip2|lzma)\n #[clap(short = 'i', long = 'input', required = true)]\n pub input: String,\n\n /// path to output file, format and compression of input is preserved\n #[clap(short = 'o', long = 'output', required = true)]\n pub output: String,\n}\n","mit" +"yacrd","./yacrd/src/util.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\n\n/* local use */\nuse crate::error;\n\n#[derive(Debug, PartialEq)]\npub enum FileType {\n Fasta,\n Fastq,\n Yacrd,\n Paf,\n M4,\n YacrdOverlap,\n}\n\npub fn get_file_type(filename: &str) -> Option {\n if filename.contains('.m4') || filename.contains('.mhap') {\n Some(FileType::M4)\n } else if filename.contains('.paf') {\n Some(FileType::Paf)\n } else if filename.contains('.yacrd') {\n Some(FileType::Yacrd)\n } else if filename.contains('.fastq') || filename.contains('.fq') {\n Some(FileType::Fastq)\n } else if filename.contains('.fasta') || filename.contains('.fa') {\n Some(FileType::Fasta)\n } else if filename.contains('.yovl') {\n Some(FileType::YacrdOverlap)\n } else {\n None\n }\n}\n\npub fn read_file(\n filename: &str,\n buffer_size: usize,\n) -> Result<(Box, niffler::compression::Format)> {\n let raw_in = Box::new(std::io::BufReader::with_capacity(\n buffer_size,\n std::fs::File::open(filename).with_context(|| error::Error::CantReadFile {\n filename: filename.to_string(),\n })?,\n ));\n\n niffler::get_reader(raw_in)\n .with_context(|| anyhow!('Error in compression detection of file {}', filename))\n}\n\npub fn write_file(\n filename: &str,\n compression: niffler::compression::Format,\n buffer_size: usize,\n) -> Result> {\n let raw_out = Box::new(std::io::BufWriter::with_capacity(\n buffer_size,\n std::fs::File::create(filename).with_context(|| error::Error::CantWriteFile {\n filename: filename.to_string(),\n })?,\n ));\n\n let output = niffler::get_writer(raw_out, compression, niffler::compression::Level::One)?;\n\n Ok(output)\n}\n\npub fn str2usize(val: &str) -> Result {\n val.parse::().with_context(|| {\n anyhow!(\n 'Error during parsing of number from string {:?} in usize',\n val\n )\n })\n}\n\npub fn str2u32(val: &str) -> Result {\n val.parse::().with_context(|| {\n anyhow!(\n 'Error during parsing of number from string {:?} in u32',\n val\n )\n })\n}\n\npub fn str2u64(val: &str) -> Result {\n val.parse::().with_context(|| {\n anyhow!(\n 'Error during parsing of number from string {:?} in u64',\n val\n )\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n mod str2usize {\n use super::*;\n\n #[test]\n fn failed() {\n match str2usize('2,5') {\n Err(e) => assert!(true, 'Error message {:?}', e),\n Ok(a) => assert!(false, 'str2usize('2,5') return {}', a),\n }\n\n match str2usize('2.5') {\n Err(e) => assert!(true, 'Error message {:?}', e),\n Ok(a) => assert!(false, 'str2usize('2.5') return {}', a),\n }\n }\n\n #[test]\n fn succeeded() {\n match str2usize('2') {\n Ok(a) => assert!(true, 'Value {}', a),\n Err(e) => assert!(false, 'str2usize('2') return {}', e),\n }\n }\n }\n\n mod str2u32 {\n use super::*;\n\n #[test]\n fn failed() {\n match str2u32('2,5') {\n Err(e) => assert!(true, 'Error message {:?}', e),\n Ok(a) => assert!(false, 'str2u32('2,5') return {}', a),\n }\n\n match str2u32('2.5') {\n Err(e) => assert!(true, 'Error message {:?}', e),\n Ok(a) => assert!(false, 'str2u32('2.5') return {}', a),\n }\n }\n\n #[test]\n fn succeeded() {\n match str2u32('2') {\n Ok(a) => assert!(true, 'Value {}', a),\n Err(e) => assert!(false, 'str2u32('2') return {}', e),\n }\n }\n }\n\n mod str2u64 {\n use super::*;\n\n #[test]\n fn failed() {\n match str2u64('2,5') {\n Err(e) => assert!(true, 'Error message {:?}', e),\n Ok(a) => assert!(false, 'str2u64('2,5') return {}', a),\n }\n\n match str2u64('2.5') {\n Err(e) => assert!(true, 'Error message {:?}', e),\n Ok(a) => assert!(false, 'str2u64('2.5') return {}', a),\n }\n }\n\n #[test]\n fn succeeded() {\n match str2u64('2') {\n Ok(a) => assert!(true, 'Value {}', a),\n Err(e) => assert!(false, 'str2u64('2') return {}', e),\n }\n }\n }\n\n mod file_type {\n use super::*;\n\n #[test]\n fn m4() {\n assert_eq!(Some(FileType::M4), get_file_type('test.m4'));\n }\n\n #[test]\n fn m4_with_other_ext() {\n assert_eq!(Some(FileType::M4), get_file_type('test.m4.other_ext'));\n }\n\n #[test]\n fn m4_with_nopoint() {\n assert_eq!(None, get_file_type('m4.other_ext'));\n }\n\n #[test]\n fn mhap() {\n assert_eq!(Some(FileType::M4), get_file_type('test.mhap'));\n }\n\n #[test]\n fn mhap_with_other_ext() {\n assert_eq!(Some(FileType::M4), get_file_type('test.mhap.other_ext'));\n }\n\n #[test]\n fn mhap_with_nopoint() {\n assert_eq!(None, get_file_type('mhap.other_ext'));\n }\n\n #[test]\n fn paf() {\n assert_eq!(Some(FileType::Paf), get_file_type('test.paf'));\n }\n\n #[test]\n fn paf_with_other_ext() {\n assert_eq!(Some(FileType::Paf), get_file_type('test.paf.other_ext'));\n }\n\n #[test]\n fn paf_with_nopoint() {\n assert_eq!(None, get_file_type('paf.other_ext'));\n }\n\n #[test]\n fn fasta() {\n assert_eq!(Some(FileType::Fasta), get_file_type('test.fasta'));\n }\n\n #[test]\n fn fasta_with_other_ext() {\n assert_eq!(Some(FileType::Fasta), get_file_type('test.fasta.other_ext'));\n }\n\n #[test]\n fn fasta_with_nopoint() {\n assert_eq!(None, get_file_type('fasta.other_ext'));\n }\n\n #[test]\n fn fa() {\n assert_eq!(Some(FileType::Fasta), get_file_type('test.fa'));\n }\n\n #[test]\n fn fa_with_other_ext() {\n assert_eq!(Some(FileType::Fasta), get_file_type('test.fa.other_ext'));\n }\n\n #[test]\n fn fa_with_nopoint() {\n assert_eq!(None, get_file_type('fa.other_ext'));\n }\n\n #[test]\n fn fastq() {\n assert_eq!(Some(FileType::Fastq), get_file_type('test.fastq'));\n }\n\n #[test]\n fn fastq_with_other_ext() {\n assert_eq!(Some(FileType::Fastq), get_file_type('test.fastq.other_ext'));\n }\n\n #[test]\n fn fastq_with_nopoint() {\n assert_eq!(None, get_file_type('fastq.other_ext'));\n }\n\n #[test]\n fn fq() {\n assert_eq!(Some(FileType::Fastq), get_file_type('test.fq'));\n }\n\n #[test]\n fn fq_with_other_ext() {\n assert_eq!(Some(FileType::Fastq), get_file_type('test.fq.other_ext'));\n }\n\n #[test]\n fn fq_with_nopoint() {\n assert_eq!(None, get_file_type('fq.other_ext'));\n }\n\n #[test]\n fn yacrd_overlap() {\n assert_eq!(Some(FileType::YacrdOverlap), get_file_type('test.yovl'));\n }\n\n #[test]\n fn yacrd_overlap_with_other_ext() {\n assert_eq!(\n Some(FileType::YacrdOverlap),\n get_file_type('test.yovl.other_ext')\n );\n }\n\n #[test]\n fn yacrd_overlap_with_nopoint() {\n assert_eq!(None, get_file_type('yovl.other_ext'));\n }\n }\n}\n","mit" +"yacrd","./yacrd/src/error.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse thiserror::Error;\n\n/* local use */\nuse crate::util;\n\n#[derive(Debug, Error)]\npub enum Error {\n #[error(\n 'Reading of the file '{filename:}' impossible, does it exist and can be read by the user?'\n )]\n CantReadFile { filename: String },\n\n #[error('Creation/opening of the file '{filename:}' impossible, directory in path exist? can be written by the user?')]\n CantWriteFile { filename: String },\n\n #[error('Format detection for '{filename:}' file not possible, filename need to contains .fasta, .fa, .fastq, fq, .paf, .m4, .mhap or .yacrd')]\n UnableToDetectFileFormat { filename: String },\n\n #[error(\n 'This operation {operation:} can't be run on this type ({filetype:?}) of file {filename:}'\n )]\n CantRunOperationOnFile {\n operation: String,\n filetype: util::FileType,\n filename: String,\n },\n\n #[error('Error durring reading of file {filename:} in format {format:?}')]\n Reading {\n filename: String,\n format: util::FileType,\n },\n\n #[error('Error during reading a file in format {format:?}')]\n ReadingErrorNoFilename { format: util::FileType },\n\n #[error('Error during writing of file in format {format:?}')]\n WritingErrorNoFilename { format: util::FileType },\n\n #[error('Error during yacrd overlap path creation {path:?}')]\n PathCreation { path: std::path::PathBuf },\n\n #[error('Error during yacrd overlap path destruction {path:?}')]\n PathDestruction { path: std::path::PathBuf },\n\n #[error('If you get this error please contact the author with this message and command line you use: {name:?}')]\n NotReachableCode { name: String },\n\n #[error('Yacrd postion seems corrupt')]\n CorruptYacrdReportInPosition,\n\n #[error('Your yacrd file {name} seems corrupt at line {line} you probably need to relaunch analisys with overlapping file')]\n CorruptYacrdReport { name: String, line: usize },\n\n #[error('Error durring open database')]\n OnDiskOpen,\n\n #[error('Error durring read database')]\n OnDiskReadDatabase,\n\n #[error('Error durring on disk deserialize vector')]\n OnDiskDeserializeVec,\n\n #[error('Error durring on disk serialize vector')]\n OnDiskSerializeVec,\n\n #[error('Error durring on disk batch application')]\n OnDiskBatchApplication,\n}\n","mit" +"yacrd","./yacrd/src/main.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse clap::Parser;\n\n/* mod declaration*/\nmod cli;\nmod editor;\nmod error;\nmod io;\nmod reads2ovl;\nmod stack;\nmod util;\n\nfn main() -> Result<()> {\n env_logger::init();\n\n let params = cli::Command::parse();\n\n /* Get bad region of reads */\n let mut reads2badregion: Box =\n if Some(util::FileType::Yacrd) == util::get_file_type(¶ms.input) {\n /* Read bad part from yacrd report */\n Box::new(stack::FromReport::new(¶ms.input)?)\n } else {\n /* Get bad part from overlap */\n let mut reads2ovl: Box = match params.ondisk.clone() {\n Some(on_disk_path) => Box::new(reads2ovl::OnDisk::new(\n on_disk_path,\n util::str2u64(¶ms.ondisk_buffer_size)?,\n params.buffer_size,\n )),\n None => Box::new(reads2ovl::FullMemory::new(params.buffer_size)),\n };\n\n reads2ovl.init(¶ms.input)?;\n\n Box::new(stack::FromOverlap::new(reads2ovl, params.coverage))\n };\n\n /* Write report */\n let raw_out = Box::new(std::io::BufWriter::new(\n std::fs::File::create(¶ms.output).with_context(|| error::Error::CantWriteFile {\n filename: params.output.clone(),\n })?,\n ));\n\n let mut out = niffler::get_writer(\n raw_out,\n niffler::compression::Format::No,\n niffler::compression::Level::One,\n )?;\n\n rayon::ThreadPoolBuilder::new()\n .num_threads(params.threads.unwrap_or(1usize))\n .build_global()?;\n reads2badregion.compute_all_bad_part();\n\n for read in reads2badregion.get_reads() {\n let (bads, len) = reads2badregion.get_bad_part(&read)?;\n editor::report(&read, *len, bads, params.not_coverage, &mut out)\n .with_context(|| anyhow!('Filename: {}', ¶ms.output))?;\n }\n\n /* Run post operation on read or overlap */\n match params.subcmd {\n Some(cli::SubCommand::Scrubb(s)) => editor::scrubbing(\n &s.input,\n &s.output,\n &mut *reads2badregion,\n params.not_coverage,\n params.buffer_size,\n )?,\n Some(cli::SubCommand::Filter(f)) => editor::filter(\n &f.input,\n &f.output,\n &mut *reads2badregion,\n params.not_coverage,\n params.buffer_size,\n )?,\n Some(cli::SubCommand::Extract(e)) => editor::extract(\n &e.input,\n &e.output,\n &mut *reads2badregion,\n params.not_coverage,\n params.buffer_size,\n )?,\n Some(cli::SubCommand::Split(s)) => editor::split(\n &s.input,\n &s.output,\n &mut *reads2badregion,\n params.not_coverage,\n params.buffer_size,\n )?,\n None => (),\n };\n\n if let Some(on_disk_path) = params.ondisk {\n let path = std::path::PathBuf::from(on_disk_path);\n if path.is_dir() {\n 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()))?;\n }\n\n if let Some(parent_path) = path.parent() {\n if path.is_dir() {\n remove_dir_all::remove_dir_all(parent_path).with_context(|| {\n error::Error::PathDestruction {\n path: parent_path.to_path_buf(),\n }\n })?;\n }\n }\n }\n\n Ok(())\n}\n","mit" +"yacrd","./yacrd/src/editor/split.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, bail, Context, Result};\nuse log::error;\n\n/* local use */\nuse crate::editor;\nuse crate::error;\nuse crate::stack;\nuse crate::util;\n\npub fn split(\n input_path: &str,\n output_path: &str,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n buffer_size: usize,\n) -> Result<()> {\n let (input, compression) = util::read_file(input_path, buffer_size)?;\n let output = util::write_file(output_path, compression, buffer_size)?;\n\n match util::get_file_type(input_path) {\n Some(util::FileType::Fasta) => fasta(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Fastq) => fastq(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Paf) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'split'.to_string(),\n filetype: util::FileType::Paf,\n filename: input_path.to_string()\n }),\n Some(util::FileType::M4) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'split'.to_string(),\n filetype: util::FileType::M4,\n filename: input_path.to_string()\n }),\n Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'split'.to_string(),\n filetype: util::FileType::Yacrd,\n filename: input_path.to_string()\n }),\n None | Some(util::FileType::YacrdOverlap) => {\n bail!(error::Error::UnableToDetectFileFormat {\n filename: input_path.to_string()\n })\n }\n };\n\n Ok(())\n}\n\nfn fasta(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(input));\n let mut writer = noodles::fasta::Writer::new(std::io::BufWriter::new(output));\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n\n let (badregion, length) = badregions.get_bad_part(record.name())?;\n\n let rtype = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype == editor::ReadType::NotCovered {\n continue;\n } else if rtype == editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n } else {\n let mut poss = vec![0];\n for interval in badregion {\n if interval.0 == 0 || interval.1 == *length as u32 {\n continue;\n }\n\n poss.push(interval.0);\n poss.push(interval.1);\n }\n poss.push(*length as u32);\n\n for pos in poss.chunks(2) {\n if pos[0] as usize > record.sequence().len()\n || pos[1] as usize > record.sequence().len()\n {\n 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());\n break;\n }\n\n writer\n .write_record(&noodles::fasta::Record::new(\n noodles::fasta::record::Definition::new(\n &format!('{}_{}_{}', record.name(), pos[0], pos[1]),\n None,\n ),\n noodles::fasta::record::Sequence::from(\n record.sequence().as_ref()[(pos[0] as usize)..(pos[1] as usize)]\n .to_vec(),\n ),\n ))\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n }\n }\n }\n\n Ok(())\n}\n\nfn fastq(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = noodles::fastq::Reader::new(std::io::BufReader::new(input));\n let mut writer = noodles::fastq::Writer::new(std::io::BufWriter::new(output));\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Fastq,\n })?;\n\n let (badregion, length) = badregions.get_bad_part(\n std::str::from_utf8(record.name())?\n .split_ascii_whitespace()\n .next()\n .unwrap(),\n )?;\n\n let rtype = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype == editor::ReadType::NotCovered {\n continue;\n } else if rtype == editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fastq,\n })?;\n } else {\n let mut sequence_description = std::str::from_utf8(record.name())?.splitn(2, ' ');\n let name = sequence_description.next().unwrap();\n let description = sequence_description.next();\n\n let mut poss = vec![0];\n for interval in badregion {\n if interval.0 == 0 || interval.1 == *length as u32 {\n continue;\n }\n\n poss.push(interval.0);\n poss.push(interval.1);\n }\n poss.push(*length as u32);\n\n for pos in poss.chunks(2) {\n if pos[0] as usize > record.sequence().len()\n || pos[1] as usize > record.sequence().len()\n {\n 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())?);\n break;\n }\n\n writer\n .write_record(&noodles::fastq::Record::new(\n match description {\n Some(desc) => format!('{}_{}_{} {}', name, pos[0], pos[1], desc),\n None => format!('{}_{}_{}', name, pos[0], pos[1]),\n }\n .as_bytes(),\n record.sequence()[(pos[0] as usize)..(pos[1] as usize)].to_vec(),\n record.quality_scores()[(pos[0] as usize)..(pos[1] as usize)].to_vec(),\n ))\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n }\n }\n }\n\n Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use crate::stack::BadPart;\n\n use crate::reads2ovl;\n use crate::reads2ovl::Reads2Ovl;\n\n const FASTA_FILE: &'static [u8] = b'>1\nACTGGGGGGACTGGGGGGACTG\n>2\nACTG\n>3\nACTG\n';\n\n const FASTA_FILE_SPLITED: &'static [u8] = b'>1_0_13\nACTGGGGGGACTG\n>1_18_22\nACTG\n>2\nACTG\n>3\nACTG\n';\n\n #[test]\n fn fasta_file() -> () {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 22);\n ovlst.add_overlap('1'.to_string(), (9, 13)).unwrap();\n ovlst.add_overlap('1'.to_string(), (18, 22)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTA_FILE_SPLITED, &output[..]);\n }\n\n const FASTQ_FILE: &'static [u8] = b'@1\nACTGGGGGGACTGGGGGGACTG\n+\n??????????????????????\n@2\nACTG\n+\n????\n@3\nACTG\n+\n????\n';\n\n const FASTQ_FILE_FILTRED: &'static [u8] = b'@1_0_13\nACTGGGGGGACTG\n+\n?????????????\n@1_18_22\nACTG\n+\n????\n@2\nACTG\n+\n????\n@3\nACTG\n+\n????\n';\n\n #[test]\n fn fastq_file() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 22);\n ovlst.add_overlap('1'.to_string(), (9, 13)).unwrap();\n ovlst.add_overlap('1'.to_string(), (18, 22)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTQ_FILE_FILTRED, &output[..]);\n }\n}\n","mit" +"yacrd","./yacrd/src/editor/scrubbing.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, bail, Context, Result};\nuse log::error;\n\n/* local use */\nuse crate::editor;\nuse crate::error;\nuse crate::stack;\nuse crate::util;\n\npub fn scrubbing(\n input_path: &str,\n output_path: &str,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n buffer_size: usize,\n) -> Result<()> {\n let (input, compression) = util::read_file(input_path, buffer_size)?;\n let output = util::write_file(output_path, compression, buffer_size)?;\n\n match util::get_file_type(input_path) {\n Some(util::FileType::Fasta) => fasta(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Fastq) => fastq(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Paf) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'scrubbing'.to_string(),\n filetype: util::FileType::Paf,\n filename: input_path.to_string()\n }),\n Some(util::FileType::M4) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'scrubbing'.to_string(),\n filetype: util::FileType::M4,\n filename: input_path.to_string()\n }),\n Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'scrubbing'.to_string(),\n filetype: util::FileType::Yacrd,\n filename: input_path.to_string()\n }),\n None | Some(util::FileType::YacrdOverlap) => {\n bail!(error::Error::UnableToDetectFileFormat {\n filename: input_path.to_string()\n })\n }\n };\n\n Ok(())\n}\n\nfn fasta(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(input));\n let mut writer = noodles::fasta::Writer::new(std::io::BufWriter::new(output));\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n\n let (badregion, length) = badregions.get_bad_part(record.name())?;\n\n let rtype = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype == editor::ReadType::NotCovered {\n continue;\n } else if badregion.is_empty() {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n } else {\n let mut poss = vec![0];\n for interval in badregion {\n poss.push(interval.0);\n poss.push(interval.1);\n }\n\n if poss.last() != Some(&(*length as u32)) {\n poss.push(*length as u32);\n };\n\n let iter = if poss[0] == 0 && poss[1] == 0 {\n &poss[2..]\n } else {\n &poss[..]\n };\n\n for pos in iter.chunks_exact(2) {\n if pos[0] as usize > record.sequence().len()\n || pos[1] as usize > record.sequence().len()\n {\n 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());\n break;\n }\n\n writer\n .write_record(&noodles::fasta::Record::new(\n noodles::fasta::record::Definition::new(\n &format!('{}_{}_{}', record.name(), pos[0], pos[1]),\n None,\n ),\n noodles::fasta::record::Sequence::from(\n record.sequence().as_ref()[(pos[0] as usize)..(pos[1] as usize)]\n .to_vec(),\n ),\n ))\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n }\n }\n }\n\n Ok(())\n}\n\nfn fastq(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = noodles::fastq::Reader::new(std::io::BufReader::new(input));\n let mut writer = noodles::fastq::Writer::new(std::io::BufWriter::new(output));\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Fastq,\n })?;\n\n let (badregion, length) = badregions.get_bad_part(\n std::str::from_utf8(record.name())?\n .split_ascii_whitespace()\n .next()\n .unwrap(),\n )?;\n\n let rtype = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype == editor::ReadType::NotCovered {\n continue;\n } else if badregion.is_empty() {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fastq,\n })?;\n } else {\n let mut sequence_description = std::str::from_utf8(record.name())?.splitn(2, ' ');\n let name = sequence_description.next().unwrap();\n let description = sequence_description.next();\n\n let mut poss = vec![0];\n for interval in badregion {\n poss.push(interval.0);\n poss.push(interval.1);\n }\n\n if poss.last() != Some(&(*length as u32)) {\n poss.push(*length as u32);\n };\n\n let iter = if poss[0] == 0 && poss[1] == 0 {\n &poss[2..]\n } else {\n &poss[..]\n };\n\n for pos in iter.chunks_exact(2) {\n if pos[0] as usize > record.sequence().len()\n || pos[1] as usize > record.sequence().len()\n {\n 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);\n break;\n }\n\n writer\n .write_record(&noodles::fastq::Record::new(\n match description {\n Some(desc) => format!('{}_{}_{} {}', name, pos[0], pos[1], desc),\n None => format!('{}_{}_{}', name, pos[0], pos[1]),\n }\n .as_bytes(),\n record.sequence()[(pos[0] as usize)..(pos[1] as usize)].to_vec(),\n record.quality_scores()[(pos[0] as usize)..(pos[1] as usize)].to_vec(),\n ))\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n }\n }\n }\n\n Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use crate::stack::BadPart;\n\n use crate::reads2ovl;\n use crate::reads2ovl::Reads2Ovl;\n\n const FASTA_FILE: &'static [u8] = b'>1\nACTGGGGGGACTGGGGGGACTG\n>2\nACTG\n>3\nACTG\n';\n\n const FASTA_FILE_SCRUBBED: &'static [u8] = b'>1_0_4\nACTG\n>1_9_13\nACTG\n>1_18_22\nACTG\n>2\nACTG\n>3\nACTG\n';\n\n #[test]\n fn fasta_keep_begin_end() -> () {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 22);\n ovlst.add_overlap('1'.to_string(), (0, 4)).unwrap();\n ovlst.add_overlap('1'.to_string(), (9, 13)).unwrap();\n ovlst.add_overlap('1'.to_string(), (18, 22)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTA_FILE_SCRUBBED, &output[..]);\n }\n\n const FASTA_FILE_SCRUBBED2: &'static [u8] = b'>1_4_18\nGGGGGACTGGGGGG\n>2\nACTG\n>3\nACTG\n';\n\n #[test]\n fn fasta_keep_middle() -> () {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 22);\n ovlst.add_overlap('1'.to_string(), (4, 18)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTA_FILE_SCRUBBED2, &output[..]);\n }\n\n const FASTQ_FILE: &'static [u8] = b'@1\nACTGGGGGGACTGGGGGGACTG\n+\n??????????????????????\n@2\nACTG\n+\n????\n@3\nACTG\n+\n????\n';\n\n const FASTQ_FILE_SCRUBBED: &'static [u8] = b'@1_0_4\nACTG\n+\n????\n@1_9_13\nACTG\n+\n????\n@1_18_22\nACTG\n+\n????\n@2\nACTG\n+\n????\n@3\nACTG\n+\n????\n';\n\n #[test]\n fn fastq_keep_begin_end() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 22);\n ovlst.add_overlap('1'.to_string(), (0, 4)).unwrap();\n ovlst.add_overlap('1'.to_string(), (9, 13)).unwrap();\n ovlst.add_overlap('1'.to_string(), (18, 22)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTQ_FILE_SCRUBBED, &output[..]);\n }\n\n const FASTQ_FILE_SCRUBBED2: &[u8] = b'@1_4_18\nGGGGGACTGGGGGG\n+\n??????????????\n@2\nACTG\n+\n????\n@3\nACTG\n+\n????\n';\n\n #[test]\n fn fastq_keep_middle() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 22);\n ovlst.add_overlap('1'.to_string(), (4, 18)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTQ_FILE_SCRUBBED2, &output[..]);\n }\n}\n","mit" +"yacrd","./yacrd/src/editor/extract.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, bail, Context, Result};\n\n/* local use */\nuse crate::editor;\nuse crate::error;\nuse crate::stack;\nuse crate::util;\n\npub fn extract(\n input_path: &str,\n output_path: &str,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n buffer_size: usize,\n) -> Result<()> {\n let (input, compression) = util::read_file(input_path, buffer_size)?;\n let output = util::write_file(output_path, compression, buffer_size)?;\n\n match util::get_file_type(input_path) {\n Some(util::FileType::Fasta) => fasta(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Fastq) => fastq(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Paf) => paf(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::M4) => m4(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'scrubbing'.to_string(),\n filetype: util::FileType::Yacrd,\n filename: input_path.to_string()\n }),\n None | Some(util::FileType::YacrdOverlap) => {\n bail!(error::Error::UnableToDetectFileFormat {\n filename: input_path.to_string()\n })\n }\n }\n\n Ok(())\n}\n\nfn fasta(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(input));\n let mut writer = noodles::fasta::Writer::new(std::io::BufWriter::new(output));\n\n let records = reader.records();\n\n for result in records {\n println!('PROUT');\n\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n\n let (badregion, length) = badregions.get_bad_part(record.name())?;\n\n let rtype = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype != editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n }\n }\n\n Ok(())\n}\n\nfn fastq(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = noodles::fastq::Reader::new(std::io::BufReader::new(input));\n let mut writer = noodles::fastq::Writer::new(std::io::BufWriter::new(output));\n\n let records = reader.records();\n\n for result in records {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Fastq,\n })?;\n\n let (badregion, length) = badregions.get_bad_part(\n std::str::from_utf8(record.name())?\n .split_ascii_whitespace()\n .next()\n .unwrap(),\n )?;\n\n let rtype = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype != editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fastq,\n })?;\n }\n }\n\n Ok(())\n}\n\nfn paf(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = csv::ReaderBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .from_reader(input);\n let mut writer = csv::WriterBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .from_writer(output);\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Paf,\n })?;\n\n let id_a = record[0].to_string();\n let id_b = record[5].to_string();\n\n let (badregion, length) = badregions.get_bad_part(&id_a)?;\n let rtype_a = editor::type_of_read(*length, badregion, not_covered);\n\n let (badregion, length) = badregions.get_bad_part(&id_b)?;\n let rtype_b = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype_a != editor::ReadType::NotBad || rtype_b != editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Paf,\n })?;\n }\n }\n\n Ok(())\n}\n\nfn m4(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = csv::ReaderBuilder::new()\n .delimiter(b' ')\n .has_headers(false)\n .from_reader(input);\n let mut writer = csv::WriterBuilder::new()\n .delimiter(b' ')\n .has_headers(false)\n .from_writer(output);\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::M4,\n })?;\n\n let id_a = record[0].to_string();\n let id_b = record[1].to_string();\n\n let (badregion, length) = badregions.get_bad_part(&id_a)?;\n let rtype_a = editor::type_of_read(*length, badregion, not_covered);\n\n let (badregion, length) = badregions.get_bad_part(&id_b)?;\n let rtype_b = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype_a != editor::ReadType::NotBad || rtype_b != editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::M4,\n })?;\n }\n }\n\n Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use crate::stack::BadPart;\n\n use crate::reads2ovl;\n use crate::reads2ovl::Reads2Ovl;\n\n const FASTA_FILE: &'static [u8] = b'>1\nACTG\n>2\nACTG\n>3\nACTG\n';\n\n const FASTA_FILE_EXTRACTED: &'static [u8] = b'>1\nACTG\n';\n\n #[test]\n fn fasta_file() -> () {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 1000);\n ovlst.add_overlap('1'.to_string(), (10, 490)).unwrap();\n ovlst.add_overlap('1'.to_string(), (510, 1000)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTA_FILE_EXTRACTED, &output[..]);\n }\n\n const FASTQ_FILE: &'static [u8] = b'@1\nACTG\n+\n????\n@2\nACTG\n+\n????\n@3\nACTG\n+\n????\n';\n\n const FASTQ_FILE_EXTRACTED: &'static [u8] = b'@1\nACTG\n+\n????\n';\n\n #[test]\n fn fastq_file() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 1000);\n ovlst.add_overlap('1'.to_string(), (10, 490)).unwrap();\n ovlst.add_overlap('1'.to_string(), (510, 1000)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTQ_FILE_EXTRACTED, &output[..]);\n }\n\n const PAF_FILE: &'static [u8] = b'1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255\n1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255\n';\n\n const PAF_FILE_EXTRACTED: &'static [u8] =\n b'1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255\n1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255\n';\n\n #[test]\n fn paf_file() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 1000);\n ovlst.add_overlap('1'.to_string(), (10, 490)).unwrap();\n ovlst.add_overlap('1'.to_string(), (510, 1000)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n paf(PAF_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(PAF_FILE_EXTRACTED, &output[..]);\n }\n\n const M4_FILE: &'static [u8] = b'1 2 0.1 2 0 100 450 1000 0 550 900 1000\n1 3 0.1 2 0 550 900 1000 0 100 450 1000\n';\n\n const M4_FILE_EXTRACTED: &'static [u8] = b'1 2 0.1 2 0 100 450 1000 0 550 900 1000\n1 3 0.1 2 0 550 900 1000 0 100 450 1000\n';\n\n #[test]\n fn m4_file() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 1000);\n ovlst.add_overlap('1'.to_string(), (10, 490)).unwrap();\n ovlst.add_overlap('1'.to_string(), (510, 1000)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n m4(M4_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(M4_FILE_EXTRACTED, &output[..]);\n }\n}\n","mit" +"yacrd","./yacrd/src/editor/mod.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* local mod */\npub mod extract;\npub mod filter;\npub mod scrubbing;\npub mod split;\n\n/* stuff declare in submod need to be accessible from mod level */\npub use self::extract::*;\npub use self::filter::*;\npub use self::scrubbing::*;\npub use self::split::*;\n\n/* crate use */\nuse anyhow::{Context, Result};\n\n/* local use */\nuse crate::error;\nuse crate::util;\n\n#[derive(Debug, PartialEq)]\npub enum ReadType {\n Chimeric,\n NotCovered,\n NotBad,\n}\n\nimpl Eq for ReadType {}\n\nimpl ReadType {\n pub fn as_str(&self) -> &'static str {\n match self {\n ReadType::Chimeric => 'Chimeric',\n ReadType::NotCovered => 'NotCovered',\n ReadType::NotBad => 'NotBad',\n }\n }\n}\n\npub fn report(\n read: &str,\n length: usize,\n badregions: &[(u32, u32)],\n not_covered: f64,\n out: &mut W,\n) -> Result<()>\nwhere\n W: std::io::Write,\n{\n let readtype = type_of_read(length, badregions, not_covered);\n writeln!(\n out,\n '{}\t{}\t{}\t{}',\n readtype.as_str(),\n read,\n length,\n bad_region_format(badregions)\n )\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Yacrd,\n })\n}\n\npub fn type_of_read(length: usize, badregions: &[(u32, u32)], not_covered: f64) -> ReadType {\n let bad_region_len = badregions.iter().fold(0, |acc, x| acc + (x.1 - x.0));\n\n if bad_region_len as f64 / length as f64 > not_covered {\n return ReadType::NotCovered;\n }\n\n let mut middle_gap = badregions\n .iter()\n .filter(|x| x.0 != 0 && x.1 != length as u32);\n if middle_gap.next().is_some() {\n return ReadType::Chimeric;\n }\n\n ReadType::NotBad\n}\n\nfn bad_region_format(bads: &[(u32, u32)]) -> String {\n bads.iter()\n .map(|b| format!('{},{},{}', b.1 - b.0, b.0, b.1))\n .collect::>()\n .join(';')\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn read_type_assignation() {\n let a = (vec![(0, 10), (990, 1000)], 1000);\n let b = (vec![(0, 10), (90, 1000)], 1000);\n let c = (vec![(0, 10), (490, 510), (990, 1000)], 1000);\n let d = (vec![(990, 1000)], 1000);\n let e = (vec![(0, 10)], 1000);\n let f = (vec![(490, 510)], 1000);\n\n assert_eq!(ReadType::NotBad, type_of_read(a.1, &a.0, 0.8));\n assert_eq!(ReadType::NotCovered, type_of_read(b.1, &b.0, 0.8));\n assert_eq!(ReadType::Chimeric, type_of_read(c.1, &c.0, 0.8));\n assert_eq!(ReadType::NotBad, type_of_read(d.1, &d.0, 0.8));\n assert_eq!(ReadType::NotBad, type_of_read(e.1, &e.0, 0.8));\n assert_eq!(ReadType::Chimeric, type_of_read(f.1, &f.0, 0.8));\n }\n}\n","mit" +"yacrd","./yacrd/src/editor/filter.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, bail, Context, Result};\n\n/* local use */\nuse crate::editor;\nuse crate::error;\nuse crate::stack;\nuse crate::util;\n\npub fn filter(\n input_path: &str,\n output_path: &str,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n buffer_size: usize,\n) -> Result<()> {\n let (input, compression) = util::read_file(input_path, buffer_size)?;\n let output = util::write_file(output_path, compression, buffer_size)?;\n\n match util::get_file_type(input_path) {\n Some(util::FileType::Fasta) => fasta(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Fastq) => fastq(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Paf) => paf(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::M4) => m4(input, output, badregions, not_covered)\n .with_context(|| anyhow!('Filename: {}', input_path.to_string()))?,\n Some(util::FileType::Yacrd) => bail!(error::Error::CantRunOperationOnFile {\n operation: 'scrubbing'.to_string(),\n filetype: util::FileType::Yacrd,\n filename: input_path.to_string()\n }),\n None | Some(util::FileType::YacrdOverlap) => {\n bail!(error::Error::UnableToDetectFileFormat {\n filename: input_path.to_string()\n })\n }\n }\n\n Ok(())\n}\n\nfn fasta(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(input));\n let mut writer = noodles::fasta::Writer::new(std::io::BufWriter::new(output));\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n\n let (badregion, length) = badregions.get_bad_part(record.name())?;\n\n let rtype = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype == editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fasta,\n })?;\n }\n }\n\n Ok(())\n}\n\npub fn fastq(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = noodles::fastq::Reader::new(std::io::BufReader::new(input));\n let mut writer = noodles::fastq::Writer::new(std::io::BufWriter::new(output));\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Fastq,\n })?;\n\n let (badregion, length) = badregions.get_bad_part(\n std::str::from_utf8(record.name())?\n .split_ascii_whitespace()\n .next()\n .unwrap(),\n )?;\n\n let rtype = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype == editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Fastq,\n })?;\n }\n }\n\n Ok(())\n}\n\npub fn paf(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = csv::ReaderBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .from_reader(input);\n let mut writer = csv::WriterBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .from_writer(output);\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::Paf,\n })?;\n\n let id_a = record[0].to_string();\n let id_b = record[5].to_string();\n\n let (badregion, length) = badregions.get_bad_part(&id_a)?;\n let rtype_a = editor::type_of_read(*length, badregion, not_covered);\n\n let (badregion, length) = badregions.get_bad_part(&id_b)?;\n let rtype_b = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype_a == editor::ReadType::NotBad && rtype_b == editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::Paf,\n })?;\n }\n }\n\n Ok(())\n}\n\npub fn m4(\n input: R,\n output: W,\n badregions: &mut dyn stack::BadPart,\n not_covered: f64,\n) -> Result<()>\nwhere\n R: std::io::Read,\n W: std::io::Write,\n{\n let mut reader = csv::ReaderBuilder::new()\n .delimiter(b' ')\n .has_headers(false)\n .from_reader(input);\n let mut writer = csv::WriterBuilder::new()\n .delimiter(b' ')\n .has_headers(false)\n .from_writer(output);\n\n for result in reader.records() {\n let record = result.with_context(|| error::Error::ReadingErrorNoFilename {\n format: util::FileType::M4,\n })?;\n\n let id_a = record[0].to_string();\n let id_b = record[1].to_string();\n\n let (badregion, length) = badregions.get_bad_part(&id_a)?;\n let rtype_a = editor::type_of_read(*length, badregion, not_covered);\n\n let (badregion, length) = badregions.get_bad_part(&id_b)?;\n let rtype_b = editor::type_of_read(*length, badregion, not_covered);\n\n if rtype_a == editor::ReadType::NotBad && rtype_b == editor::ReadType::NotBad {\n writer\n .write_record(&record)\n .with_context(|| error::Error::WritingErrorNoFilename {\n format: util::FileType::M4,\n })?;\n }\n }\n\n Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use crate::stack::BadPart;\n\n use crate::reads2ovl;\n use crate::reads2ovl::Reads2Ovl;\n\n const FASTA_FILE: &'static [u8] = b'>1\nACTG\n>2\nACTG\n>3\nACTG\n';\n\n const FASTA_FILE_FILTRED: &'static [u8] = b'>2\nACTG\n>3\nACTG\n';\n\n #[test]\n fn fasta_file() -> () {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 1000);\n ovlst.add_overlap('1'.to_string(), (10, 490)).unwrap();\n ovlst.add_overlap('1'.to_string(), (510, 1000)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fasta(FASTA_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTA_FILE_FILTRED, &output[..]);\n }\n\n const FASTQ_FILE: &'static [u8] = b'@1\nACTG\n+\n????\n@2\nACTG\n+\n????\n@3\nACTG\n+\n????\n';\n\n const FASTQ_FILE_FILTRED: &'static [u8] = b'@2\nACTG\n+\n????\n@3\nACTG\n+\n????\n';\n\n #[test]\n fn fastq_file() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 1000);\n ovlst.add_overlap('1'.to_string(), (10, 490)).unwrap();\n ovlst.add_overlap('1'.to_string(), (510, 1000)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n fastq(FASTQ_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(FASTQ_FILE_FILTRED, &output[..]);\n }\n\n const PAF_FILE: &'static [u8] = b'1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255\n1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255\n';\n\n const PAF_FILE_FILTRED: &'static [u8] = b'';\n\n #[test]\n fn paf_file() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 1000);\n ovlst.add_overlap('1'.to_string(), (10, 490)).unwrap();\n ovlst.add_overlap('1'.to_string(), (510, 1000)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n paf(PAF_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(PAF_FILE_FILTRED, &output[..]);\n }\n\n const M4_FILE: &'static [u8] = b'1 2 0.1 2 0 100 450 1000 0 550 900 1000\n1 3 0.1 2 0 550 900 1000 0 100 450 1000\n';\n\n const M4_FILE_FILTRED: &'static [u8] = b'';\n\n #[test]\n fn m4_file() {\n let mut ovlst = reads2ovl::FullMemory::new(8192);\n\n ovlst.add_length('1'.to_string(), 1000);\n ovlst.add_overlap('1'.to_string(), (10, 490)).unwrap();\n ovlst.add_overlap('1'.to_string(), (510, 1000)).unwrap();\n\n let mut stack = stack::FromOverlap::new(Box::new(ovlst), 0);\n\n stack.compute_all_bad_part();\n\n let mut output: Vec = Vec::new();\n m4(M4_FILE, &mut output, &mut stack, 0.8).unwrap();\n\n assert_eq!(M4_FILE_FILTRED, &output[..]);\n }\n}\n","mit" +"yacrd","./yacrd/src/io.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#[derive(Debug, Clone, serde::Deserialize)]\npub struct PafRecord<'a> {\n pub read_a: &'a str,\n pub length_a: usize,\n pub begin_a: u32,\n pub end_a: u32,\n pub _strand: char,\n pub read_b: &'a str,\n pub length_b: usize,\n pub begin_b: u32,\n pub end_b: u32,\n}\n\n#[derive(Debug, Clone, serde::Deserialize)]\npub struct M4Record<'a> {\n pub read_a: &'a str,\n pub read_b: &'a str,\n pub _error: f64,\n pub _shared_min: u64,\n pub _strand_a: char,\n pub begin_a: u32,\n pub end_a: u32,\n pub length_a: usize,\n pub _strand_b: char,\n pub begin_b: u32,\n pub end_b: u32,\n pub length_b: usize,\n}\n","mit" +"pcon","./pcon/src/spectrum.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{Context, Result};\nuse rayon::prelude::*;\n\n/* local use */\nuse crate::error::IO::*;\nuse crate::error::*;\nuse crate::*;\n\n/// Based on Kmergenie we assume kmer spectrum is a mixture of Pareto law and some Gaussians law\n/// Erroneous kmer follow Pareto law, Gaussians law represente true and repetitive kmer\n/// We use this property to found the threshold to remove many Erroneous kmer and keep Many True kmer\n#[derive(Debug, PartialEq)]\npub enum ThresholdMethod {\n /// The first local minimum match with the intersection of Pareto and Gaussians\n FirstMinimum,\n\n /// More we remove kmer less we remove Erroneous kmer when remove less than n percent view before \n Rarefaction,\n\n /// Remove at most n percent of total kmer\n PercentAtMost,\n\n /// Remove at least n percent of total kmer\n PercentAtLeast,\n}\n\n/// A struct to represent kmer spectrum and usefull corresponding function\npub struct Spectrum {\n data: Box<[u64]>,\n}\n\nimpl Spectrum {\n pub fn from_counter(counter: &counter::Counter) -> Self {\n let counts = unsafe {\n &(*(counter.get_raw_count() as *const [counter::AtoCount] as *const [counter::Count]))\n };\n\n let data = counts\n .par_chunks(counts.len() / rayon::current_num_threads())\n .map(|chunk| {\n let mut d: Box<[u64]> = vec![0u64; 256].into_boxed_slice();\n\n for count in chunk.iter() {\n d[*count as usize] = d[*count as usize].saturating_add(1);\n }\n\n d\n })\n .reduce(\n || vec![0u64; 256].into_boxed_slice(),\n |a, b| {\n let mut d = Vec::with_capacity(256);\n\n for x in a.iter().zip(b.iter()) {\n d.push(x.0.saturating_add(*x.1));\n }\n\n d.into_boxed_slice()\n },\n );\n\n Self { data }\n }\n\n pub fn get_threshold(&self, method: ThresholdMethod, params: f64) -> Option {\n match method {\n ThresholdMethod::FirstMinimum => self.first_minimum(),\n ThresholdMethod::Rarefaction => self.rarefaction(params),\n ThresholdMethod::PercentAtMost => self.percent_at_most(params),\n ThresholdMethod::PercentAtLeast => self.percent_at_least(params),\n }\n }\n\n fn first_minimum(&self) -> Option {\n for (i, d) in self.data.windows(2).enumerate() {\n if d[1] > d[0] {\n return Some(i as u8);\n }\n }\n\n None\n }\n\n fn rarefaction(&self, limit: f64) -> Option {\n let mut cumulative_sum = 0;\n\n for (index, value) in self.data.iter().enumerate() {\n cumulative_sum += index as u64 * value;\n\n if (*value as f64 / cumulative_sum as f64) < limit {\n return Some(index as u8);\n }\n }\n\n None\n }\n\n fn percent_at_most(&self, percent: f64) -> Option {\n self.percent_at_least(percent).map(|x| x - 1)\n }\n\n fn percent_at_least(&self, percent: f64) -> Option {\n let total: u64 = self\n .data\n .iter()\n .enumerate()\n .map(|(index, value)| index as u64 * value)\n .sum();\n\n let mut cumulative_sum = 0;\n for (index, value) in self.data.iter().enumerate() {\n cumulative_sum += index as u64 * value;\n\n if (cumulative_sum as f64 / total as f64) > percent {\n return Some(index as u8);\n }\n }\n\n None\n }\n\n #[allow(dead_code)]\n pub(crate) fn get_raw_histogram(&self) -> &[u64] {\n &self.data\n }\n\n pub fn write_csv(&self, mut writer: W) -> Result<()>\n where\n W: std::io::Write,\n {\n for (i, nb) in self.data.iter().enumerate() {\n writeln!(writer, '{},{}', i, nb).with_context(|| Error::IO(ErrorDurringWrite))?;\n }\n\n Ok(())\n }\n\n pub fn write_histogram(&self, mut out: W, point: Option) -> std::io::Result<()>\n where\n W: std::io::Write,\n {\n // Draw kmer spectrum in console\n let shape = get_shape();\n\n let factor = (*self.data.iter().max().unwrap() as f64).log(10.0) / shape.1 as f64;\n\n let normalized: Box<[f64]> = self\n .data\n .iter()\n .map(|y| {\n if *y == 0 {\n 0.0\n } else {\n (*y as f64).log(10.0) / factor\n }\n })\n .collect();\n\n for h in (1..=shape.1).rev() {\n for w in 0..shape.0 {\n if normalized[w] >= h as f64 {\n let delta = normalized[w] - h as f64;\n if delta > 1.0 {\n write!(out, '\u{258c}')?;\n } else if delta > 0.5 {\n write!(out, '\u{2596}')?;\n } else {\n write!(out, ' ')?;\n }\n } else {\n write!(out, ' ')?;\n }\n }\n\n writeln!(out)?;\n }\n\n let mut last_line = vec![b' '; shape.0];\n for x in (0..shape.0).step_by(5) {\n last_line[x] = b'5'\n }\n last_line[0] = b'0';\n if let Some(pos) = point {\n if (pos as usize) < last_line.len() {\n last_line[pos as usize] = b'*';\n }\n }\n\n writeln!(out, '{}', std::str::from_utf8(&last_line).unwrap())?;\n\n Ok(())\n }\n}\n\n#[allow(dead_code)]\nfn term_size() -> (usize, usize) {\n match term_size::dimensions() {\n Some((w, h)) => (w, h),\n None => (80, 24),\n }\n}\n\n#[cfg(test)]\nfn get_shape() -> (usize, usize) {\n (256, 48)\n}\n\n#[cfg(not(test))]\nfn get_shape() -> (usize, usize) {\n let term_size = term_size();\n\n (\n core::cmp::min(256, term_size.0),\n core::cmp::min(48, term_size.1),\n )\n}\n\n#[cfg(test)]\nmod tests {\n\n use super::*;\n\n lazy_static::lazy_static! {\n static ref COUNTER: crate::counter::Counter = {\n let mut counter = crate::counter::Counter::new(5);\n\n for i in 0..cocktail::kmer::get_kmer_space_size(5) {\n counter.inc(i);\n }\n\n counter.inc(0);\n\n counter\n };\n }\n\n #[test]\n fn from_counter() {\n let spectrum = Spectrum::from_counter(&COUNTER);\n\n assert_eq!(\n spectrum.get_raw_histogram(),\n &[\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 0, 0, 0, 0, 0\n ]\n );\n }\n\n static SPECTRUM: [u64; 256] = [\n 992273316, 64106898, 6792586, 1065818, 220444, 62400, 36748, 54062, 100806, 178868, 287058,\n 424184, 568742, 705680, 805332, 871544, 874546, 827252, 744428, 636722, 523488, 418036,\n 320506, 237956, 170642, 118046, 77290, 48320, 30500, 21096, 15632, 12758, 11838, 10888,\n 10402, 9872, 9018, 7960, 7236, 6304, 5276, 4524, 3714, 3056, 2628, 2018, 1578, 1256, 1036,\n 906, 708, 716, 592, 476, 540, 520, 446, 388, 316, 264, 258, 200, 230, 172, 164, 184, 154,\n 162, 126, 124, 126, 156, 152, 98, 116, 108, 134, 116, 88, 124, 96, 94, 96, 72, 52, 56, 68,\n 50, 54, 66, 54, 28, 44, 48, 30, 42, 48, 32, 38, 34, 44, 30, 32, 28, 18, 34, 20, 28, 26, 28,\n 28, 32, 22, 16, 10, 26, 8, 26, 14, 14, 30, 6, 32, 38, 26, 26, 16, 30, 20, 38, 20, 22, 22,\n 28, 14, 16, 20, 20, 20, 10, 12, 14, 12, 10, 18, 16, 16, 12, 18, 2, 14, 6, 12, 8, 0, 6, 2,\n 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,\n 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,\n 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,\n 0, 4, 2, 0, 4, 2, 0, 0, 284,\n ];\n\n #[test]\n fn first_local_min() {\n let spectrum = Spectrum {\n data: Box::new(SPECTRUM),\n };\n\n assert_eq!(\n spectrum.get_threshold(ThresholdMethod::FirstMinimum, 0.1),\n Some(6)\n );\n }\n\n #[test]\n fn failled_first_local_min() {\n let tmp = (0..256).map(|_| 1).collect::>();\n\n let spectrum = Spectrum { data: tmp };\n\n assert_eq!(\n spectrum.get_threshold(ThresholdMethod::FirstMinimum, 0.1),\n None\n );\n }\n\n #[test]\n fn rarefaction() {\n let spectrum = Spectrum {\n data: Box::new(SPECTRUM),\n };\n\n assert_eq!(\n spectrum.get_threshold(ThresholdMethod::Rarefaction, 0.1),\n Some(2)\n );\n }\n\n #[test]\n fn failled_rarefaction() {\n let tmp = (0..256).map(|_| 1).collect::>();\n\n let spectrum = Spectrum { data: tmp };\n\n assert_eq!(\n spectrum.get_threshold(ThresholdMethod::FirstMinimum, 0.00001),\n None\n );\n }\n\n #[test]\n fn test_draw_hist() {\n let spectrum = Spectrum {\n data: Box::new(SPECTRUM),\n };\n\n let mut output = vec![];\n spectrum.write_histogram(&mut output, Some(6)).unwrap();\n\n let good_output = ' \n▖ \n▌ \n▌ \n▌ \n▌ \n▌ \n▌▖ \n▌▌ \n▌▌ \n▌▌ \n▌▌ \n▌▌ \n▌▌▌ \n▌▌▌ \n▌▌▌ \n▌▌▌ \n▌▌▌▌ ▖▖▖▖ \n▌▌▌▌ ▖▌▌▌▌▌▌▖▖ \n▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▖ ▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌ ▖▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ \n▌▌▌▌▌▖ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ \n▌▌▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ ▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ \n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖ ▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▖▌▖▖ ▖▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▖▌▌ ▌▖▖▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖ ▖ ▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ���▖ ▖▖ ▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▌▖▌▌▌▌▌▌▖▌▖ ▌ ▖▖▖▖▌ ▖ ▖ ▖ ▌▌▖▖ ▖ ▌ ▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▖▌▌▌▌▌▌ ▌ ▌ ▌ ▌▌▌▌ ▌▖▌▖▌▌▌ ▖▖▖ ▖ ▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▌ ▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▖▌▖ ▌▌▌▖▌ ▌ ▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▌▌▌ ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▌ ▌▖ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▌▌▌▌ ▌ ▌▌ ▌ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ ▌▌▌▌ ▌ ▌ ▌ ▌▌ ▌ ▌ ▌ ▌ ▌▌ ▌ ▌ ▌ ▌\n▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▖▌▌▌▌ ▌▖▌▖ ▖▌▖▖▌▌ ▖ ▖▌ ▖▖▌▖ ▖▖▖▖▖ ▖▖ ▖▖ ▖▖▖ ▖▌▖ ▖ ▖▖▖ ▖▖▖▖▖ ▖ ▖▖▖▖▌ ▖▌▌ ▖ ▖▖ ▌▖ ▖ ▖ ▌▖ ▌▖ ▌\n0 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\n';\n\n assert_eq!(good_output, std::str::from_utf8(&output).unwrap());\n }\n}\n","mit" +"pcon","./pcon/src/binding.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\nuse crate::error;\nuse error::*;\n\nuse crate::counter;\nuse crate::dump;\nuse crate::solid;\n\n/* Helper */\nfn cstr2string(c_path: *const std::os::raw::c_char) -> String {\n unsafe { String::from_utf8_unchecked(std::ffi::CStr::from_ptr(c_path).to_bytes().to_owned()) }\n}\n\nfn reader_from_c_path(\n c_path: *const std::os::raw::c_char,\n) -> Result>, error::IO> {\n let path = cstr2string(c_path);\n\n let file = match std::fs::File::open(&path) {\n Ok(f) => f,\n Err(_) => return Err(IO::CantOpenFile),\n };\n\n let niffler = match niffler::get_reader(Box::new(file)) {\n Ok(f) => f,\n Err(_) => return Err(IO::ErrorDurringRead),\n };\n\n Ok(std::io::BufReader::new(niffler.0))\n}\n\nfn writer_from_c_path(\n c_path: *const std::os::raw::c_char,\n) -> Result>, error::IO> {\n let path = cstr2string(c_path);\n\n let file = match std::fs::File::create(&path) {\n Ok(f) => f,\n Err(_) => return Err(IO::CantOpenFile),\n };\n\n Ok(std::io::BufWriter::new(Box::new(file)))\n}\n\n/* Error section */\n/// Create a new pcon io error it's init to no error, see [error::IO]. In python corresponding string error is emit.\n#[no_mangle]\npub extern 'C' fn pcon_error_new() -> *mut error::IO {\n Box::into_raw(Box::new(error::IO::NoError))\n}\n\n/// Free a pcon io error\n///\n/// # Safety\n/// It's safe\n#[no_mangle]\npub unsafe extern 'C' fn pcon_error_free(error: *mut error::IO) {\n if error.is_null() {\n return;\n }\n\n let boxed = Box::from_raw(error);\n\n drop(boxed);\n}\n\n/* Counter section */\n/// Create a new Counter. In python binding Counter is an object, new is the default constructor.\n/// See [counter::Counter::new].\n#[no_mangle]\npub extern 'C' fn pcon_counter_new(k: u8) -> *mut counter::Counter {\n Box::into_raw(Box::new(counter::Counter::new(k)))\n}\n\n/// Free a Counter. In Python use del on Counter object.\n///\n/// # Safety\n/// It's safe\n#[no_mangle]\npub unsafe extern 'C' fn pcon_counter_free(counter: *mut counter::Counter) {\n if counter.is_null() {\n return;\n }\n\n let boxed = Box::from_raw(counter);\n\n drop(boxed);\n}\n\n/// Perform count of kmer in fasta file in path, this file can be compress in gzip, bzip2, xz.\n/// You must check value of `io_error` is equal to NoError before use `counter`.\n///\n/// In Python it's count_fasta method of Counter object.\n/// See [counter::Counter::count_fasta].\n#[no_mangle]\npub extern 'C' fn pcon_counter_count_fasta(\n counter: &mut counter::Counter,\n c_path: *const std::os::raw::c_char,\n read_buffer_len: usize,\n io_error: &mut error::IO,\n) {\n let reader = reader_from_c_path(c_path);\n\n match reader {\n Ok(r) => counter.count_fasta(r, read_buffer_len),\n Err(e) => *io_error = e,\n }\n}\n\n/// Increase the count of `kmer`\n///\n/// In Python it's inc method of Counter object.\n/// See [counter::Counter::inc].\n#[no_mangle]\npub extern 'C' fn pcon_counter_inc(counter: &mut counter::Counter, kmer: u64) {\n counter.inc(kmer);\n}\n\n/// Increase the count of a canonical `kmer`\n///\n/// In Python it's inc_canonic method of Counter object.\n/// See [counter::Counter::inc_canonic].\n#[no_mangle]\npub extern 'C' fn pcon_counter_inc_canonic(counter: &mut counter::Counter, kmer: u64) {\n counter.inc_canonic(kmer);\n}\n\n/// Get the count of value `kmer`\n///\n/// In Python it's get method of Counter object.\n/// See [counter::Counter::get].\n#[no_mangle]\npub extern 'C' fn pcon_counter_get(counter: &counter::Counter, kmer: u64) -> counter::Count {\n counter.get(kmer)\n}\n\n/// Get the count of value a canonical `kmer`\n///\n/// In Python it's get_canonic method of Counter object.\n/// See [counter::Counter::get_canonic].\n#[no_mangle]\npub extern 'C' fn pcon_counter_get_canonic(\n counter: &counter::Counter,\n kmer: u64,\n) -> counter::Count {\n counter.get_canonic(kmer)\n}\n\n/// Serialize Counter in path of file\n/// You must check value of `io_error` is equal to NoError before use `counter`\n///\n/// In Python it's serialize method of Counter object.\n/// See [counter::Counter::serialize].\n#[no_mangle]\npub extern 'C' fn pcon_serialize_counter(\n counter: &counter::Counter,\n c_path: *const std::os::raw::c_char,\n io_error: &mut error::IO,\n) {\n let writer = writer_from_c_path(c_path);\n\n match writer {\n Ok(w) => match counter.serialize(w) {\n Ok(_) => (),\n Err(_) => *io_error = IO::ErrorDurringWrite,\n },\n Err(e) => *io_error = e,\n }\n}\n\n/// Deserialize Counter from `c_path` in `counter`\n/// You must check value of `io_error` is equal to NoError before use `counter`\n///\n/// In Python it's deserialize class method of Counter.\n/// See [counter::Counter::deserialize].\n#[no_mangle]\npub extern 'C' fn pcon_deserialize_counter(\n counter: &mut counter::Counter,\n c_path: *const std::os::raw::c_char,\n io_error: &mut error::IO,\n) {\n let reader = reader_from_c_path(c_path);\n\n match reader {\n Ok(r) => match counter::Counter::deserialize(r) {\n Ok(c) => *counter = c,\n Err(_) => *io_error = IO::ErrorDurringRead,\n },\n Err(e) => *io_error = e,\n }\n}\n\n/* solid section */\n/// Create a new Solid. In python binding Solid is an object, new is the default constructor.\n/// See [solid::Solid::new]\n#[no_mangle]\npub extern 'C' fn pcon_solid_new(k: u8) -> *mut solid::Solid {\n Box::into_raw(Box::new(solid::Solid::new(k)))\n}\n\n/// Create a new Solid from value in Counter\n/// In python binding, this is a Solid class method from_counter.\n/// See [solid::Solid::from_counter].\n#[no_mangle]\npub extern 'C' fn pcon_solid_from_counter(\n counter: &counter::Counter,\n abundance: counter::Count,\n) -> *mut solid::Solid {\n Box::into_raw(Box::new(solid::Solid::from_counter(counter, abundance)))\n}\n\n/// Free a Solid. In Python use del on Solid object.\n///\n/// # Safety\n/// It's safe\n#[no_mangle]\npub unsafe extern 'C' fn pcon_solid_free(solid: *mut solid::Solid) {\n if solid.is_null() {\n return;\n }\n\n let boxed = Box::from_raw(solid);\n\n drop(boxed);\n}\n\n/// Set the solidity status of `kmer` to `value`\n///\n/// In Python it's set method of Solid object.\n/// See [solid::Solid::set].\n#[no_mangle]\npub extern 'C' fn pcon_solid_set(solid: &mut solid::Solid, kmer: u64, value: bool) {\n solid.set(kmer, value);\n}\n\n/// Set the solidity status of a canonical `kmer` to `value`\n///\n/// In Python it's set_canonic method of Solid object.\n/// See [solid::Solid::set_canonic].\n#[no_mangle]\npub extern 'C' fn pcon_solid_set_canonic(solid: &mut solid::Solid, kmer: u64, value: bool) {\n solid.set_canonic(kmer, value);\n}\n\n/// Get the solidity status of `kmer`\n///\n/// In Python it's get method of Solid object.\n/// See [solid::Solid::get].\n#[no_mangle]\npub extern 'C' fn pcon_solid_get(solid: &mut solid::Solid, kmer: u64) -> bool {\n solid.get(kmer)\n}\n\n/// Get the solidity status of a canonical `kmer`\n///\n/// In Python it's get_canonic method of Solid object.\n/// See [solid::Solid::get_canonic].\n#[no_mangle]\npub extern 'C' fn pcon_solid_get_canonic(solid: &mut solid::Solid, kmer: u64) -> bool {\n solid.get_canonic(kmer)\n}\n\n/// Serialize Solid in path of file\n/// You must check value of `io_error` is equal to NoError before use `solid`\n///\n/// In Python it's serialize method of Solid object.\n/// See [solid::Solid::serialize].\n#[no_mangle]\npub extern 'C' fn pcon_serialize_solid(\n solid: &solid::Solid,\n c_path: *const std::os::raw::c_char,\n io_error: &mut error::IO,\n) {\n let writer = writer_from_c_path(c_path);\n\n match writer {\n Ok(w) => match solid.serialize(w) {\n Ok(_) => (),\n Err(_) => *io_error = IO::ErrorDurringWrite,\n },\n Err(e) => *io_error = e,\n }\n}\n\n/// Deserialize Solid from `c_path` in `counter`\n/// You must check value of `io_error` is equal to NoError before use `solid`\n///\n/// In Python it's deserialize class method of solid.\n/// See [solid::Solid::deserialize].\n#[no_mangle]\npub extern 'C' fn pcon_deserialize_solid(\n solid: &mut solid::Solid,\n c_path: *const std::os::raw::c_char,\n io_error: &mut error::IO,\n) {\n let reader = reader_from_c_path(c_path);\n\n match reader {\n Ok(r) => match solid::Solid::deserialize(r) {\n Ok(s) => *solid = s,\n Err(_) => *io_error = IO::ErrorDurringRead,\n },\n Err(e) => *io_error = e,\n }\n}\n\n/* Dump section */\n/// See [dump::csv].\n/// You must check value of `io_error` is equal to NoError to be sure no problem occure durring write\n///\n/// In Python it's csv function of dump module.\n#[no_mangle]\npub extern 'C' fn pcon_dump_csv(\n counter: &counter::Counter,\n abundance: counter::Count,\n c_path: *const std::os::raw::c_char,\n io_error: &mut error::IO,\n) {\n let writer = writer_from_c_path(c_path);\n\n match writer {\n Ok(w) => match dump::csv(w, counter, abundance) {\n Ok(_) => (),\n Err(_) => *io_error = IO::ErrorDurringWrite,\n },\n Err(e) => *io_error = e,\n }\n}\n\n/// See [dump::solid()].\n/// You must check value of `io_error` is equal to NoError to be sure no problem occure durring write\n///\n/// In Python it's solid function of dump module.\n#[no_mangle]\npub extern 'C' fn pcon_dump_solid(\n counter: &counter::Counter,\n abundance: counter::Count,\n c_path: *const std::os::raw::c_char,\n io_error: &mut error::IO,\n) {\n let writer = writer_from_c_path(c_path);\n\n match writer {\n Ok(w) => match dump::solid(w, counter, abundance) {\n Ok(_) => (),\n Err(_) => *io_error = IO::ErrorDurringWrite,\n },\n Err(e) => *io_error = e,\n }\n}\n\n/// See [dump::spectrum].\n/// You must check value of `io_error` is equal to NoError to be sure no problem occure durring write\n///\n/// In Python it's spectrum function of dump module.\n#[no_mangle]\npub extern 'C' fn pcon_dump_spectrum(\n counter: &counter::Counter,\n c_path: *const std::os::raw::c_char,\n io_error: &mut error::IO,\n) {\n let writer = writer_from_c_path(c_path);\n\n match writer {\n Ok(w) => match dump::spectrum(w, counter) {\n Ok(_) => (),\n Err(_) => *io_error = IO::ErrorDurringWrite,\n },\n Err(e) => *io_error = e,\n }\n}\n\n/// See [set_count_nb_threads]\n#[no_mangle]\npub extern 'C' fn pcon_set_nb_threads(nb_threads: usize) {\n crate::set_nb_threads(nb_threads);\n}\n","mit" +"pcon","./pcon/src/static_counter.rs","/* std use */\nuse std::io::Read;\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse byteorder::ReadBytesExt;\n\n/* local use */\nuse crate::counter;\nuse crate::error::IO::*;\nuse crate::error::*;\n\n/// A struct to get a fast access to count\npub struct StaticCounter {\n pub k: u8,\n pub(crate) count: Box<[u8]>,\n}\n\nimpl StaticCounter {\n /// Deserialize counter for given [std::io::Read]\n pub fn deserialize(r: R) -> Result\n where\n R: std::io::Read,\n {\n let mut reader = r;\n\n let k = reader\n .read_u8()\n .with_context(|| Error::IO(ErrorDurringRead))\n .with_context(|| anyhow!('Error durring deserialize counter'))?;\n\n let mut deflate = flate2::read::MultiGzDecoder::new(reader);\n let mut tmp = vec![0u8; cocktail::kmer::get_hash_space_size(k) as usize].into_boxed_slice();\n\n deflate\n .read_exact(&mut tmp)\n .with_context(|| Error::IO(ErrorDurringRead))\n .with_context(|| anyhow!('Error durring deserialize counter'))?;\n\n Ok(Self { k, count: tmp })\n }\n\n /// Get the counter of a kmer\n pub fn get(&self, kmer: u64) -> counter::Count {\n self.get_canonic(cocktail::kmer::canonical(kmer, self.k))\n }\n\n /// Get the counter of a canonical kmer\n pub fn get_canonic(&self, canonical: u64) -> counter::Count {\n let hash = (canonical >> 1) as usize;\n\n self.count[hash]\n }\n\n pub(crate) fn get_raw_count(&self) -> &[counter::Count] {\n &self.count\n }\n}\n\n#[cfg(test)]\nmod tests {\n const FASTA_FILE: &[u8] = b'>random_seq 0\nGTTCTGCAAATTAGAACAGACAATACACTGGCAGGCGTTGCGTTGGGGGAGATCTTCCGTAACGAGCCGGCATTTGTAAGAAAGAGATTTCGAGTAAATG\n>random_seq 1\nAGGATAGAAGCTTAAGTACAAGATAATTCCCATAGAGGAAGGGTGGTATTACAGTGCCGCCTGTTGAAAGCCCCAATCCCGCTTCAATTGTTGAGCTCAG\n';\n\n const FASTA_COUNT: &[u8] = &[\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 1, 1,\n ];\n\n #[test]\n fn count_fasta() {\n let mut counter = crate::counter::Counter::new(5);\n\n counter.count_fasta(FASTA_FILE, 1);\n let static_count = counter.into_static();\n\n assert_eq!(static_count.get_raw_count(), &FASTA_COUNT[..]);\n }\n\n lazy_static::lazy_static! {\n static ref COUNTER: crate::static_counter::StaticCounter = {\n let mut counter = crate::counter::Counter::new(5);\n\n for i in 0..cocktail::kmer::get_kmer_space_size(5) {\n counter.inc(i);\n }\n\n counter.into_static()\n };\n }\n\n const ALLKMERSEEONE: &[u8] = &[\n 5, 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 237, 208, 1, 9, 0, 0, 0, 128, 32, 232, 255, 232, 134,\n 148, 19, 100, 233, 1, 1, 118, 18, 53, 208, 0, 2, 0, 0,\n ];\n\n #[test]\n fn deserialize() {\n let counter =\n crate::static_counter::StaticCounter::deserialize(&ALLKMERSEEONE[..]).unwrap();\n\n assert_eq!(counter.k, COUNTER.k);\n\n for (a, b) in counter\n .get_raw_count()\n .iter()\n .zip(COUNTER.get_raw_count().iter())\n {\n assert_eq!(a, b);\n }\n }\n}\n","mit" +"pcon","./pcon/src/cli.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n#[derive(clap::Parser, Debug)]\n#[clap(version = '0.1', author = 'Pierre Marijon ')]\n/// Prompt COuNter is short kmer counter\npub struct Command {\n #[clap(subcommand)]\n pub subcmd: SubCommand,\n\n #[clap(short = 't', long = 'threads')]\n /// Number of thread use by pcon to count, 0 use all avaible core, default value 0\n pub threads: Option,\n\n #[clap(short = 'v', long = 'verbosity', parse(from_occurrences))]\n /// verbosity level also control by environment variable PCON_LOG if flag is set PCON_LOG value is ignored\n pub verbosity: i8,\n}\n\n#[derive(clap::Parser, Debug)]\npub enum SubCommand {\n Count(SubCommandCount),\n Dump(SubCommandDump),\n}\n\n#[derive(clap::Parser, Debug)]\n/// Perform kmer count\npub struct SubCommandCount {\n #[clap(short = 'k', long = 'kmer-size')]\n /// Size of kmer\n pub kmer: u8,\n\n #[clap(short = 'i', long = 'inputs')]\n /// Path to inputs\n pub inputs: Vec,\n\n #[clap(short = 'o', long = 'output')]\n /// 'Path where count are store in binary format'\n pub output: Option,\n\n #[clap(short = 'b', long = 'record_buffer')]\n /// Number of sequence record load in buffer, default 8192\n pub record_buffer: Option,\n\n #[clap(short = 'a', long = 'abundance', default_value = '0')]\n /// Minimal abundance\n pub abundance: crate::counter::Count,\n\n #[clap(short = 'c', long = 'csv')]\n /// Path where count is write in csv\n pub csv: Option,\n\n #[clap(short = 's', long = 'solid')]\n /// Path where count is write in solid format\n pub solid: Option,\n\n #[clap(short = 'S', long = 'spectrum')]\n /// Path where kmer spectrum is write\n pub spectrum: Option,\n}\n\n#[derive(clap::Parser, Debug)]\n/// Convert count in usable format\npub struct SubCommandDump {\n #[clap(short = 'i', long = 'input', help = 'Path to count file')]\n pub input: String,\n\n #[clap(short = 'a', long = 'abundance', default_value = '0')]\n /// Minimal abundance\n pub abundance: crate::counter::Count,\n\n #[clap(short = 'c', long = 'csv')]\n /// Path where count is write in csv\n pub csv: Option,\n\n #[clap(short = 's', long = 'solid')]\n /// Path where count is write in solid format\n pub solid: Option,\n\n #[clap(short = 'S', long = 'spectrum')]\n /// Path where kmer spectrum is write\n pub spectrum: Option,\n\n #[clap(short = 'b', long = 'bin')]\n /// Path where count is write in bin\n pub bin: Option,\n}\n\nuse crate::error::{Cli, Error};\nuse Cli::*;\n\npub fn check_count_param(params: SubCommandCount) -> Result {\n if (params.kmer & 1) == 0 {\n return Err(Error::Cli(KMustBeOdd));\n }\n\n if params.kmer > 32 {\n return Err(Error::Cli(KMustBeLower32));\n }\n\n Ok(params)\n}\n\npub fn check_dump_param(params: SubCommandDump) -> Result {\n if ![¶ms.csv, ¶ms.solid, ¶ms.spectrum, ¶ms.bin]\n .iter()\n .any(|x| x.is_some())\n {\n return Err(Error::Cli(ADumpOptionMustBeSet));\n }\n\n Ok(params)\n}\n\npub fn i82level(level: i8) -> Option {\n match level {\n std::i8::MIN..=0 => None,\n 1 => Some(log::Level::Error),\n 2 => Some(log::Level::Warn),\n 3 => Some(log::Level::Info),\n 4 => Some(log::Level::Debug),\n 5..=std::i8::MAX => Some(log::Level::Trace),\n }\n}\n","mit" +"pcon","./pcon/src/solid.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse bitvec::prelude::*;\nuse byteorder::{ReadBytesExt, WriteBytesExt};\n\n/* local use */\nuse crate::error::IO::*;\nuse crate::error::*;\nuse crate::*;\n\n/// A struct to store if a kmer is Solid or not. Only kmer with abundance upper than a threshold is solid\npub struct Solid {\n pub k: u8,\n solid: BitBox,\n}\n\nimpl Solid {\n /// Create a new Solid for kmer size equal to `k`\n pub fn new(k: u8) -> Self {\n Self {\n k,\n solid: bitbox![u8, Lsb0; 0; cocktail::kmer::get_hash_space_size(k) as usize],\n }\n }\n\n /// Create a new Solid with count in `counter` only kmer upper than `abundance` are solid\n pub fn from_counter(counter: &counter::Counter, abundance: counter::Count) -> Self {\n let counts = unsafe {\n &(*(counter.get_raw_count() as *const [counter::AtoCount] as *const [counter::Count]))\n };\n\n let mut solid = bitbox![u8, Lsb0; 0; counts.len()];\n\n unsafe {\n for (index, count) in (*(counter.get_raw_count() as *const [counter::AtoCount]\n as *const [counter::Count]))\n .iter()\n .enumerate()\n {\n if *count > abundance {\n solid.set(index, true);\n }\n }\n }\n\n Self {\n k: counter.k,\n solid,\n }\n }\n\n /// Solidity status of `kmer` is set to `value`\n pub fn set(&mut self, kmer: u64, value: bool) {\n self.set_canonic(cocktail::kmer::canonical(kmer, self.k), value);\n }\n\n /// Solidity status of a canonical`kmer` is set to `value`\n pub fn set_canonic(&mut self, canonical: u64, value: bool) {\n let hash = (canonical >> 1) as usize;\n\n if let Some(mut v) = self.solid.get_mut(hash) {\n *v = value;\n }\n }\n\n /// Get the solidity status of `kmer`\n pub fn get(&self, kmer: u64) -> bool {\n self.get_canonic(cocktail::kmer::canonical(kmer, self.k))\n }\n\n /// Get the solidity status of a canonical `kmer`\n pub fn get_canonic(&self, canonical: u64) -> bool {\n let hash = (canonical >> 1) as usize;\n\n self.solid[hash]\n }\n\n #[allow(dead_code)]\n pub(crate) fn get_raw_solid(&self) -> &BitBox {\n &self.solid\n }\n\n /// Serialize counter in given [std::io::Write]\n pub fn serialize(&self, w: W) -> Result<()>\n where\n W: std::io::Write,\n {\n let mut writer = niffler::get_writer(\n Box::new(w),\n niffler::compression::Format::Gzip,\n niffler::compression::Level::One,\n )?;\n\n writer\n .write_u8(self.k)\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('Error durring serialize solid'))?;\n\n writer\n .write_all(self.solid.as_raw_slice())\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('Error durring serialize solid'))?;\n\n Ok(())\n }\n\n /// Deserialize counter for given [std::io::Read]\n pub fn deserialize(r: R) -> Result\n where\n R: std::io::Read,\n {\n let mut reader = niffler::get_reader(Box::new(r))?.0;\n\n let k = reader\n .read_u8()\n .with_context(|| Error::IO(ErrorDurringRead))\n .with_context(|| anyhow!('Error durring deserialize solid'))?;\n\n // >> 3 <-> divide by 8\n let mut tmp =\n vec![0u8; (cocktail::kmer::get_hash_space_size(k) >> 3) as usize].into_boxed_slice();\n\n reader\n .read_exact(&mut tmp)\n .with_context(|| Error::IO(ErrorDurringRead))\n .with_context(|| anyhow!('Error durring deserialize solid'))?;\n\n Ok(Self {\n k,\n solid: BitBox::from_boxed_slice(tmp),\n })\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n const FASTA_FILE: &[u8] = b'>random_seq 0\nGTTCTGCAAATTAGAACAGACAATACACTGGCAGGCGTTGCGTTGGGGGAGATCTTCCGTAACGAGCCGGCATTTGTAAGAAAGAGATTTCGAGTAAATG\n>random_seq 1\nAGGATAGAAGCTTAAGTACAAGATAATTCCCATAGAGGAAGGGTGGTATTACAGTGCCGCCTGTTGAAAGCCCCAATCCCGCTTCAATTGTTGAGCTCAG\n';\n\n fn get_solid() -> solid::Solid {\n let mut counter = crate::counter::Counter::new(5);\n\n counter.count_fasta(FASTA_FILE, 1);\n\n solid::Solid::from_counter(&counter, 0)\n }\n\n const SOLID: &[u8] = &[\n 112, 64, 113, 143, 130, 8, 128, 4, 6, 60, 214, 0, 243, 8, 193, 1, 30, 4, 34, 97, 4, 70,\n 192, 12, 16, 144, 133, 38, 192, 41, 1, 4, 218, 179, 140, 0, 0, 140, 242, 35, 90, 56, 205,\n 179, 64, 3, 25, 20, 226, 0, 32, 76, 1, 134, 48, 64, 7, 0, 200, 144, 98, 131, 2, 203,\n ];\n\n #[test]\n fn presence() {\n let solid = get_solid();\n\n assert_eq!(solid.get_raw_solid().as_raw_slice(), SOLID);\n }\n\n const SOLID_SET: &[u8] = &[\n 112, 64, 113, 143, 130, 8, 128, 4, 6, 52, 214, 0, 243, 8, 193, 1, 30, 4, 2, 97, 4, 70, 192,\n 12, 16, 144, 133, 36, 192, 41, 1, 4, 218, 179, 140, 0, 0, 140, 242, 35, 90, 56, 205, 179,\n 64, 3, 25, 20, 226, 0, 32, 76, 1, 134, 48, 64, 7, 0, 192, 144, 98, 131, 2, 203,\n ];\n\n #[test]\n fn set_value() {\n let mut solid = get_solid();\n\n solid.set(cocktail::kmer::seq2bit(b'GTTCT'), false);\n solid.set(cocktail::kmer::seq2bit(b'AAATG'), false);\n solid.set(cocktail::kmer::seq2bit(b'AGGAT'), false);\n solid.set(cocktail::kmer::seq2bit(b'CTCAG'), false);\n\n assert_eq!(solid.get_raw_solid().as_raw_slice(), SOLID_SET);\n }\n\n const FASTA_SOLID: &[u8] = &[\n 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 1, 65, 0, 190, 255, 5, 112, 64, 113, 143, 130, 8, 128,\n 4, 6, 60, 214, 0, 243, 8, 193, 1, 30, 4, 34, 97, 4, 70, 192, 12, 16, 144, 133, 38, 192, 41,\n 1, 4, 218, 179, 140, 0, 0, 140, 242, 35, 90, 56, 205, 179, 64, 3, 25, 20, 226, 0, 32, 76,\n 1, 134, 48, 64, 7, 0, 200, 144, 98, 131, 2, 203, 186, 210, 139, 120, 65, 0, 0, 0,\n ];\n\n #[test]\n fn serialize() {\n let mut outfile = Vec::new();\n\n let solid = get_solid();\n solid.serialize(&mut outfile).unwrap();\n\n assert_eq!(&outfile[..], &FASTA_SOLID[..]);\n }\n\n #[test]\n fn deserialize() {\n let solid = crate::solid::Solid::deserialize(&FASTA_SOLID[..]).unwrap();\n\n assert_eq!(solid.k, 5);\n assert_eq!(solid.get_raw_solid().as_raw_slice(), SOLID);\n }\n}\n","mit" +"pcon","./pcon/src/dump.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse cocktail::*;\n\n/* local use */\nuse crate::error::IO::*;\nuse crate::error::*;\nuse crate::*;\n\npub fn dump(params: cli::SubCommandDump) -> Result<()> {\n let params = cli::check_dump_param(params)?;\n\n log::info!('Start of read of count');\n let reader = std::fs::File::open(¶ms.input)\n .with_context(|| Error::IO(CantOpenFile))\n .with_context(|| anyhow!('File {}', params.input.clone()))?;\n\n let counter = counter::Counter::deserialize(reader)\n .with_context(|| Error::IO(ErrorDurringRead))\n .with_context(|| anyhow!('File {}', params.input.clone()))?;\n\n log::info!('End of read of count');\n\n dump_worker(\n counter,\n params.bin,\n params.csv,\n params.solid,\n params.spectrum,\n params.abundance,\n );\n\n Ok(())\n}\n\npub(crate) fn dump_worker(\n counter: counter::Counter,\n bin_path: Option,\n csv_path: Option,\n solid_path: Option,\n spectrum_path: Option,\n abundance: counter::Count,\n) {\n rayon::scope(|s| {\n s.spawn(|_| {\n if let Some(output) = bin_path.clone() {\n log::info!('Start of dump count data in binary');\n let writer = std::io::BufWriter::new(\n std::fs::File::create(&output)\n .with_context(|| Error::IO(CantCreateFile))\n .with_context(|| anyhow!('File {}', output.clone()))\n .unwrap(),\n );\n\n counter\n .serialize(writer)\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('In file {}', output.clone()))\n .unwrap();\n\n log::info!('End of dump count data in binary');\n }\n });\n\n s.spawn(|_| {\n if let Some(output) = csv_path.clone() {\n log::info!('Start of dump count data in csv');\n\n let writer = std::io::BufWriter::new(\n std::fs::File::create(&output)\n .with_context(|| Error::IO(CantOpenFile))\n .with_context(|| anyhow!('File {}', output.clone()))\n .unwrap(),\n );\n\n csv(writer, &counter, abundance)\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('File {} in csv format', output))\n .unwrap();\n\n log::info!('End of dump count data in csv');\n }\n });\n\n s.spawn(|_| {\n if let Some(output) = solid_path.clone() {\n log::info!('Start of dump count data in solid format');\n\n let writer = std::io::BufWriter::new(\n std::fs::File::create(&output)\n .with_context(|| Error::IO(CantOpenFile))\n .with_context(|| anyhow!('File {}', output.clone()))\n .unwrap(),\n );\n\n solid(writer, &counter, abundance)\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('File {} in solid format', output))\n .unwrap();\n\n log::info!('End of dump count data in solid format');\n }\n });\n\n s.spawn(|_| {\n if let Some(output) = spectrum_path.clone() {\n log::info!('Start of dump count data in spectrum');\n\n let writer = std::io::BufWriter::new(\n std::fs::File::create(&output)\n .with_context(|| Error::IO(CantOpenFile))\n .with_context(|| anyhow!('File {}', output.clone()))\n .unwrap(),\n );\n\n spectrum(writer, &counter)\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('File {} in spectrum format', output))\n .unwrap();\n\n log::info!('End of dump count data in spectrum');\n }\n });\n });\n}\n\n/// Write in the given instance of io::Write the count in `counter` in binary format.\npub fn binary(writer: W, counter: &counter::Counter) -> Result<()>\nwhere\n W: std::io::Write,\n{\n counter\n .serialize(writer)\n .with_context(|| Error::IO(ErrorDurringWrite))?;\n\n Ok(())\n}\n\n/// Write in the given instance of io::Write the count in `counter` in csv format.\n/// Only count upper than `abundance` is write.\npub fn csv(mut writer: W, counter: &counter::Counter, abundance: counter::Count) -> Result<()>\nwhere\n W: std::io::Write,\n{\n let counts = unsafe {\n &(*(counter.get_raw_count() as *const [counter::AtoCount] as *const [counter::Count]))\n };\n\n for (hash, value) in counts.iter().enumerate() {\n let kmer = if cocktail::kmer::parity_even(hash as u64) {\n kmer::kmer2seq((hash as u64) << 1, counter.k)\n } else {\n kmer::kmer2seq(((hash as u64) << 1) ^ 0b1, counter.k)\n };\n\n if value > &abundance {\n writeln!(writer, '{},{}', kmer, value).with_context(|| Error::IO(ErrorDurringWrite))?;\n }\n }\n\n Ok(())\n}\n\n/// Serialize in the given instance of io::Write an instance of [solid::Solid] build from counts in `counter` upper than `abundance`.\npub fn solid(writer: W, counter: &counter::Counter, abundance: counter::Count) -> Result<()>\nwhere\n W: std::io::Write,\n{\n let solid = solid::Solid::from_counter(counter, abundance);\n\n solid\n .serialize(writer)\n .with_context(|| Error::IO(ErrorDurringWrite))?;\n\n Ok(())\n}\n\n/// Write in the given instance of io::Write the kmer spectrum from counts in `counter`\npub fn spectrum(writer: W, counter: &counter::Counter) -> Result<()>\nwhere\n W: std::io::Write,\n{\n let spectrum = spectrum::Spectrum::from_counter(counter);\n\n spectrum\n .write_csv(writer)\n .with_context(|| Error::IO(ErrorDurringWrite))?;\n\n Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n lazy_static::lazy_static! {\n static ref COUNTER: crate::counter::Counter = {\n let mut counter = crate::counter::Counter::new(5);\n\n for i in 0..cocktail::kmer::get_kmer_space_size(5) {\n counter.inc(i);\n }\n\n counter.inc(0);\n\n counter\n };\n }\n\n const CSV_ABUNDANCE_MIN_1: &[u8] = &[\n 65, 65, 65, 65, 65, 44, 51, 10, 65, 65, 65, 65, 71, 44, 50, 10, 65, 65, 65, 67, 67, 44, 50,\n 10, 65, 65, 65, 67, 84, 44, 50, 10, 65, 65, 65, 84, 67, 44, 50, 10, 65, 65, 65, 84, 84, 44,\n 50, 10, 65, 65, 65, 71, 65, 44, 50, 10, 65, 65, 65, 71, 71, 44, 50, 10, 65, 65, 67, 65, 67,\n 44, 50, 10, 65, 65, 67, 65, 84, 44, 50, 10, 65, 65, 67, 67, 65, 44, 50, 10, 65, 65, 67, 67,\n 71, 44, 50, 10, 65, 65, 67, 84, 65, 44, 50, 10, 65, 65, 67, 84, 71, 44, 50, 10, 65, 65, 67,\n 71, 67, 44, 50, 10, 65, 65, 67, 71, 84, 44, 50, 10, 65, 65, 84, 65, 67, 44, 50, 10, 65, 65,\n 84, 65, 84, 44, 50, 10, 65, 65, 84, 67, 65, 44, 50, 10, 65, 65, 84, 67, 71, 44, 50, 10, 65,\n 65, 84, 84, 65, 44, 50, 10, 65, 65, 84, 84, 71, 44, 50, 10, 65, 65, 84, 71, 67, 44, 50, 10,\n 65, 65, 84, 71, 84, 44, 50, 10, 65, 65, 71, 65, 65, 44, 50, 10, 65, 65, 71, 65, 71, 44, 50,\n 10, 65, 65, 71, 67, 67, 44, 50, 10, 65, 65, 71, 67, 84, 44, 50, 10, 65, 65, 71, 84, 67, 44,\n 50, 10, 65, 65, 71, 84, 84, 44, 50, 10, 65, 65, 71, 71, 65, 44, 50, 10, 65, 65, 71, 71, 71,\n 44, 50, 10, 65, 67, 65, 65, 67, 44, 50, 10, 65, 67, 65, 65, 84, 44, 50, 10, 65, 67, 65, 67,\n 65, 44, 50, 10, 65, 67, 65, 67, 71, 44, 50, 10, 65, 67, 65, 84, 65, 44, 50, 10, 65, 67, 65,\n 84, 71, 44, 50, 10, 65, 67, 65, 71, 67, 44, 50, 10, 65, 67, 65, 71, 84, 44, 50, 10, 65, 67,\n 67, 65, 65, 44, 50, 10, 65, 67, 67, 65, 71, 44, 50, 10, 65, 67, 67, 67, 67, 44, 50, 10, 65,\n 67, 67, 67, 84, 44, 50, 10, 65, 67, 67, 84, 67, 44, 50, 10, 65, 67, 67, 84, 84, 44, 50, 10,\n 65, 67, 67, 71, 65, 44, 50, 10, 65, 67, 67, 71, 71, 44, 50, 10, 65, 67, 84, 65, 65, 44, 50,\n 10, 65, 67, 84, 65, 71, 44, 50, 10, 65, 67, 84, 67, 67, 44, 50, 10, 65, 67, 84, 67, 84, 44,\n 50, 10, 65, 67, 84, 84, 67, 44, 50, 10, 65, 67, 84, 84, 84, 44, 50, 10, 65, 67, 84, 71, 65,\n 44, 50, 10, 65, 67, 84, 71, 71, 44, 50, 10, 65, 67, 71, 65, 67, 44, 50, 10, 65, 67, 71, 65,\n 84, 44, 50, 10, 65, 67, 71, 67, 65, 44, 50, 10, 65, 67, 71, 67, 71, 44, 50, 10, 65, 67, 71,\n 84, 65, 44, 50, 10, 65, 67, 71, 84, 71, 44, 50, 10, 65, 67, 71, 71, 67, 44, 50, 10, 65, 67,\n 71, 71, 84, 44, 50, 10, 65, 84, 65, 65, 67, 44, 50, 10, 65, 84, 65, 65, 84, 44, 50, 10, 65,\n 84, 65, 67, 65, 44, 50, 10, 65, 84, 65, 67, 71, 44, 50, 10, 65, 84, 65, 84, 65, 44, 50, 10,\n 65, 84, 65, 84, 71, 44, 50, 10, 65, 84, 65, 71, 67, 44, 50, 10, 65, 84, 65, 71, 84, 44, 50,\n 10, 65, 84, 67, 65, 65, 44, 50, 10, 65, 84, 67, 65, 71, 44, 50, 10, 65, 84, 67, 67, 67, 44,\n 50, 10, 65, 84, 67, 67, 84, 44, 50, 10, 65, 84, 67, 84, 67, 44, 50, 10, 65, 84, 67, 84, 84,\n 44, 50, 10, 65, 84, 67, 71, 65, 44, 50, 10, 65, 84, 67, 71, 71, 44, 50, 10, 65, 84, 84, 65,\n 65, 44, 50, 10, 65, 84, 84, 65, 71, 44, 50, 10, 65, 84, 84, 67, 67, 44, 50, 10, 65, 84, 84,\n 67, 84, 44, 50, 10, 65, 84, 84, 84, 67, 44, 50, 10, 65, 84, 84, 84, 84, 44, 50, 10, 65, 84,\n 84, 71, 65, 44, 50, 10, 65, 84, 84, 71, 71, 44, 50, 10, 65, 84, 71, 65, 67, 44, 50, 10, 65,\n 84, 71, 65, 84, 44, 50, 10, 65, 84, 71, 67, 65, 44, 50, 10, 65, 84, 71, 67, 71, 44, 50, 10,\n 65, 84, 71, 84, 65, 44, 50, 10, 65, 84, 71, 84, 71, 44, 50, 10, 65, 84, 71, 71, 67, 44, 50,\n 10, 65, 84, 71, 71, 84, 44, 50, 10, 65, 71, 65, 65, 65, 44, 50, 10, 65, 71, 65, 65, 71, 44,\n 50, 10, 65, 71, 65, 67, 67, 44, 50, 10, 65, 71, 65, 67, 84, 44, 50, 10, 65, 71, 65, 84, 67,\n 44, 50, 10, 65, 71, 65, 84, 84, 44, 50, 10, 65, 71, 65, 71, 65, 44, 50, 10, 65, 71, 65, 71,\n 71, 44, 50, 10, 65, 71, 67, 65, 67, 44, 50, 10, 65, 71, 67, 65, 84, 44, 50, 10, 65, 71, 67,\n 67, 65, 44, 50, 10, 65, 71, 67, 67, 71, 44, 50, 10, 65, 71, 67, 84, 65, 44, 50, 10, 65, 71,\n 67, 84, 71, 44, 50, 10, 65, 71, 67, 71, 67, 44, 50, 10, 65, 71, 67, 71, 84, 44, 50, 10, 65,\n 71, 84, 65, 67, 44, 50, 10, 65, 71, 84, 65, 84, 44, 50, 10, 65, 71, 84, 67, 65, 44, 50, 10,\n 65, 71, 84, 67, 71, 44, 50, 10, 65, 71, 84, 84, 65, 44, 50, 10, 65, 71, 84, 84, 71, 44, 50,\n 10, 65, 71, 84, 71, 67, 44, 50, 10, 65, 71, 84, 71, 84, 44, 50, 10, 65, 71, 71, 65, 65, 44,\n 50, 10, 65, 71, 71, 65, 71, 44, 50, 10, 65, 71, 71, 67, 67, 44, 50, 10, 65, 71, 71, 67, 84,\n 44, 50, 10, 65, 71, 71, 84, 67, 44, 50, 10, 65, 71, 71, 84, 84, 44, 50, 10, 65, 71, 71, 71,\n 65, 44, 50, 10, 65, 71, 71, 71, 71, 44, 50, 10, 67, 65, 65, 65, 67, 44, 50, 10, 67, 65, 65,\n 65, 84, 44, 50, 10, 67, 65, 65, 67, 65, 44, 50, 10, 67, 65, 65, 67, 71, 44, 50, 10, 67, 65,\n 65, 84, 65, 44, 50, 10, 67, 65, 65, 84, 71, 44, 50, 10, 67, 65, 65, 71, 67, 44, 50, 10, 67,\n 65, 65, 71, 84, 44, 50, 10, 67, 65, 67, 65, 65, 44, 50, 10, 67, 65, 67, 65, 71, 44, 50, 10,\n 67, 65, 67, 67, 67, 44, 50, 10, 67, 65, 67, 67, 84, 44, 50, 10, 67, 65, 67, 84, 67, 44, 50,\n 10, 67, 65, 67, 84, 84, 44, 50, 10, 67, 65, 67, 71, 65, 44, 50, 10, 67, 65, 67, 71, 71, 44,\n 50, 10, 67, 65, 84, 65, 65, 44, 50, 10, 67, 65, 84, 65, 71, 44, 50, 10, 67, 65, 84, 67, 67,\n 44, 50, 10, 67, 65, 84, 67, 84, 44, 50, 10, 67, 65, 84, 84, 67, 44, 50, 10, 67, 65, 84, 84,\n 84, 44, 50, 10, 67, 65, 84, 71, 65, 44, 50, 10, 67, 65, 84, 71, 71, 44, 50, 10, 67, 65, 71,\n 65, 67, 44, 50, 10, 67, 65, 71, 65, 84, 44, 50, 10, 67, 65, 71, 67, 65, 44, 50, 10, 67, 65,\n 71, 67, 71, 44, 50, 10, 67, 65, 71, 84, 65, 44, 50, 10, 67, 65, 71, 84, 71, 44, 50, 10, 67,\n 65, 71, 71, 67, 44, 50, 10, 67, 65, 71, 71, 84, 44, 50, 10, 67, 67, 65, 65, 65, 44, 50, 10,\n 67, 67, 65, 65, 71, 44, 50, 10, 67, 67, 65, 67, 67, 44, 50, 10, 67, 67, 65, 67, 84, 44, 50,\n 10, 67, 67, 65, 84, 67, 44, 50, 10, 67, 67, 65, 84, 84, 44, 50, 10, 67, 67, 65, 71, 65, 44,\n 50, 10, 67, 67, 65, 71, 71, 44, 50, 10, 67, 67, 67, 65, 67, 44, 50, 10, 67, 67, 67, 65, 84,\n 44, 50, 10, 67, 67, 67, 67, 65, 44, 50, 10, 67, 67, 67, 67, 71, 44, 50, 10, 67, 67, 67, 84,\n 65, 44, 50, 10, 67, 67, 67, 84, 71, 44, 50, 10, 67, 67, 67, 71, 67, 44, 50, 10, 67, 67, 67,\n 71, 84, 44, 50, 10, 67, 67, 84, 65, 67, 44, 50, 10, 67, 67, 84, 65, 84, 44, 50, 10, 67, 67,\n 84, 67, 65, 44, 50, 10, 67, 67, 84, 67, 71, 44, 50, 10, 67, 67, 84, 84, 65, 44, 50, 10, 67,\n 67, 84, 84, 71, 44, 50, 10, 67, 67, 84, 71, 67, 44, 50, 10, 67, 67, 84, 71, 84, 44, 50, 10,\n 67, 67, 71, 65, 65, 44, 50, 10, 67, 67, 71, 65, 71, 44, 50, 10, 67, 67, 71, 67, 67, 44, 50,\n 10, 67, 67, 71, 67, 84, 44, 50, 10, 67, 67, 71, 84, 67, 44, 50, 10, 67, 67, 71, 84, 84, 44,\n 50, 10, 67, 67, 71, 71, 65, 44, 50, 10, 67, 67, 71, 71, 71, 44, 50, 10, 67, 84, 65, 65, 65,\n 44, 50, 10, 67, 84, 65, 65, 71, 44, 50, 10, 67, 84, 65, 67, 67, 44, 50, 10, 67, 84, 65, 67,\n 84, 44, 50, 10, 67, 84, 65, 84, 67, 44, 50, 10, 67, 84, 65, 84, 84, 44, 50, 10, 67, 84, 65,\n 71, 65, 44, 50, 10, 67, 84, 65, 71, 71, 44, 50, 10, 67, 84, 67, 65, 67, 44, 50, 10, 67, 84,\n 67, 65, 84, 44, 50, 10, 67, 84, 67, 67, 65, 44, 50, 10, 67, 84, 67, 67, 71, 44, 50, 10, 67,\n 84, 67, 84, 65, 44, 50, 10, 67, 84, 67, 84, 71, 44, 50, 10, 67, 84, 67, 71, 67, 44, 50, 10,\n 67, 84, 67, 71, 84, 44, 50, 10, 67, 84, 84, 65, 67, 44, 50, 10, 67, 84, 84, 65, 84, 44, 50,\n 10, 67, 84, 84, 67, 65, 44, 50, 10, 67, 84, 84, 67, 71, 44, 50, 10, 67, 84, 84, 84, 65, 44,\n 50, 10, 67, 84, 84, 84, 71, 44, 50, 10, 67, 84, 84, 71, 67, 44, 50, 10, 67, 84, 84, 71, 84,\n 44, 50, 10, 67, 84, 71, 65, 65, 44, 50, 10, 67, 84, 71, 65, 71, 44, 50, 10, 67, 84, 71, 67,\n 67, 44, 50, 10, 67, 84, 71, 67, 84, 44, 50, 10, 67, 84, 71, 84, 67, 44, 50, 10, 67, 84, 71,\n 84, 84, 44, 50, 10, 67, 84, 71, 71, 65, 44, 50, 10, 67, 84, 71, 71, 71, 44, 50, 10, 67, 71,\n 65, 65, 67, 44, 50, 10, 67, 71, 65, 65, 84, 44, 50, 10, 67, 71, 65, 67, 65, 44, 50, 10, 67,\n 71, 65, 67, 71, 44, 50, 10, 67, 71, 65, 84, 65, 44, 50, 10, 67, 71, 65, 84, 71, 44, 50, 10,\n 67, 71, 65, 71, 67, 44, 50, 10, 67, 71, 65, 71, 84, 44, 50, 10, 67, 71, 67, 65, 65, 44, 50,\n 10, 67, 71, 67, 65, 71, 44, 50, 10, 67, 71, 67, 67, 67, 44, 50, 10, 67, 71, 67, 67, 84, 44,\n 50, 10, 67, 71, 67, 84, 67, 44, 50, 10, 67, 71, 67, 84, 84, 44, 50, 10, 67, 71, 67, 71, 65,\n 44, 50, 10, 67, 71, 67, 71, 71, 44, 50, 10, 67, 71, 84, 65, 65, 44, 50, 10, 67, 71, 84, 65,\n 71, 44, 50, 10, 67, 71, 84, 67, 67, 44, 50, 10, 67, 71, 84, 67, 84, 44, 50, 10, 67, 71, 84,\n 84, 67, 44, 50, 10, 67, 71, 84, 84, 84, 44, 50, 10, 67, 71, 84, 71, 65, 44, 50, 10, 67, 71,\n 84, 71, 71, 44, 50, 10, 67, 71, 71, 65, 67, 44, 50, 10, 67, 71, 71, 65, 84, 44, 50, 10, 67,\n 71, 71, 67, 65, 44, 50, 10, 67, 71, 71, 67, 71, 44, 50, 10, 67, 71, 71, 84, 65, 44, 50, 10,\n 67, 71, 71, 84, 71, 44, 50, 10, 67, 71, 71, 71, 67, 44, 50, 10, 67, 71, 71, 71, 84, 44, 50,\n 10, 84, 65, 65, 65, 67, 44, 50, 10, 84, 65, 65, 65, 84, 44, 50, 10, 84, 65, 65, 67, 65, 44,\n 50, 10, 84, 65, 65, 67, 71, 44, 50, 10, 84, 65, 65, 84, 65, 44, 50, 10, 84, 65, 65, 84, 71,\n 44, 50, 10, 84, 65, 65, 71, 67, 44, 50, 10, 84, 65, 65, 71, 84, 44, 50, 10, 84, 65, 67, 65,\n 65, 44, 50, 10, 84, 65, 67, 65, 71, 44, 50, 10, 84, 65, 67, 67, 67, 44, 50, 10, 84, 65, 67,\n 67, 84, 44, 50, 10, 84, 65, 67, 84, 67, 44, 50, 10, 84, 65, 67, 84, 84, 44, 50, 10, 84, 65,\n 67, 71, 65, 44, 50, 10, 84, 65, 67, 71, 71, 44, 50, 10, 84, 65, 84, 65, 65, 44, 50, 10, 84,\n 65, 84, 65, 71, 44, 50, 10, 84, 65, 84, 67, 67, 44, 50, 10, 84, 65, 84, 67, 84, 44, 50, 10,\n 84, 65, 84, 84, 67, 44, 50, 10, 84, 65, 84, 84, 84, 44, 50, 10, 84, 65, 84, 71, 65, 44, 50,\n 10, 84, 65, 84, 71, 71, 44, 50, 10, 84, 65, 71, 65, 67, 44, 50, 10, 84, 65, 71, 65, 84, 44,\n 50, 10, 84, 65, 71, 67, 65, 44, 50, 10, 84, 65, 71, 67, 71, 44, 50, 10, 84, 65, 71, 84, 65,\n 44, 50, 10, 84, 65, 71, 84, 71, 44, 50, 10, 84, 65, 71, 71, 67, 44, 50, 10, 84, 65, 71, 71,\n 84, 44, 50, 10, 84, 67, 65, 65, 65, 44, 50, 10, 84, 67, 65, 65, 71, 44, 50, 10, 84, 67, 65,\n 67, 67, 44, 50, 10, 84, 67, 65, 67, 84, 44, 50, 10, 84, 67, 65, 84, 67, 44, 50, 10, 84, 67,\n 65, 84, 84, 44, 50, 10, 84, 67, 65, 71, 65, 44, 50, 10, 84, 67, 65, 71, 71, 44, 50, 10, 84,\n 67, 67, 65, 67, 44, 50, 10, 84, 67, 67, 65, 84, 44, 50, 10, 84, 67, 67, 67, 65, 44, 50, 10,\n 84, 67, 67, 67, 71, 44, 50, 10, 84, 67, 67, 84, 65, 44, 50, 10, 84, 67, 67, 84, 71, 44, 50,\n 10, 84, 67, 67, 71, 67, 44, 50, 10, 84, 67, 67, 71, 84, 44, 50, 10, 84, 67, 84, 65, 67, 44,\n 50, 10, 84, 67, 84, 65, 84, 44, 50, 10, 84, 67, 84, 67, 65, 44, 50, 10, 84, 67, 84, 67, 71,\n 44, 50, 10, 84, 67, 84, 84, 65, 44, 50, 10, 84, 67, 84, 84, 71, 44, 50, 10, 84, 67, 84, 71,\n 67, 44, 50, 10, 84, 67, 84, 71, 84, 44, 50, 10, 84, 67, 71, 65, 65, 44, 50, 10, 84, 67, 71,\n 65, 71, 44, 50, 10, 84, 67, 71, 67, 67, 44, 50, 10, 84, 67, 71, 67, 84, 44, 50, 10, 84, 67,\n 71, 84, 67, 44, 50, 10, 84, 67, 71, 84, 84, 44, 50, 10, 84, 67, 71, 71, 65, 44, 50, 10, 84,\n 67, 71, 71, 71, 44, 50, 10, 84, 84, 65, 65, 65, 44, 50, 10, 84, 84, 65, 65, 71, 44, 50, 10,\n 84, 84, 65, 67, 67, 44, 50, 10, 84, 84, 65, 67, 84, 44, 50, 10, 84, 84, 65, 84, 67, 44, 50,\n 10, 84, 84, 65, 84, 84, 44, 50, 10, 84, 84, 65, 71, 65, 44, 50, 10, 84, 84, 65, 71, 71, 44,\n 50, 10, 84, 84, 67, 65, 67, 44, 50, 10, 84, 84, 67, 65, 84, 44, 50, 10, 84, 84, 67, 67, 65,\n 44, 50, 10, 84, 84, 67, 67, 71, 44, 50, 10, 84, 84, 67, 84, 65, 44, 50, 10, 84, 84, 67, 84,\n 71, 44, 50, 10, 84, 84, 67, 71, 67, 44, 50, 10, 84, 84, 67, 71, 84, 44, 50, 10, 84, 84, 84,\n 65, 67, 44, 50, 10, 84, 84, 84, 65, 84, 44, 50, 10, 84, 84, 84, 67, 65, 44, 50, 10, 84, 84,\n 84, 67, 71, 44, 50, 10, 84, 84, 84, 84, 65, 44, 50, 10, 84, 84, 84, 84, 71, 44, 50, 10, 84,\n 84, 84, 71, 67, 44, 50, 10, 84, 84, 84, 71, 84, 44, 50, 10, 84, 84, 71, 65, 65, 44, 50, 10,\n 84, 84, 71, 65, 71, 44, 50, 10, 84, 84, 71, 67, 67, 44, 50, 10, 84, 84, 71, 67, 84, 44, 50,\n 10, 84, 84, 71, 84, 67, 44, 50, 10, 84, 84, 71, 84, 84, 44, 50, 10, 84, 84, 71, 71, 65, 44,\n 50, 10, 84, 84, 71, 71, 71, 44, 50, 10, 84, 71, 65, 65, 67, 44, 50, 10, 84, 71, 65, 65, 84,\n 44, 50, 10, 84, 71, 65, 67, 65, 44, 50, 10, 84, 71, 65, 67, 71, 44, 50, 10, 84, 71, 65, 84,\n 65, 44, 50, 10, 84, 71, 65, 84, 71, 44, 50, 10, 84, 71, 65, 71, 67, 44, 50, 10, 84, 71, 65,\n 71, 84, 44, 50, 10, 84, 71, 67, 65, 65, 44, 50, 10, 84, 71, 67, 65, 71, 44, 50, 10, 84, 71,\n 67, 67, 67, 44, 50, 10, 84, 71, 67, 67, 84, 44, 50, 10, 84, 71, 67, 84, 67, 44, 50, 10, 84,\n 71, 67, 84, 84, 44, 50, 10, 84, 71, 67, 71, 65, 44, 50, 10, 84, 71, 67, 71, 71, 44, 50, 10,\n 84, 71, 84, 65, 65, 44, 50, 10, 84, 71, 84, 65, 71, 44, 50, 10, 84, 71, 84, 67, 67, 44, 50,\n 10, 84, 71, 84, 67, 84, 44, 50, 10, 84, 71, 84, 84, 67, 44, 50, 10, 84, 71, 84, 84, 84, 44,\n 50, 10, 84, 71, 84, 71, 65, 44, 50, 10, 84, 71, 84, 71, 71, 44, 50, 10, 84, 71, 71, 65, 67,\n 44, 50, 10, 84, 71, 71, 65, 84, 44, 50, 10, 84, 71, 71, 67, 65, 44, 50, 10, 84, 71, 71, 67,\n 71, 44, 50, 10, 84, 71, 71, 84, 65, 44, 50, 10, 84, 71, 71, 84, 71, 44, 50, 10, 84, 71, 71,\n 71, 67, 44, 50, 10, 84, 71, 71, 71, 84, 44, 50, 10, 71, 65, 65, 65, 65, 44, 50, 10, 71, 65,\n 65, 65, 71, 44, 50, 10, 71, 65, 65, 67, 67, 44, 50, 10, 71, 65, 65, 67, 84, 44, 50, 10, 71,\n 65, 65, 84, 67, 44, 50, 10, 71, 65, 65, 84, 84, 44, 50, 10, 71, 65, 65, 71, 65, 44, 50, 10,\n 71, 65, 65, 71, 71, 44, 50, 10, 71, 65, 67, 65, 67, 44, 50, 10, 71, 65, 67, 65, 84, 44, 50,\n 10, 71, 65, 67, 67, 65, 44, 50, 10, 71, 65, 67, 67, 71, 44, 50, 10, 71, 65, 67, 84, 65, 44,\n 50, 10, 71, 65, 67, 84, 71, 44, 50, 10, 71, 65, 67, 71, 67, 44, 50, 10, 71, 65, 67, 71, 84,\n 44, 50, 10, 71, 65, 84, 65, 67, 44, 50, 10, 71, 65, 84, 65, 84, 44, 50, 10, 71, 65, 84, 67,\n 65, 44, 50, 10, 71, 65, 84, 67, 71, 44, 50, 10, 71, 65, 84, 84, 65, 44, 50, 10, 71, 65, 84,\n 84, 71, 44, 50, 10, 71, 65, 84, 71, 67, 44, 50, 10, 71, 65, 84, 71, 84, 44, 50, 10, 71, 65,\n 71, 65, 65, 44, 50, 10, 71, 65, 71, 65, 71, 44, 50, 10, 71, 65, 71, 67, 67, 44, 50, 10, 71,\n 65, 71, 67, 84, 44, 50, 10, 71, 65, 71, 84, 67, 44, 50, 10, 71, 65, 71, 84, 84, 44, 50, 10,\n 71, 65, 71, 71, 65, 44, 50, 10, 71, 65, 71, 71, 71, 44, 50, 10, 71, 67, 65, 65, 67, 44, 50,\n 10, 71, 67, 65, 65, 84, 44, 50, 10, 71, 67, 65, 67, 65, 44, 50, 10, 71, 67, 65, 67, 71, 44,\n 50, 10, 71, 67, 65, 84, 65, 44, 50, 10, 71, 67, 65, 84, 71, 44, 50, 10, 71, 67, 65, 71, 67,\n 44, 50, 10, 71, 67, 65, 71, 84, 44, 50, 10, 71, 67, 67, 65, 65, 44, 50, 10, 71, 67, 67, 65,\n 71, 44, 50, 10, 71, 67, 67, 67, 67, 44, 50, 10, 71, 67, 67, 67, 84, 44, 50, 10, 71, 67, 67,\n 84, 67, 44, 50, 10, 71, 67, 67, 84, 84, 44, 50, 10, 71, 67, 67, 71, 65, 44, 50, 10, 71, 67,\n 67, 71, 71, 44, 50, 10, 71, 67, 84, 65, 65, 44, 50, 10, 71, 67, 84, 65, 71, 44, 50, 10, 71,\n 67, 84, 67, 67, 44, 50, 10, 71, 67, 84, 67, 84, 44, 50, 10, 71, 67, 84, 84, 67, 44, 50, 10,\n 71, 67, 84, 84, 84, 44, 50, 10, 71, 67, 84, 71, 65, 44, 50, 10, 71, 67, 84, 71, 71, 44, 50,\n 10, 71, 67, 71, 65, 67, 44, 50, 10, 71, 67, 71, 65, 84, 44, 50, 10, 71, 67, 71, 67, 65, 44,\n 50, 10, 71, 67, 71, 67, 71, 44, 50, 10, 71, 67, 71, 84, 65, 44, 50, 10, 71, 67, 71, 84, 71,\n 44, 50, 10, 71, 67, 71, 71, 67, 44, 50, 10, 71, 67, 71, 71, 84, 44, 50, 10, 71, 84, 65, 65,\n 67, 44, 50, 10, 71, 84, 65, 65, 84, 44, 50, 10, 71, 84, 65, 67, 65, 44, 50, 10, 71, 84, 65,\n 67, 71, 44, 50, 10, 71, 84, 65, 84, 65, 44, 50, 10, 71, 84, 65, 84, 71, 44, 50, 10, 71, 84,\n 65, 71, 67, 44, 50, 10, 71, 84, 65, 71, 84, 44, 50, 10, 71, 84, 67, 65, 65, 44, 50, 10, 71,\n 84, 67, 65, 71, 44, 50, 10, 71, 84, 67, 67, 67, 44, 50, 10, 71, 84, 67, 67, 84, 44, 50, 10,\n 71, 84, 67, 84, 67, 44, 50, 10, 71, 84, 67, 84, 84, 44, 50, 10, 71, 84, 67, 71, 65, 44, 50,\n 10, 71, 84, 67, 71, 71, 44, 50, 10, 71, 84, 84, 65, 65, 44, 50, 10, 71, 84, 84, 65, 71, 44,\n 50, 10, 71, 84, 84, 67, 67, 44, 50, 10, 71, 84, 84, 67, 84, 44, 50, 10, 71, 84, 84, 84, 67,\n 44, 50, 10, 71, 84, 84, 84, 84, 44, 50, 10, 71, 84, 84, 71, 65, 44, 50, 10, 71, 84, 84, 71,\n 71, 44, 50, 10, 71, 84, 71, 65, 67, 44, 50, 10, 71, 84, 71, 65, 84, 44, 50, 10, 71, 84, 71,\n 67, 65, 44, 50, 10, 71, 84, 71, 67, 71, 44, 50, 10, 71, 84, 71, 84, 65, 44, 50, 10, 71, 84,\n 71, 84, 71, 44, 50, 10, 71, 84, 71, 71, 67, 44, 50, 10, 71, 84, 71, 71, 84, 44, 50, 10, 71,\n 71, 65, 65, 65, 44, 50, 10, 71, 71, 65, 65, 71, 44, 50, 10, 71, 71, 65, 67, 67, 44, 50, 10,\n 71, 71, 65, 67, 84, 44, 50, 10, 71, 71, 65, 84, 67, 44, 50, 10, 71, 71, 65, 84, 84, 44, 50,\n 10, 71, 71, 65, 71, 65, 44, 50, 10, 71, 71, 65, 71, 71, 44, 50, 10, 71, 71, 67, 65, 67, 44,\n 50, 10, 71, 71, 67, 65, 84, 44, 50, 10, 71, 71, 67, 67, 65, 44, 50, 10, 71, 71, 67, 67, 71,\n 44, 50, 10, 71, 71, 67, 84, 65, 44, 50, 10, 71, 71, 67, 84, 71, 44, 50, 10, 71, 71, 67, 71,\n 67, 44, 50, 10, 71, 71, 67, 71, 84, 44, 50, 10, 71, 71, 84, 65, 67, 44, 50, 10, 71, 71, 84,\n 65, 84, 44, 50, 10, 71, 71, 84, 67, 65, 44, 50, 10, 71, 71, 84, 67, 71, 44, 50, 10, 71, 71,\n 84, 84, 65, 44, 50, 10, 71, 71, 84, 84, 71, 44, 50, 10, 71, 71, 84, 71, 67, 44, 50, 10, 71,\n 71, 84, 71, 84, 44, 50, 10, 71, 71, 71, 65, 65, 44, 50, 10, 71, 71, 71, 65, 71, 44, 50, 10,\n 71, 71, 71, 67, 67, 44, 50, 10, 71, 71, 71, 67, 84, 44, 50, 10, 71, 71, 71, 84, 67, 44, 50,\n 10, 71, 71, 71, 84, 84, 44, 50, 10, 71, 71, 71, 71, 65, 44, 50, 10, 71, 71, 71, 71, 71, 44,\n 50, 10,\n ];\n\n const CSV_ABUNDANCE_MIN_2: &[u8] = &[65, 65, 65, 65, 65, 44, 51, 10];\n\n #[test]\n fn csv() {\n let mut outfile = Vec::new();\n let counter = &*COUNTER;\n\n crate::dump::csv(&mut outfile, counter, 1).unwrap();\n assert_eq!(&outfile[..], &CSV_ABUNDANCE_MIN_1[..]);\n\n outfile.clear();\n\n crate::dump::csv(&mut outfile, counter, 2).unwrap();\n assert_eq!(&outfile[..], &CSV_ABUNDANCE_MIN_2[..]);\n }\n\n const SOLID_ABUNDANCE_MIN_1: &[u8] = &[\n 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 165, 192, 49, 1, 0, 0, 0, 64, 176, 75, 255, 200, 132,\n 48, 156, 2, 70, 0, 241, 137, 65, 0, 0, 0,\n ];\n\n const SOLID_ABUNDANCE_MIN_2: &[u8] = &[\n 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 165, 192, 49, 1, 0, 0, 0, 130, 48, 61, 232, 95, 153, 16,\n 140, 175, 17, 95, 201, 40, 124, 65, 0, 0, 0,\n ];\n\n #[test]\n fn solid() {\n let mut outfile = Vec::new();\n let counter = &*COUNTER;\n\n crate::dump::solid(&mut outfile, counter, 1).unwrap();\n assert_eq!(&outfile[..], &SOLID_ABUNDANCE_MIN_1[..]);\n\n outfile.clear();\n\n crate::dump::solid(&mut outfile, counter, 2).unwrap();\n assert_eq!(&outfile[..], &SOLID_ABUNDANCE_MIN_2[..]);\n }\n\n const SPECTRUM_ABUNDANCE_MIN_1: &[u8] = &[\n 48, 44, 48, 10, 49, 44, 48, 10, 50, 44, 53, 49, 49, 10, 51, 44, 49, 10, 52, 44, 48, 10, 53,\n 44, 48, 10, 54, 44, 48, 10, 55, 44, 48, 10, 56, 44, 48, 10, 57, 44, 48, 10, 49, 48, 44, 48,\n 10, 49, 49, 44, 48, 10, 49, 50, 44, 48, 10, 49, 51, 44, 48, 10, 49, 52, 44, 48, 10, 49, 53,\n 44, 48, 10, 49, 54, 44, 48, 10, 49, 55, 44, 48, 10, 49, 56, 44, 48, 10, 49, 57, 44, 48, 10,\n 50, 48, 44, 48, 10, 50, 49, 44, 48, 10, 50, 50, 44, 48, 10, 50, 51, 44, 48, 10, 50, 52, 44,\n 48, 10, 50, 53, 44, 48, 10, 50, 54, 44, 48, 10, 50, 55, 44, 48, 10, 50, 56, 44, 48, 10, 50,\n 57, 44, 48, 10, 51, 48, 44, 48, 10, 51, 49, 44, 48, 10, 51, 50, 44, 48, 10, 51, 51, 44, 48,\n 10, 51, 52, 44, 48, 10, 51, 53, 44, 48, 10, 51, 54, 44, 48, 10, 51, 55, 44, 48, 10, 51, 56,\n 44, 48, 10, 51, 57, 44, 48, 10, 52, 48, 44, 48, 10, 52, 49, 44, 48, 10, 52, 50, 44, 48, 10,\n 52, 51, 44, 48, 10, 52, 52, 44, 48, 10, 52, 53, 44, 48, 10, 52, 54, 44, 48, 10, 52, 55, 44,\n 48, 10, 52, 56, 44, 48, 10, 52, 57, 44, 48, 10, 53, 48, 44, 48, 10, 53, 49, 44, 48, 10, 53,\n 50, 44, 48, 10, 53, 51, 44, 48, 10, 53, 52, 44, 48, 10, 53, 53, 44, 48, 10, 53, 54, 44, 48,\n 10, 53, 55, 44, 48, 10, 53, 56, 44, 48, 10, 53, 57, 44, 48, 10, 54, 48, 44, 48, 10, 54, 49,\n 44, 48, 10, 54, 50, 44, 48, 10, 54, 51, 44, 48, 10, 54, 52, 44, 48, 10, 54, 53, 44, 48, 10,\n 54, 54, 44, 48, 10, 54, 55, 44, 48, 10, 54, 56, 44, 48, 10, 54, 57, 44, 48, 10, 55, 48, 44,\n 48, 10, 55, 49, 44, 48, 10, 55, 50, 44, 48, 10, 55, 51, 44, 48, 10, 55, 52, 44, 48, 10, 55,\n 53, 44, 48, 10, 55, 54, 44, 48, 10, 55, 55, 44, 48, 10, 55, 56, 44, 48, 10, 55, 57, 44, 48,\n 10, 56, 48, 44, 48, 10, 56, 49, 44, 48, 10, 56, 50, 44, 48, 10, 56, 51, 44, 48, 10, 56, 52,\n 44, 48, 10, 56, 53, 44, 48, 10, 56, 54, 44, 48, 10, 56, 55, 44, 48, 10, 56, 56, 44, 48, 10,\n 56, 57, 44, 48, 10, 57, 48, 44, 48, 10, 57, 49, 44, 48, 10, 57, 50, 44, 48, 10, 57, 51, 44,\n 48, 10, 57, 52, 44, 48, 10, 57, 53, 44, 48, 10, 57, 54, 44, 48, 10, 57, 55, 44, 48, 10, 57,\n 56, 44, 48, 10, 57, 57, 44, 48, 10, 49, 48, 48, 44, 48, 10, 49, 48, 49, 44, 48, 10, 49, 48,\n 50, 44, 48, 10, 49, 48, 51, 44, 48, 10, 49, 48, 52, 44, 48, 10, 49, 48, 53, 44, 48, 10, 49,\n 48, 54, 44, 48, 10, 49, 48, 55, 44, 48, 10, 49, 48, 56, 44, 48, 10, 49, 48, 57, 44, 48, 10,\n 49, 49, 48, 44, 48, 10, 49, 49, 49, 44, 48, 10, 49, 49, 50, 44, 48, 10, 49, 49, 51, 44, 48,\n 10, 49, 49, 52, 44, 48, 10, 49, 49, 53, 44, 48, 10, 49, 49, 54, 44, 48, 10, 49, 49, 55, 44,\n 48, 10, 49, 49, 56, 44, 48, 10, 49, 49, 57, 44, 48, 10, 49, 50, 48, 44, 48, 10, 49, 50, 49,\n 44, 48, 10, 49, 50, 50, 44, 48, 10, 49, 50, 51, 44, 48, 10, 49, 50, 52, 44, 48, 10, 49, 50,\n 53, 44, 48, 10, 49, 50, 54, 44, 48, 10, 49, 50, 55, 44, 48, 10, 49, 50, 56, 44, 48, 10, 49,\n 50, 57, 44, 48, 10, 49, 51, 48, 44, 48, 10, 49, 51, 49, 44, 48, 10, 49, 51, 50, 44, 48, 10,\n 49, 51, 51, 44, 48, 10, 49, 51, 52, 44, 48, 10, 49, 51, 53, 44, 48, 10, 49, 51, 54, 44, 48,\n 10, 49, 51, 55, 44, 48, 10, 49, 51, 56, 44, 48, 10, 49, 51, 57, 44, 48, 10, 49, 52, 48, 44,\n 48, 10, 49, 52, 49, 44, 48, 10, 49, 52, 50, 44, 48, 10, 49, 52, 51, 44, 48, 10, 49, 52, 52,\n 44, 48, 10, 49, 52, 53, 44, 48, 10, 49, 52, 54, 44, 48, 10, 49, 52, 55, 44, 48, 10, 49, 52,\n 56, 44, 48, 10, 49, 52, 57, 44, 48, 10, 49, 53, 48, 44, 48, 10, 49, 53, 49, 44, 48, 10, 49,\n 53, 50, 44, 48, 10, 49, 53, 51, 44, 48, 10, 49, 53, 52, 44, 48, 10, 49, 53, 53, 44, 48, 10,\n 49, 53, 54, 44, 48, 10, 49, 53, 55, 44, 48, 10, 49, 53, 56, 44, 48, 10, 49, 53, 57, 44, 48,\n 10, 49, 54, 48, 44, 48, 10, 49, 54, 49, 44, 48, 10, 49, 54, 50, 44, 48, 10, 49, 54, 51, 44,\n 48, 10, 49, 54, 52, 44, 48, 10, 49, 54, 53, 44, 48, 10, 49, 54, 54, 44, 48, 10, 49, 54, 55,\n 44, 48, 10, 49, 54, 56, 44, 48, 10, 49, 54, 57, 44, 48, 10, 49, 55, 48, 44, 48, 10, 49, 55,\n 49, 44, 48, 10, 49, 55, 50, 44, 48, 10, 49, 55, 51, 44, 48, 10, 49, 55, 52, 44, 48, 10, 49,\n 55, 53, 44, 48, 10, 49, 55, 54, 44, 48, 10, 49, 55, 55, 44, 48, 10, 49, 55, 56, 44, 48, 10,\n 49, 55, 57, 44, 48, 10, 49, 56, 48, 44, 48, 10, 49, 56, 49, 44, 48, 10, 49, 56, 50, 44, 48,\n 10, 49, 56, 51, 44, 48, 10, 49, 56, 52, 44, 48, 10, 49, 56, 53, 44, 48, 10, 49, 56, 54, 44,\n 48, 10, 49, 56, 55, 44, 48, 10, 49, 56, 56, 44, 48, 10, 49, 56, 57, 44, 48, 10, 49, 57, 48,\n 44, 48, 10, 49, 57, 49, 44, 48, 10, 49, 57, 50, 44, 48, 10, 49, 57, 51, 44, 48, 10, 49, 57,\n 52, 44, 48, 10, 49, 57, 53, 44, 48, 10, 49, 57, 54, 44, 48, 10, 49, 57, 55, 44, 48, 10, 49,\n 57, 56, 44, 48, 10, 49, 57, 57, 44, 48, 10, 50, 48, 48, 44, 48, 10, 50, 48, 49, 44, 48, 10,\n 50, 48, 50, 44, 48, 10, 50, 48, 51, 44, 48, 10, 50, 48, 52, 44, 48, 10, 50, 48, 53, 44, 48,\n 10, 50, 48, 54, 44, 48, 10, 50, 48, 55, 44, 48, 10, 50, 48, 56, 44, 48, 10, 50, 48, 57, 44,\n 48, 10, 50, 49, 48, 44, 48, 10, 50, 49, 49, 44, 48, 10, 50, 49, 50, 44, 48, 10, 50, 49, 51,\n 44, 48, 10, 50, 49, 52, 44, 48, 10, 50, 49, 53, 44, 48, 10, 50, 49, 54, 44, 48, 10, 50, 49,\n 55, 44, 48, 10, 50, 49, 56, 44, 48, 10, 50, 49, 57, 44, 48, 10, 50, 50, 48, 44, 48, 10, 50,\n 50, 49, 44, 48, 10, 50, 50, 50, 44, 48, 10, 50, 50, 51, 44, 48, 10, 50, 50, 52, 44, 48, 10,\n 50, 50, 53, 44, 48, 10, 50, 50, 54, 44, 48, 10, 50, 50, 55, 44, 48, 10, 50, 50, 56, 44, 48,\n 10, 50, 50, 57, 44, 48, 10, 50, 51, 48, 44, 48, 10, 50, 51, 49, 44, 48, 10, 50, 51, 50, 44,\n 48, 10, 50, 51, 51, 44, 48, 10, 50, 51, 52, 44, 48, 10, 50, 51, 53, 44, 48, 10, 50, 51, 54,\n 44, 48, 10, 50, 51, 55, 44, 48, 10, 50, 51, 56, 44, 48, 10, 50, 51, 57, 44, 48, 10, 50, 52,\n 48, 44, 48, 10, 50, 52, 49, 44, 48, 10, 50, 52, 50, 44, 48, 10, 50, 52, 51, 44, 48, 10, 50,\n 52, 52, 44, 48, 10, 50, 52, 53, 44, 48, 10, 50, 52, 54, 44, 48, 10, 50, 52, 55, 44, 48, 10,\n 50, 52, 56, 44, 48, 10, 50, 52, 57, 44, 48, 10, 50, 53, 48, 44, 48, 10, 50, 53, 49, 44, 48,\n 10, 50, 53, 50, 44, 48, 10, 50, 53, 51, 44, 48, 10, 50, 53, 52, 44, 48, 10, 50, 53, 53, 44,\n 48, 10,\n ];\n\n #[test]\n fn spectrum() {\n let mut outfile = Vec::new();\n let counter = &*COUNTER;\n\n crate::dump::spectrum(&mut outfile, counter).unwrap();\n\n assert_eq!(&outfile[..], &SPECTRUM_ABUNDANCE_MIN_1[..]);\n }\n}\n","mit" +"pcon","./pcon/src/error.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse thiserror::Error;\n\n/// All error produce by Pcon\n#[derive(Debug, Error)]\npub enum Error {\n /// See enum [Cli]\n #[error(transparent)]\n Cli(#[from] Cli),\n\n /// See enum [IO]\n #[error(transparent)]\n IO(#[from] IO),\n}\n\n/// Error emmit durring Cli parsing\n#[derive(Debug, Error)]\npub enum Cli {\n /// For efficient computation of canonical the kmer size must be odd\n #[error('Kmer size must be odd')]\n KMustBeOdd,\n\n /// Kmer is store 2bit form on 64bit we can't manage larger kmer \n #[error('Kmer size must be lower than 32')]\n KMustBeLower32,\n\n /// You must set at least one dump option csv, solid, spectrum\n #[error('You must set at least one dump option csv, solid, spectrum')]\n ADumpOptionMustBeSet,\n}\n\n/// Error emmit when pcon try to work with file\n#[repr(C)]\n#[derive(Debug, Error)]\npub enum IO {\n /// We can't create file. In C binding it's equal to 0\n #[error('We can't create file')]\n CantCreateFile,\n\n /// We can't open file. In C binding it's equal to 1\n #[error('We can't open file')]\n CantOpenFile,\n\n /// Error durring write in file. In C binding it's equal to 2\n #[error('Error durring write')]\n ErrorDurringWrite,\n\n /// Error durring read file. In C binding it's equal to 3\n #[error('Error durring read')]\n ErrorDurringRead,\n\n /// No error, this exist only for C binding it's the value of a new error pointer\n #[error('Isn't error if you see this please contact the author with this message and a description of what you do with pcon')]\n NoError,\n}\n","mit" +"pcon","./pcon/src/count.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\n\n/* local use */\nuse crate::error::IO::*;\nuse crate::error::*;\nuse crate::*;\n\npub fn count(params: cli::SubCommandCount) -> Result<()> {\n let params = cli::check_count_param(params)?;\n\n let record_buffer = if let Some(len) = params.record_buffer {\n len\n } else {\n 8192\n };\n\n log::info!('Start of count structure initialization');\n let mut counter = counter::Counter::new(params.kmer);\n log::info!('End of count structure initialization');\n\n for input in params.inputs.iter() {\n log::info!('Start of kmer count of the file {}', input);\n let reader = niffler::get_reader(Box::new(\n std::fs::File::open(input)\n .with_context(|| Error::IO(CantOpenFile))\n .with_context(|| anyhow!('File {}', input.clone()))?,\n ))\n .with_context(|| anyhow!('File {}', input.clone()))?\n .0;\n\n counter.count_fasta(reader, record_buffer);\n\n log::info!('End of kmer count of the file {}', &input);\n }\n\n dump::dump_worker(\n counter,\n params.output,\n params.csv,\n params.solid,\n params.spectrum,\n params.abundance,\n );\n\n Ok(())\n}\n","mit" +"pcon","./pcon/src/counter.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* std use */\nuse std::io::Read;\nuse std::io::Write;\nuse std::sync::atomic;\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse byteorder::{ReadBytesExt, WriteBytesExt};\nuse rayon::prelude::*;\n\n/* local use */\nuse crate::error::IO::*;\nuse crate::error::*;\n\npub type AtoCount = atomic::AtomicU8;\npub type Count = u8;\n\n/// A counter of kmer based on cocktail crate 2bit conversion, canonicalisation and hashing.\n/// If kmer occure more than 256 other occurence are ignored\npub struct Counter {\n pub k: u8,\n count: Box<[AtoCount]>,\n}\n\nimpl Counter {\n /// Create a new Counter for kmer size equal to k, record_buffer_len control the number of record read in same time\n pub fn new(k: u8) -> Self {\n let tmp = vec![0u8; cocktail::kmer::get_hash_space_size(k) as usize];\n\n Self {\n k,\n count: unsafe {\n std::mem::transmute::, Box<[AtoCount]>>(tmp.into_boxed_slice())\n },\n }\n }\n\n /// Read the given an instance of io::Read as a fasta format and count kmer init\n pub fn count_fasta(&mut self, fasta: R, record_buffer_len: usize)\n where\n R: std::io::Read,\n {\n let mut reader = noodles::fasta::Reader::new(std::io::BufReader::new(fasta));\n\n let mut iter = reader.records();\n let mut records = Vec::with_capacity(record_buffer_len);\n\n let mut end = false;\n while !end {\n for i in 0..record_buffer_len {\n if let Some(Ok(record)) = iter.next() {\n records.push(record);\n } else {\n end = true;\n records.truncate(i);\n break;\n }\n }\n\n log::info!('Buffer len: {}', records.len());\n\n records.par_iter().for_each(|record| {\n if record.sequence().len() >= self.k as usize {\n let tokenizer =\n cocktail::tokenizer::Canonical::new(record.sequence().as_ref(), self.k);\n\n for canonical in tokenizer {\n Counter::inc_canonic_ato(&self.count, canonical);\n }\n }\n });\n\n records.clear()\n }\n }\n\n /// Increase the counter of a kmer\n pub fn inc(&mut self, kmer: u64) {\n self.inc_canonic(cocktail::kmer::canonical(kmer, self.k));\n }\n\n /// Increase the counter of a canonical kmer\n pub fn inc_canonic(&self, canonical: u64) {\n Counter::inc_canonic_ato(&self.count, canonical);\n }\n\n fn inc_canonic_ato(count: &[AtoCount], canonical: u64) {\n let hash = (canonical >> 1) as usize;\n\n if count[hash].load(std::sync::atomic::Ordering::SeqCst) != std::u8::MAX {\n count[hash].fetch_add(1, std::sync::atomic::Ordering::SeqCst);\n }\n }\n\n /// Get the counter of a kmer\n pub fn get(&self, kmer: u64) -> Count {\n self.get_canonic(cocktail::kmer::canonical(kmer, self.k))\n }\n\n /// Get the counter of a canonical kmer\n pub fn get_canonic(&self, canonical: u64) -> Count {\n let hash = (canonical >> 1) as usize;\n\n self.count[hash].load(atomic::Ordering::SeqCst)\n }\n\n pub(crate) fn get_raw_count(&self) -> &[AtoCount] {\n &self.count\n }\n\n /// Serialize counter in given [std::io::Write]\n pub fn serialize(&self, w: W) -> Result<()>\n where\n W: std::io::Write,\n {\n let mut writer = w;\n let count = unsafe { &*(&self.count as *const Box<[AtoCount]> as *const Box<[Count]>) };\n\n writer\n .write_u8(self.k)\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('Error durring serialize counter'))?;\n\n for b in count\n .par_chunks(2usize.pow(25))\n .map(|in_buffer| {\n let mut out_buffer = Vec::new();\n\n {\n let mut writer =\n flate2::write::GzEncoder::new(&mut out_buffer, flate2::Compression::fast());\n\n writer\n .write_all(in_buffer)\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('Error durring serialize counter'))?;\n }\n\n Ok(out_buffer)\n })\n .collect::>>>()\n {\n let buf = b?;\n\n writer\n .write_all(&buf)\n .with_context(|| Error::IO(ErrorDurringWrite))\n .with_context(|| anyhow!('Error durring serialize counter'))?;\n }\n\n Ok(())\n }\n\n /// Deserialize counter for given [std::io::Read]\n pub fn deserialize(r: R) -> Result\n where\n R: std::io::Read,\n {\n let mut reader = r;\n\n let k = reader\n .read_u8()\n .with_context(|| Error::IO(ErrorDurringRead))\n .with_context(|| anyhow!('Error durring deserialize counter'))?;\n\n let mut deflate = flate2::read::MultiGzDecoder::new(reader);\n let mut tmp = vec![0u8; cocktail::kmer::get_hash_space_size(k) as usize].into_boxed_slice();\n\n deflate\n .read_exact(&mut tmp)\n .with_context(|| Error::IO(ErrorDurringRead))\n .with_context(|| anyhow!('Error durring deserialize counter'))?;\n\n Ok(Self {\n k,\n count: unsafe { std::mem::transmute::, Box<[AtoCount]>>(tmp) },\n })\n }\n\n /// Convert a counter in a StaticCounter\n pub fn into_static(self) -> crate::static_counter::StaticCounter {\n crate::static_counter::StaticCounter {\n k: self.k,\n count: unsafe { std::mem::transmute::, Box<[Count]>>(self.count) },\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n const FASTA_FILE: &[u8] = b'>random_seq 0\nGTTCTGCAAATTAGAACAGACAATACACTGGCAGGCGTTGCGTTGGGGGAGATCTTCCGTAACGAGCCGGCATTTGTAAGAAAGAGATTTCGAGTAAATG\n>random_seq 1\nAGGATAGAAGCTTAAGTACAAGATAATTCCCATAGAGGAAGGGTGGTATTACAGTGCCGCCTGTTGAAAGCCCCAATCCCGCTTCAATTGTTGAGCTCAG\n';\n\n const FASTA_COUNT: &[u8] = &[\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 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,\n 1, 1,\n ];\n\n #[test]\n fn count_fasta() {\n let mut counter = crate::counter::Counter::new(5);\n\n counter.count_fasta(FASTA_FILE, 1);\n\n unsafe {\n assert_eq!(\n std::mem::transmute::<&[AtoCount], &[Count]>(counter.get_raw_count()),\n &FASTA_COUNT[..]\n );\n }\n }\n\n const FASTQ_FILE: &[u8] = b'@random_seq 0\nCCAGTAGCTTGGTGTACCGACGCTGTAGAGTTACAGTCTCGCGTGGATATAAGCTACTATCGACAGCAGGGTACGTTGTGAGTAATCTAACGTCATCTCT\n+\nX-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\n@random_seq 1\nTCAAATTGGCCGCCGCACAGTGAACCCGGAACTAAACAAGCACCGCACCGTTTGGTACACTTGAACACCGTATAAATTCATGGTGTTTATAAGCCAATGG\n+\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* project mod declaration */\npub mod cli;\npub mod error;\n\npub mod count;\npub mod counter;\npub mod dump;\npub mod solid;\npub mod spectrum;\npub mod static_counter;\n\npub mod binding;\n\n/// Set the number of threads use by pcon\npub fn set_nb_threads(nb_threads: usize) {\n rayon::ThreadPoolBuilder::new()\n .num_threads(nb_threads)\n .build_global()\n .unwrap();\n}\n","mit" +"pcon","./pcon/src/main.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::Result;\nuse clap::Parser;\n\nuse pcon::*;\n\nfn main() -> Result<()> {\n let params = cli::Command::parse();\n\n if let Some(level) = cli::i82level(params.verbosity) {\n env_logger::builder()\n .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis))\n .filter_level(level.to_level_filter())\n .init();\n } else {\n env_logger::Builder::from_env('PCON_LOG')\n .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis))\n .init();\n }\n\n if let Some(threads) = params.threads {\n log::info!('Set number of threads to {}', threads);\n\n set_nb_threads(threads);\n }\n\n match params.subcmd {\n cli::SubCommand::Count(params) => count::count(params),\n cli::SubCommand::Dump(params) => dump::dump(params),\n }\n}\n","mit" +"fpa","./fpa/src/io/paf.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* local use */\nuse crate::io;\n\n/* standard use */\nuse std::cmp::min;\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct Record {\n pub read_a: String,\n pub length_a: u64,\n pub begin_a: u64,\n pub end_a: u64,\n pub strand: char,\n pub read_b: String,\n pub length_b: u64,\n pub begin_b: u64,\n pub end_b: u64,\n pub nb_match_base: u64,\n pub nb_base: u64,\n pub mapping_quality: u64,\n pub sam_field: Vec,\n pub position: (u64, u64),\n}\n\nimpl io::MappingRecord for Record {\n fn read_a(&self) -> String {\n self.read_a.clone()\n }\n\n fn length_a(&self) -> u64 {\n self.length_a\n }\n\n fn begin_a(&self) -> u64 {\n self.begin_a\n }\n\n fn end_a(&self) -> u64 {\n self.end_a\n }\n\n fn strand(&self) -> char {\n self.strand\n }\n\n fn read_b(&self) -> String {\n self.read_b.clone()\n }\n\n fn length_b(&self) -> u64 {\n self.length_b\n }\n\n fn begin_b(&self) -> u64 {\n self.begin_b\n }\n\n fn end_b(&self) -> u64 {\n self.end_b\n }\n\n fn position(&self) -> (u64, u64) {\n self.position\n }\n\n fn set_position(&mut self, p: (u64, u64)) {\n self.position = p;\n }\n\n fn length(&self) -> u64 {\n min(self.end_a - self.begin_a, self.end_b - self.begin_b)\n }\n\n fn len_to_end_a(&self) -> u64 {\n self.length_a - self.end_a\n }\n\n fn len_to_end_b(&self) -> u64 {\n self.length_b - self.end_b\n }\n\n fn set_read_a(&mut self, new_name: String) {\n self.read_a = new_name;\n }\n fn set_read_b(&mut self, new_name: String) {\n self.read_b = new_name;\n }\n}\n\ntype RecordInner = (\n String,\n u64,\n u64,\n u64,\n char,\n String,\n u64,\n u64,\n u64,\n u64,\n u64,\n Vec,\n);\n\npub struct Records<'a, R: 'a + std::io::Read> {\n inner: csv::DeserializeRecordsIter<'a, R, RecordInner>,\n}\n\nimpl<'a, R: std::io::Read> Iterator for Records<'a, R> {\n type Item = csv::Result;\n\n fn next(&mut self) -> Option> {\n let position = self.inner.reader().position().byte();\n self.inner.next().map(|res| {\n res.map(\n |(\n read_a,\n length_a,\n begin_a,\n end_a,\n strand,\n read_b,\n length_b,\n begin_b,\n end_b,\n nb_match_base,\n nb_base,\n mapping_quality_and_sam,\n )| {\n let mapping_quality = mapping_quality_and_sam[0].parse::().unwrap();\n\n let sam_field = if mapping_quality_and_sam.len() > 1 {\n mapping_quality_and_sam[1..].to_vec()\n } else {\n Vec::new()\n };\n\n let new_position = self.inner.reader().position().byte();\n Record {\n read_a,\n length_a,\n begin_a,\n end_a,\n strand,\n read_b,\n length_b,\n begin_b,\n end_b,\n nb_match_base,\n nb_base,\n mapping_quality,\n sam_field,\n position: (position, new_position),\n }\n },\n )\n })\n }\n}\n\npub struct Reader {\n inner: csv::Reader,\n}\n\nimpl Reader {\n pub fn new(reader: R) -> Self {\n Reader {\n inner: csv::ReaderBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .flexible(true)\n .from_reader(reader),\n }\n }\n\n /// Iterate over all records.\n pub fn records(&mut self) -> Records {\n Records {\n inner: self.inner.deserialize(),\n }\n }\n}\n\n#[derive(Debug)]\npub struct Writer {\n inner: csv::Writer,\n}\n\nimpl Writer {\n /// Write to a given writer.\n pub fn new(writer: W) -> Self {\n Writer {\n inner: csv::WriterBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .flexible(true)\n .from_writer(writer),\n }\n }\n\n /// Write a given GFF record.\n pub fn write(&mut self, record: &Record) -> csv::Result {\n let buffer: Vec = Vec::new();\n let mut wrapper = csv::WriterBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .flexible(true)\n .from_writer(buffer);\n\n wrapper.serialize((\n &record.read_a,\n record.length_a,\n record.begin_a,\n record.end_a,\n record.strand,\n &record.read_b,\n record.length_b,\n record.begin_b,\n record.end_b,\n record.nb_match_base,\n record.nb_base,\n record.mapping_quality,\n &record.sam_field,\n ))?;\n\n let nb_bytes = wrapper.into_inner().unwrap().len() as u64;\n\n self.inner.serialize((\n &record.read_a,\n record.length_a,\n record.begin_a,\n record.end_a,\n record.strand,\n &record.read_b,\n record.length_b,\n record.begin_b,\n record.end_b,\n record.nb_match_base,\n record.nb_base,\n record.mapping_quality,\n &record.sam_field,\n ))?;\n\n Ok(nb_bytes)\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n\n const PAF_FILE: &'static [u8] = b'1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255\n1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255\n';\n\n const PAF_SAM_FIELD_FILE: &'static [u8] =\n b'1\t12000\t20\t4500\t-\t2\t10000\t5500\t10000\t4500\t4500\t255\tam:I:5\n1\t12000\t5500\t10000\t-\t3\t10000\t0\t4500\t4500\t4500\t255\ttest:B:true\tam:I:5\n';\n\n const READ_A: &'static [&str; 2] = &['1', '1'];\n const LENGTH_A: &'static [u64; 2] = &[12000, 12000];\n const BEGIN_A: &'static [u64; 2] = &[20, 5500];\n const END_A: &'static [u64; 2] = &[4500, 10000];\n const STRAND: &'static [char; 2] = &['-', '-'];\n const READ_B: &'static [&str; 2] = &['2', '3'];\n const LENGTH_B: &'static [u64; 2] = &[10000, 10000];\n const BEGIN_B: &'static [u64; 2] = &[5500, 0];\n const END_B: &'static [u64; 2] = &[10000, 4500];\n const NB_MATCH_BASE: &'static [u64; 2] = &[4500, 4500];\n const NB_BASE: &'static [u64; 2] = &[4500, 4500];\n const MAPPING_QUALITY: &'static [u64; 2] = &[255, 255];\n\n #[test]\n fn read() {\n let mut reader = Reader::new(PAF_FILE);\n\n let sam_field: [Vec; 2] = [Vec::new(), Vec::new()];\n\n for (i, r) in reader.records().enumerate() {\n let record = r.unwrap();\n\n assert_eq!(record.read_a, READ_A[i]);\n assert_eq!(record.length_a, LENGTH_A[i]);\n assert_eq!(record.begin_a, BEGIN_A[i]);\n assert_eq!(record.end_a, END_A[i]);\n assert_eq!(record.strand, STRAND[i]);\n assert_eq!(record.read_b, READ_B[i]);\n assert_eq!(record.length_b, LENGTH_B[i]);\n assert_eq!(record.begin_b, BEGIN_B[i]);\n assert_eq!(record.end_b, END_B[i]);\n assert_eq!(record.nb_match_base, NB_MATCH_BASE[i]);\n assert_eq!(record.nb_base, NB_BASE[i]);\n assert_eq!(record.mapping_quality, MAPPING_QUALITY[i]);\n assert_eq!(record.sam_field, sam_field[i]);\n }\n }\n\n #[test]\n fn read_sam_field() {\n let mut reader = Reader::new(PAF_SAM_FIELD_FILE);\n\n let sam_field = &[vec!['am:I:5'], vec!['test:B:true', 'am:I:5']];\n\n for (i, r) in reader.records().enumerate() {\n let record = r.unwrap();\n\n assert_eq!(record.read_a, READ_A[i]);\n assert_eq!(record.length_a, LENGTH_A[i]);\n assert_eq!(record.begin_a, BEGIN_A[i]);\n assert_eq!(record.end_a, END_A[i]);\n assert_eq!(record.strand, STRAND[i]);\n assert_eq!(record.read_b, READ_B[i]);\n assert_eq!(record.length_b, LENGTH_B[i]);\n assert_eq!(record.begin_b, BEGIN_B[i]);\n assert_eq!(record.end_b, END_B[i]);\n assert_eq!(record.nb_match_base, NB_MATCH_BASE[i]);\n assert_eq!(record.nb_base, NB_BASE[i]);\n assert_eq!(record.mapping_quality, MAPPING_QUALITY[i]);\n assert_eq!(record.sam_field, sam_field[i]);\n }\n }\n\n #[test]\n fn write() {\n let mut reader = Reader::new(PAF_FILE);\n let mut writer = Writer::new(vec![]);\n for r in reader.records() {\n writer\n .write(&r.ok().expect('Error reading record'))\n .ok()\n .expect('Error writing record');\n }\n assert_eq!(writer.inner.into_inner().unwrap(), PAF_FILE);\n }\n\n #[test]\n fn write_sam_field() {\n let mut reader = Reader::new(PAF_SAM_FIELD_FILE);\n let mut writer = Writer::new(vec![]);\n for r in reader.records() {\n writer\n .write(&r.ok().expect('Error reading record'))\n .ok()\n .expect('Error writing record');\n }\n assert_eq!(writer.inner.into_inner().unwrap(), PAF_SAM_FIELD_FILE);\n }\n}\n","mit" +"fpa","./fpa/src/io/gfa/gfa1.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* std use */\nuse std::clone::Clone;\nuse std::collections::{HashMap, HashSet};\n\n/* crate use */\nuse petgraph::graph::NodeIndex;\n\n/* project use */\nuse crate::filter;\nuse crate::io;\nuse filter::Filter;\n\n// read_a strand read_a strand length\ntype LineType = (String, char, String, char, u64);\n// read_a strand leng_a read_b strand len_b position len_containment\ntype ContainmentType = (String, char, u64, String, char, u64, u64, u64);\n\ntype Graph = petgraph::Graph<(String, u64), LineType>;\n\npub struct Gfa1 {\n keep_internal: bool,\n keep_containment: bool,\n graph: Graph,\n containments: HashMap<(String, u64), ContainmentType>,\n test_containment: filter::Containment,\n test_internalmatch: filter::InternalMatch,\n node2index: HashMap<(String, u64), petgraph::graph::NodeIndex>,\n}\n\nimpl Gfa1 {\n pub fn new(keep_internal: bool, keep_containment: bool, internal_threshold: f64) -> Self {\n Gfa1 {\n keep_internal,\n keep_containment,\n graph: Graph::new(),\n containments: HashMap::new(),\n test_containment: filter::Containment::new(internal_threshold),\n test_internalmatch: filter::InternalMatch::new(internal_threshold),\n node2index: HashMap::new(),\n }\n }\n\n pub fn add(&mut self, record: &dyn io::MappingRecord) {\n if self.test_internalmatch.run(&*record) {\n self.add_internalmatch(record);\n } else if self.test_containment.run(&*record) {\n self.add_containment(record);\n } else {\n self.add_dovetails(record);\n }\n }\n\n fn add_containment(&mut self, record: &dyn io::MappingRecord) {\n if record.strand() == '+' {\n if record.begin_a() <= record.begin_b() && record.len_to_end_a() < record.len_to_end_b()\n {\n // B contain A\n self.containments.insert(\n (record.read_a(), record.length_a()),\n (\n record.read_b(),\n '+',\n record.length_b(),\n record.read_a(),\n '+',\n record.length_a(),\n record.begin_b(),\n record.length(),\n ),\n );\n } else if record.begin_a() >= record.begin_b()\n && record.len_to_end_a() > record.len_to_end_b()\n {\n // A contain B\n self.containments.insert(\n (record.read_b(), record.length_b()),\n (\n record.read_a(),\n '+',\n record.length_a(),\n record.read_b(),\n '+',\n record.length_b(),\n record.begin_a(),\n record.length(),\n ),\n );\n } else {\n println!(\n 'Containment Record not managed {:?} {:?}',\n record.read_a(),\n record.read_b()\n );\n }\n } else if record.begin_a() <= record.len_to_end_b()\n && record.len_to_end_a() < record.begin_b()\n {\n // B contain A\n self.containments.insert(\n (record.read_a(), record.length_a()),\n (\n record.read_b(),\n '+',\n record.length_b(),\n record.read_a(),\n '-',\n record.length_a(),\n record.begin_b(),\n record.length(),\n ),\n );\n } else if record.begin_a() >= record.len_to_end_b()\n && record.len_to_end_a() > record.begin_b()\n {\n // A contain B\n self.containments.insert(\n (record.read_b(), record.length_b()),\n (\n record.read_a(),\n '+',\n record.length_a(),\n record.read_b(),\n '-',\n record.length_b(),\n record.begin_a(),\n record.length(),\n ),\n );\n } else {\n println!(\n 'Containment Record not managed {:?} {:?}',\n record.read_a(),\n record.read_b()\n );\n }\n }\n\n fn add_internalmatch(&mut self, record: &dyn io::MappingRecord) {\n if self.keep_internal {\n self.add_dovetails(record);\n }\n }\n\n fn add_dovetails(&mut self, record: &dyn io::MappingRecord) {\n let node_a = self.add_node((record.read_a(), record.length_a()));\n let node_b = self.add_node((record.read_b(), record.length_b()));\n\n if record.strand() == '+' {\n if record.begin_a() > record.begin_b() {\n // A overlap B\n self.add_edge(\n node_a,\n node_b,\n (record.read_a(), '+', record.read_b(), '+', record.length()),\n );\n } else {\n // B overlap A\n self.add_edge(\n node_b,\n node_a,\n (record.read_b(), '+', record.read_a(), '+', record.length()),\n );\n }\n } else if record.begin_a() > record.len_to_end_a() {\n if record.begin_a() > record.len_to_end_b() {\n // A overlap B\n self.add_edge(\n node_a,\n node_b,\n (record.read_a(), '+', record.read_b(), '-', record.length()),\n );\n } else {\n // B overlap Af\n self.add_edge(\n node_b,\n node_a,\n (record.read_b(), '+', record.read_a(), '-', record.length()),\n );\n }\n } else if (record.length_a() - record.begin_a()) > record.end_b() {\n // A overlap B\n self.add_edge(\n node_a,\n node_b,\n (record.read_a(), '-', record.read_b(), '+', record.length()),\n );\n } else {\n // B overlap A\n self.add_edge(\n node_b,\n node_a,\n (record.read_b(), '-', record.read_a(), '+', record.length()),\n );\n }\n }\n\n pub fn write(&mut self, writer: &mut W) {\n if !self.keep_containment {\n let remove_key: Vec<((String, u64), ContainmentType)> =\n self.containments.drain().collect();\n for (key, _) in remove_key {\n let index = self.add_node(key.clone());\n self.graph.remove_node(index);\n }\n }\n\n writer\n .write_all(b'H\tVN:Z:1.0\n')\n .expect('Error durring gfa1 write');\n\n let mut writed = HashSet::new();\n for (read_a, _, len_a, read_b, _, len_b, _, _) in self.containments.values() {\n if !writed.contains(&(read_a, len_a)) {\n writer\n .write_fmt(format_args!('S\t{}\t*\tLN:i:{}\n', read_a, len_a))\n .expect('Error durring gfa1 write');\n\n writed.insert((read_a, len_a));\n }\n\n if !writed.contains(&(read_b, len_b)) {\n writer\n .write_fmt(format_args!('S\t{}\t*\tLN:i:{}\n', read_b, len_b))\n .expect('Error durring gfa1 write');\n writed.insert((read_b, len_b));\n }\n }\n\n for node in self.graph.node_indices() {\n if self.graph.neighbors_undirected(node).count() != 0 {\n let segment = self.graph.node_weight(node).unwrap();\n if writed.contains(&(&segment.0, &segment.1)) {\n continue;\n }\n\n writer\n .write_fmt(format_args!('S\t{}\t*\tLN:i:{}\n', segment.0, segment.1))\n .expect('Error durring gfa1 write');\n }\n }\n\n for edge in self.graph.edge_references() {\n writer\n .write_fmt(format_args!(\n 'L\t{}\t{}\t{}\t{}\t{}M\n',\n edge.weight().0,\n edge.weight().1,\n edge.weight().2,\n edge.weight().3,\n edge.weight().4\n ))\n .expect('Error durring gfa1 write');\n }\n\n for value in self.containments.values() {\n writer\n .write_fmt(format_args!(\n 'C\t{}\t{}\t{}\t{}\t{}\t{}M\n',\n value.0, value.1, value.3, value.4, value.6, value.7\n ))\n .expect('Error durring gfa1 write');\n }\n }\n\n fn add_node(&mut self, node: (String, u64)) -> petgraph::graph::NodeIndex {\n let graph = &mut self.graph;\n *self\n .node2index\n .entry(node)\n .or_insert_with_key(|n| graph.add_node(n.clone()))\n }\n\n fn add_edge(&mut self, node_a: NodeIndex, node_b: NodeIndex, new_edge: LineType) {\n if let Some(e) = self.graph.find_edge(node_a, node_b) {\n if self.graph.edge_weight(e).unwrap().4 < new_edge.4 {\n self.graph.update_edge(node_a, node_b, new_edge);\n }\n } else {\n self.graph.add_edge(node_a, node_b, new_edge);\n }\n }\n}\n","mit" +"fpa","./fpa/src/io/gfa/mod.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\npub mod gfa1;\npub use self::gfa1::Gfa1;\n","mit" +"fpa","./fpa/src/io/mod.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\npub mod gfa;\npub mod m4;\npub mod paf;\n\npub trait MappingRecord {\n fn read_a(&self) -> String;\n fn length_a(&self) -> u64;\n fn begin_a(&self) -> u64;\n fn end_a(&self) -> u64;\n fn strand(&self) -> char;\n fn read_b(&self) -> String;\n fn length_b(&self) -> u64;\n fn begin_b(&self) -> u64;\n fn end_b(&self) -> u64;\n fn position(&self) -> (u64, u64);\n fn set_position(&mut self, p: (u64, u64));\n\n fn length(&self) -> u64;\n\n fn len_to_end_a(&self) -> u64;\n fn len_to_end_b(&self) -> u64;\n\n fn set_read_a(&mut self, new_name: String);\n fn set_read_b(&mut self, new_name: String);\n}\n\npub enum MappingFormat {\n Paf,\n M4,\n}\n","mit" +"fpa","./fpa/src/io/m4.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* local use */\nuse crate::io;\n\n/* standard use */\nuse std::cmp::min;\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct Record {\n pub read_a: String,\n pub read_b: String,\n pub error: f64,\n pub shared_min_mers: u64,\n pub strand_a: char,\n pub begin_a: u64,\n pub end_a: u64,\n pub length_a: u64,\n pub strand_b: char,\n pub begin_b: u64,\n pub end_b: u64,\n pub length_b: u64,\n pub position: (u64, u64),\n}\n\nimpl io::MappingRecord for Record {\n fn read_a(&self) -> String {\n self.read_a.clone()\n }\n\n fn length_a(&self) -> u64 {\n self.length_a\n }\n\n fn begin_a(&self) -> u64 {\n self.begin_a\n }\n\n fn end_a(&self) -> u64 {\n self.end_a\n }\n\n fn strand(&self) -> char {\n if self.strand_a == self.strand_b {\n '+'\n } else {\n '-'\n }\n }\n\n fn read_b(&self) -> String {\n self.read_b.clone()\n }\n\n fn length_b(&self) -> u64 {\n self.length_b\n }\n\n fn begin_b(&self) -> u64 {\n self.begin_b\n }\n\n fn end_b(&self) -> u64 {\n self.end_b\n }\n\n fn position(&self) -> (u64, u64) {\n self.position\n }\n\n fn set_position(&mut self, p: (u64, u64)) {\n self.position = p;\n }\n\n fn length(&self) -> u64 {\n min(self.end_a - self.begin_a, self.end_b - self.begin_b)\n }\n\n fn len_to_end_a(&self) -> u64 {\n self.length_a - self.end_a\n }\n fn len_to_end_b(&self) -> u64 {\n self.length_b - self.end_b\n }\n\n fn set_read_a(&mut self, new_name: String) {\n self.read_a = new_name;\n }\n fn set_read_b(&mut self, new_name: String) {\n self.read_b = new_name;\n }\n}\n\ntype RecordInner = (\n String,\n String,\n f64,\n u64,\n char,\n u64,\n u64,\n u64,\n char,\n u64,\n u64,\n u64,\n);\n\npub struct Records<'a, R: 'a + std::io::Read> {\n inner: csv::DeserializeRecordsIter<'a, R, RecordInner>,\n}\n\nimpl<'a, R: std::io::Read> Iterator for Records<'a, R> {\n type Item = csv::Result;\n\n fn next(&mut self) -> Option> {\n let position = self.inner.reader().position().byte();\n self.inner.next().map(|res| {\n res.map(\n |(\n read_a,\n read_b,\n error,\n shared_min_mers,\n strand_a,\n begin_a,\n end_a,\n length_a,\n strand_b,\n begin_b,\n end_b,\n length_b,\n )| {\n let new_position = self.inner.reader().position().byte();\n\n Record {\n read_a,\n read_b,\n error,\n shared_min_mers,\n strand_a,\n begin_a,\n end_a,\n length_a,\n strand_b,\n begin_b,\n end_b,\n length_b,\n position: (position, new_position),\n }\n },\n )\n })\n }\n}\n\npub struct Reader {\n inner: csv::Reader,\n}\n\nimpl Reader {\n pub fn new(reader: R) -> Self {\n Reader {\n inner: csv::ReaderBuilder::new()\n .delimiter(b' ')\n .has_headers(false)\n .flexible(true)\n .from_reader(reader),\n }\n }\n\n /// Iterate over all records.\n pub fn records(&mut self) -> Records {\n Records {\n inner: self.inner.deserialize(),\n }\n }\n}\n\n#[derive(Debug)]\npub struct Writer {\n inner: csv::Writer,\n}\n\nimpl Writer {\n /// Write to a given writer.\n pub fn new(writer: W) -> Self {\n Writer {\n inner: csv::WriterBuilder::new()\n .delimiter(b' ')\n .has_headers(false)\n .flexible(true)\n .from_writer(writer),\n }\n }\n\n /// Write a given Blasr m4 record.\n pub fn write(&mut self, record: &Record) -> csv::Result {\n let buffer: Vec = Vec::new();\n let mut wrapper = csv::WriterBuilder::new()\n .delimiter(b'\t')\n .has_headers(false)\n .flexible(true)\n .from_writer(buffer);\n\n wrapper.serialize((\n &record.read_a,\n &record.read_b,\n record.error,\n record.shared_min_mers,\n record.strand_a,\n record.begin_a,\n record.end_a,\n record.length_a,\n record.strand_b,\n record.begin_b,\n record.end_b,\n record.length_b,\n ))?;\n\n let nb_bytes = wrapper.into_inner().unwrap().len() as u64;\n\n self.inner.serialize((\n &record.read_a,\n &record.read_b,\n record.error,\n record.shared_min_mers,\n record.strand_a,\n record.begin_a,\n record.end_a,\n record.length_a,\n record.strand_b,\n record.begin_b,\n record.end_b,\n record.length_b,\n ))?;\n\n Ok(nb_bytes)\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n\n const M4_FILE: &'static [u8] = b'1 2 0.1 2 0 100 450 1000 0 550 900 1000\n1 3 0.1 2 0 550 900 1000 0 100 450 1000\n';\n\n const READ_A: &'static [&str; 2] = &['1', '1'];\n const READ_B: &'static [&str; 2] = &['2', '3'];\n const ERROR: &'static [f64; 2] = &[0.1, 0.1];\n const SHARED_MIN_MERS: &'static [u64; 2] = &[2, 2];\n const STRAND_A: &'static [char; 2] = &['0', '0'];\n const STRAND_B: &'static [char; 2] = &['0', '0'];\n const BEGIN_A: &'static [u64; 2] = &[100, 550];\n const END_A: &'static [u64; 2] = &[450, 900];\n const LENGTH_A: &'static [u64; 2] = &[1000, 1000];\n const BEGIN_B: &'static [u64; 2] = &[550, 100];\n const END_B: &'static [u64; 2] = &[900, 450];\n const LENGTH_B: &'static [u64; 2] = &[1000, 1000];\n\n #[test]\n fn read() {\n let mut reader = Reader::new(M4_FILE);\n\n for (i, r) in reader.records().enumerate() {\n let record = r.unwrap();\n\n assert_eq!(record.read_a, READ_A[i]);\n assert_eq!(record.read_b, READ_B[i]);\n assert_eq!(record.error, ERROR[i]);\n assert_eq!(record.shared_min_mers, SHARED_MIN_MERS[i]);\n assert_eq!(record.strand_a, STRAND_A[i]);\n assert_eq!(record.begin_a, BEGIN_A[i]);\n assert_eq!(record.end_a, END_A[i]);\n assert_eq!(record.length_a, LENGTH_A[i]);\n assert_eq!(record.strand_b, STRAND_B[i]);\n assert_eq!(record.begin_b, BEGIN_B[i]);\n assert_eq!(record.end_b, END_B[i]);\n assert_eq!(record.length_b, LENGTH_B[i]);\n }\n }\n\n #[test]\n fn write() {\n let mut reader = Reader::new(M4_FILE);\n let mut writer = Writer::new(vec![]);\n for r in reader.records() {\n writer\n .write(&r.ok().expect('Error reading record'))\n .ok()\n .expect('Error writing record');\n }\n\n assert_eq!(writer.inner.into_inner().unwrap(), M4_FILE);\n }\n}\n","mit" +"fpa","./fpa/src/filter/namematch.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\n/* standard use */\n\npub struct NameMatch {\n regex: regex::Regex,\n}\n\nimpl NameMatch {\n pub fn new(regex: &str) -> Self {\n NameMatch {\n regex: regex::Regex::new(regex).expect('Error in regex build'),\n }\n }\n}\n\nimpl filter::Filter for NameMatch {\n fn run(&self, r: &dyn io::MappingRecord) -> bool {\n self.regex.is_match(&r.read_a()) || self.regex.is_match(&r.read_b())\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n use filter::Filter;\n\n lazy_static! {\n static ref RECORD: io::paf::Record = {\n io::paf::Record {\n read_a: 'read_1'.to_string(),\n length_a: 20000,\n begin_a: 1,\n end_a: 19999,\n strand: '+',\n read_b: 'read_2'.to_string(),\n length_b: 20000,\n begin_b: 1,\n end_b: 19999,\n nb_match_base: 500,\n nb_base: 500,\n mapping_quality: 255,\n sam_field: Vec::new(),\n position: (0, 50),\n }\n };\n }\n\n #[test]\n fn positif() {\n let nm = NameMatch::new('read_1');\n\n assert_eq!(nm.run(&*RECORD), true);\n }\n\n #[test]\n fn negatif() {\n let nm = NameMatch::new('read_1');\n\n assert_ne!(nm.run(&*RECORD), false);\n }\n}\n","mit" +"fpa","./fpa/src/filter/sequence_length.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\npub struct SequenceLength {\n length_threshold: u64,\n ordering: std::cmp::Ordering,\n}\n\nimpl SequenceLength {\n pub fn new(length_threshold: u64, ord: std::cmp::Ordering) -> Self {\n SequenceLength {\n length_threshold,\n ordering: ord,\n }\n }\n}\n\nimpl filter::Filter for SequenceLength {\n fn run(&self, r: &dyn io::MappingRecord) -> bool {\n r.length_a().cmp(&self.length_threshold) == self.ordering\n || r.length_b().cmp(&self.length_threshold) == self.ordering\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n use filter::Filter;\n\n lazy_static! {\n static ref RECORD: io::paf::Record = {\n io::paf::Record {\n read_a: 'read_1'.to_string(),\n length_a: 5000,\n begin_a: 0,\n end_a: 5000,\n strand: '+',\n read_b: 'read_2'.to_string(),\n length_b: 20000,\n begin_b: 5000,\n end_b: 10000,\n nb_match_base: 500,\n nb_base: 500,\n mapping_quality: 255,\n sam_field: Vec::new(),\n position: (0, 50),\n }\n };\n }\n\n #[test]\n fn positif() {\n let mut nm = SequenceLength::new(5001, std::cmp::Ordering::Less);\n\n assert_eq!(nm.run(&*RECORD), true);\n\n nm = SequenceLength::new(20001, std::cmp::Ordering::Greater);\n\n assert_eq!(nm.run(&*RECORD), false);\n }\n\n #[test]\n fn negatif() {\n let mut nm = SequenceLength::new(5001, std::cmp::Ordering::Less);\n\n assert_ne!(nm.run(&*RECORD), false);\n\n nm = SequenceLength::new(20001, std::cmp::Ordering::Greater);\n\n assert_ne!(nm.run(&*RECORD), true);\n }\n}\n","mit" +"fpa","./fpa/src/filter/samename.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\n/* standard use */\n\npub struct SameName {}\n\nimpl SameName {\n pub fn new() -> Self {\n SameName {}\n }\n}\n\nimpl filter::Filter for SameName {\n fn run(&self, r: &dyn io::MappingRecord) -> bool {\n r.read_a() == r.read_b()\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n use filter::Filter;\n\n lazy_static! {\n static ref RECORD: io::paf::Record = {\n io::paf::Record {\n read_a: 'read_1'.to_string(),\n length_a: 5000,\n begin_a: 0,\n end_a: 5000,\n strand: '+',\n read_b: 'read_1'.to_string(),\n length_b: 20000,\n begin_b: 5000,\n end_b: 10000,\n nb_match_base: 500,\n nb_base: 500,\n mapping_quality: 255,\n sam_field: Vec::new(),\n position: (0, 50),\n }\n };\n }\n\n #[test]\n fn positif() {\n let nm = SameName::new();\n\n assert_eq!(nm.run(&*RECORD), true);\n }\n\n #[test]\n fn negatif() {\n let nm = SameName::new();\n\n assert_ne!(nm.run(&*RECORD), false);\n }\n}\n","mit" +"fpa","./fpa/src/filter/internalmatch.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\n/* standard use */\nuse std::cmp::{max, min};\n\npub struct InternalMatch {\n internal_threshold: f64,\n}\n\nimpl InternalMatch {\n pub fn new(internal_threshold: f64) -> Self {\n InternalMatch { internal_threshold }\n }\n}\n\nimpl filter::Filter for InternalMatch {\n fn run(&self, r: &dyn io::MappingRecord) -> bool {\n let overhang = if r.strand() == '+' {\n min(r.begin_a(), r.begin_b()) + min(r.length_a() - r.end_a(), r.length_b() - r.end_b())\n } else {\n min(r.begin_a(), r.length_b() - r.end_b()) + min(r.begin_b(), r.length_a() - r.end_a())\n };\n\n let maplen = max(r.end_a() - r.begin_a(), r.end_b() - r.begin_b());\n\n overhang > min(1000, (maplen as f64 * self.internal_threshold) as u64)\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n use filter::Filter;\n\n lazy_static! {\n static ref RECORD: io::paf::Record = {\n io::paf::Record {\n read_a: 'read_1'.to_string(),\n length_a: 20000,\n begin_a: 500,\n end_a: 1000,\n strand: '+',\n read_b: 'read_2'.to_string(),\n length_b: 20000,\n begin_b: 5000,\n end_b: 5500,\n nb_match_base: 500,\n nb_base: 500,\n mapping_quality: 255,\n sam_field: Vec::new(),\n position: (0, 50),\n }\n };\n }\n\n #[test]\n fn positif() {\n let nm = InternalMatch::new(0.8);\n\n assert_eq!(nm.run(&*RECORD), true);\n }\n\n #[test]\n fn negatif() {\n let nm = InternalMatch::new(0.8);\n\n assert_ne!(nm.run(&*RECORD), false);\n }\n}\n","mit" +"fpa","./fpa/src/filter/dovetails.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\n/* standard use */\n\npub struct Dovetails {\n internal_threshold: f64,\n}\n\nimpl Dovetails {\n pub fn new(internal_threshold: f64) -> Self {\n Dovetails { internal_threshold }\n }\n}\n\nimpl filter::Filter for Dovetails {\n fn run(&self, r: &dyn io::MappingRecord) -> bool {\n !filter::InternalMatch::new(self.internal_threshold).run(r)\n && !filter::Containment::new(self.internal_threshold).run(r)\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n use filter::Filter;\n\n lazy_static! {\n static ref RECORD: io::paf::Record = {\n io::paf::Record {\n read_a: 'read_1'.to_string(),\n length_a: 20000,\n begin_a: 15000,\n end_a: 20000,\n strand: '+',\n read_b: 'read_2'.to_string(),\n length_b: 20000,\n begin_b: 0,\n end_b: 15000,\n nb_match_base: 500,\n nb_base: 500,\n mapping_quality: 255,\n sam_field: Vec::new(),\n position: (0, 50),\n }\n };\n }\n\n #[test]\n fn positif() {\n let nm = Dovetails::new(0.8);\n\n assert_eq!(nm.run(&*RECORD), true);\n }\n\n #[test]\n fn negatif() {\n let nm = Dovetails::new(0.8);\n\n assert_ne!(nm.run(&*RECORD), false);\n }\n}\n","mit" +"fpa","./fpa/src/filter/containment.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\n/* standard use */\n\npub struct Containment {\n internal_threshold: f64,\n}\n\nimpl Containment {\n pub fn new(internal_threshold: f64) -> Self {\n Containment { internal_threshold }\n }\n}\n\nimpl filter::Filter for Containment {\n fn run(&self, r: &dyn io::MappingRecord) -> bool {\n if filter::InternalMatch::new(self.internal_threshold).run(r) {\n return false;\n }\n\n (r.strand() == '+'\n && r.begin_a() <= r.begin_b()\n && r.length_a() - r.end_a() < r.length_b() - r.end_b())\n || (r.strand() == '-'\n && r.begin_a() <= r.length_b() - r.end_b()\n && r.length_a() - r.end_a() < r.begin_b())\n || (r.strand() == '+'\n && r.begin_a() >= r.begin_b()\n && r.length_a() - r.end_a() > r.length_b() - r.end_b())\n || (r.strand() == '-'\n && r.begin_a() >= r.length_b() - r.end_b()\n && r.length_a() - r.end_a() > r.begin_b())\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n use filter::Filter;\n\n lazy_static! {\n static ref RECORD: io::paf::Record = {\n io::paf::Record {\n read_a: 'read_1'.to_string(),\n length_a: 5000,\n begin_a: 0,\n end_a: 5000,\n strand: '+',\n read_b: 'read_2'.to_string(),\n length_b: 20000,\n begin_b: 5000,\n end_b: 10000,\n nb_match_base: 500,\n nb_base: 500,\n mapping_quality: 255,\n sam_field: Vec::new(),\n position: (0, 50),\n }\n };\n }\n\n #[test]\n fn positif() {\n let nm = Containment::new(0.8);\n\n assert_eq!(nm.run(&*RECORD), true);\n }\n\n #[test]\n fn negatif() {\n let nm = Containment::new(0.8);\n\n assert_ne!(nm.run(&*RECORD), false);\n }\n}\n","mit" +"fpa","./fpa/src/filter/mod.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\nuse crate::io;\n\npub trait Filter {\n fn run(&self, r: &dyn io::MappingRecord) -> bool;\n}\n\npub mod length;\npub use self::length::Length;\n\npub mod dovetails;\npub use self::dovetails::Dovetails;\n\npub mod containment;\npub use self::containment::Containment;\n\npub mod internalmatch;\npub use self::internalmatch::InternalMatch;\n\npub mod samename;\npub use self::samename::SameName;\n\npub mod namematch;\npub use self::namematch::NameMatch;\n\npub mod sequence_length;\npub use self::sequence_length::SequenceLength;\n","mit" +"fpa","./fpa/src/filter/length.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\npub struct Length {\n length_threshold: u64,\n ordering: std::cmp::Ordering,\n}\n\nimpl Length {\n pub fn new(length_threshold: u64, ord: std::cmp::Ordering) -> Self {\n Length {\n length_threshold,\n ordering: ord,\n }\n }\n}\n\nimpl filter::Filter for Length {\n fn run(&self, r: &dyn io::MappingRecord) -> bool {\n r.length().cmp(&self.length_threshold) == self.ordering\n }\n}\n\n#[cfg(test)]\nmod test {\n\n use super::*;\n use filter::Filter;\n\n lazy_static! {\n static ref RECORD: io::paf::Record = {\n io::paf::Record {\n read_a: 'read_1'.to_string(),\n length_a: 5000,\n begin_a: 0,\n end_a: 5000,\n strand: '+',\n read_b: 'read_2'.to_string(),\n length_b: 20000,\n begin_b: 5000,\n end_b: 10000,\n nb_match_base: 500,\n nb_base: 500,\n mapping_quality: 255,\n sam_field: Vec::new(),\n position: (0, 50),\n }\n };\n }\n\n #[test]\n fn positif() {\n let mut nm = Length::new(5001, std::cmp::Ordering::Less);\n\n assert_eq!(nm.run(&*RECORD), true);\n\n nm = Length::new(5001, std::cmp::Ordering::Greater);\n\n assert_eq!(nm.run(&*RECORD), false);\n }\n\n #[test]\n fn negatif() {\n let mut nm = Length::new(5001, std::cmp::Ordering::Less);\n\n assert_ne!(nm.run(&*RECORD), false);\n\n nm = Length::new(5001, std::cmp::Ordering::Greater);\n\n assert_ne!(nm.run(&*RECORD), true);\n }\n}\n","mit" +"fpa","./fpa/src/file.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* standard use */\nuse std::io;\nuse std::io::{BufReader, BufWriter};\n\npub fn get_input(input_name: &str) -> (Box, niffler::compression::Format) {\n match input_name {\n '-' => niffler::get_reader(Box::new(BufReader::new(io::stdin())))\n .expect('File is probably empty'),\n _ => niffler::from_path(input_name).expect('File is probably empty'),\n }\n}\n\npub fn choose_compression(\n input_compression: niffler::compression::Format,\n compression_set: bool,\n compression_value: &str,\n) -> niffler::compression::Format {\n if !compression_set {\n return input_compression;\n }\n\n match compression_value {\n 'gzip' => niffler::compression::Format::Gzip,\n 'bzip2' => niffler::compression::Format::Bzip,\n 'lzma' => niffler::compression::Format::Lzma,\n _ => niffler::compression::Format::No,\n }\n}\n\npub fn get_output(output_name: &str, format: niffler::compression::Format) -> Box {\n match output_name {\n '-' => niffler::get_writer(\n Box::new(BufWriter::new(io::stdout())),\n format,\n niffler::compression::Level::One,\n )\n .unwrap(),\n _ => niffler::to_path(output_name, format, niffler::compression::Level::One).unwrap(),\n }\n}\n","mit" +"fpa","./fpa/src/cli/keep.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\nuse crate::cli::Filters;\n\npub struct Keep {\n filters: Vec>,\n internal_threshold: f64,\n}\n\nimpl Keep {\n pub fn new(\n internal_match: f64,\n matches: &std::collections::HashMap,\n ) -> Self {\n let filters = Vec::new();\n let mut k = Keep {\n filters,\n internal_threshold: internal_match,\n };\n\n if let Some(keep) = matches.get('keep') {\n k.generate(keep);\n }\n\n k\n }\n}\n\nimpl Filters for Keep {\n fn pass(&self, r: &dyn io::MappingRecord) -> bool {\n if self.filters.is_empty() {\n true\n } else {\n self.filters.iter().all(|x| x.run(r))\n }\n }\n\n fn internal_match(&self) -> f64 {\n self.internal_threshold\n }\n\n fn add_filter(&mut self, f: Box) {\n self.filters.push(f);\n }\n}\n","mit" +"fpa","./fpa/src/cli/modifier.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* project use */\nuse crate::generator;\nuse crate::io;\n\npub struct Modifier {\n modifiers: Vec>,\n}\n\nimpl Modifier {\n pub fn new(\n internal_match: f64,\n matches: &std::collections::HashMap,\n ) -> Self {\n let mut modifiers: Vec> = Vec::new();\n\n if let Some(m) = matches.get('rename') {\n if m.is_present('input') {\n modifiers.push(Box::new(generator::Renaming::new(\n m.value_of('input').unwrap(),\n true,\n )));\n } else if m.is_present('output') {\n modifiers.push(Box::new(generator::Renaming::new(\n m.value_of('output').unwrap(),\n false,\n )));\n }\n }\n\n if let Some(m) = matches.get('gfa') {\n modifiers.push(Box::new(generator::Gfa1::new(\n m.value_of('output').unwrap().to_string(),\n m.is_present('internalmatch'),\n m.is_present('containment'),\n internal_match,\n )))\n }\n\n Modifier { modifiers }\n }\n\n pub fn pass(&mut self, r: &mut dyn io::MappingRecord) {\n for m in self.modifiers.iter_mut() {\n m.run(r);\n }\n }\n\n pub fn write(&mut self) {\n for m in self.modifiers.iter_mut() {\n m.write();\n }\n }\n}\n","mit" +"fpa","./fpa/src/cli/mod.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\n/* local use */\npub mod subcommand;\npub use self::subcommand::*;\n\npub mod drop;\npub use self::drop::Drop;\n\npub mod keep;\npub use self::keep::Keep;\n\npub mod modifier;\npub use self::modifier::*;\n\n/* crates use */\nuse clap::{App, Arg, ArgMatches};\n\npub fn app<'a>() -> App<'a> {\n App::new('fpa')\n .version('0.5.1 Sandslash')\n .author('Pierre Marijon ')\n .about('fpa take long read mapping information and filter them')\n .arg(Arg::new('input')\n .short('i')\n .long('input')\n .default_value('-')\n .about('Path to input file, use '-' for stdin')\n )\n .arg(Arg::new('output')\n .short('o')\n .long('output')\n .default_value('-')\n .about('Path to output file, use '-' for stdout')\n )\n\n .arg(Arg::new('internal-match-threshold')\n .takes_value(true)\n .long('internal-threshold')\n .default_value('0.8')\n .about('A match is internal match if overhang length > match length * internal threshold this option set internal match')\n )\n .arg(Arg::new('compression-out')\n .short('z')\n .takes_value(true)\n .long('compression-out')\n .possible_values(&['gzip', 'bzip2', 'lzma', 'no'])\n .about('Output compression format, the input compression format is chosen by default')\n )\n .arg(Arg::new('format')\n .short('F')\n .long('format')\n .takes_value(true)\n .about('Force the format used')\n .possible_values(&['paf', 'm4'])\n )\n .subcommand(subcommand::get_keep())\n .subcommand(subcommand::get_drop())\n .subcommand(subcommand::get_rename())\n .subcommand(subcommand::get_index())\n .subcommand(subcommand::get_gfa())\n}\n\npub fn get_subcmd(app: &mut App) -> std::collections::HashMap {\n let basic_cli = vec![\n 'fpa'.to_string(),\n '-i'.to_string(),\n 'foo'.to_string(),\n '-o'.to_string(),\n 'bar'.to_string(),\n ];\n let mut sub2matches = std::collections::HashMap::new();\n\n let mut cli: Vec = std::env::args().collect();\n loop {\n /* parse cli */\n let matches = app\n .try_get_matches_from_mut(cli)\n .unwrap_or_else(|e| e.exit());\n\n let (name, sub) = match matches.subcommand() {\n Some((n, s)) => (n, s),\n None => break,\n };\n\n sub2matches.insert(name.to_string(), sub.clone());\n\n let (subname, subsub) = match sub.subcommand() {\n Some((n, s)) => (n, s),\n None => break,\n };\n\n if subsub.values_of('').is_none() {\n break;\n }\n\n /* rebuild a new cli*/\n cli = basic_cli.clone();\n cli.push(subname.to_string());\n cli.extend(subsub.values_of('').unwrap().map(|x| x.to_string()));\n }\n\n sub2matches\n}\n\npub trait Filters {\n fn pass(&self, r: &dyn io::MappingRecord) -> bool;\n\n fn internal_match(&self) -> f64;\n\n fn add_filter(&mut self, f: Box);\n\n fn generate(&mut self, m: &clap::ArgMatches) {\n let internal_match = self.internal_match();\n if m.is_present('containment') {\n self.add_filter(Box::new(filter::Containment::new(internal_match)));\n }\n\n if m.is_present('internalmatch') {\n self.add_filter(Box::new(filter::InternalMatch::new(internal_match)));\n }\n\n if m.is_present('dovetail') {\n self.add_filter(Box::new(filter::Dovetails::new(internal_match)));\n }\n\n if let Some(length_lower) = m.value_of('length_lower') {\n self.add_filter(Box::new(filter::Length::new(\n length_lower.parse::().unwrap(),\n std::cmp::Ordering::Less,\n )));\n }\n\n if let Some(length_lower) = m.value_of('length_upper') {\n self.add_filter(Box::new(filter::Length::new(\n length_lower.parse::().unwrap(),\n std::cmp::Ordering::Greater,\n )));\n }\n\n if let Some(name_match) = m.value_of('name_match') {\n self.add_filter(Box::new(filter::NameMatch::new(name_match)));\n }\n\n if m.is_present('same_name') {\n self.add_filter(Box::new(filter::SameName::new()));\n }\n\n if let Some(sequence_length_lower) = m.value_of('sequence_length_lower') {\n self.add_filter(Box::new(filter::SequenceLength::new(\n sequence_length_lower.parse::().unwrap(),\n std::cmp::Ordering::Less,\n )));\n }\n\n if let Some(sequence_length_lower) = m.value_of('sequence_length_upper') {\n self.add_filter(Box::new(filter::SequenceLength::new(\n sequence_length_lower.parse::().unwrap(),\n std::cmp::Ordering::Greater,\n )));\n }\n }\n}\n","mit" +"fpa","./fpa/src/cli/subcommand.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crates use */\nuse clap::{App, Arg};\n\npub fn get_keep<'a>() -> App<'a> {\n App::new('keep')\n .setting(clap::AppSettings::AllowExternalSubcommands)\n .about('fpa keep only mapping match this constraints')\n .arg(\n Arg::new('containment')\n .short('c')\n .long('containment')\n .about('Keep only containment mapping'),\n )\n .arg(\n Arg::new('internalmatch')\n .short('i')\n .long('internalmatch')\n .about('Keep only internal mapping'),\n )\n .arg(\n Arg::new('dovetail')\n .short('d')\n .long('dovetail')\n .about('Keep only dovetail mapping'),\n )\n .arg(\n Arg::new('length_lower')\n .short('l')\n .long('length-lower')\n .takes_value(true)\n .about('Keep only mapping with length lower than value'),\n )\n .arg(\n Arg::new('length_upper')\n .short('L')\n .long('length-upper')\n .takes_value(true)\n .about('Keep only mapping with length upper than value'),\n )\n .arg(\n Arg::new('name_match')\n .short('n')\n .long('name-match')\n .takes_value(true)\n .about('Keep only mapping where one reads match with regex'),\n )\n .arg(\n Arg::new('same_name')\n .short('m')\n .long('same-name')\n .about('Keep only mapping where reads have same name'),\n )\n .arg(\n Arg::new('sequence_length_lower')\n .short('s')\n .long('sequence-length-lower')\n .takes_value(true)\n .about('Keep only mapping where one reads have length lower than value'),\n )\n .arg(\n Arg::new('sequence_length_upper')\n .short('S')\n .long('sequence-length-upper')\n .takes_value(true)\n .about('Keep only mapping where one reads have length upper than value'),\n )\n}\n\npub fn get_drop<'a>() -> clap::App<'a> {\n App::new('drop')\n .setting(clap::AppSettings::AllowExternalSubcommands)\n .about('fpa drop mapping match this constraints')\n .arg(\n Arg::new('containment')\n .short('c')\n .long('containment')\n .about('Drop containment mapping'),\n )\n .arg(\n Arg::new('internalmatch')\n .short('i')\n .long('internalmatch')\n .about('Drop internal mapping'),\n )\n .arg(\n Arg::new('dovetail')\n .short('d')\n .long('dovetail')\n .about('Drop dovetail mapping'),\n )\n .arg(\n Arg::new('length_lower')\n .short('l')\n .long('length-lower')\n .takes_value(true)\n .about('Drop mapping with length lower than value'),\n )\n .arg(\n Arg::new('length_upper')\n .short('L')\n .long('length-upper')\n .takes_value(true)\n .about('Drop mapping with length upper than value'),\n )\n .arg(\n Arg::new('name_match')\n .short('n')\n .long('name-match')\n .takes_value(true)\n .about('Drop mapping where one reads match with regex'),\n )\n .arg(\n Arg::new('same_name')\n .short('m')\n .long('same-name')\n .about('Drop mapping where reads have same name'),\n )\n .arg(\n Arg::new('sequence_length_lower')\n .short('s')\n .long('sequence-length-lower')\n .takes_value(true)\n .about('Drop mapping where one reads have length lower than value'),\n )\n .arg(\n Arg::new('sequence_length_upper')\n .short('S')\n .long('sequence-length-upper')\n .takes_value(true)\n .about('Drop mapping where one reads have length upper than value'),\n )\n}\n\npub fn get_rename<'a>() -> clap::App<'a> {\n App::new('rename')\n .setting(clap::AppSettings::AllowExternalSubcommands)\n .about('fpa rename reads with name you chose or with incremental counter')\n .arg(\n Arg::new('input')\n .short('i')\n .long('input')\n .takes_value(true)\n .about('Rename reads with value in path passed as parameter'),\n )\n .arg(\n Arg::new('output')\n .short('o')\n .long('output')\n .takes_value(true)\n .about('Write rename table in path passed as parameter'),\n )\n}\n\npub fn get_index<'a>() -> clap::App<'a> {\n App::new('index')\n .setting(clap::AppSettings::AllowExternalSubcommands)\n .about('fpa generate a index of mapping passing filter')\n .arg(\n Arg::new('filename')\n .short('f')\n .long('filename')\n .takes_value(true)\n .display_order(108)\n .about('Write index of mapping passing filter in path passed as parameter'),\n )\n .arg(\n Arg::new('type')\n .short('t')\n .long('type')\n .takes_value(true)\n .default_value('both')\n .possible_values(&['query', 'target', 'both'])\n .about(\n 'Type of index, only reference read when it's query, target or both of them',\n ),\n )\n}\n\npub fn get_gfa<'a>() -> clap::App<'a> {\n App::new('gfa')\n .setting(clap::AppSettings::AllowExternalSubcommands)\n .about('fpa generate a overlap graph in gfa1 format with mapping passing filter')\n .arg(\n Arg::new('output')\n .short('o')\n .long('output')\n .required(true)\n .takes_value(true)\n .about(\n 'Write mapping passing filter in gfa1 graph format in path passed as parameter',\n ),\n )\n .arg(\n Arg::new('containment')\n .short('c')\n .long('containment')\n .about('Keep containment overlap'),\n )\n .arg(\n Arg::new('internalmatch')\n .short('i')\n .long('internalmatch')\n .about('Keep internal match overlap'),\n )\n}\n","mit" +"fpa","./fpa/src/cli/drop.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* project use */\nuse crate::filter;\nuse crate::io;\n\nuse crate::cli::Filters;\n\npub struct Drop {\n filters: Vec>,\n internal_threshold: f64,\n}\n\nimpl Drop {\n pub fn new(\n internal_match: f64,\n matches: &std::collections::HashMap,\n ) -> Self {\n let filters = Vec::new();\n let mut d = Drop {\n filters,\n internal_threshold: internal_match,\n };\n\n if let Some(drop) = matches.get('drop') {\n d.generate(drop);\n }\n\n d\n }\n}\n\nimpl Filters for Drop {\n fn pass(&self, r: &dyn io::MappingRecord) -> bool {\n if self.filters.is_empty() {\n true\n } else {\n !self.filters.iter().any(|x| x.run(r))\n }\n }\n\n fn internal_match(&self) -> f64 {\n self.internal_threshold\n }\n\n fn add_filter(&mut self, f: Box) {\n self.filters.push(f);\n }\n}\n","mit" +"fpa","./fpa/src/type_def.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n#[derive(Clone, Debug, PartialEq)]\npub enum WorkOnWichPart {\n Query,\n Target,\n Both,\n}\n\nimpl From<&str> for WorkOnWichPart {\n fn from(index_type: &str) -> Self {\n match index_type {\n 'query' => WorkOnWichPart::Query,\n 'target' => WorkOnWichPart::Target,\n 'both' => WorkOnWichPart::Both,\n _ => WorkOnWichPart::Both,\n }\n }\n}\n","mit" +"fpa","./fpa/src/main.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#[macro_use]\nextern crate serde_derive;\n\n#[cfg(test)]\n#[macro_use]\nextern crate lazy_static;\n\n/* project mod */\nmod cli;\nmod file;\nmod filter;\nmod generator;\nmod io;\nmod type_def;\n\nuse cli::Filters;\nuse generator::Modifier;\nuse io::MappingRecord;\n\nfn main() {\n let mut app = cli::app();\n let matches = app\n .try_get_matches_from_mut(std::env::args())\n .unwrap_or_else(|e| e.exit());\n\n let subcmd = cli::get_subcmd(&mut app);\n\n /* Manage input and output file */\n let (input, compression) = file::get_input(matches.value_of('input').unwrap());\n\n let format = if matches.is_present('format') {\n match matches.value_of('format').unwrap() {\n 'paf' => io::MappingFormat::Paf,\n 'm4' => io::MappingFormat::M4,\n _ => io::MappingFormat::Paf,\n }\n } else {\n io::MappingFormat::Paf\n };\n\n let out_compression = file::choose_compression(\n compression,\n matches.is_present('compression-out'),\n matches.value_of('compression-out').unwrap_or('no'),\n );\n\n let output: std::io::BufWriter> = std::io::BufWriter::new(\n file::get_output(matches.value_of('output').unwrap(), out_compression),\n );\n\n let internal_match_threshold = matches\n .value_of('internal-match-threshold')\n .unwrap()\n .parse::()\n .unwrap();\n\n match format {\n io::MappingFormat::Paf => paf(input, output, internal_match_threshold, subcmd),\n io::MappingFormat::M4 => m4(input, output, internal_match_threshold, subcmd),\n }\n}\n\nfn paf(\n input: Box,\n output: std::io::BufWriter>,\n internal_match_threshold: f64,\n subcmd: std::collections::HashMap,\n) {\n let mut writer = io::paf::Writer::new(output);\n let mut reader = io::paf::Reader::new(input);\n let drop = cli::Drop::new(internal_match_threshold, &subcmd);\n let keep = cli::Keep::new(internal_match_threshold, &subcmd);\n let mut modifier = cli::Modifier::new(internal_match_threshold, &subcmd);\n\n let mut index = if let Some(m) = subcmd.get('index') {\n generator::Indexing::new(m.value_of('filename').unwrap(), m.value_of('type').unwrap())\n } else {\n generator::Indexing::empty()\n };\n\n let mut position = 0;\n for result in reader.records() {\n let mut record = result.expect('Trouble during read of input mapping');\n\n // keep\n if !keep.pass(&record) {\n continue;\n }\n\n // drop\n if !drop.pass(&record) {\n continue;\n }\n\n // modifier\n modifier.pass(&mut record);\n\n let new_position = position\n + writer\n .write(&record)\n .expect('Trouble during write of output');\n\n record.set_position((position, new_position));\n\n index.run(&mut record);\n\n position = new_position;\n }\n\n // close modifier\n modifier.write();\n\n index.write();\n}\n\nfn m4(\n input: Box,\n output: std::io::BufWriter>,\n internal_match_threshold: f64,\n subcmd: std::collections::HashMap,\n) {\n let mut writer = io::m4::Writer::new(output);\n let mut reader = io::m4::Reader::new(input);\n let drop = cli::Drop::new(internal_match_threshold, &subcmd);\n let keep = cli::Keep::new(internal_match_threshold, &subcmd);\n let mut modifier = cli::Modifier::new(internal_match_threshold, &subcmd);\n\n let mut index = if let Some(m) = subcmd.get('index') {\n generator::Indexing::new(m.value_of('filename').unwrap(), m.value_of('type').unwrap())\n } else {\n generator::Indexing::empty()\n };\n\n let mut position = 0;\n for result in reader.records() {\n let mut record = result.expect('Trouble during read of input mapping');\n\n // keep\n if !keep.pass(&record) {\n continue;\n }\n\n // drop\n if !drop.pass(&record) {\n continue;\n }\n\n // modifier\n modifier.pass(&mut record);\n\n let new_position = position\n + writer\n .write(&record)\n .expect('Trouble during write of output');\n\n record.set_position((position, new_position));\n\n index.run(&mut record);\n\n position = new_position;\n }\n\n // close modifier\n modifier.write();\n\n index.write();\n}\n","mit" +"fpa","./fpa/src/generator/indexing.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* std use */\nuse std::collections::HashMap;\n\n/* project use */\nuse crate::generator;\nuse crate::io;\nuse crate::type_def::WorkOnWichPart;\n\npub struct Indexing {\n index_type: WorkOnWichPart,\n file_index_path: String,\n index_table: HashMap>,\n}\n\nimpl Indexing {\n pub fn new(file_index_path: &str, index_type: &str) -> Self {\n Indexing {\n file_index_path: file_index_path.to_string(),\n index_type: WorkOnWichPart::from(index_type),\n index_table: HashMap::new(),\n }\n }\n\n pub fn empty() -> Self {\n Indexing {\n file_index_path: ''.to_string(),\n index_type: WorkOnWichPart::Both,\n index_table: HashMap::new(),\n }\n }\n\n fn run_both(&mut self, r: &mut dyn io::MappingRecord) {\n self.index_table\n .entry(r.read_a())\n .or_insert_with(Vec::new)\n .push(r.position());\n if r.read_a() != r.read_b() {\n self.index_table\n .entry(r.read_b())\n .or_insert_with(Vec::new)\n .push(r.position());\n }\n }\n\n fn run_query(&mut self, r: &mut dyn io::MappingRecord) {\n self.index_table\n .entry(r.read_a())\n .or_insert_with(Vec::new)\n .push(r.position());\n }\n\n fn run_target(&mut self, r: &mut dyn io::MappingRecord) {\n self.index_table\n .entry(r.read_b())\n .or_insert_with(Vec::new)\n .push(r.position());\n }\n}\n\nimpl generator::Modifier for Indexing {\n fn run(&mut self, r: &mut dyn io::MappingRecord) {\n if self.file_index_path.is_empty() {\n return;\n }\n\n match self.index_type {\n WorkOnWichPart::Both => self.run_both(r),\n WorkOnWichPart::Query => self.run_query(r),\n WorkOnWichPart::Target => self.run_target(r),\n }\n }\n\n fn write(&mut self) {\n if self.file_index_path.is_empty() {\n return;\n }\n\n let mut writer = csv::Writer::from_path(&self.file_index_path)\n .expect('Can't create file to write index');\n\n for (key, val) in &self.index_table {\n let mut iterator = val.iter();\n let mut position = *iterator.next().unwrap();\n\n let mut positions: Vec<(u64, u64)> = Vec::new();\n for v in iterator {\n if v.0 - position.1 > 1 {\n positions.push(position);\n position = *v;\n } else {\n position.1 = v.1;\n }\n }\n positions.push(position);\n\n let positions_str = positions\n .iter()\n .map(|x| x.0.to_string() + ':' + &x.1.to_string())\n .collect::>()\n .join(';');\n writer\n .write_record(&[key, &positions_str])\n .expect('Error durring write index file');\n }\n }\n}\n","mit" +"fpa","./fpa/src/generator/gfa.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* std use */\n\n/* crate use */\n\n/* projet use */\nuse crate::generator;\nuse crate::io;\n\npub struct Gfa1 {\n gfa_path: String,\n gfa_object: io::gfa::Gfa1,\n}\n\nimpl Gfa1 {\n pub fn new(\n gfa_path: String,\n keep_internal: bool,\n keep_containment: bool,\n internal_threshold: f64,\n ) -> Self {\n Gfa1 {\n gfa_path,\n gfa_object: io::gfa::Gfa1::new(keep_internal, keep_containment, internal_threshold),\n }\n }\n}\n\nimpl generator::Modifier for Gfa1 {\n fn run(&mut self, r: &mut dyn io::MappingRecord) {\n self.gfa_object.add(r);\n }\n\n fn write(&mut self) {\n let mut writer = std::io::BufWriter::new(\n std::fs::File::create(&self.gfa_path).expect('Can't create gfa ou'),\n );\n self.gfa_object.write(&mut writer);\n }\n}\n","mit" +"fpa","./fpa/src/generator/mod.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\nuse crate::io;\n\npub trait Modifier {\n fn run(&mut self, r: &mut dyn io::MappingRecord);\n\n fn write(&mut self);\n}\n\npub mod renaming;\npub use self::renaming::Renaming;\n\npub mod indexing;\npub use self::indexing::Indexing;\n\npub mod gfa;\npub use self::gfa::Gfa1;\n","mit" +"fpa","./fpa/src/generator/renaming.rs","/*\nCopyright (c) 2018 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/* std use */\nuse std::collections::HashMap;\nuse std::fs::File;\nuse std::path::Path;\n\n/* project use */\nuse crate::generator;\nuse crate::io;\n\npub struct Renaming {\n file_rename_path: String,\n rename_table: HashMap,\n index: u64,\n index_mode: bool,\n}\n\nimpl Renaming {\n pub fn new(file_rename_path: &str, in_file: bool) -> Self {\n if in_file {\n if !Path::new(file_rename_path).exists() {\n panic!('Rename file not exist')\n }\n\n let mut table = HashMap::new();\n let mut reader = csv::ReaderBuilder::new()\n .has_headers(false)\n .from_reader(File::open(file_rename_path).unwrap());\n\n for result in reader.records() {\n let record = result.expect('Error during parse of renaming file');\n table.insert(record[0].to_string(), record[1].to_string());\n }\n\n Renaming {\n file_rename_path: file_rename_path.to_string(),\n rename_table: table,\n index: 0,\n index_mode: false,\n }\n } else {\n Renaming {\n file_rename_path: file_rename_path.to_string(),\n rename_table: HashMap::new(),\n index: 1,\n index_mode: true,\n }\n }\n }\n\n fn run_index(&self, r: &mut dyn io::MappingRecord) {\n if self.rename_table.contains_key(&r.read_a()) {\n let key = r.read_a();\n r.set_read_a(self.rename_table.get(&key).unwrap().to_string());\n }\n\n if self.rename_table.contains_key(&r.read_b()) {\n let key = r.read_b();\n r.set_read_b(self.rename_table.get(&key).unwrap().to_string());\n }\n }\n\n fn run_no_index(&mut self, r: &mut dyn io::MappingRecord) {\n let mut key = r.read_a();\n if !self.rename_table.contains_key(&key) {\n self.rename_table.insert(r.read_a(), self.index.to_string());\n self.index += 1;\n }\n\n r.set_read_a(self.rename_table.get(&key).unwrap().to_string());\n\n key = r.read_b();\n if !self.rename_table.contains_key(&key) {\n self.rename_table.insert(r.read_b(), self.index.to_string());\n self.index += 1;\n }\n r.set_read_b(self.rename_table.get(&key).unwrap().to_string());\n }\n}\n\nimpl generator::Modifier for Renaming {\n fn run(&mut self, r: &mut dyn io::MappingRecord) {\n if self.index_mode {\n self.run_no_index(r);\n } else {\n self.run_index(r);\n }\n }\n\n fn write(&mut self) {\n if self.index != 0 {\n let mut writer = csv::Writer::from_path(&self.file_rename_path)\n .expect('Can't create file to write renaming file');\n\n for (key, val) in &self.rename_table {\n writer\n .write_record(&[key, val])\n .expect('Error durring write renaming file');\n }\n }\n }\n}\n","mit" +"br","./br/tests/br_large.rs","#[cfg(test)]\nmod tests {\n use std::io::Read;\n use std::process::{Command, Stdio};\n\n fn run_finish(mut child: std::process::Child) -> bool {\n if !child.wait().expect('Error durring br run').success() {\n let mut stdout = String::new();\n let mut stderr = String::new();\n\n child.stdout.unwrap().read_to_string(&mut stdout).unwrap();\n child.stderr.unwrap().read_to_string(&mut stderr).unwrap();\n\n println!('stdout: {}', stdout);\n println!('stderr: {}', stderr);\n\n false\n } else {\n true\n }\n }\n\n #[test]\n fn run() {\n let child = Command::new('./target/debug/br_large')\n .args(&[\n '-i',\n 'tests/data/raw.fasta',\n '-o',\n 'tests/data/corr.fasta',\n '-S',\n 'tests/data/raw.k31.fasta',\n '-k',\n '31',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create br subprocess');\n\n assert!(run_finish(child));\n }\n\n #[test]\n fn no_kmer_size() {\n let child = Command::new('./target/debug/br_large')\n .args(&[\n '-i',\n 'tests/data/raw.fasta',\n '-o',\n 'tests/data/corr.fasta',\n '-S',\n 'tests/data/raw.k31.fasta',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create br subprocess');\n\n assert!(!run_finish(child));\n }\n}\n","mit" +"br","./br/tests/br.rs","#[cfg(test)]\nmod tests {\n use std::io::Read;\n use std::process::{Command, Stdio};\n\n fn run_finish(mut child: std::process::Child) -> bool {\n if !child.wait().expect('Error durring br run').success() {\n let mut stdout = String::new();\n let mut stderr = String::new();\n\n child.stdout.unwrap().read_to_string(&mut stdout).unwrap();\n child.stderr.unwrap().read_to_string(&mut stderr).unwrap();\n\n println!('stdout: {}', stdout);\n println!('stderr: {}', stderr);\n\n false\n } else {\n true\n }\n }\n\n #[test]\n fn count() {\n let child = Command::new('./target/debug/br')\n .args(&[\n '-i',\n 'tests/data/raw.fasta',\n '-o',\n 'tests/data/corr.fasta',\n '-k',\n '11',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create br subprocess');\n\n assert!(run_finish(child));\n }\n\n #[test]\n fn solid() {\n let child = Command::new('./target/debug/br')\n .args(&[\n '-i',\n 'tests/data/raw.fasta',\n '-o',\n 'tests/data/corr.fasta',\n '-s',\n 'tests/data/raw.k11.a2.solid',\n ])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create br subprocess');\n\n assert!(run_finish(child));\n }\n\n #[test]\n fn no_count_no_solid() {\n let child = Command::new('./target/debug/br')\n .args(&['-i', 'tests/data/raw.fasta', '-o', 'tests/data/corr.fasta'])\n .stderr(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .expect('Couldn't create br subprocess');\n\n assert!(!run_finish(child));\n }\n}\n","mit" +"br","./br/src/correct/graph.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse log::debug;\n\n/* local use */\nuse crate::correct::*;\n\npub struct Graph<'a> {\n valid_kmer: &'a set::BoxKmerSet<'a>,\n}\n\nimpl<'a> Graph<'a> {\n pub fn new(valid_kmer: &'a set::BoxKmerSet<'a>) -> Self {\n Self { valid_kmer }\n }\n}\n\nimpl<'a> Corrector for Graph<'a> {\n fn valid_kmer(&self) -> &set::BoxKmerSet {\n self.valid_kmer\n }\n\n fn correct_error(&self, mut kmer: u64, seq: &[u8]) -> Option<(Vec, usize)> {\n let (error_len, first_correct_kmer) = error_len(seq, kmer, self.valid_kmer());\n\n let mut viewed_kmer = rustc_hash::FxHashSet::default();\n\n let mut local_corr = Vec::new();\n\n let alts = alt_nucs(self.valid_kmer(), kmer);\n if alts.len() != 1 {\n debug!('failed multiple successor {:?}', alts);\n return None;\n }\n\n kmer = add_nuc_to_end(kmer >> 2, alts[0], self.k());\n local_corr.push(cocktail::kmer::bit2nuc(alts[0]));\n viewed_kmer.insert(kmer);\n\n while self.valid_kmer().get(kmer) {\n let alts = next_nucs(self.valid_kmer(), kmer);\n\n if alts.len() != 1 {\n debug!('failed branching node {:?}', alts);\n return None;\n }\n\n kmer = add_nuc_to_end(kmer, alts[0], self.k());\n\n if viewed_kmer.contains(&kmer) {\n debug!('we view this kmer previously');\n return None;\n }\n viewed_kmer.insert(kmer);\n\n local_corr.push(cocktail::kmer::bit2nuc(alts[0]));\n\n if kmer == first_correct_kmer {\n break;\n }\n }\n\n Some((local_corr, error_len + 1))\n }\n}\n\n#[cfg(test)]\nmod tests {\n\n use super::*;\n\n fn init() {\n let _ = env_logger::builder()\n .is_test(true)\n .filter_level(log::LevelFilter::Trace)\n .try_init();\n }\n\n #[test]\n fn branching_path_csc() {\n init();\n\n let refe = b'TCTTTATTTTC';\n // ||||| |||||\n let read = b'TCTTTGTTTTC';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n data.set(cocktail::kmer::seq2bit(b'TTTTT'), true);\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn branching_path_cdc() {\n init();\n\n let refe = b'GATACATGGACACTAGTATG';\n // ||||||||||\n let read = b'GATACATGGAACTAGTATG';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n data.set(cocktail::kmer::seq2bit(b'GGACT'), true);\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(read, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn branching_path_cic() {\n init();\n\n let refe = b'GATACATGGACACTAGTATG';\n // ||||||||||\n let read = b'GATACATGGATCACTAGTATG';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n data.set(cocktail::kmer::seq2bit(b'GGACT'), true);\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn csc() {\n init();\n\n let refe = b'TCTTTATTTTC';\n // ||||| |||||\n let read = b'TCTTTGTTTTC';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cssc() {\n init();\n\n let refe = b'TCTCTAATCTTC';\n // ||||| |||||\n let read = b'TCTCTGGTCTTC';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn csssc() {\n init();\n\n let refe = b'TCTCTAAATCTTC';\n // ||||| |||||\n let read = b'TCTCTGGGTCTTC';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrect\n }\n\n #[test]\n fn cscsc() {\n init();\n\n let refe = b'TCTTTACATTTTT';\n // ||||| | |||||\n let read = b'TCTTTGCGTTTTT';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cdc() {\n init();\n\n let refe = b'GATACATGGACACTAGTATG';\n // ||||||||||\n let read = b'GATACATGGAACTAGTATG';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(refe, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cddc() {\n init();\n\n let refe = b'CAAAGCATTTTT';\n // |||||\n let read = b'CAAAGTTTTT';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(refe, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cic() {\n init();\n\n let refe = b'GATACATGGACACTAGTATG';\n // ||||||||||\n let read = b'GATACATGGATCACTAGTATG';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn ciic() {\n init();\n\n let refe = b'GATACATGGACACTAGTATG';\n // ||||||||||\n let read = b'GATACATGGATTCACTAGTATG';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Graph::new(&set);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n}\n","mit" +"br","./br/src/correct/greedy.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse log::debug;\n\n/* local use */\nuse crate::correct::*;\n\nstruct Score;\n\nimpl bio::alignment::pairwise::MatchFunc for Score {\n fn score(&self, a: u8, b: u8) -> i32 {\n if a == b {\n 1\n } else {\n -1\n }\n }\n}\n\npub struct Greedy<'a> {\n valid_kmer: &'a set::BoxKmerSet<'a>,\n max_search: u8,\n nb_validate: u8,\n}\n\nimpl<'a> Greedy<'a> {\n pub fn new(valid_kmer: &'a set::BoxKmerSet, max_search: u8, nb_validate: u8) -> Self {\n Self {\n valid_kmer,\n max_search,\n nb_validate,\n }\n }\n\n fn match_alignement(&self, before_seq: Vec, read: &[u8], corr: &[u8]) -> Option {\n let mut r = before_seq.clone();\n r.extend_from_slice(read);\n\n let mut c = before_seq.clone();\n c.extend_from_slice(corr);\n\n let mut aligner =\n bio::alignment::pairwise::Aligner::with_capacity(10, 10, -1, -1, Score {});\n let alignment = aligner.global(r.as_slice(), c.as_slice());\n\n let mut offset = 0;\n for ops in alignment.operations[before_seq.len()..].windows(2) {\n match ops[0] {\n bio::alignment::AlignmentOperation::Del => offset -= 1,\n bio::alignment::AlignmentOperation::Ins => offset += 1,\n _ => (),\n }\n\n if ops[0] == bio::alignment::AlignmentOperation::Match && ops[0] == ops[1] {\n let mut offset_corr = 0;\n for op in alignment.operations.iter().rev() {\n match op {\n bio::alignment::AlignmentOperation::Del => offset_corr -= 1,\n bio::alignment::AlignmentOperation::Ins => offset_corr += 1,\n _ => break,\n }\n }\n return Some(offset - offset_corr);\n }\n }\n\n None\n }\n\n fn follow_graph(&self, mut kmer: u64) -> Option<(u8, u64)> {\n let alts = next_nucs(self.valid_kmer(), kmer);\n\n if alts.len() != 1 {\n debug!('failled branching node {:?}', alts);\n return None;\n }\n\n kmer = add_nuc_to_end(kmer, alts[0], self.k());\n\n Some((cocktail::kmer::bit2nuc(alts[0]), kmer))\n }\n\n fn check_next_kmers(&self, mut kmer: u64, seq: &[u8]) -> bool {\n if seq.len() < self.nb_validate as usize {\n return false;\n }\n\n for nuc in &seq[..self.nb_validate as usize] {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(*nuc), self.k());\n if !self.valid_kmer.get(kmer) {\n return false;\n }\n }\n\n true\n }\n}\n\nimpl<'a> Corrector for Greedy<'a> {\n fn k(&self) -> u8 {\n self.valid_kmer.k()\n }\n\n fn valid_kmer(&self) -> &set::BoxKmerSet {\n self.valid_kmer\n }\n\n fn correct_error(&self, mut kmer: u64, seq: &[u8]) -> Option<(Vec, usize)> {\n let alts = alt_nucs(self.valid_kmer(), kmer);\n if alts.len() != 1 {\n debug!('failled multiple successor {:?}', alts);\n return None;\n }\n\n let mut viewed_kmer = rustc_hash::FxHashSet::default();\n\n let mut local_corr = Vec::new();\n let before_seq = cocktail::kmer::kmer2seq(kmer >> 2, self.k() - 1)\n .as_bytes()\n .to_vec();\n\n kmer = add_nuc_to_end(kmer >> 2, alts[0], self.k());\n\n local_corr.push(cocktail::kmer::bit2nuc(alts[0]));\n viewed_kmer.insert(kmer);\n\n for i in 0..(self.max_search as usize) {\n if let Some((base, new_kmer)) = self.follow_graph(kmer) {\n local_corr.push(base);\n kmer = new_kmer;\n }\n\n if viewed_kmer.contains(&kmer) {\n debug!('we view this kmer previously');\n return None;\n }\n viewed_kmer.insert(kmer);\n\n if seq.len() < i as usize {\n return None;\n }\n\n if let Some(off) = self.match_alignement(before_seq.clone(), &seq[..i], &local_corr) {\n if self.check_next_kmers(kmer, &seq[i..]) {\n let offset: usize = (local_corr.len() as i64 + off) as usize;\n return Some((local_corr, offset));\n }\n }\n }\n\n None\n }\n}\n\n#[cfg(test)]\nmod tests {\n\n use super::*;\n\n static K: u8 = 11;\n static REFE: &[u8] = b'TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG';\n\n fn init() {\n let _ = env_logger::builder()\n .is_test(true)\n .filter_level(log::LevelFilter::Trace)\n .try_init();\n }\n\n fn get_solid() -> pcon::solid::Solid {\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(K);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(REFE, K) {\n data.set(kmer, true);\n }\n\n data\n }\n\n #[test]\n fn branching_path_csc() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // |||||||||||||||||||||||| |||||||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACATTTCACTGCCCGATACGCAGATGAAAGAGG';\n\n let mut data = get_solid();\n\n data.set(cocktail::kmer::seq2bit(b'CACATTTCGCG'), true);\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn branching_path_cdc() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||||||//////////////////////////\n let read = b'TAAGGCGCGTCCCGCACACATTTCCTGCCCGATACGCAGATGAAAGAGG';\n\n let mut data = get_solid();\n\n data.set(cocktail::kmer::seq2bit(b'CACATTTCGCG'), true);\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn branching_path_cic() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||||||\\\\\\\\\\\\\\\\\\\\\\\\\\\n let read = b'TAAGGCGCGTCCCGCACACATTTCAGCTGCCCGATACGCAGATGAAAGAGG';\n\n let mut data = get_solid();\n\n data.set(cocktail::kmer::seq2bit(b'CACACATTTCT'), true);\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn csc() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // |||||||||||||||||||||||| |||||||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACATTTCACTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cssc() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||||| |||||||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACATTTGACTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn csssc() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||||| ||||||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACATTTGATTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cscsc() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||||| ||||||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACATTTGATTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n #[ignore]\n fn cdc() {\n init();\n\n // TTTCGCTGCCCG\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||||||//////////////////////////\n let read = b'TAAGGCGCGTCCCGCACACATTTCCTGCCCGATACGCAGATGAAAGAGG';\n // TTTCCTGCCCG\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n #[ignore]\n fn cddc() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACATCGCTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n #[ignore]\n fn cdddc() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACACGCTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cic() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG\n // ||||||||||||||||||||||||\\\\\\\\\\\\\\\\\\\\\\\\\\\\n let read = b'TAAGGCGCGTCCCGCACACATTTCAGCTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn ciic() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTC--GCTGCCCGATACGCAGATGAAAGAGG\n // |||||||||||||||||||||||| ||||||||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACATTTCAAGCTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn ciiic() {\n init();\n\n // TAAGGCGCGTCCCGCACACATTTC---GCTGCCCGATACGCAGATGAAAGAGG\n // |||||||||||||||||||||||| ||||||||||||||||||||||||||\n let read = b'TAAGGCGCGTCCCGCACACATTTCAAAGCTGCCCGATACGCAGATGAAAGAGG';\n\n let data = get_solid();\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Greedy::new(&set, 7, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(REFE, corrector.correct(REFE).as_slice()); // test not overcorrection\n }\n}\n","mit" +"br","./br/src/correct/exist/two.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse strum_macros::EnumIter;\n\n/* crate use */\nuse crate::correct::exist::{Exist, Scenario};\nuse crate::correct::*;\nuse crate::set;\n\n////////////////////////////////////\n// Scenario for correct two error //\n////////////////////////////////////\n#[derive(Debug, EnumIter, Clone, Copy)]\npub enum ScenarioTwo {\n II(usize, u8),\n IS(usize, u8),\n SS(usize, u8),\n SD(usize, u8),\n DD(usize, u8),\n\n ICI(usize, u8),\n ICS(usize, u8),\n ICD(usize, u8),\n SCI(usize, u8),\n SCS(usize, u8),\n SCD(usize, u8),\n DCI(usize, u8),\n DCD(usize, u8),\n}\n\nimpl Scenario for ScenarioTwo {\n fn init(&self, c: usize, k: u8) -> Self {\n match self {\n ScenarioTwo::II(_, _) => ScenarioTwo::II(c, k),\n ScenarioTwo::IS(_, _) => ScenarioTwo::IS(c, k),\n ScenarioTwo::SS(_, _) => ScenarioTwo::SS(c, k),\n ScenarioTwo::SD(_, _) => ScenarioTwo::SD(c, k),\n ScenarioTwo::DD(_, _) => ScenarioTwo::DD(c, k),\n ScenarioTwo::ICI(_, _) => ScenarioTwo::ICI(c, k),\n ScenarioTwo::ICS(_, _) => ScenarioTwo::ICS(c, k),\n ScenarioTwo::ICD(_, _) => ScenarioTwo::ICD(c, k),\n ScenarioTwo::SCI(_, _) => ScenarioTwo::SCI(c, k),\n ScenarioTwo::SCS(_, _) => ScenarioTwo::SCS(c, k),\n ScenarioTwo::SCD(_, _) => ScenarioTwo::SCD(c, k),\n ScenarioTwo::DCI(_, _) => ScenarioTwo::DCI(c, k),\n ScenarioTwo::DCD(_, _) => ScenarioTwo::DCD(c, k),\n }\n }\n\n fn c(&self) -> usize {\n match self {\n ScenarioTwo::II(c, _) => *c,\n ScenarioTwo::IS(c, _) => *c,\n ScenarioTwo::SS(c, _) => *c,\n ScenarioTwo::SD(c, _) => *c,\n ScenarioTwo::DD(c, _) => *c,\n ScenarioTwo::ICI(c, _) => *c,\n ScenarioTwo::ICS(c, _) => *c,\n ScenarioTwo::ICD(c, _) => *c,\n ScenarioTwo::SCI(c, _) => *c,\n ScenarioTwo::SCS(c, _) => *c,\n ScenarioTwo::SCD(c, _) => *c,\n ScenarioTwo::DCI(c, _) => *c,\n ScenarioTwo::DCD(c, _) => *c,\n }\n }\n\n fn apply(\n &self,\n valid_kmer: &set::BoxKmerSet,\n mut kmer: u64,\n seq: &[u8],\n ) -> Option<(u64, usize)> {\n match self {\n ScenarioTwo::II(_, _) => Some((kmer, 3)), // kmer not change check from base 3\n ScenarioTwo::IS(_, _) => Some((kmer, 2)), // kmer not change check from base 2\n ScenarioTwo::SS(_, k) => {\n if seq.len() < 2 {\n None\n } else {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k);\n if valid_kmer.get(kmer) {\n None\n } else {\n let alts = alt_nucs(valid_kmer, kmer);\n if alts.len() != 1 {\n None\n } else {\n Some((add_nuc_to_end(kmer >> 2, alts[0], *k), 2))\n }\n }\n }\n }\n ScenarioTwo::SD(_, k) => {\n if seq.is_empty() {\n None\n } else {\n let alts = alt_nucs(valid_kmer, kmer << 2);\n if alts.len() != 1 {\n None\n } else {\n Some((add_nuc_to_end(kmer, alts[0], *k), 1))\n }\n }\n }\n ScenarioTwo::DD(_, k) => {\n let alts = alt_nucs(valid_kmer, kmer << 2);\n if alts.len() != 1 {\n None\n } else {\n Some((add_nuc_to_end(kmer, alts[0], *k), 0))\n }\n }\n ScenarioTwo::ICI(_, k) => {\n // If seq is to short we can't apply\n if seq.len() < 4 {\n None\n } else {\n let corr = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[3]), *k); // If kmer with thrid base is valid is an ICI\n\n if valid_kmer.get(corr) {\n Some((corr, 4))\n } else {\n None\n }\n }\n }\n ScenarioTwo::ICS(_, k) => {\n // If seq is to short we can't apply\n if seq.len() < 4 {\n None\n } else {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k);\n if valid_kmer.get(kmer) {\n None\n } else {\n let alts = alt_nucs(valid_kmer, kmer);\n if alts.len() != 1 {\n None\n } else {\n Some((add_nuc_to_end(kmer >> 2, alts[0], *k), 3))\n }\n }\n }\n }\n ScenarioTwo::ICD(_, k) => {\n // If seq is to short we can't apply\n if seq.len() < 4 {\n None\n } else {\n let second = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[2]), *k);\n\n let alts = alt_nucs(valid_kmer, second << 2);\n if alts.len() != 1 {\n None\n } else {\n Some((add_nuc_to_end(second, alts[0], *k), 3))\n }\n }\n }\n ScenarioTwo::SCI(_, k) => {\n if seq.len() < 4 {\n None\n } else {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k);\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[3]), *k);\n\n Some((kmer, 4))\n }\n }\n ScenarioTwo::SCS(_, k) => {\n if seq.len() < 3 {\n None\n } else {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k);\n if valid_kmer.get(kmer) {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[2]), *k);\n\n if !valid_kmer.get(kmer) {\n let alts = alt_nucs(valid_kmer, kmer);\n\n if alts.len() == 1 {\n Some((add_nuc_to_end(kmer >> 2, alts[0], *k), 3))\n } else {\n None\n }\n } else {\n None\n }\n } else {\n None\n }\n }\n }\n ScenarioTwo::SCD(_, k) => {\n if seq.len() < 2 {\n None\n } else {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k);\n\n let alts = alt_nucs(valid_kmer, kmer << 2);\n\n if alts.len() != 1 {\n None\n } else {\n Some((add_nuc_to_end(kmer, alts[0], *k), 2))\n }\n }\n }\n ScenarioTwo::DCI(_, k) => {\n if seq.len() < 4 {\n None\n } else {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[1]), *k);\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[3]), *k);\n\n Some((kmer, 4))\n }\n }\n ScenarioTwo::DCD(_, k) => {\n if seq.len() < 2 {\n None\n } else {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(seq[0]), *k);\n\n let alts = alt_nucs(valid_kmer, kmer << 2);\n if alts.len() != 1 {\n None\n } else {\n Some((add_nuc_to_end(kmer, alts[0], *k), 1))\n }\n }\n }\n }\n }\n\n fn correct(&self, valid_kmer: &set::BoxKmerSet, kmer: u64, seq: &[u8]) -> (Vec, usize) {\n match self {\n ScenarioTwo::II(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 2),\n ScenarioTwo::IS(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 2),\n ScenarioTwo::SS(_, _) | ScenarioTwo::SD(_, _) | ScenarioTwo::DD(_, _) => {\n let (corr, offset) = self\n .apply(valid_kmer, kmer, seq)\n .expect('we can't failled her');\n\n (\n vec![\n cocktail::kmer::bit2nuc((corr & 0b1100) >> 2),\n cocktail::kmer::bit2nuc(corr & 0b11),\n ],\n offset,\n )\n }\n ScenarioTwo::ICI(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 3),\n ScenarioTwo::ICD(_, _) => {\n let (corr, offset) = self\n .apply(valid_kmer, kmer, seq)\n .expect('we can't failled her');\n\n (\n vec![\n cocktail::kmer::bit2nuc((corr & 0b1100) >> 2),\n cocktail::kmer::bit2nuc(corr & 0b11),\n ],\n offset - 1,\n )\n }\n ScenarioTwo::ICS(_, _) => {\n let (corr, offset) = self\n .apply(valid_kmer, kmer, seq)\n .expect('we can't failled her');\n\n (\n vec![\n cocktail::kmer::bit2nuc((corr & 0b1100) >> 2),\n cocktail::kmer::bit2nuc(corr & 0b11),\n ],\n offset + 1,\n )\n }\n ScenarioTwo::SCI(_, _)\n | ScenarioTwo::SCS(_, _)\n | ScenarioTwo::SCD(_, _)\n | ScenarioTwo::DCD(_, _) => {\n let (corr, offset) = self\n .apply(valid_kmer, kmer, seq)\n .expect('we can't failled her');\n\n (\n vec![\n cocktail::kmer::bit2nuc((corr & 0b110000) >> 4),\n cocktail::kmer::bit2nuc((corr & 0b1100) >> 2),\n cocktail::kmer::bit2nuc(corr & 0b11),\n ],\n offset,\n )\n }\n /* ScenarioTwo::DCD => {\n None\n },\n */\n _ => (vec![], 1),\n }\n }\n}\n\npub type Two<'a> = Exist<'a, ScenarioTwo>;\n\n#[cfg(test)]\nmod tests {\n\n use super::*;\n\n use crate::correct::Corrector;\n\n fn init() {\n let _ = env_logger::builder()\n .is_test(true)\n .filter_level(log::LevelFilter::Trace)\n .try_init();\n }\n\n fn filter<'a>(ori: &[u8]) -> Vec {\n ori.iter()\n .cloned()\n .filter(|x| *x != b'-')\n .collect::>()\n }\n\n #[test]\n fn short() {\n init();\n\n let refe = filter(b'CTGGTGCACTACCGGATAGG');\n // |||||| |\n let read = filter(b'-------ACTACCTG');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(read, corrector.correct(&read).as_slice()); // test correction work\n }\n\n #[test]\n fn ciic() {\n init();\n\n let refe = filter(b'GATACATGGA--CACTAGTATG');\n // |||||||||| ||||||||||\n let read = filter(b'GATACATGGATTCACTAGTATG');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cisc() {\n init();\n\n let refe = filter(b'GATACATGGA-CACTAGTATG');\n // |||||||||| |||||||||\n let read = filter(b'GATACATGGATGACTAGTATG');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cssc() {\n init();\n\n let refe = b'TCGTTATTCGGTGGACTCCT';\n // |||||||||| ||||||||\n let read = b'TCGTTATTCGAAGGACTCCT';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn csdc() {\n init();\n\n let refe = b'AACAGCTGAATCTACCATTG';\n // |||||||||| /////////\n let read = b'AACAGCTGAAGTACCATTG';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cddc() {\n init();\n\n let refe = b'TGCCGTAGGCCATTGCGGCT';\n // |||||||||| ||||||||\n let read = b'TGCCGTAGGC--TTGCGGCT';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(&filter(read)).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cicic() {\n init();\n\n let refe = filter(b'ATAGTAACGG-A-CACACTT');\n // |||||||||| | |||||||\n let read = filter(b'ATAGTAACGGAAGCACACTT');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 3);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cicsc() {\n init();\n\n let refe = filter(b'GAGCCCAGAG-CGATATTCT');\n // |||||||||| | |||||||\n let read = filter(b'GAGCCCAGAGACTATATTCT');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cicdc() {\n init();\n\n let refe = filter(b'TCGAAAGCAT-GGGTACGTT');\n // |||||||||| | |||||||\n let read = filter(b'TCGAAAGCATAG-GTACGTT');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cscic() {\n init();\n\n let refe = filter(b'AAGGATGCATCG-ACTCAAG');\n // |||||||||| | |||||||\n let read = filter(b'AAGGATGCATGGAACTCAAG');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cscsc() {\n init();\n\n let refe = filter(b'ACACGTGCGCTTGGAGGTAC');\n // |||||||||| | |||||||\n let read = filter(b'ACACGTGCGCATCGAGGTAC');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cscdc() {\n init();\n\n let refe = filter(b'TATGCTCTGCGTAATCATAG');\n // |||||||||| | |||||||\n let read = filter(b'TATGCTCTGCAT-ATCATAG');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cdcic() {\n init();\n\n let refe = filter(b'GCTTCGTGATAG-TACGCTT');\n // |||||||||| | |||||||\n let read = filter(b'GCTTCGTGAT-GATACGCTT');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cdcsc() {\n init();\n\n let refe = filter(b'GGACCTGATCACGTCAATTA');\n // |||||||||| | |||||||\n let read = filter(b'GGACCTGATC-CCTCAATTA');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cdcdc() {\n init();\n\n let refe = filter(b'GGAATACGTGCGTTGGGTAA');\n // |||||||||| | |||||||\n let read = filter(b'GGAATACGTG-G-TGGGTAA');\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = Two::new(&set, 2);\n\n assert_eq!(&refe, corrector.correct(&read).as_slice()); // test correction work\n assert_eq!(&refe, corrector.correct(&refe).as_slice()); // test not overcorrection\n }\n}\n","mit" +"br","./br/src/correct/exist/one.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse strum_macros::EnumIter;\n\n/* crate use */\nuse crate::correct::exist::{Exist, Scenario};\nuse crate::set;\n\n////////////////////////////////////\n// Scenario for correct one error //\n////////////////////////////////////\n#[derive(Debug, EnumIter, Clone, Copy)]\npub enum ScenarioOne {\n I(usize, u8),\n S(usize, u8),\n D(usize, u8),\n}\n\nimpl Scenario for ScenarioOne {\n fn init(&self, c: usize, k: u8) -> Self {\n match self {\n ScenarioOne::I(_, _) => ScenarioOne::I(c, k),\n ScenarioOne::S(_, _) => ScenarioOne::S(c, k),\n ScenarioOne::D(_, _) => ScenarioOne::D(c, k),\n }\n }\n\n fn c(&self) -> usize {\n match self {\n ScenarioOne::I(c, _) => *c,\n ScenarioOne::S(c, _) => *c,\n ScenarioOne::D(c, _) => *c,\n }\n }\n\n fn apply(&self, _valid_kmer: &set::BoxKmerSet, kmer: u64, _seq: &[u8]) -> Option<(u64, usize)> {\n match self {\n ScenarioOne::I(_, _) => Some((kmer, 2)),\n ScenarioOne::S(_, _) => Some((kmer, 1)),\n ScenarioOne::D(_, _) => Some((kmer, 0)),\n }\n }\n\n fn correct(&self, _valid_kmer: &set::BoxKmerSet, kmer: u64, _seq: &[u8]) -> (Vec, usize) {\n match self {\n ScenarioOne::I(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 2),\n ScenarioOne::S(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 1),\n ScenarioOne::D(_, _) => (vec![cocktail::kmer::bit2nuc(kmer & 0b11)], 0),\n }\n }\n}\n\npub type One<'a> = Exist<'a, ScenarioOne>;\n\n#[cfg(test)]\nmod tests {\n\n use super::*;\n use crate::correct::Corrector;\n\n fn init() {\n let _ = env_logger::builder()\n .is_test(true)\n .filter_level(log::LevelFilter::Trace)\n .try_init();\n }\n\n fn filter<'a>(ori: &[u8]) -> Vec {\n ori.iter()\n .cloned()\n .filter(|x| *x != b'-')\n .collect::>()\n }\n\n #[test]\n fn csc() {\n init();\n\n let refe = b'ACTGACGAC';\n let read = b'ACTGATGAC';\n\n let mut data = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn csc_relaxe() {\n init();\n\n let refe = b'ACTGACCACT';\n let read = b'ACTGATCACT';\n let conf = b'ACTGACAC';\n\n let mut data = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n for kmer in cocktail::tokenizer::Tokenizer::new(conf, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cssc() {\n init();\n\n let refe = b'ACTGACGAG';\n let read = b'ACTGATAAG';\n\n let mut data = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // don't correct\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cic() {\n init();\n\n let refe = filter(b'ACTGA-CGAC');\n let read = filter(b'ACTGATCGAC');\n\n let mut data = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(&read).as_slice());\n assert_eq!(refe, corrector.correct(&refe).as_slice());\n }\n\n #[test]\n fn cic_relaxe() {\n init();\n\n // GCGTAC-G\n // AGCGTAC\n // GTACTTG\n let refe = filter(b'GAGCGTAC-GTTGGAT');\n let read = filter(b'GAGCGTACTGTTGGAT');\n let conf = b'GCGTACGTGA';\n\n let mut data = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(&refe, 7) {\n data.set(kmer, true);\n }\n\n for kmer in cocktail::tokenizer::Tokenizer::new(conf, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(&read).as_slice());\n assert_eq!(refe, corrector.correct(&refe).as_slice());\n }\n\n #[test]\n fn ciic() {\n init();\n\n let refe = b'ACTGACGA';\n let read = b'ACTGATTCGA';\n\n let mut data = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // don't correct\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cdc() {\n init();\n\n let refe = b'ACTGACGACCC';\n let read = b'ACTGAGACCC';\n\n let mut data = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cdc_relaxe() {\n init();\n\n let refe = b'GAGCGTACGTTGGAT';\n let read = b'GAGCGTAGTTGGAT';\n let conf = b'GCGTACTT';\n\n let mut data = pcon::solid::Solid::new(7);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 7) {\n data.set(kmer, true);\n }\n\n for kmer in cocktail::tokenizer::Tokenizer::new(conf, 7) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cddc() {\n init();\n\n let refe = b'ACTGACGAG';\n let read = b'ACTGAAG';\n\n let mut data = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = One::new(&set, 2);\n\n assert_eq!(read, corrector.correct(read).as_slice()); // don't correct\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n}\n","mit" +"br","./br/src/correct/exist/mod.rs","/* crate use */\nuse log::debug;\nuse strum::IntoEnumIterator;\n\n/* crate use */\nuse crate::correct::*;\nuse crate::set;\n\n///////////////////////////////////////////\n// Generic Trait for correction scenario //\n///////////////////////////////////////////\npub trait Scenario: std::fmt::Debug + Copy {\n fn init(&self, c: usize, k: u8) -> Self;\n\n fn c(&self) -> usize;\n\n fn apply(&self, valid_kmer: &set::BoxKmerSet, kmer: u64, seq: &[u8]) -> Option<(u64, usize)>;\n\n fn correct(&self, valid_kmer: &set::BoxKmerSet, kmer: u64, _seq: &[u8]) -> (Vec, usize);\n\n fn get_score(&self, valid_kmer: &set::BoxKmerSet, ori: u64, seq: &[u8]) -> usize {\n if let Some((mut kmer, offset)) = self.apply(valid_kmer, ori, seq) {\n if !valid_kmer.get(kmer) {\n return 0;\n }\n\n if offset + self.c() > seq.len() {\n return 0;\n }\n\n let mut score = 0;\n\n for nuc in &seq[offset..offset + self.c()] {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(*nuc), valid_kmer.k());\n\n if valid_kmer.get(kmer) {\n score += 1\n } else {\n break;\n }\n }\n\n score\n } else {\n 0\n }\n }\n\n fn one_more(&self, valid_kmer: &set::BoxKmerSet, mut kmer: u64, seq: &[u8]) -> bool {\n // Get correction\n let (corr, offset) = self.correct(valid_kmer, kmer, seq);\n\n // Can we read one base more\n if seq.len() > self.c() + offset + 1 {\n kmer >>= 2;\n // Apply correction on kmer\n corr.iter().for_each(|nuc| {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(*nuc), valid_kmer.k())\n });\n\n // Apply base previously check\n seq[offset..(offset + self.c() + 1)].iter().for_each(|nuc| {\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(*nuc), valid_kmer.k())\n });\n\n valid_kmer.get(kmer)\n } else {\n false\n }\n }\n}\n\n//////////////////////////////////////////\n// Exsist use scenario to correct error //\n//////////////////////////////////////////\npub struct Exist<'a, S>\nwhere\n S: Scenario + IntoEnumIterator,\n{\n valid_kmer: &'a set::BoxKmerSet<'a>,\n c: u8,\n _phantom: std::marker::PhantomData<&'a S>,\n}\n\nimpl<'a, S> Exist<'a, S>\nwhere\n S: Scenario + IntoEnumIterator,\n{\n pub fn new(valid_kmer: &'a set::BoxKmerSet, c: u8) -> Self {\n Self {\n valid_kmer,\n c,\n _phantom: std::marker::PhantomData,\n }\n }\n\n fn get_scenarii(&self, kmer: u64, seq: &[u8]) -> Vec {\n let mut scenarii: Vec = Vec::new();\n\n for mut scenario in S::iter() {\n scenario = scenario.init(self.c as usize, self.valid_kmer.k());\n\n if scenario.get_score(self.valid_kmer, kmer, seq) == self.c as usize {\n scenarii.push(scenario)\n }\n }\n\n scenarii\n }\n}\n\nimpl<'a, S> Corrector for Exist<'a, S>\nwhere\n S: Scenario + IntoEnumIterator,\n{\n fn valid_kmer(&self) -> &set::BoxKmerSet {\n self.valid_kmer\n }\n\n fn correct_error(&self, kmer: u64, seq: &[u8]) -> Option<(Vec, usize)> {\n let alts = alt_nucs(self.valid_kmer, kmer);\n\n if alts.len() != 1 {\n debug!('not one alts {:?}', alts);\n return None;\n }\n debug!('one alts {:?}', alts);\n\n let corr = add_nuc_to_end(kmer >> 2, alts[0], self.k());\n let mut scenarii = self.get_scenarii(corr, seq);\n\n if scenarii.is_empty() {\n debug!('no scenario');\n None\n } else if scenarii.len() == 1 {\n debug!('one {:?}', scenarii);\n Some(scenarii[0].correct(self.valid_kmer, corr, seq))\n } else {\n debug!('multiple {:?}', scenarii);\n scenarii.retain(|x| x.one_more(self.valid_kmer, corr, seq));\n debug!('multiple {:?}', scenarii);\n\n if scenarii.len() == 1 {\n Some(scenarii[0].correct(self.valid_kmer, corr, seq))\n } else {\n None\n }\n }\n }\n}\n\npub mod one;\npub mod two;\n","mit" +"br","./br/src/correct/mod.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* local use */\nuse crate::set;\n\nconst MASK_LOOKUP: [u64; 32] = {\n let mut lookup = [0; 32];\n\n let mut k = 1;\n while k < 32 {\n lookup[k] = (1 << (2 * k)) - 1;\n\n k += 1;\n }\n\n lookup\n};\n\n#[inline(always)]\npub(crate) fn mask(k: u8) -> u64 {\n MASK_LOOKUP[k as usize]\n}\n\npub trait Corrector {\n fn valid_kmer(&self) -> &set::BoxKmerSet;\n\n fn correct_error(&self, kmer: u64, seq: &[u8]) -> Option<(Vec, usize)>;\n\n fn k(&self) -> u8 {\n self.valid_kmer().k()\n }\n\n fn correct(&self, seq: &[u8]) -> Vec {\n let mut correct: Vec = Vec::with_capacity(seq.len());\n\n if seq.len() < self.k() as usize {\n return seq.to_vec();\n }\n\n let mut i = self.k() as usize;\n let mut kmer = cocktail::kmer::seq2bit(&seq[0..i]);\n\n for n in &seq[0..i] {\n correct.push(*n);\n }\n\n let mut previous = self.valid_kmer().get(kmer);\n while i < seq.len() {\n let nuc = seq[i];\n\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(nuc), self.k());\n\n if !self.valid_kmer().get(kmer) && previous {\n if let Some((local_correct, offset)) = self.correct_error(kmer, &seq[i..]) {\n kmer >>= 2;\n\n for nuc in local_correct {\n kmer = add_nuc_to_end(\n kmer,\n cocktail::kmer::nuc2bit(nuc),\n self.valid_kmer().k(),\n );\n correct.push(nuc);\n }\n\n log::debug!('error at position {} cor', i);\n\n previous = true;\n i += offset;\n } else {\n correct.push(nuc);\n\n log::debug!('error at position {} not', i);\n\n i += 1;\n previous = false;\n }\n } else {\n previous = self.valid_kmer().get(kmer);\n correct.push(nuc);\n\n i += 1;\n }\n }\n\n correct\n }\n}\n\npub(crate) fn add_nuc_to_end(kmer: u64, nuc: u64, k: u8) -> u64 {\n ((kmer << 2) & mask(k)) ^ nuc\n}\n\npub(crate) fn alt_nucs(valid_kmer: &set::BoxKmerSet, ori: u64) -> Vec {\n next_nucs(valid_kmer, ori >> 2)\n}\n\npub(crate) fn next_nucs(valid_kmer: &set::BoxKmerSet, kmer: u64) -> Vec {\n let mut correct_nuc: Vec = Vec::with_capacity(4);\n\n for alt_nuc in 0..4 {\n if valid_kmer.get(add_nuc_to_end(kmer, alt_nuc, valid_kmer.k())) {\n correct_nuc.push(alt_nuc);\n }\n }\n\n correct_nuc\n}\n\npub(crate) fn error_len(\n subseq: &[u8],\n mut kmer: u64,\n valid_kmer: &set::BoxKmerSet,\n) -> (usize, u64) {\n let mut j = 0;\n\n loop {\n j += 1;\n\n if j >= subseq.len() {\n break;\n }\n\n kmer = add_nuc_to_end(kmer, cocktail::kmer::nuc2bit(subseq[j]), valid_kmer.k());\n\n if valid_kmer.get(kmer) {\n break;\n }\n }\n\n (j, kmer)\n}\n\npub mod exist;\npub mod gap_size;\npub mod graph;\npub mod greedy;\n\npub use exist::one::One;\npub use exist::two::Two;\npub use gap_size::GapSize;\npub use graph::Graph;\npub use greedy::Greedy;\n\n#[cfg(test)]\nmod tests {\n\n use super::*;\n\n #[test]\n fn found_alt_kmer() {\n let mut data = pcon::solid::Solid::new(5);\n data.set(cocktail::kmer::seq2bit(b'ACTGA'), true);\n data.set(cocktail::kmer::seq2bit(b'ACTGT'), true);\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let kmer = cocktail::kmer::seq2bit(b'ACTGC');\n\n assert_eq!(alt_nucs(&set, kmer), vec![0, 2]);\n }\n}\n","mit" +"br","./br/src/correct/gap_size.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse log::debug;\n\n/* local use */\nuse crate::correct::*;\n\npub struct GapSize<'a> {\n valid_kmer: &'a set::BoxKmerSet<'a>,\n graph: graph::Graph<'a>,\n one: One<'a>,\n}\n\nimpl<'a> GapSize<'a> {\n pub fn new(valid_kmer: &'a set::BoxKmerSet<'a>, c: u8) -> Self {\n Self {\n valid_kmer,\n graph: graph::Graph::new(valid_kmer),\n one: One::new(valid_kmer, c),\n }\n }\n\n pub fn ins_sub_correction(&self, kmer: u64, gap_size: usize) -> Option<(Vec, usize)> {\n let mut alts = alt_nucs(self.valid_kmer, kmer);\n\n if alts.len() != 1 {\n debug!('not one alts {:?}', alts);\n return None;\n }\n\n let mut corr = add_nuc_to_end(kmer >> 2, alts[0], self.k());\n let mut local_corr = vec![cocktail::kmer::bit2nuc(alts[0])];\n let mut viewed_kmer = rustc_hash::FxHashSet::default();\n viewed_kmer.insert(corr);\n\n for i in 0..gap_size {\n alts = next_nucs(self.valid_kmer, corr);\n\n if alts.len() != 1 {\n debug!(\n 'failled multiple successor {} {:?} i: {}',\n cocktail::kmer::kmer2seq(corr, self.valid_kmer.k()),\n alts,\n i\n );\n return None;\n }\n\n corr = add_nuc_to_end(corr, alts[0], self.k());\n debug!(\n 'kmer {}',\n cocktail::kmer::kmer2seq(corr, self.valid_kmer.k())\n );\n if viewed_kmer.contains(&corr) {\n debug!(\n 'we view this kmer previously {}',\n cocktail::kmer::kmer2seq(corr, self.k())\n );\n return None;\n }\n viewed_kmer.insert(corr);\n\n local_corr.push(cocktail::kmer::bit2nuc(alts[0]));\n }\n\n let offset = local_corr.len();\n Some((local_corr, offset))\n }\n}\n\nimpl<'a> Corrector for GapSize<'a> {\n fn valid_kmer(&self) -> &set::BoxKmerSet<'a> {\n self.valid_kmer\n }\n\n fn correct_error(&self, kmer: u64, seq: &[u8]) -> Option<(Vec, usize)> {\n let (error_len, _first_correct_kmer) = error_len(seq, kmer, self.valid_kmer());\n\n debug!('error_len {}', error_len);\n match error_len.cmp(&(self.k() as usize)) {\n std::cmp::Ordering::Less => self.graph.correct_error(kmer, seq), // we can avoid a second compute of error_len\n std::cmp::Ordering::Equal => self.one.correct_error(kmer, seq),\n std::cmp::Ordering::Greater => {\n self.ins_sub_correction(kmer, error_len - self.k() as usize)\n }\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n\n use super::*;\n\n fn init() {\n let _ = env_logger::builder()\n .is_test(true)\n .filter_level(log::LevelFilter::Trace)\n .try_init();\n }\n\n #[test]\n fn csc() {\n init();\n\n let refe = b'AGCGTATCTT';\n // ||||| |||||\n let read = b'AGCGTTTCTT';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = GapSize::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cssc() {\n init();\n\n let refe = b'TCTCTAATCTTC';\n // ||||| |||||\n let read = b'TCTCTGGTCTTC';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = GapSize::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn csssc() {\n init();\n\n let refe = b'TCTCTAAATCTTC';\n // ||||| |||||\n let read = b'TCTCTGGGTCTTC';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = GapSize::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrect\n }\n\n #[test]\n fn cscsc() {\n init();\n\n let refe = b'GTGTGACTTACACCTCGTTGAGCACCCGATGTTGGTATAGTCCGAACAAC';\n // ||||| | |||||\n let read = b'GTGTGACTTACACCTCGTTGAGTAGCCGATGTTGGTATAGTCCGAACAAC';\n\n println!('{}', String::from_utf8(refe.to_vec()).unwrap());\n println!('{}', String::from_utf8(read.to_vec()).unwrap());\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(11);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 11) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = GapSize::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n\n #[test]\n fn cdc() {\n init();\n\n let refe = b'GATACATGGACACTAGTATG';\n // ||||||||||\n let read = b'GATACATGGAACTAGTATG';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = GapSize::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cddc() {\n init();\n\n let refe = b'CAAAGCATTTTT';\n // |||||\n let read = b'CAAAGTTTTT';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = GapSize::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice());\n assert_eq!(refe, corrector.correct(refe).as_slice());\n }\n\n #[test]\n fn cic() {\n init();\n\n let refe = b'GGATAACTCT';\n // |||||\n let read = b'GGATATACTCT';\n\n let mut data: pcon::solid::Solid = pcon::solid::Solid::new(5);\n\n for kmer in cocktail::tokenizer::Tokenizer::new(refe, 5) {\n data.set(kmer, true);\n }\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(data));\n\n let corrector = GapSize::new(&set, 2);\n\n assert_eq!(refe, corrector.correct(read).as_slice()); // test correction work\n assert_eq!(refe, corrector.correct(refe).as_slice()); // test not overcorrection\n }\n}\n","mit" +"br","./br/src/cli.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse log::Level;\n\npub fn i82level(level: i8) -> Option {\n match level {\n std::i8::MIN..=0 => None,\n 1 => Some(log::Level::Error),\n 2 => Some(log::Level::Warn),\n 3 => Some(log::Level::Info),\n 4 => Some(log::Level::Debug),\n 5..=std::i8::MAX => Some(log::Level::Trace),\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn loglevel() {\n assert_eq!(i82level(i8::MIN), None);\n assert_eq!(i82level(-3), None);\n assert_eq!(i82level(1), Some(log::Level::Error));\n assert_eq!(i82level(2), Some(log::Level::Warn));\n assert_eq!(i82level(3), Some(log::Level::Info));\n assert_eq!(i82level(4), Some(log::Level::Debug));\n assert_eq!(i82level(5), Some(log::Level::Trace));\n assert_eq!(i82level(i8::MAX), Some(log::Level::Trace));\n }\n}\n","mit" +"br","./br/src/error.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse thiserror::Error;\n\n/// All error produce by Pcon\n#[derive(Debug, Error)]\npub enum Error {\n /// See enum [Cli]\n #[error(transparent)]\n Cli(#[from] Cli),\n\n /// See enum [IO]\n #[error(transparent)]\n IO(#[from] IO),\n\n #[error('Can't compute minimal abundance')]\n CantComputeAbundance,\n}\n\n/// Error emmit durring Cli parsing\n#[derive(Debug, Error)]\npub enum Cli {\n /// Number of inputs and outputs must be the same\n #[error('Kmer size must be odd')]\n NotSameNumberOfInAndOut,\n\n #[error('You must provide a solidity path '-s', a kmer solid path '-S' or a kmer length '-k'')]\n NoSolidityNoKmer,\n\n #[error('If you provide kmer solid path '-S' you must provide a kmer length '-k'')]\n KmerSolidNeedK,\n\n #[error('Abundance method threshold can't be parse')]\n CantParseAbundanceMethod,\n}\n\n/// Error emmit when pcon try to work with file\n#[repr(C)]\n#[derive(Debug, Error)]\npub enum IO {\n /// We can't create file. In C binding it's equal to 0\n #[error('We can't create file')]\n CantCreateFile,\n\n /// We can't open file. In C binding it's equal to 1\n #[error('We can't open file')]\n CantOpenFile,\n\n /// Error durring write in file. In C binding it's equal to 2\n #[error('Error durring write')]\n ErrorDurringWrite,\n\n /// Error durring read file. In C binding it's equal to 3\n #[error('Error durring read')]\n ErrorDurringRead,\n\n /// No error, this exist only for C binding it's the value of a new error pointer\n #[error('Isn't error if you see this please contact the author with this message and a description of what you do with pcon')]\n NoError,\n}\n","mit" +"br","./br/src/lib.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* local mod */\npub mod cli;\npub mod correct;\npub mod error;\npub mod set;\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse rayon::iter::ParallelBridge;\nuse rayon::prelude::*;\n\n/* local use */\nuse error::IO::*;\nuse error::*;\n\npub fn run_correction<'a>(\n inputs: &[String],\n outputs: &[String],\n methods: Vec>,\n two_side: bool,\n record_buffer_len: usize,\n) -> Result<()> {\n for (input, output) in inputs.iter().zip(outputs) {\n log::info!('Read file {} write in {}', input, output);\n\n let reader = bio::io::fasta::Reader::new(std::io::BufReader::new(\n std::fs::File::open(input)\n .with_context(|| error::Error::IO(CantOpenFile))\n .with_context(|| anyhow!('File {}', input.clone()))?,\n ));\n\n let mut write = bio::io::fasta::Writer::new(std::io::BufWriter::new(\n std::fs::File::create(&output)\n .with_context(|| error::Error::IO(CantCreateFile))\n .with_context(|| anyhow!('File {}', output.clone()))?,\n ));\n\n let mut iter = reader.records();\n let mut records = Vec::with_capacity(record_buffer_len);\n let mut corrected: Vec;\n\n let mut end = false;\n loop {\n for _ in 0..record_buffer_len {\n if let Some(Ok(record)) = iter.next() {\n records.push(record);\n } else {\n end = true;\n break;\n }\n }\n\n log::info!('Buffer len: {}', records.len());\n\n corrected = records\n .drain(..)\n .par_bridge()\n .map(|record| {\n log::debug!('begin correct read {} {}', record.id(), record.seq().len());\n\n let seq = record.seq();\n\n let mut correct = seq.to_vec();\n methods\n .iter()\n .for_each(|x| correct = x.correct(correct.as_slice()));\n\n if !two_side {\n correct.reverse();\n methods\n .iter()\n .for_each(|x| correct = x.correct(correct.as_slice()));\n\n correct.reverse();\n }\n\n log::debug!('end correct read {}', record.id());\n bio::io::fasta::Record::with_attrs(record.id(), record.desc(), &correct)\n })\n .collect();\n\n for corr in corrected {\n write\n .write_record(&corr)\n .with_context(|| Error::IO(IO::ErrorDurringWrite))\n .with_context(|| anyhow!('File {}', output.clone()))?\n }\n\n records.clear();\n\n if end {\n break;\n }\n }\n }\n\n Ok(())\n}\n\npub fn build_methods<'a>(\n params: Option>,\n solid: &'a set::BoxKmerSet,\n confirm: u8,\n max_search: u8,\n) -> Vec> {\n let mut methods: Vec> = Vec::new();\n\n if let Some(ms) = params {\n for method in ms {\n match &method[..] {\n 'one' => methods.push(Box::new(correct::One::new(solid, confirm))),\n 'two' => methods.push(Box::new(correct::Two::new(solid, confirm))),\n 'graph' => methods.push(Box::new(correct::Graph::new(solid))),\n 'greedy' => {\n methods.push(Box::new(correct::Greedy::new(solid, max_search, confirm)))\n }\n 'gap_size' => methods.push(Box::new(correct::GapSize::new(solid, confirm))),\n _ => unreachable!(),\n }\n }\n } else {\n methods.push(Box::new(correct::One::new(solid, confirm)));\n }\n\n methods\n}\n\n/// Set the number of threads use by count step\npub fn set_nb_threads(nb_threads: usize) {\n rayon::ThreadPoolBuilder::new()\n .num_threads(nb_threads)\n .build_global()\n .unwrap();\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn methods_list() {\n // Not perfect test\n\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(pcon::solid::Solid::new(5)));\n let mut methods = build_methods(None, &set, 2, 5);\n\n assert_eq!(methods.len(), 1);\n\n methods = build_methods(Some(vec!['one'.to_string(), 'two'.to_string()]), &set, 2, 5);\n\n assert_eq!(methods.len(), 2);\n\n methods = build_methods(\n Some(vec![\n 'one'.to_string(),\n 'two'.to_string(),\n 'graph'.to_string(),\n 'greedy'.to_string(),\n 'gap_size'.to_string(),\n 'gap_size'.to_string(),\n ]),\n &set,\n 2,\n 5,\n );\n\n assert_eq!(methods.len(), 6);\n }\n\n #[test]\n #[should_panic]\n fn methods_unreachable() {\n let set: set::BoxKmerSet = Box::new(set::Pcon::new(pcon::solid::Solid::new(5)));\n let _ = build_methods(Some(vec!['oe'.to_string(), 'tw'.to_string()]), &set, 2, 5);\n }\n\n #[test]\n fn change_number_of_thread() {\n set_nb_threads(16);\n assert_eq!(rayon::current_num_threads(), 16);\n }\n}\n","mit" +"br","./br/src/set/hash.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* local use */\npub use crate::set::KmerSet;\n\npub struct Hash {\n set: rustc_hash::FxHashSet,\n k: u8,\n}\n\nimpl Hash {\n pub fn new(inputs: Vec, k: u8) -> Self\n where\n R: std::io::Read,\n {\n let mut set = rustc_hash::FxHashSet::default();\n\n for input in inputs {\n let mut records = bio::io::fasta::Reader::new(input).records();\n\n while let Some(Ok(record)) = records.next() {\n for cano in cocktail::tokenizer::Canonical::new(record.seq(), k) {\n set.insert(cano);\n }\n }\n }\n\n Self { set, k }\n }\n}\n\nimpl KmerSet for Hash {\n fn get(&self, kmer: u64) -> bool {\n self.set.contains(&cocktail::kmer::canonical(kmer, self.k))\n }\n\n fn k(&self) -> u8 {\n self.k\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n static FILE: &[u8] = b'>1\nACGTGGGAATTGTGGCCACATCACGAGGTCCTGCGTATTGACGACTGTAAAGCGAGTGGCCGTGGAATTTCAAGCTCAATTAGCCGAACCAATCCGCCTA';\n\n #[test]\n fn canonical() {\n let file = std::io::Cursor::new(FILE);\n\n let hash = Hash::new(vec![file], 11);\n\n let set: crate::set::BoxKmerSet = Box::new(hash);\n\n let mut records = bio::io::fasta::Reader::new(FILE).records();\n for cano in cocktail::tokenizer::Canonical::new(records.next().unwrap().unwrap().seq(), 11)\n {\n assert!(set.get(cano))\n }\n }\n\n #[test]\n fn forward() {\n let file = std::io::Cursor::new(FILE);\n\n let hash = Hash::new(vec![file], 11);\n\n let set: crate::set::BoxKmerSet = Box::new(hash);\n\n let mut records = bio::io::fasta::Reader::new(FILE).records();\n for kmer in cocktail::tokenizer::Tokenizer::new(records.next().unwrap().unwrap().seq(), 11)\n {\n assert!(set.get(kmer))\n }\n }\n\n #[test]\n fn absence() {\n let file = std::io::Cursor::new(FILE);\n\n let hash = Hash::new(vec![file], 11);\n\n let set: crate::set::BoxKmerSet = Box::new(hash);\n\n assert!(!set.get(0));\n }\n\n #[test]\n fn k() {\n let file = std::io::Cursor::new(FILE);\n\n let hash = Hash::new(vec![file], 11);\n\n let set: crate::set::BoxKmerSet = Box::new(hash);\n\n assert_eq!(set.k(), 11);\n }\n}\n","mit" +"br","./br/src/set/mod.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\npub mod hash;\npub mod pcon;\n\npub use self::hash::Hash;\npub use self::pcon::Pcon;\n\npub trait KmerSet: Sync {\n fn get(&self, kmer: u64) -> bool;\n\n fn k(&self) -> u8;\n}\n\npub type BoxKmerSet<'a> = Box;\n","mit" +"br","./br/src/set/pcon.rs","/*\nCopyright (c) 2020 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* local use */\nuse crate::set::KmerSet;\n\npub struct Pcon {\n set: pcon::solid::Solid,\n}\n\nimpl Pcon {\n pub fn new(set: pcon::solid::Solid) -> Self {\n Pcon { set }\n }\n}\n\nimpl KmerSet for Pcon {\n fn get(&self, kmer: u64) -> bool {\n self.set.get(kmer)\n }\n\n fn k(&self) -> u8 {\n self.set.k\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n static SEQ: &[u8] = b'ACGTGGGAATTGTGGCCACATCACGAGGTCCTGCGTATTGACGACTGTAAAGCGAGTGGCCGTGGAATTTCAAGCTCAATTAGCCGAACCAATCCGCCTA';\n\n #[test]\n fn canonical() {\n let mut solid = pcon::solid::Solid::new(11);\n for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) {\n solid.set(cano, true);\n }\n\n let set: crate::set::BoxKmerSet = Box::new(Pcon::new(solid));\n\n for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) {\n assert!(set.get(cano))\n }\n }\n\n #[test]\n fn forward() {\n let mut solid = pcon::solid::Solid::new(11);\n for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) {\n solid.set(cano, true);\n }\n\n let set: crate::set::BoxKmerSet = Box::new(Pcon::new(solid));\n\n for kmer in cocktail::tokenizer::Tokenizer::new(SEQ, 11) {\n assert!(set.get(kmer))\n }\n }\n\n #[test]\n fn absence() {\n let mut solid = pcon::solid::Solid::new(11);\n for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) {\n solid.set(cano, true);\n }\n\n let set: crate::set::BoxKmerSet = Box::new(Pcon::new(solid));\n\n assert!(!set.get(0));\n }\n\n #[test]\n fn k() {\n let mut solid = pcon::solid::Solid::new(11);\n for cano in cocktail::tokenizer::Canonical::new(SEQ, 11) {\n solid.set(cano, true);\n }\n\n let set: crate::set::BoxKmerSet = Box::new(Pcon::new(solid));\n\n assert_eq!(set.k(), 11);\n }\n}\n","mit" +"br","./br/src/bin/br_large.rs","/*\nCopyright (c) 2021 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse clap::Parser;\n\nuse br::error::IO::*;\nuse br::error::*;\nuse br::*;\n\n#[derive(clap::Parser, Debug)]\n#[clap(\n version = '0.1',\n author = 'Pierre Marijon ',\n about = 'A version of br where memory usage depend on number of kmer not kmer length'\n)]\npub struct Command {\n /// fasta file to be correct\n #[clap(short = 'i', long = 'inputs')]\n pub inputs: Vec,\n\n /// path where corrected read was write\n #[clap(short = 'o', long = 'outputs')]\n pub outputs: Vec,\n\n /// use kmer present in fasta file as solid kmer and store them in HashSet\n #[clap(short = 'S', long = 'kmer-solid')]\n pub kmer_solid: Vec,\n\n /// kmer length lower or equal to 32\n #[clap(short = 'k', long = 'kmer')]\n pub kmer_size: Option,\n\n /// correction method used, methods are applied in the order you specify, default value is 'one'\n #[clap(\n short = 'm',\n long = 'method',\n possible_values = &['one', 'two', 'graph', 'greedy', 'gap_size'],\n )]\n pub methods: Option>,\n\n /// number of kmer need to be solid after one, greedy correction to validate it, default value is '2'\n #[clap(short = 'c', long = 'confirm')]\n pub confirm: Option,\n\n /// number of base we use to try correct error, default value is '7'\n #[clap(short = 'M', long = 'max-search')]\n pub max_search: Option,\n\n /// if this flag is set br correct only in forward orientation\n #[clap(short = 'n', long = 'not-two-side')]\n pub two_side: bool,\n\n /// Number of thread use by br, 0 use all avaible core, default value 0\n #[clap(short = 't', long = 'threads')]\n pub threads: Option,\n\n /// Number of sequence record load in buffer, default 8192\n #[clap(short = 'b', long = 'record_buffer')]\n pub record_buffer: Option,\n\n /// verbosity level also control by environment variable BR_LOG if flag is set BR_LOG value is ignored\n #[clap(short = 'v', long = 'verbosity', parse(from_occurrences))]\n pub verbosity: i8,\n}\n\n#[cfg(not(tarpaulin_include))]\nfn main() -> Result<()> {\n let params = Command::parse();\n\n let mut files = Vec::new();\n\n for path in params.kmer_solid {\n files.push(std::io::BufReader::new(\n std::fs::File::open(&path)\n .with_context(|| Error::IO(CantOpenFile))\n .with_context(|| anyhow!('File {:?}', path.clone()))?,\n ));\n }\n\n let solid: set::BoxKmerSet = Box::new(set::Hash::new(\n files,\n params.kmer_size.ok_or(Error::Cli(Cli::KmerSolidNeedK))?,\n ));\n\n let confirm = params.confirm.unwrap_or(2);\n let max_search = params.max_search.unwrap_or(7);\n let record_buffer = params.record_buffer.unwrap_or(8192);\n\n let methods = br::build_methods(params.methods, &solid, confirm, max_search);\n\n br::run_correction(\n ¶ms.inputs,\n ¶ms.outputs,\n methods,\n params.two_side,\n record_buffer,\n )?;\n\n Ok(())\n}\n","mit" +"br","./br/src/bin/br.rs","/*\nCopyright (c) 2019 Pierre Marijon \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the 'Software'), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* crate use */\nuse anyhow::{anyhow, Context, Result};\nuse clap::Parser;\n\nuse br::error::Cli::*;\nuse br::error::*;\nuse br::*;\n\n#[derive(clap::Parser, Debug)]\n#[clap(\n version = '0.1',\n author = 'Pierre Marijon ',\n about = 'Br: Brutal rewrite a simple long read corrector based on kmer spectrum methode'\n)]\npub struct Command {\n /// solidity bitfield produce by pcon\n #[clap(short = 's', long = 'solidity')]\n pub solidity: Option,\n\n /// kmer length if you didn't provide solidity path you must give a kmer length\n #[clap(short = 'k', long = 'kmer')]\n pub kmer_size: Option,\n\n /// fasta file to be correct\n #[clap(short = 'i', long = 'inputs')]\n pub inputs: Vec,\n\n /// path where corrected read was write\n #[clap(short = 'o', long = 'outputs')]\n pub outputs: Vec,\n\n /// if you want choose the minimum abundance you can set this parameter\n #[clap(short = 'a', long = 'abundance')]\n pub abundance: Option,\n\n /// 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\n #[clap(short = 'A', long = 'abundance-method')]\n pub abundance_method: Option,\n\n /// correction method used, methods are applied in the order you specify, default value is 'one'\n #[clap(\n short = 'm',\n long = 'method',\n possible_values = &['one', 'two', 'graph', 'greedy', 'gap_size'],\n )]\n pub methods: Option>,\n\n /// number of kmer need to be solid after one, greedy correction to validate it, default value is '2'\n #[clap(short = 'c', long = 'confirm')]\n pub confirm: Option,\n\n /// number of base we use to try correct error, default value is '7'\n #[clap(short = 'M', long = 'max-search')]\n pub max_search: Option,\n\n /// if this flag is set br correct only in forward orientation\n #[clap(short = 'n', long = 'not-two-side')]\n pub two_side: bool,\n\n /// Number of thread use by br, 0 use all avaible core, default value 0\n #[clap(short = 't', long = 'threads')]\n pub threads: Option,\n\n /// Number of sequence record load in buffer, default 8192\n #[clap(short = 'b', long = 'record_buffer')]\n pub record_buffer: Option,\n\n /// verbosity level also control by environment variable BR_LOG if flag is set BR_LOG value is ignored\n #[clap(short = 'v', long = 'verbosity', parse(from_occurrences))]\n pub verbosity: i8,\n}\n\n#[cfg(not(tarpaulin_include))]\nfn main() -> Result<()> {\n let params = Command::parse();\n\n if params.inputs.len() != params.outputs.len() {\n return Err(anyhow!(Error::Cli(NotSameNumberOfInAndOut)));\n }\n\n if let Some(level) = cli::i82level(params.verbosity) {\n env_logger::builder()\n .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis))\n .filter_level(level.to_level_filter())\n .init();\n } else {\n env_logger::Builder::from_env('BR_LOG')\n .format_timestamp(Some(env_logger::fmt::TimestampPrecision::Millis))\n .init();\n }\n\n let confirm = params.confirm.unwrap_or(2);\n let max_search = params.max_search.unwrap_or(7);\n let record_buffer = params.record_buffer.unwrap_or(8192);\n\n if let Some(threads) = params.threads {\n log::info!('Set number of threads to {}', threads);\n\n set_nb_threads(threads);\n }\n\n let solid = if let Some(path) = params.solidity {\n read_solidity(path)?\n } else if let Some(kmer_size) = params.kmer_size {\n let count = count_kmer(¶ms.inputs, kmer_size, record_buffer)?;\n\n let abundance_method = params.abundance_method.unwrap_or(AbundanceMethod {\n method: pcon::spectrum::ThresholdMethod::FirstMinimum,\n params: 0.0,\n });\n\n let threshold = params.abundance.unwrap_or(compute_abundance_threshold(\n &count,\n abundance_method,\n std::io::stdout(),\n )?);\n\n Box::new(set::Pcon::new(pcon::solid::Solid::from_counter(\n &count, threshold,\n )))\n } else {\n anyhow::bail!(Error::Cli(NoSolidityNoKmer));\n };\n\n let methods = br::build_methods(params.methods, &solid, confirm, max_search);\n\n br::run_correction(\n ¶ms.inputs,\n ¶ms.outputs,\n methods,\n params.two_side,\n record_buffer,\n )?;\n\n Ok(())\n}\n\nfn read_solidity<'a>(path: String) -> Result> {\n let solidity_reader = std::io::BufReader::new(\n std::fs::File::open(&path)\n .with_context(|| Error::IO(IO::CantOpenFile))\n .with_context(|| anyhow!('File {:?}', path.clone()))?,\n );\n\n log::info!('Load solidity file');\n\n Ok(Box::new(set::Pcon::new(pcon::solid::Solid::deserialize(\n solidity_reader,\n )?)))\n}\n\nfn count_kmer(\n inputs: &[String],\n kmer_size: u8,\n record_buffer_len: usize,\n) -> Result {\n let mut counter = pcon::counter::Counter::new(kmer_size);\n\n log::info!('Start count kmer from input');\n for input in inputs {\n let fasta = std::io::BufReader::new(\n std::fs::File::open(&input)\n .with_context(|| Error::IO(IO::CantOpenFile))\n .with_context(|| anyhow!('File {:?}', input.clone()))?,\n );\n\n counter.count_fasta(fasta, record_buffer_len);\n }\n log::info!('End count kmer from input');\n\n Ok(counter)\n}\n\nfn compute_abundance_threshold(\n count: &pcon::counter::Counter,\n method: AbundanceMethod,\n out: W,\n) -> Result\nwhere\n W: std::io::Write,\n{\n let spectrum = pcon::spectrum::Spectrum::from_counter(count);\n\n let abundance = spectrum\n .get_threshold(method.method, method.params)\n .ok_or(Error::CantComputeAbundance)?;\n\n spectrum\n .write_histogram(out, Some(abundance))\n .with_context(|| anyhow!('Error durring write of kmer histograme'))?;\n println!('If this curve seems bad or minimum abundance choose (marked by *) not apopriate set parameter -a');\n\n Ok(abundance as u8)\n}\n\n#[derive(Debug)]\npub struct AbundanceMethod {\n pub method: pcon::spectrum::ThresholdMethod,\n pub params: f64,\n}\n\nimpl std::str::FromStr for AbundanceMethod {\n type Err = br::error::Cli;\n\n fn from_str(s: &str) -> Result {\n let elements: Vec<&str> = s.split('_').collect();\n\n if elements.len() > 2 {\n Err(Cli::CantParseAbundanceMethod)\n } else {\n let method = match elements[0] {\n 'first-minimum' => pcon::spectrum::ThresholdMethod::FirstMinimum,\n 'rarefaction' => pcon::spectrum::ThresholdMethod::Rarefaction,\n 'percent-most' => pcon::spectrum::ThresholdMethod::PercentAtMost,\n 'percent-least' => pcon::spectrum::ThresholdMethod::PercentAtLeast,\n _ => return Err(Cli::CantParseAbundanceMethod),\n };\n\n let params = if method == pcon::spectrum::ThresholdMethod::FirstMinimum {\n 0.0\n } else if let Ok(p) = f64::from_str(elements[1]) {\n if p > 0.0 && p < 1.0 {\n p\n } else {\n return Err(Cli::CantParseAbundanceMethod);\n }\n } else {\n return Err(Cli::CantParseAbundanceMethod);\n };\n\n Ok(AbundanceMethod { method, params })\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use std::str::FromStr;\n\n use std::io::Seek;\n use std::io::Write;\n\n use rand::seq::SliceRandom;\n use rand::{Rng, SeedableRng};\n\n fn init() {\n let _ = env_logger::builder()\n .is_test(true)\n .filter_level(log::LevelFilter::Trace)\n .try_init();\n }\n\n fn generate_seq_file() -> tempfile::NamedTempFile {\n let mut rng = rand::rngs::SmallRng::seed_from_u64(42);\n\n let nucs = [b'A', b'C', b'T', b'G'];\n\n let mut sequence = (0..1000)\n .map(|_| *nucs.choose(&mut rng).unwrap())\n .collect::>();\n\n let mut tmpfile = tempfile::NamedTempFile::new().unwrap();\n\n writeln!(\n tmpfile.as_file_mut(),\n '>42\n{}',\n std::str::from_utf8(&sequence).unwrap()\n )\n .unwrap();\n\n for _ in 0..25 {\n for nuc in sequence.iter_mut() {\n if rng.gen_ratio(2, 100) {\n *nuc = *nucs.choose(&mut rng).unwrap();\n }\n }\n\n writeln!(\n tmpfile.as_file_mut(),\n '>42\n{}',\n std::str::from_utf8(&sequence).unwrap()\n )\n .unwrap();\n }\n\n tmpfile.seek(std::io::SeekFrom::Start(0)).unwrap();\n\n tmpfile\n }\n\n static COUNT: &[u8] = &[\n 5, 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 5, 192, 88, 111, 210, 96, 140, 18, 100, 144, 140, 66,\n 57, 202, 213, 210, 227, 251, 122, 209, 155, 149, 210, 99, 20, 10, 45, 45, 163, 21, 156,\n 107, 68, 221, 3, 137, 17, 141, 154, 232, 18, 227, 139, 15, 186, 159, 224, 15, 94, 78, 76,\n 83, 27, 34, 168, 118, 148, 79, 51, 105, 75, 153, 164, 57, 61, 52, 44, 92, 198, 11, 32, 67,\n 54, 96, 145, 102, 241, 117, 12, 49, 47, 27, 207, 213, 54, 64, 2, 180, 143, 57, 9, 161, 101,\n 12, 185, 36, 251, 126, 44, 132, 165, 125, 114, 154, 23, 35, 121, 156, 139, 119, 204, 206,\n 161, 217, 58, 42, 106, 113, 224, 81, 128, 27, 6, 198, 78, 233, 104, 93, 85, 187, 130, 198,\n 101, 7, 83, 206, 191, 7, 130, 237, 249, 135, 248, 43, 106, 209, 84, 52, 178, 239, 37, 164,\n 94, 133, 67, 14, 110, 244, 91, 215, 151, 194, 158, 142, 101, 31, 121, 205, 4, 177, 95, 123,\n 38, 187, 235, 233, 213, 146, 41, 81, 119, 52, 93, 236, 202, 35, 95, 82, 192, 246, 115, 201,\n 129, 108, 211, 34, 114, 5, 95, 4, 95, 8, 134, 104, 93, 255, 85, 10, 196, 46, 179, 204, 159,\n 124, 218, 139, 46, 203, 167, 84, 177, 81, 184, 34, 82, 187, 133, 114, 250, 58, 215, 185,\n 176, 225, 30, 132, 237, 74, 125, 61, 17, 106, 78, 94, 55, 230, 76, 210, 234, 244, 90, 239,\n 101, 184, 226, 169, 202, 122, 207, 151, 47, 194, 28, 74, 181, 217, 219, 51, 84, 94, 148,\n 71, 84, 51, 237, 138, 228, 66, 117, 143, 193, 12, 101, 195, 31, 27, 238, 67, 210, 150, 244,\n 181, 84, 0, 145, 165, 0, 106, 248, 28, 151, 31, 67, 27, 161, 176, 229, 125, 247, 92, 5, 47,\n 33, 10, 63, 221, 20, 4, 70, 129, 42, 24, 213, 67, 202, 104, 176, 130, 216, 110, 186, 192,\n 36, 197, 71, 250, 155, 77, 31, 136, 65, 95, 216, 170, 184, 96, 137, 147, 30, 149, 64, 197,\n 5, 209, 12, 5, 222, 120, 96, 48, 209, 196, 251, 142, 201, 176, 103, 139, 165, 7, 16, 236,\n 73, 133, 23, 206, 189, 170, 180, 136, 56, 220, 159, 80, 139, 138, 136, 195, 81, 251, 159,\n 136, 179, 197, 119, 181, 109, 243, 6, 13, 200, 56, 77, 228, 137, 240, 43, 57, 42, 164, 19,\n 14, 5, 246, 149, 250, 230, 182, 242, 159, 43, 136, 23, 148, 125, 242, 178, 181, 96, 84, 56,\n 35, 26, 253, 241, 219, 77, 19, 54, 216, 250, 74, 127, 8, 92, 90, 242, 49, 196, 222, 243,\n 67, 159, 11, 162, 220, 157, 134, 53, 220, 65, 216, 198, 19, 175, 254, 202, 208, 0, 2, 0, 0,\n ];\n\n #[test]\n fn _count_kmer() {\n init();\n\n let file = generate_seq_file();\n\n let path = file.path().to_str().unwrap().to_string();\n\n let count = count_kmer(&[path], 5, 26).unwrap();\n\n let mut output = std::io::Cursor::new(Vec::new());\n count.serialize(&mut output).unwrap();\n\n assert_eq!(COUNT, output.into_inner());\n }\n\n #[test]\n fn _compute_abundance_threshold() {\n init();\n\n let output = vec![];\n let count = pcon::counter::Counter::deserialize(COUNT).unwrap();\n\n let abu_method = AbundanceMethod {\n method: pcon::spectrum::ThresholdMethod::FirstMinimum,\n params: 0.0,\n };\n\n assert_eq!(\n 2,\n compute_abundance_threshold(&count, abu_method, output).unwrap()\n );\n }\n\n static SOLID: &[u8] = &[\n 31, 139, 8, 0, 0, 0, 0, 0, 4, 255, 77, 136, 193, 9, 0, 64, 8, 195, 94, 183, 255, 136, 55,\n 134, 15, 145, 216, 10, 130, 208, 180, 52, 15, 40, 113, 147, 62, 223, 181, 248, 140, 93,\n 161, 13, 1, 52, 40, 137, 69, 44, 65, 0, 0, 0,\n ];\n\n #[test]\n fn _read_solidity() {\n init();\n\n let count = pcon::counter::Counter::deserialize(COUNT).unwrap();\n let compute = pcon::solid::Solid::from_counter(&count, 2);\n\n let mut compute_out = vec![];\n compute.serialize(&mut compute_out).unwrap();\n\n assert_eq!(SOLID, compute_out.as_slice());\n\n let mut tmpfile = tempfile::NamedTempFile::new().unwrap();\n\n tmpfile.write_all(SOLID).unwrap();\n\n let path = tmpfile.path().to_str().unwrap().to_string();\n\n let read = read_solidity(path).unwrap();\n for kmer in 0..cocktail::kmer::get_kmer_space_size(5) {\n assert_eq!(compute.get(kmer), read.get(kmer));\n }\n }\n\n #[test]\n fn abundance_method_parsing() {\n init();\n\n let tmp = AbundanceMethod::from_str('first-minimum').unwrap();\n assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::FirstMinimum);\n assert_eq!(tmp.params, 0.0);\n\n let tmp = AbundanceMethod::from_str('rarefaction_0.5').unwrap();\n assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::Rarefaction);\n assert_eq!(tmp.params, 0.5);\n\n let tmp = AbundanceMethod::from_str('percent-most_0.1').unwrap();\n assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::PercentAtMost);\n assert_eq!(tmp.params, 0.1);\n\n let tmp = AbundanceMethod::from_str('percent-least_0.8').unwrap();\n assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::PercentAtLeast);\n assert_eq!(tmp.params, 0.8);\n\n // First minimum params is always 0.0\n let tmp = AbundanceMethod::from_str('first-minimum_0.8').unwrap();\n assert_eq!(tmp.method, pcon::spectrum::ThresholdMethod::FirstMinimum);\n assert_eq!(tmp.params, 0.0);\n\n // name not match\n assert!(AbundanceMethod::from_str('aesxàyxauie_0.8').is_err());\n\n // to many field\n assert!(AbundanceMethod::from_str('first-minimum_0.8_aiue_auie').is_err());\n\n // params to large\n assert!(AbundanceMethod::from_str('rarefaction_34.8').is_err());\n\n // params don't care\n assert!(AbundanceMethod::from_str('first-minimum_42.42').is_ok());\n assert!(AbundanceMethod::from_str('first-minimum_auie').is_ok());\n }\n}\n","mit" +"rasusa","./rasusa/tests/main.rs","use assert_cmd::prelude::*;\n// Add methods on commands\nuse predicates::prelude::*;\nuse std::process::Command; // Run programs // Used for writing assertions\n\n#[test]\nfn input_file_doesnt_exist() -> Result<(), Box> {\n let mut cmd = Command::main_binary()?;\n cmd.args(vec!['-i', 'file/doesnt/exist.fa', '-g', '5mb', '-c', '20']);\n cmd.assert()\n .failure()\n .stderr(predicate::str::contains('does not exist'));\n\n Ok(())\n}\n\n#[test]\nfn output_file_in_nonexistant_dir() -> Result<(), Box> {\n let mut cmd = Command::main_binary()?;\n cmd.args(vec![\n '-i',\n 'tests/cases/file1.fq.gz',\n '-g',\n '5mb',\n '-c',\n '20',\n '-o',\n 'dir/doesnt/exists/out.fq.gz',\n ]);\n cmd.assert()\n .failure()\n .stderr(predicate::str::contains('No such file'));\n\n Ok(())\n}\n\n#[test]\nfn valid_inputs_raises_no_errors() -> Result<(), Box> {\n let mut cmd = Command::main_binary()?;\n cmd.args(vec![\n '-i',\n 'tests/cases/file1.fq.gz',\n '-g',\n '5mb',\n '-c',\n '20',\n ]);\n\n cmd.assert().success();\n\n Ok(())\n}\n\n#[test]\nfn input_and_output_filetypes_different_raises_no_errors() -> Result<(), Box>\n{\n let mut cmd = Command::main_binary()?;\n cmd.args(vec![\n '-i',\n 'tests/cases/file1.fq.gz',\n '-g',\n '5mb',\n '-c',\n '20',\n '-o',\n '/tmp/out.fasta',\n ]);\n\n cmd.assert().success();\n\n Ok(())\n}\n\n#[test]\nfn invalid_input_and_output_combination_raises_error() -> Result<(), Box> {\n let mut cmd = Command::main_binary()?;\n cmd.args(vec![\n '-i',\n 'tests/cases/file1.fq.gz',\n '-g',\n '5mb',\n '-c',\n '20',\n '-o',\n '/tmp/out.fasta',\n '-o',\n '/tmp/out2.fq',\n ]);\n\n cmd.assert()\n .failure()\n .stderr(predicate::str::contains('Got 1 --input but 2 --output'));\n\n Ok(())\n}\n\n#[test]\nfn unequal_number_of_reads_raises_error() -> Result<(), Box> {\n let mut cmd = Command::main_binary()?;\n cmd.args(vec![\n '-i',\n 'tests/cases/file1.fq.gz',\n 'tests/cases/r2.fq.gz',\n '-g',\n '5mb',\n '-c',\n '20',\n '-o',\n '/tmp/out.fq',\n '-o',\n '/tmp/out2.fq',\n ]);\n\n cmd.assert().failure().stderr(predicate::str::contains(\n 'Illumina files are assumed to have the same number of reads',\n ));\n\n Ok(())\n}\n\n#[test]\nfn two_valid_illumina_inputs_suceeds() -> Result<(), Box> {\n let mut cmd = Command::main_binary()?;\n cmd.args(vec![\n '-i',\n 'tests/cases/r1.fq.gz',\n 'tests/cases/r2.fq.gz',\n '-g',\n '4',\n '-c',\n '2',\n '-o',\n '/tmp/out.fq',\n '-o',\n '/tmp/out2.fq',\n ]);\n\n cmd.assert().success();\n\n Ok(())\n}\n","mit" +"rasusa","./rasusa/src/fastx.rs","use crate::cli::CompressionExt;\nuse needletail::errors::ParseErrorKind::EmptyFile;\nuse needletail::parse_fastx_file;\nuse std::fs::File;\nuse std::io::{BufWriter, Write};\nuse std::path::{Path, PathBuf};\nuse thiserror::Error;\n\n/// A collection of custom errors relating to the working with files for this package.\n#[derive(Error, Debug)]\npub enum FastxError {\n /// Indicates that the file is not one of the allowed file types as specified by [`FileType`](#filetype).\n #[error('File type of {0} is not fasta or fastq')]\n UnknownFileType(String),\n\n /// Indicates that the specified input file could not be opened/read.\n #[error('Read error')]\n ReadError {\n source: needletail::errors::ParseError,\n },\n\n /// Indicates that a sequence record could not be parsed.\n #[error('Failed to parse record')]\n ParseError {\n source: needletail::errors::ParseError,\n },\n\n /// Indicates that the specified output file could not be created.\n #[error('Output file could not be created')]\n CreateError { source: std::io::Error },\n\n /// Indicates and error trying to create the compressor\n #[error(transparent)]\n CompressOutputError(#[from] niffler::Error),\n\n /// Indicates that some indices we expected to find in the input file weren't found.\n #[error('Some expected indices were not in the input file')]\n IndicesNotFound,\n\n /// Indicates that writing to the output file failed.\n #[error('Could not write to output file')]\n WriteError { source: anyhow::Error },\n}\n\n/// A `Struct` used for seamlessly dealing with either compressed or uncompressed fasta/fastq files.\n#[derive(Debug, PartialEq)]\npub struct Fastx {\n /// The path for the file.\n path: PathBuf,\n}\n\nimpl Fastx {\n /// Create a `Fastx` object from a `std::path::Path`.\n ///\n /// # Example\n ///\n /// ```rust\n /// let path = std::path::Path::new('input.fa.gz');\n /// let fastx = Fastx::from_path(path);\n /// ```\n pub fn from_path(path: &Path) -> Self {\n Fastx {\n path: path.to_path_buf(),\n }\n }\n /// Create the file associated with this `Fastx` object for writing.\n ///\n /// # Errors\n /// If the file cannot be created then an `Err` containing a variant of [`FastxError`](#fastxerror) is\n /// returned.\n ///\n /// # Example\n ///\n /// ```rust\n /// let path = std::path::Path::new('output.fa');\n /// let fastx = Fastx{ path };\n /// { // this scoping means the file handle is closed afterwards.\n /// let file_handle = fastx.create(6, None)?;\n /// write!(file_handle, '>read1\nACGT\n')?\n /// }\n /// ```\n pub fn create(\n &self,\n compression_lvl: niffler::compression::Level,\n compression_fmt: Option,\n ) -> Result, FastxError> {\n let file = File::create(&self.path).map_err(|source| FastxError::CreateError { source })?;\n let file_handle = Box::new(BufWriter::new(file));\n let fmt = match compression_fmt {\n None => niffler::Format::from_path(&self.path),\n Some(f) => f,\n };\n niffler::get_writer(file_handle, fmt, compression_lvl)\n .map_err(FastxError::CompressOutputError)\n }\n\n /// Returns a vector containing the lengths of all the reads in the file.\n ///\n /// # Errors\n /// If the file cannot be opened or there is an issue parsing any records then an\n /// `Err` containing a variant of [`FastxError`](#fastxerror) is returned.\n ///\n /// # Example\n ///\n /// ```rust\n /// let text = '@read1\nACGT\n+\n!!!!\n@read2\nG\n+\n!';\n /// let mut file = tempfile::Builder::new().suffix('.fq').tempfile().unwrap();\n /// file.write_all(text.as_bytes()).unwrap();\n /// let fastx = Fastx{ file.path() };\n /// let actual = fastx.read_lengths().unwrap();\n /// let expected: Vec = vec![4, 1];\n /// assert_eq!(actual, expected)\n /// ```\n pub fn read_lengths(&self) -> Result, FastxError> {\n let mut read_lengths: Vec = vec![];\n let mut reader = match parse_fastx_file(&self.path) {\n Ok(rdr) => rdr,\n Err(e) if e.kind == EmptyFile => return Ok(read_lengths),\n Err(source) => return Err(FastxError::ReadError { source }),\n };\n\n while let Some(record) = reader.next() {\n match record {\n Ok(rec) => read_lengths.push(rec.num_bases() as u32),\n Err(err) => return Err(FastxError::ParseError { source: err }),\n }\n }\n Ok(read_lengths)\n }\n\n /// Writes reads, with indices contained within `reads_to_keep`, to the specified handle\n /// `write_to`.\n ///\n /// # Errors\n /// This function could raise an `Err` instance of [`FastxError`](#fastxerror) in the following\n /// circumstances:\n /// - If the file (of `self`) cannot be opened.\n /// - If writing to `write_to` fails.\n /// - If, after iterating through all reads in the file, there is still elements left in\n /// `reads_to_keep`. *Note: in this case, this function still writes all reads where indices\n /// were found in the file.*\n ///\n /// # Example\n ///\n /// ```rust\n /// let text = '@read1\nACGT\n+\n!!!!\n@read2\nCCCC\n+\n$$$$\n';\n /// let mut input = tempfile::Builder::new().suffix('.fastq').tempfile().unwrap();\n /// input.write_all(text.as_bytes()).unwrap();\n /// let fastx = Fastx::from_path(input.path()).unwrap();\n /// let mut reads_to_keep: Vec = vec![false, true]);\n /// let output = Builder::new().suffix('.fastq').tempfile().unwrap();\n /// let output_fastx = Fastx::from_path(output.path()).unwrap();\n /// {\n /// let mut out_fh = output_fastx.create().unwrap();\n /// let filter_result = fastx.filter_reads_into(&mut reads_to_keep, 1, &mut out_fh);\n /// assert!(filter_result.is_ok());\n /// }\n /// let actual = std::fs::read_to_string(output).unwrap();\n /// let expected = '@read2\nCCCC\n+\n$$$$\n';\n /// assert_eq!(actual, expected)\n /// ```\n pub fn filter_reads_into(\n &self,\n reads_to_keep: &[bool],\n nb_reads_keep: usize,\n write_to: &mut T,\n ) -> Result {\n let mut total_len = 0;\n let mut reader =\n parse_fastx_file(&self.path).map_err(|source| FastxError::ReadError { source })?;\n let mut read_idx: usize = 0;\n let mut nb_reads_written = 0;\n\n while let Some(record) = reader.next() {\n match record {\n Err(source) => return Err(FastxError::ParseError { source }),\n Ok(rec) if reads_to_keep[read_idx] => {\n total_len += rec.num_bases();\n rec.write(write_to, None)\n .map_err(|err| FastxError::WriteError {\n source: anyhow::Error::from(err),\n })?;\n nb_reads_written += 1;\n if nb_reads_keep == nb_reads_written {\n break;\n }\n }\n Ok(_) => (),\n }\n\n read_idx += 1;\n }\n\n if nb_reads_written == nb_reads_keep {\n Ok(total_len)\n } else {\n Err(FastxError::IndicesNotFound)\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::any::Any;\n use std::io::{Read, Write};\n use std::path::Path;\n use tempfile::Builder;\n\n #[test]\n fn fastx_from_fasta() {\n let path = Path::new('data/my.fa');\n\n let actual = Fastx::from_path(path);\n let expected = Fastx {\n path: path.to_path_buf(),\n };\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn create_invalid_output_file_raises_error() {\n let path = Path::new('invalid/out/path.fq');\n\n let actual = Fastx::from_path(path)\n .create(niffler::Level::Eight, None)\n .err()\n .unwrap();\n let expected = FastxError::CreateError {\n source: std::io::Error::new(\n std::io::ErrorKind::Other,\n String::from('No such file or directory (os error 2)'),\n ),\n };\n\n assert_eq!(actual.type_id(), expected.type_id())\n }\n\n #[test]\n fn create_valid_output_file_and_can_write_to_it() {\n let file = Builder::new().suffix('.fastq').tempfile().unwrap();\n let mut writer = Fastx::from_path(file.path())\n .create(niffler::Level::Eight, None)\n .unwrap();\n\n let actual = writer.write(b'foo\nbar');\n\n assert!(actual.is_ok())\n }\n\n #[test]\n fn create_valid_compressed_output_file_and_can_write_to_it() {\n let file = Builder::new().suffix('.fastq.gz').tempfile().unwrap();\n let mut writer = Fastx::from_path(file.path())\n .create(niffler::Level::Four, None)\n .unwrap();\n\n let actual = writer.write(b'foo\nbar');\n\n assert!(actual.is_ok())\n }\n\n #[test]\n fn get_read_lengths_for_empty_fasta_returns_empty_vector() {\n let text = '';\n let mut file = Builder::new().suffix('.fa').tempfile().unwrap();\n file.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(file.path());\n\n let actual = fastx.read_lengths().unwrap();\n let expected: Vec = Vec::new();\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn get_read_lengths_for_fasta() {\n let text = '>read1\nACGT\n>read2\nG';\n let mut file = Builder::new().suffix('.fa').tempfile().unwrap();\n file.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(file.path());\n\n let actual = fastx.read_lengths().unwrap();\n let expected: Vec = vec![4, 1];\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn get_read_lengths_for_fastq() {\n let text = '@read1\nACGT\n+\n!!!!\n@read2\nG\n+\n!';\n let mut file = Builder::new().suffix('.fq').tempfile().unwrap();\n file.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(file.path());\n\n let actual = fastx.read_lengths().unwrap();\n let expected: Vec = vec![4, 1];\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn filter_reads_empty_indices_no_output() {\n let text = '@read1\nACGT\n+\n!!!!';\n let mut input = Builder::new().suffix('.fastq').tempfile().unwrap();\n input.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(input.path());\n let reads_to_keep: Vec = vec![false];\n let output = Builder::new().suffix('.fastq').tempfile().unwrap();\n let output_fastx = Fastx::from_path(output.path());\n let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap();\n let filter_result = fastx.filter_reads_into(&reads_to_keep, 0, &mut out_fh);\n\n assert!(filter_result.is_ok());\n\n let mut actual = String::new();\n output.into_file().read_to_string(&mut actual).unwrap();\n let expected = String::new();\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn filter_fastq_reads_one_index_matches_only_read() {\n let text = '@read1\nACGT\n+\n!!!!\n';\n let mut input = Builder::new().suffix('.fastq').tempfile().unwrap();\n input.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(input.path());\n let reads_to_keep: Vec = vec![true];\n let output = Builder::new().suffix('.fastq').tempfile().unwrap();\n let output_fastx = Fastx::from_path(output.path());\n {\n let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap();\n let filter_result = fastx.filter_reads_into(&reads_to_keep, 1, &mut out_fh);\n assert!(filter_result.is_ok());\n }\n\n let actual = std::fs::read_to_string(output).unwrap();\n let expected = text;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn filter_fasta_reads_one_index_matches_only_read() {\n let text = '>read1\nACGT\n';\n let mut input = Builder::new().suffix('.fa').tempfile().unwrap();\n input.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(input.path());\n let reads_to_keep: Vec = vec![true];\n let output = Builder::new().suffix('.fa').tempfile().unwrap();\n let output_fastx = Fastx::from_path(output.path());\n {\n let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap();\n let filter_result = fastx.filter_reads_into(&reads_to_keep, 1, &mut out_fh);\n assert!(filter_result.is_ok());\n }\n\n let actual = std::fs::read_to_string(output).unwrap();\n let expected = text;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn filter_fastq_reads_one_index_matches_one_of_two_reads() {\n let text = '@read1\nACGT\n+\n!!!!\n@read2\nCCCC\n+\n$$$$\n';\n let mut input = Builder::new().suffix('.fastq').tempfile().unwrap();\n input.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(input.path());\n let reads_to_keep: Vec = vec![false, true];\n let output = Builder::new().suffix('.fastq').tempfile().unwrap();\n let output_fastx = Fastx::from_path(output.path());\n {\n let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap();\n let filter_result = fastx.filter_reads_into(&reads_to_keep, 1, &mut out_fh);\n assert!(filter_result.is_ok());\n }\n\n let actual = std::fs::read_to_string(output).unwrap();\n let expected = '@read2\nCCCC\n+\n$$$$\n';\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn filter_fastq_reads_two_indices_matches_first_and_last_reads() {\n let text = '@read1\nACGT\n+\n!!!!\n@read2\nCCCC\n+\n$$$$\n@read3\nA\n+\n$\n';\n let mut input = Builder::new().suffix('.fastq').tempfile().unwrap();\n input.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(input.path());\n let reads_to_keep: Vec = vec![true, false, true];\n let output = Builder::new().suffix('.fastq').tempfile().unwrap();\n let output_fastx = Fastx::from_path(output.path());\n {\n let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap();\n let filter_result = fastx.filter_reads_into(&reads_to_keep, 2, &mut out_fh);\n assert!(filter_result.is_ok());\n }\n\n let actual = std::fs::read_to_string(output).unwrap();\n let expected = '@read1\nACGT\n+\n!!!!\n@read3\nA\n+\n$\n';\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn filter_fasta_reads_one_index_out_of_range() {\n let text = '>read1 length=4\nACGT\n>read2\nCCCC\n';\n let mut input = Builder::new().suffix('.fa').tempfile().unwrap();\n input.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(input.path());\n let reads_to_keep: Vec = vec![true, false, true];\n let output = Builder::new().suffix('.fa').tempfile().unwrap();\n let output_fastx = Fastx::from_path(output.path());\n {\n let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap();\n let filter_result = fastx.filter_reads_into(&reads_to_keep, 2, &mut out_fh);\n assert!(filter_result.is_err());\n }\n\n let actual = std::fs::read_to_string(output).unwrap();\n let expected = '>read1 length=4\nACGT\n';\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn filter_fastq_reads_one_index_out_of_range() {\n let text = '@read1 length=4\nACGT\n+\n!!!!\n@read2\nC\n+\n^\n';\n let mut input = Builder::new().suffix('.fq').tempfile().unwrap();\n input.write_all(text.as_bytes()).unwrap();\n let fastx = Fastx::from_path(input.path());\n let reads_to_keep: Vec = vec![true, false, true];\n let output = Builder::new().suffix('.fq').tempfile().unwrap();\n let output_fastx = Fastx::from_path(output.path());\n {\n let mut out_fh = output_fastx.create(niffler::Level::Four, None).unwrap();\n let filter_result = fastx.filter_reads_into(&reads_to_keep, 2, &mut out_fh);\n assert!(filter_result.is_err());\n }\n\n let actual = std::fs::read_to_string(output).unwrap();\n let expected = '@read1 length=4\nACGT\n+\n!!!!\n';\n\n assert_eq!(actual, expected)\n }\n}\n","mit" +"rasusa","./rasusa/src/cli.rs","use regex::Regex;\nuse std::ffi::{OsStr, OsString};\nuse std::ops::{Div, Mul};\nuse std::path::{Path, PathBuf};\nuse std::str::FromStr;\nuse structopt::StructOpt;\nuse thiserror::Error;\n\n/// Randomly subsample reads to a specified coverage.\n#[derive(Debug, StructOpt)]\n#[structopt()]\npub struct Cli {\n /// The fast{a,q} file(s) to subsample.\n ///\n /// For paired Illumina you may either pass this flag twice `-i r1.fq -i r2.fq` or give two\n /// files consecutively `-i r1.fq r2.fq`.\n #[structopt(\n short = 'i',\n long = 'input',\n parse(try_from_os_str = check_path_exists),\n multiple = true,\n required = true\n )]\n pub input: Vec,\n\n /// Output filepath(s); stdout if not present.\n ///\n /// For paired Illumina you may either pass this flag twice `-o o1.fq -o o2.fq` or give two\n /// files consecutively `-o o1.fq o2.fq`. NOTE: The order of the pairs is assumed to be the\n /// same as that given for --input. This option is required for paired input.\n #[structopt(short = 'o', long = 'output', parse(from_os_str), multiple = true)]\n pub output: Vec,\n\n /// Genome size to calculate coverage with respect to. e.g., 4.3kb, 7Tb, 9000, 4.1MB\n #[structopt(short = 'g', long = 'genome-size')]\n pub genome_size: GenomeSize,\n\n /// The desired coverage to sub-sample the reads to.\n #[structopt(short = 'c', long = 'coverage', value_name = 'FLOAT')]\n pub coverage: Coverage,\n\n /// Random seed to use.\n #[structopt(short = 's', long = 'seed', value_name = 'INT')]\n pub seed: Option,\n\n /// Switch on verbosity.\n #[structopt(short)]\n pub verbose: bool,\n\n /// u: uncompressed; b: Bzip2; g: Gzip; l: Lzma\n ///\n /// Rasusa will attempt to infer the output compression format automatically from the filename\n /// extension. This option is used to override that. If writing to stdout, the default is\n /// uncompressed\n #[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)]\n pub output_type: Option,\n\n /// Compression level to use if compressing output\n #[structopt(short = 'l', long, parse(try_from_str = parse_level), default_value='6', value_name = '1-9')]\n pub compress_level: niffler::Level,\n}\n\nimpl Cli {\n /// Checks there is a valid and equal number of `--input` and `--output` arguments given.\n ///\n /// # Errors\n /// A [`CliError::BadInputOutputCombination`](#clierror) is returned for the following:\n /// - Either `--input` or `--output` are passed more than twice\n /// - An unequal number of `--input` and `--output` are passed. The only exception to\n /// this is if one `--input` and zero `--output` are passed, in which case, the output\n /// will be sent to STDOUT.\n pub fn validate_input_output_combination(&self) -> Result<(), CliError> {\n let out_len = self.output.len();\n let in_len = self.input.len();\n\n if in_len > 2 {\n let msg = String::from('Got more than 2 files for input.');\n return Err(CliError::BadInputOutputCombination(msg));\n }\n if out_len > 2 {\n let msg = String::from('Got more than 2 files for output.');\n return Err(CliError::BadInputOutputCombination(msg));\n }\n match (in_len as isize - out_len as isize) as isize {\n diff if diff == 1 && in_len == 1 => Ok(()),\n diff if diff != 0 => Err(CliError::BadInputOutputCombination(format!(\n 'Got {} --input but {} --output',\n in_len, out_len\n ))),\n _ => Ok(()),\n }\n }\n}\n\n/// A collection of custom errors relating to the command line interface for this package.\n#[derive(Error, Debug, PartialEq)]\npub enum CliError {\n /// Indicates that a string cannot be parsed into a [`MetricSuffix`](#metricsuffix).\n #[error('{0} is not a valid metric suffix')]\n InvalidMetricSuffix(String),\n\n /// Indicates that a string cannot be parsed into a [`GenomeSize`](#genomesize).\n #[error('{0} is not a valid genome size. Valid forms include 4gb, 3000, 8.7Kb etc.')]\n InvalidGenomeSizeString(String),\n\n /// Indicates that a string cannot be parsed into a [`Coverage`](#coverage).\n #[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')]\n InvalidCoverageValue(String),\n\n /// Indicates that a string cannot be parsed into a [`CompressionFormat`](#compressionformat).\n #[error('{0} is not a valid output format')]\n InvalidCompression(String),\n\n /// Indicates a bad combination of input and output files was passed.\n #[error('Bad combination of input and output files: {0}')]\n BadInputOutputCombination(String),\n}\n\n/// A metric suffix is a unit suffix used to indicate the multiples of (in this case) base pairs.\n/// For instance, the metric suffix 'Kb' refers to kilobases. Therefore, 6.9kb means 6900 base pairs.\n#[derive(PartialEq, Debug)]\nenum MetricSuffix {\n Base,\n Kilo,\n Mega,\n Giga,\n Tera,\n}\n\nimpl FromStr for MetricSuffix {\n type Err = CliError;\n\n /// Parses a string into a `MetricSuffix`.\n ///\n /// # Example\n /// ```rust\n /// let s = '5.5mb';\n /// let metric_suffix = MetricSuffix::from_str(s);\n ///\n /// assert_eq!(metric_suffix, MetricSuffix::Mega)\n /// ```\n fn from_str(suffix: &str) -> Result {\n let suffix_lwr = suffix.to_lowercase();\n let metric_suffix = match suffix_lwr.as_str() {\n s if 'b'.contains(s) => MetricSuffix::Base,\n s if 'kb'.contains(s) => MetricSuffix::Kilo,\n s if 'mb'.contains(s) => MetricSuffix::Mega,\n s if 'gb'.contains(s) => MetricSuffix::Giga,\n s if 'tb'.contains(s) => MetricSuffix::Tera,\n _ => {\n return Err(CliError::InvalidMetricSuffix(suffix.to_string()));\n }\n };\n Ok(metric_suffix)\n }\n}\n\n/// Allow for multiplying a `f64` by a `MetricSuffix`.\n///\n/// # Example\n///\n/// ```rust\n/// let metric_suffix = MetricSuffix::Mega;\n/// let x: f64 = 5.5;\n///\n/// assert_eq!(x * metric_suffix, 5_500_000)\n/// ```\nimpl Mul for f64 {\n type Output = Self;\n\n fn mul(self, rhs: MetricSuffix) -> Self::Output {\n match rhs {\n MetricSuffix::Base => self,\n MetricSuffix::Kilo => self * 1_000.0,\n MetricSuffix::Mega => self * 1_000_000.0,\n MetricSuffix::Giga => self * 1_000_000_000.0,\n MetricSuffix::Tera => self * 1_000_000_000_000.0,\n }\n }\n}\n\n/// An object for collecting together methods for working with the genome size parameter for this\n/// package.\n#[derive(Debug, PartialOrd, PartialEq, Copy, Clone)]\npub struct GenomeSize(u64);\n\n/// Allow for comparison of a `u64` and a `GenomeSize`.\n///\n/// # Example\n///\n/// ```rust\n/// assert!(GenomeSize(10) == 10)\n/// ```\nimpl PartialEq for GenomeSize {\n fn eq(&self, other: &u64) -> bool {\n self.0 == *other\n }\n}\n\nimpl FromStr for GenomeSize {\n type Err = CliError;\n\n /// Parses a string into a `GenomeSize`.\n ///\n /// # Example\n /// ```rust\n /// let s = '5.5mb';\n /// let genome_size = GenomeSize::from_str(s);\n ///\n /// assert_eq!(genome_size, GenomeSize(5_500_000))\n /// ```\n fn from_str(s: &str) -> Result {\n let text = s.to_lowercase();\n let re = Regex::new(r'(?P[0-9]*\.?[0-9]+)(?P\w*)$').unwrap();\n let captures = match re.captures(text.as_str()) {\n Some(cap) => cap,\n None => {\n return Err(CliError::InvalidGenomeSizeString(s.to_string()));\n }\n };\n let size = captures\n .name('size')\n .unwrap()\n .as_str()\n .parse::()\n .unwrap();\n let metric_suffix = MetricSuffix::from_str(captures.name('sfx').unwrap().as_str())?;\n\n Ok(GenomeSize((size * metric_suffix) as u64))\n }\n}\n\n/// Allow for multiplying a `GenomeSize` by a [`Coverage`](#coverage).\n///\n/// # Example\n///\n/// ```rust\n/// let genome_size = GenomeSize(100);\n/// let covg = Coverage(5);\n///\n/// assert_eq!(genome_size * covg, 500)\n/// ```\nimpl Mul for GenomeSize {\n type Output = u64;\n\n fn mul(self, rhs: Coverage) -> Self::Output {\n (self.0 as f32 * rhs.0) as u64\n }\n}\n\n/// Allow for dividing a `u64` by a `GenomeSize`.\n///\n/// # Example\n///\n/// ```rust\n/// let x: u64 = 210;\n/// let size = GenomeSize(200);\n///\n/// let actual = x / size;\n/// let expected = 1.05;\n///\n/// assert_eq!(actual, expected)\n/// ```\nimpl Div for u64 {\n type Output = f64;\n\n fn div(self, rhs: GenomeSize) -> Self::Output {\n (self as f64) / (rhs.0 as f64)\n }\n}\n\n/// An object for collecting together methods for working with the coverage parameter for this\n/// package.\n#[derive(Debug, PartialOrd, PartialEq, Copy, Clone)]\npub struct Coverage(f32);\n\n/// Allow for comparison of a `f32` and a `Coverage`.\n///\n/// # Example\n///\n/// ```rust\n/// assert!(Coverage(10) == 10.0)\n/// ```\nimpl PartialEq for Coverage {\n fn eq(&self, other: &f32) -> bool {\n self.0 == *other\n }\n}\n\nimpl FromStr for Coverage {\n type Err = CliError;\n\n /// Parses a string into a `Coverage`.\n ///\n /// # Example\n /// ```rust\n /// let s = '100x';\n /// let covg = Coverage::from_str(s);\n ///\n /// assert_eq!(covg, Coverage(100))\n /// ```\n fn from_str(s: &str) -> Result {\n let re = Regex::new(r'^(?P[0-9]*\.?[0-9]+)(?i)x?$').unwrap();\n let captures = match re.captures(s) {\n Some(cap) => cap,\n None => {\n return Err(CliError::InvalidCoverageValue(s.to_string()));\n }\n };\n Ok(Coverage(\n captures\n .name('covg')\n .unwrap()\n .as_str()\n .parse::()\n .unwrap(),\n ))\n }\n}\n\n/// Allow for multiplying a `Coverage` by a [`GenomeSize`](#genomesize).\n///\n/// # Example\n///\n/// ```rust\n/// let covg = Coverage(5);\n/// let genome_size = GenomeSize(100);\n///\n/// assert_eq!(covg * genome_size, 500)\n/// ```\nimpl Mul for Coverage {\n type Output = u64;\n\n fn mul(self, rhs: GenomeSize) -> Self::Output {\n (self.0 * (rhs.0 as f32)) as u64\n }\n}\n\npub trait CompressionExt {\n fn from_path + ?Sized>(p: &S) -> Self;\n}\n\nimpl CompressionExt for niffler::compression::Format {\n /// Attempts to infer the compression type from the file extension. If the extension is not\n /// known, then Uncompressed is returned.\n fn from_path + ?Sized>(p: &S) -> Self {\n let path = Path::new(p);\n match path.extension().map(|s| s.to_str()) {\n Some(Some('gz')) => Self::Gzip,\n Some(Some('bz') | Some('bz2')) => Self::Bzip,\n Some(Some('lzma')) => Self::Lzma,\n _ => Self::No,\n }\n }\n}\n\nfn parse_compression_format(s: &str) -> Result {\n match s {\n 'b' | 'B' => Ok(niffler::Format::Bzip),\n 'g' | 'G' => Ok(niffler::Format::Gzip),\n 'l' | 'L' => Ok(niffler::Format::Lzma),\n 'u' | 'U' => Ok(niffler::Format::No),\n _ => Err(CliError::InvalidCompression(s.to_string())),\n }\n}\n/// A utility function that allows the CLI to error if a path doesn't exist\nfn check_path_exists + ?Sized>(s: &S) -> Result {\n let path = PathBuf::from(s);\n if path.exists() {\n Ok(path)\n } else {\n Err(OsString::from(format!('{:?} does not exist', path)))\n }\n}\n\n/// A utility function to validate compression level is in allowed range\n#[allow(clippy::redundant_clone)]\nfn parse_level(s: &str) -> Result {\n let lvl = match s.parse::() {\n Ok(1) => niffler::Level::One,\n Ok(2) => niffler::Level::Two,\n Ok(3) => niffler::Level::Three,\n Ok(4) => niffler::Level::Four,\n Ok(5) => niffler::Level::Five,\n Ok(6) => niffler::Level::Six,\n Ok(7) => niffler::Level::Seven,\n Ok(8) => niffler::Level::Eight,\n Ok(9) => niffler::Level::Nine,\n _ => return Err(format!('Compression level {} not in the range 1-9', s)),\n };\n Ok(lvl)\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n const ERROR: f32 = f32::EPSILON;\n\n #[test]\n fn no_args_given_raises_error() {\n let passed_args = vec!['rasusa'];\n let args: Result = Cli::from_iter_safe(passed_args);\n\n let actual = args.unwrap_err().kind;\n let expected = clap::ErrorKind::MissingRequiredArgument;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn no_input_file_given_raises_error() {\n let passed_args = vec!['rasusa', '-c', '30', '-g', '3mb'];\n let args: Result = Cli::from_iter_safe(passed_args);\n\n let actual = args.unwrap_err().kind;\n let expected = clap::ErrorKind::MissingRequiredArgument;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn no_coverage_given_raises_error() {\n let passed_args = vec!['rasusa', '-i', 'in.fq', '-g', '3mb'];\n let args: Result = Cli::from_iter_safe(passed_args);\n\n let actual = args.unwrap_err().kind;\n let expected = clap::ErrorKind::MissingRequiredArgument;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn invalid_coverage_given_raises_error() {\n let passed_args = vec!['rasusa', '-i', 'in.fq', '-g', '3mb', '-c', 'foo'];\n let args: Result = Cli::from_iter_safe(passed_args);\n\n let actual = args.unwrap_err().kind;\n let expected = clap::ErrorKind::ValueValidation;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn no_genome_size_given_raises_error() {\n let passed_args = vec!['rasusa', '-i', 'in.fq', '-c', '5'];\n let args: Result = Cli::from_iter_safe(passed_args);\n\n let actual = args.unwrap_err().kind;\n let expected = clap::ErrorKind::MissingRequiredArgument;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn invalid_genome_size_given_raises_error() {\n let passed_args = vec!['rasusa', '-i', 'in.fq', '-c', '5', '-g', '8jb'];\n let args: Result = Cli::from_iter_safe(passed_args);\n\n let actual = args.unwrap_err().kind;\n let expected = clap::ErrorKind::ValueValidation;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn invalid_seed_given_raises_error() {\n let passed_args = vec!['rasusa', '-i', 'in.fq', '-c', '5', '-g', '8mb', '-s', 'foo'];\n let args: Result = Cli::from_iter_safe(passed_args);\n\n let actual = args.unwrap_err().kind;\n let expected = clap::ErrorKind::ValueValidation;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn all_valid_args_parsed_as_expected() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec![\n 'rasusa',\n '-i',\n infile,\n '-c',\n '5',\n '-g',\n '8mb',\n '-s',\n '88',\n '-o',\n 'my/output/file.fq',\n ];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n assert_eq!(args.input[0], PathBuf::from_str(infile).unwrap());\n assert_eq!(args.coverage, Coverage(5.0));\n assert_eq!(args.genome_size, GenomeSize(8_000_000));\n assert_eq!(args.seed, Some(88));\n assert_eq!(\n args.output[0],\n PathBuf::from_str('my/output/file.fq').unwrap()\n )\n }\n\n #[test]\n fn all_valid_args_with_two_inputs_parsed_as_expected() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec![\n 'rasusa',\n '-i',\n infile,\n infile,\n '-c',\n '5',\n '-g',\n '8mb',\n '-s',\n '88',\n '-o',\n 'my/output/file.fq',\n ];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n let expected_input = vec![\n PathBuf::from_str(infile).unwrap(),\n PathBuf::from_str(infile).unwrap(),\n ];\n assert_eq!(args.input, expected_input);\n assert_eq!(args.coverage, Coverage(5.0));\n assert_eq!(args.genome_size, GenomeSize(8_000_000));\n assert_eq!(args.seed, Some(88));\n assert_eq!(\n args.output[0],\n PathBuf::from_str('my/output/file.fq').unwrap()\n )\n }\n\n #[test]\n fn all_valid_args_with_two_inputs_using_flag_twice_parsed_as_expected() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec![\n 'rasusa',\n '-i',\n infile,\n '-i',\n infile,\n '-c',\n '5',\n '-g',\n '8mb',\n '-s',\n '88',\n '-o',\n 'my/output/file.fq',\n ];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n let expected_input = vec![\n PathBuf::from_str(infile).unwrap(),\n PathBuf::from_str(infile).unwrap(),\n ];\n assert_eq!(args.input, expected_input);\n assert_eq!(args.coverage, Coverage(5.0));\n assert_eq!(args.genome_size, GenomeSize(8_000_000));\n assert_eq!(args.seed, Some(88));\n assert_eq!(\n args.output[0],\n PathBuf::from_str('my/output/file.fq').unwrap()\n )\n }\n\n #[test]\n fn three_inputs_raises_error() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec![\n 'rasusa',\n '-i',\n infile,\n '-i',\n infile,\n '-i',\n infile,\n '-c',\n '5',\n '-g',\n '8mb',\n '-s',\n '88',\n '-o',\n 'my/output/file.fq',\n ];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n let actual: CliError = args.validate_input_output_combination().unwrap_err();\n let expected =\n CliError::BadInputOutputCombination(String::from('Got more than 2 files for input.'));\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn three_outputs_raises_error() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec![\n 'rasusa',\n '-i',\n infile,\n '-i',\n infile,\n '-c',\n '5',\n '-g',\n '8mb',\n '-s',\n '88',\n '-o',\n 'my/output/file.fq',\n '-o',\n 'out.fq',\n '-o',\n 'out.fq',\n ];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n let actual: CliError = args.validate_input_output_combination().unwrap_err();\n let expected =\n CliError::BadInputOutputCombination(String::from('Got more than 2 files for output.'));\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn one_input_no_output_is_ok() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec!['rasusa', '-i', infile, '-c', '5', '-g', '8mb', '-s', '88'];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n let actual = args.validate_input_output_combination();\n\n assert!(actual.is_ok())\n }\n\n #[test]\n fn two_inputs_one_output_raises_error() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec![\n 'rasusa', '-i', infile, '-i', infile, '-c', '5', '-g', '8mb', '-s', '88', '-o',\n 'out.fq',\n ];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n let actual: CliError = args.validate_input_output_combination().unwrap_err();\n let expected =\n CliError::BadInputOutputCombination(String::from('Got 2 --input but 1 --output'));\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn one_input_two_outputs_raises_error() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec![\n 'rasusa', '-i', infile, '-c', '5', '-g', '8mb', '-s', '88', '-o', 'out.fq', '-o',\n 'out.fq',\n ];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n let actual: CliError = args.validate_input_output_combination().unwrap_err();\n let expected =\n CliError::BadInputOutputCombination(String::from('Got 1 --input but 2 --output'));\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn two_input_two_outputs_is_ok() {\n let infile = 'tests/cases/r1.fq.gz';\n let passed_args = vec![\n 'rasusa', '-i', infile, '-i', infile, '-c', '5', '-g', '8mb', '-s', '88', '-o',\n 'out.fq', '-o', 'out.fq',\n ];\n let args = Cli::from_iter_safe(passed_args).unwrap();\n\n let actual = args.validate_input_output_combination();\n\n assert!(actual.is_ok())\n }\n\n #[test]\n fn float_multiply_with_base_unit() {\n let actual = 4.5 * MetricSuffix::Base;\n let expected = 4.5;\n\n let diff = (actual.abs() - expected).abs();\n assert!(diff < f64::EPSILON)\n }\n\n #[test]\n fn integer_only_returns_integer() {\n let actual = GenomeSize::from_str('6').unwrap();\n let expected = 6;\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn float_only_returns_integer() {\n let actual = GenomeSize::from_str('6.5').unwrap();\n let expected = 6;\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn int_and_suffix_returns_multiplied_int() {\n let actual = GenomeSize::from_str('5mb').unwrap();\n let expected = 5_000_000;\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn float_and_suffix_returns_multiplied_float_as_int() {\n let actual = GenomeSize::from_str('5.4kB').unwrap();\n let expected = 5_400;\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn float_without_leading_int_and_suffix_returns_multiplied_float_as_int() {\n let actual = GenomeSize::from_str('.77G').unwrap();\n let expected = 770_000_000;\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn int_and_tera_suffix_returns_multiplied_int() {\n let actual = GenomeSize::from_str('7TB').unwrap();\n let expected = 7_000_000_000_000;\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn int_and_base_suffix_returns_int_without_scaling() {\n let actual = GenomeSize::from_str('7B').unwrap();\n let expected = 7;\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn invalid_suffix_returns_err() {\n let genome_size = String::from('.77uB');\n let actual = GenomeSize::from_str(genome_size.as_str()).unwrap_err();\n let expected = CliError::InvalidMetricSuffix(String::from('ub'));\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn empty_string_returns_error() {\n let actual = GenomeSize::from_str('').unwrap_err();\n let expected = CliError::InvalidGenomeSizeString(String::from(''));\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn suffix_with_no_size_returns_error() {\n let actual = GenomeSize::from_str('gb');\n\n assert!(actual.is_err());\n }\n\n #[test]\n fn int_coverage_returns_float() {\n let actual = Coverage::from_str('56').unwrap();\n let expected = 56.0;\n\n assert!((expected - actual.0).abs() < ERROR)\n }\n\n #[test]\n fn float_coverage_returns_float() {\n let actual = Coverage::from_str('56.6').unwrap();\n let expected = 56.6;\n\n assert!((expected - actual.0).abs() < ERROR)\n }\n\n #[test]\n fn empty_coverage_returns_err() {\n let coverage = String::from('');\n\n let actual = Coverage::from_str(coverage.as_str()).unwrap_err();\n let expected = CliError::InvalidCoverageValue(coverage);\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn non_number_coverage_returns_err() {\n let coverage = String::from('foo');\n\n let actual = Coverage::from_str(coverage.as_str()).unwrap_err();\n let expected = CliError::InvalidCoverageValue(coverage);\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn zero_coverage_returns_zero() {\n let actual = Coverage::from_str('0').unwrap();\n let expected = 0.0;\n\n assert!((expected - actual.0).abs() < ERROR)\n }\n\n #[test]\n fn int_ending_in_x_coverage_returns_float() {\n let actual = Coverage::from_str('1X').unwrap();\n let expected = 1.0;\n\n assert!((expected - actual.0).abs() < ERROR)\n }\n\n #[test]\n fn float_ending_in_x_coverage_returns_float() {\n let actual = Coverage::from_str('1.9X').unwrap();\n let expected = 1.9;\n\n assert!((expected - actual.0).abs() < ERROR)\n }\n\n #[test]\n fn mega_suffix_from_string() {\n let actual = MetricSuffix::from_str('MB').unwrap();\n let expected = MetricSuffix::Mega;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn kilo_suffix_from_string() {\n let actual = MetricSuffix::from_str('kB').unwrap();\n let expected = MetricSuffix::Kilo;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn giga_suffix_from_string() {\n let actual = MetricSuffix::from_str('Gb').unwrap();\n let expected = MetricSuffix::Giga;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn tera_suffix_from_string() {\n let actual = MetricSuffix::from_str('tb').unwrap();\n let expected = MetricSuffix::Tera;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn base_suffix_from_string() {\n let actual = MetricSuffix::from_str('B').unwrap();\n let expected = MetricSuffix::Base;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn empty_string_is_base_metric_suffix() {\n let suffix = String::from('');\n let actual = MetricSuffix::from_str(suffix.as_str()).unwrap();\n let expected = MetricSuffix::Base;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn invalid_suffix_raises_error() {\n let suffix = String::from('ub');\n let actual = MetricSuffix::from_str(suffix.as_str()).unwrap_err();\n let expected = CliError::InvalidMetricSuffix(suffix);\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn multiply_genome_size_by_coverage() {\n let genome_size = GenomeSize::from_str('4.2kb').unwrap();\n let covg = Coverage::from_str('11.7866').unwrap();\n\n let actual = genome_size * covg;\n let expected: u64 = 49_503;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn multiply_coverage_by_genome_size() {\n let genome_size = GenomeSize::from_str('4.2kb').unwrap();\n let covg = Coverage::from_str('11.7866').unwrap();\n\n let actual = covg * genome_size;\n let expected: u64 = 49_503;\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn divide_u64_by_genome_size() {\n let x: u64 = 210;\n let size = GenomeSize(200);\n\n let actual = x / size;\n let expected = 1.05;\n\n let diff = (actual.abs() - expected).abs();\n assert!(diff < f64::EPSILON)\n }\n\n #[test]\n fn compression_format_from_str() {\n let mut s = 'B';\n assert_eq!(parse_compression_format(s).unwrap(), niffler::Format::Bzip);\n\n s = 'g';\n assert_eq!(parse_compression_format(s).unwrap(), niffler::Format::Gzip);\n\n s = 'l';\n assert_eq!(parse_compression_format(s).unwrap(), niffler::Format::Lzma);\n\n s = 'U';\n assert_eq!(parse_compression_format(s).unwrap(), niffler::Format::No);\n\n s = 'a';\n assert_eq!(\n parse_compression_format(s).unwrap_err(),\n CliError::InvalidCompression(s.to_string())\n );\n }\n\n #[test]\n fn test_in_compress_range() {\n assert!(parse_level('1').is_ok());\n assert!(parse_level('9').is_ok());\n assert!(parse_level('0').is_err());\n assert!(parse_level('10').is_err());\n assert!(parse_level('f').is_err());\n assert!(parse_level('5.5').is_err());\n assert!(parse_level('-3').is_err());\n }\n\n #[test]\n fn compression_format_from_path() {\n assert_eq!(niffler::Format::from_path('foo.gz'), niffler::Format::Gzip);\n assert_eq!(\n niffler::Format::from_path(Path::new('foo.gz')),\n niffler::Format::Gzip\n );\n assert_eq!(niffler::Format::from_path('baz'), niffler::Format::No);\n assert_eq!(niffler::Format::from_path('baz.fq'), niffler::Format::No);\n assert_eq!(\n niffler::Format::from_path('baz.fq.bz2'),\n niffler::Format::Bzip\n );\n assert_eq!(\n niffler::Format::from_path('baz.fq.bz'),\n niffler::Format::Bzip\n );\n assert_eq!(\n niffler::Format::from_path('baz.fq.lzma'),\n niffler::Format::Lzma\n );\n }\n}\n","mit" +"rasusa","./rasusa/src/main.rs","#![allow(clippy::redundant_clone)] // due to a structopt problem\nuse std::io::stdout;\n\nuse anyhow::{Context, Result};\nuse fern::colors::{Color, ColoredLevelConfig};\nuse log::{debug, error, info};\nuse structopt::StructOpt;\n\npub use crate::cli::Cli;\npub use crate::fastx::Fastx;\npub use crate::subsampler::SubSampler;\n\nmod cli;\nmod fastx;\nmod subsampler;\n\n/// Sets up the logging based on whether you want verbose logging or not. If `verbose` is `false`\n/// then info, warning, and error messages will be printed. If `verbose` is `true` then debug\n/// messages will also be printed.\n///\n/// # Errors\n/// Will error if `fern` fails to apply the logging setup.\nfn setup_logger(verbose: bool) -> Result<(), fern::InitError> {\n let colors = ColoredLevelConfig::new()\n .warn(Color::Yellow)\n .debug(Color::Magenta)\n .error(Color::Red)\n .trace(Color::Green);\n\n let log_level = if verbose {\n log::LevelFilter::Debug\n } else {\n log::LevelFilter::Info\n };\n\n fern::Dispatch::new()\n .format(move |out, message, record| {\n out.finish(format_args!(\n '{}[{}][{}] {}',\n chrono::Local::now().format('[%Y-%m-%d][%H:%M:%S]'),\n record.target(),\n colors.color(record.level()),\n message\n ))\n })\n .level(log_level)\n .chain(std::io::stderr())\n .apply()?;\n Ok(())\n}\n\nfn main() -> Result<()> {\n let args: Cli = Cli::from_args();\n setup_logger(args.verbose).context('Failed to setup the logger')?;\n debug!('{:?}', args);\n\n args.validate_input_output_combination()?;\n let is_illumina = args.input.len() == 2;\n if is_illumina {\n info!('Two input files given. Assuming paired Illumina...')\n }\n\n let input_fastx = Fastx::from_path(&args.input[0]);\n\n let mut output_handle = match args.output.len() {\n 0 => match args.output_type {\n None => Box::new(stdout()),\n Some(fmt) => niffler::basic::get_writer(Box::new(stdout()), fmt, args.compress_level)?,\n },\n _ => {\n let out_fastx = Fastx::from_path(&args.output[0]);\n out_fastx\n .create(args.compress_level, args.output_type)\n .context('unable to create the first output file')?\n }\n };\n\n let target_total_bases: u64 = args.genome_size * args.coverage;\n info!(\n 'Target number of bases to subsample to is: {}',\n target_total_bases\n );\n\n info!('Gathering read lengths...');\n let mut read_lengths = input_fastx\n .read_lengths()\n .context('unable to gather read lengths for the first input file')?;\n\n if is_illumina {\n let second_input_fastx = Fastx::from_path(&args.input[1]);\n let expected_num_reads = read_lengths.len();\n info!('Gathering read lengths for second input file...');\n let mate_lengths = second_input_fastx\n .read_lengths()\n .context('unable to gather read lengths for the second input file')?;\n\n if mate_lengths.len() != expected_num_reads {\n 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());\n std::process::exit(1);\n } else {\n info!(\n 'Both input files have the same number of reads ({}) 👍',\n expected_num_reads\n );\n }\n // add the paired read lengths to the existing lengths\n for (i, len) in mate_lengths.iter().enumerate() {\n read_lengths[i] += len;\n }\n }\n info!('{} reads detected', read_lengths.len());\n\n let subsampler = SubSampler {\n target_total_bases,\n seed: args.seed,\n };\n\n let (reads_to_keep, nb_reads_to_keep) = subsampler.indices(&read_lengths);\n if is_illumina {\n info!('Keeping {} reads from each input', nb_reads_to_keep);\n } else {\n info!('Keeping {} reads', nb_reads_to_keep);\n }\n debug!('Indices of reads being kept:\n{:?}', reads_to_keep);\n\n let mut total_kept_bases =\n input_fastx.filter_reads_into(&reads_to_keep, nb_reads_to_keep, &mut output_handle)? as u64;\n\n // repeat the same process for the second input fastx (if illumina)\n if is_illumina {\n let second_input_fastx = Fastx::from_path(&args.input[1]);\n let second_out_fastx = Fastx::from_path(&args.output[1]);\n let mut second_output_handle = second_out_fastx\n .create(args.compress_level, args.output_type)\n .context('unable to create the second output file')?;\n\n total_kept_bases += second_input_fastx.filter_reads_into(\n &reads_to_keep,\n nb_reads_to_keep,\n &mut second_output_handle,\n )? as u64;\n }\n\n let actual_covg = total_kept_bases / args.genome_size;\n info!('Actual coverage of kept reads is {:.2}x', actual_covg);\n\n info!('Done 🎉');\n\n Ok(())\n}\n","mit" +"rasusa","./rasusa/src/subsampler.rs","use rand::prelude::*;\n\n/// A `Struct` for dealing with the randomised part of sub-sampling.\npub struct SubSampler {\n /// Number of bases to sub-sample down to. \n pub target_total_bases: u64,\n /// Random seed to use for sub-sampling. If `None` is used, then the random number generator\n /// will be seeded by the operating system.\n pub seed: Option,\n}\n\nimpl SubSampler {\n /// Returns a vector of indices for elements in `v`, but shuffled.\n ///\n /// # Note\n ///\n /// If the file has more than 4,294,967,296 reads, this function's behaviour is undefined.\n ///\n /// # Example\n ///\n /// ```rust\n /// let v: Vec = vec![55, 1];\n /// let sampler = SubSampler {\n /// target_total_bases: 100,\n /// seed: None,\n /// };\n /// let mut num_times_shuffled = 0;\n /// let iterations = 500;\n /// for _ in 0..iterations {\n /// let idxs = sampler.shuffled_indices(&v);\n /// if idxs == vec![1, 0] {\n /// num_times_shuffled += 1;\n /// }\n /// }\n /// // chances of shuffling the same way 100 times in a row is 3.054936363499605e-151\n /// assert!(num_times_shuffled > 0 && num_times_shuffled < iterations)\n /// ```\n fn shuffled_indices(&self, v: &[T]) -> Vec {\n let mut indices: Vec = (0..v.len() as u32).collect();\n let mut rng = match self.seed {\n Some(s) => rand_pcg::Pcg64::seed_from_u64(s),\n None => rand_pcg::Pcg64::seed_from_u64(random()),\n };\n\n indices.shuffle(&mut rng);\n indices\n }\n\n /// Sub-samples `lengths` to the desired `target_total_bases` specified in the `SubSampler` and\n /// returns the indices for the reads that were selected.\n ///\n /// # Example\n ///\n /// ```rust\n /// let v: Vec = vec![50, 50, 50];\n /// let sampler = SubSampler {\n /// target_total_bases: 100,\n /// seed: Some(1),\n /// };\n /// let actual = sampler.indices(&v);\n ///\n /// assert_eq!(actual.len(), 3);\n /// assert!(actual[1]);\n /// assert!(actual[2]);\n /// assert!(actual[3]);\n /// ```\n pub fn indices(&self, lengths: &[u32]) -> (Vec, usize) {\n let mut indices = self.shuffled_indices(lengths).into_iter();\n let mut to_keep: Vec = vec![false; lengths.len()];\n let mut total_bases_kept: u64 = 0;\n\n let mut nb_reads_to_keep = 0;\n while total_bases_kept < self.target_total_bases {\n let idx = match indices.next() {\n Some(i) => i as usize,\n None => break,\n };\n to_keep[idx] = true;\n total_bases_kept += u64::from(lengths[idx.to_owned()]);\n nb_reads_to_keep += 1;\n }\n\n (to_keep, nb_reads_to_keep)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn shuffled_indices_for_empty_vector_returns_empty() {\n let v: Vec = Vec::new();\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: None,\n };\n\n let actual = sampler.shuffled_indices(&v);\n\n assert!(actual.is_empty())\n }\n\n #[test]\n fn shuffled_indices_for_vector_len_one_returns_zero() {\n let v: Vec = vec![55];\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: None,\n };\n\n let actual = sampler.shuffled_indices(&v);\n let expected: Vec = vec![0];\n\n assert_eq!(actual, expected)\n }\n\n #[test]\n fn shuffled_indices_for_vector_len_two_does_shuffle() {\n let v: Vec = vec![55, 1];\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: None,\n };\n\n let mut num_times_shuffled = 0;\n let iterations = 500;\n for _ in 0..iterations {\n let idxs = sampler.shuffled_indices(&v);\n if idxs == vec![1, 0] {\n num_times_shuffled += 1;\n }\n }\n\n // chances of shuffling the same way 100 times in a row is 3.054936363499605e-151\n assert!(num_times_shuffled > 0 && num_times_shuffled < iterations)\n }\n\n #[test]\n fn shuffled_indices_with_seed_produces_same_ordering() {\n let v: Vec = vec![55, 1, 8];\n let sampler1 = SubSampler {\n target_total_bases: 100,\n seed: Some(1),\n };\n\n let sampler2 = SubSampler {\n target_total_bases: 100,\n seed: Some(1),\n };\n let idxs1 = sampler1.shuffled_indices(&v);\n let idxs2 = sampler2.shuffled_indices(&v);\n\n for i in 0..idxs1.len() {\n assert_eq!(idxs1[i], idxs2[i])\n }\n }\n\n #[test]\n fn subsample_empty_lengths_returns_empty() {\n let v: Vec = Vec::new();\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: None,\n };\n\n let (_, nb_select) = sampler.indices(&v);\n\n assert_eq!(nb_select, 0)\n }\n\n #[test]\n fn subsample_one_length_target_zero_returns_empty() {\n let v: Vec = Vec::new();\n let sampler = SubSampler {\n target_total_bases: 0,\n seed: None,\n };\n\n let (_, nb_select) = sampler.indices(&v);\n\n assert_eq!(nb_select, 0);\n }\n\n #[test]\n fn subsample_one_length_less_than_target_returns_zero() {\n let v: Vec = vec![5];\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: None,\n };\n\n let (actual, nb_select) = sampler.indices(&v);\n\n assert_eq!(nb_select, 1);\n assert!(actual[0])\n }\n\n #[test]\n fn subsample_one_length_greater_than_target_returns_zero() {\n let v: Vec = vec![500];\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: None,\n };\n\n let (actual, nb_select) = sampler.indices(&v);\n\n assert_eq!(nb_select, 1);\n assert!(actual[0])\n }\n\n #[test]\n fn subsample_three_lengths_sum_greater_than_target_returns_two() {\n let v: Vec = vec![50, 50, 50];\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: Some(1),\n };\n\n let (actual, nb_select) = sampler.indices(&v);\n\n assert_eq!(nb_select, 2);\n assert!(!actual[0]);\n assert!(actual[1]);\n assert!(actual[2]);\n }\n\n #[test]\n fn subsample_three_lengths_sum_less_than_target_returns_three() {\n let v: Vec = vec![5, 5, 5];\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: None,\n };\n\n let (actual, _) = sampler.indices(&v);\n let expected = vec![true; 3];\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn subsample_three_lengths_sum_equal_target_returns_three() {\n let v: Vec = vec![25, 25, 50];\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: None,\n };\n\n let (actual, _) = sampler.indices(&v);\n let expected = vec![true; 3];\n\n assert_eq!(actual, expected);\n }\n\n #[test]\n fn subsample_three_lengths_all_greater_than_target_returns_two() {\n let v: Vec = vec![500, 500, 500];\n let sampler = SubSampler {\n target_total_bases: 100,\n seed: Some(1),\n };\n\n let (actual, nb_select) = sampler.indices(&v);\n println!('{:?}', actual);\n\n assert_eq!(nb_select, 1);\n assert!(!actual[0]);\n assert!(!actual[1]);\n assert!(actual[2]);\n }\n}\n","mit"