repo_name
stringclasses
6 values
path
stringlengths
15
35
content
stringlengths
1.16k
33.7k
license
stringclasses
1 value
kmrf
./kmrf/src/cli.rs
/*\nCopyright (c) 2020 Pierre Marijon <pierre.marijon@hhu.de>\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 <pierre.marijon@hhu.de>',\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<String>,\n\n /// fasta file to be correct\n #[clap(short = 'i', long = 'inputs')]\n pub inputs: Vec<String>,\n\n /// path where corrected read was write\n #[clap(short = 'o', long = 'outputs')]\n pub outputs: Vec<String>,\n\n /// if you want choose the minimum abundance you can set this parameter\n #[clap(short = 'a', long = 'abundance')]\n pub abundance: Option<u8>,\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<f64>,\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<usize>,\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<u8>,\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<usize>,\n\n /// Number of sequence record load in buffer, default 8192\n #[clap(short = 'b', long = 'record_buffer')]\n pub record_buffer: Option<usize>,\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<Level> {\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<String>,\n kmer: Option<u8>,\n inputs: &[String],\n record_buffer_len: usize,\n abundance: Option<u8>,\n) -> Result<pcon::solid::Solid> {\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 <pierre.marijon@hhu.de>\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 <pierre.marijon@hhu.de>\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<String>,\n outputs: Vec<String>,\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 <pierre.marijon@hhu.de>\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 &params.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 <pmarijon@mpi-inf.mpg.de>\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<String> = 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<String> = 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<String> = 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<String> = 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 <pmarijon@mpi-inf.mpg.de>\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<Vec<(u32, u32)>> {\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<String> {\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 <pmarijon@mpi-inf.mpg.de>\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<String, (Vec<(u32, u32)>, 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<dyn std::io::Read>) -> 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<dyn std::io::Read>) -> 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<Vec<(u32, u32)>>;\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<String>;\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::<rustc_hash::FxHashSet<String>>(),\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::<rustc_hash::FxHashSet<String>>(),\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 <pmarijon@mpi-inf.mpg.de>\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<String, Vec<(u32, u32)>>,\n reads2len: rustc_hash::FxHashMap<String, usize>,\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<Vec<(u32, u32)>> {\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<Vec<(u32, u32)>> {\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<String> {\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 <pmarijon@mpi-inf.mpg.de>\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<String>;\n}\n\npub struct FromOverlap {\n ovl: Box<dyn reads2ovl::Reads2Ovl>,\n coverage: u64,\n buffer: reads2ovl::MapReads2Ovl,\n empty: (Vec<(u32, u32)>, usize),\n}\n\nimpl FromOverlap {\n pub fn new(ovl: Box<dyn reads2ovl::Reads2Ovl>, 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<Reverse<u32>> =\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::<reads2ovl::MapReads2Ovl>(),\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<String> {\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<Self> {\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<Vec<(u32, u32)>> {\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<String> {\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::<rustc_hash::FxHashSet<String>>(),\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::<rustc_hash::FxHashSet<String>>(),\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::<rustc_hash::FxHashSet<String>>(),\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 <pmarijon@mpi-inf.mpg.de>\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 <pierre@marijon.fr>',\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<usize>,\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<String>,\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<SubCommand>,\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 <pmarijon@mpi-inf.mpg.de>\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<FileType> {\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<dyn std::io::Read>, 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<Box<dyn std::io::Write>> {\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<usize> {\n val.parse::<usize>().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<u32> {\n val.parse::<u32>().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<u64> {\n val.parse::<u64>().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 <pmarijon@mpi-inf.mpg.de>\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 <pmarijon@mpi-inf.mpg.de>\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<dyn stack::BadPart> =\n if Some(util::FileType::Yacrd) == util::get_file_type(&params.input) {\n /* Read bad part from yacrd report */\n Box::new(stack::FromReport::new(&params.input)?)\n } else {\n /* Get bad part from overlap */\n let mut reads2ovl: Box<dyn reads2ovl::Reads2Ovl> = match params.ondisk.clone() {\n Some(on_disk_path) => Box::new(reads2ovl::OnDisk::new(\n on_disk_path,\n util::str2u64(&params.ondisk_buffer_size)?,\n params.buffer_size,\n )),\n None => Box::new(reads2ovl::FullMemory::new(params.buffer_size)),\n };\n\n reads2ovl.init(&params.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(&params.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: {}', &params.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 <pmarijon@mpi-inf.mpg.de>\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<R, W>(\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<R, W>(\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<u8> = 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<u8> = 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 <pmarijon@mpi-inf.mpg.de>\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<R, W>(\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<R, W>(\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<u8> = 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<u8> = 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<u8> = 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<u8> = 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 <pmarijon@mpi-inf.mpg.de>\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<R, W>(\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<R, W>(\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<R, W>(\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<R, W>(\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<u8> = 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<u8> = 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<u8> = 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<u8> = 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 <pmarijon@mpi-inf.mpg.de>\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<W>(\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::<Vec<String>>()\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 <pmarijon@mpi-inf.mpg.de>\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<R, W>(\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<R, W>(\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<R, W>(\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<R, W>(\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<u8> = 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<u8> = 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<u8> = 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<u8> = 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 <pmarijon@mpi-inf.mpg.de>\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 <pierre.marijon@hhu.de>\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<u8> {\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<u8> {\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<u8> {\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<u8> {\n self.percent_at_least(percent).map(|x| x - 1)\n }\n\n fn percent_at_least(&self, percent: f64) -> Option<u8> {\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<W>(&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<W>(&self, mut out: W, point: Option<u8>) -> 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::<Box<[u64]>>();\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::<Box<[u64]>>();\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 <pmarijon@mpi-inf.mpg.de>\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<std::io::BufReader<Box<dyn std::io::Read>>, 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<std::io::BufWriter<Box<dyn std::io::Write>>, 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: R) -> Result<Self>\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 <pmarijon@mpi-inf.mpg.de>\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 <pmarijon@mpi-inf.mpg.de>')]\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<usize>,\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<String>,\n\n #[clap(short = 'o', long = 'output')]\n /// 'Path where count are store in binary format'\n pub output: Option<String>,\n\n #[clap(short = 'b', long = 'record_buffer')]\n /// Number of sequence record load in buffer, default 8192\n pub record_buffer: Option<usize>,\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<String>,\n\n #[clap(short = 's', long = 'solid')]\n /// Path where count is write in solid format\n pub solid: Option<String>,\n\n #[clap(short = 'S', long = 'spectrum')]\n /// Path where kmer spectrum is write\n pub spectrum: Option<String>,\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<String>,\n\n #[clap(short = 's', long = 'solid')]\n /// Path where count is write in solid format\n pub solid: Option<String>,\n\n #[clap(short = 'S', long = 'spectrum')]\n /// Path where kmer spectrum is write\n pub spectrum: Option<String>,\n\n #[clap(short = 'b', long = 'bin')]\n /// Path where count is write in bin\n pub bin: Option<String>,\n}\n\nuse crate::error::{Cli, Error};\nuse Cli::*;\n\npub fn check_count_param(params: SubCommandCount) -> Result<SubCommandCount, Error> {\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<SubCommandDump, Error> {\n if ![&params.csv, &params.solid, &params.spectrum, &params.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<log::Level> {\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 <pmarijon@mpi-inf.mpg.de>\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<u8, Lsb0>,\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<u8, Lsb0> {\n &self.solid\n }\n\n /// Serialize counter in given [std::io::Write]\n pub fn serialize<W>(&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: R) -> Result<Self>\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
git clone https://github.com/natir/br.git
git clone https://github.com/natir/pcon
git clone https://github.com/natir/yacrd
git clone https://github.com/natir/rasusa
git clone https://github.com/natir/fpa
git clone https://github.com/natir/kmrf

rm -f RustBioGPT-train.csv && for i in `find . -name "*.rs"`;do paste -d "," <(echo $i|perl -pe "s/\.\/(\w+)\/.+/\"\1\"/g") <(echo $i|perl -pe "s/(.+)/\"\1\"/g") <(perl -pe "s/\n/\\\n/g" $i|perl -pe s"/\"/\'/g" |perl -pe "s/(.+)/\"\1\"/g") <(echo "mit"|perl -pe "s/(.+)/\"\1\"/g") >> RustBioGPT-train.csv; done

sed -i '1i "repo_name","path","content","license"' RustBioGPT-train.csv
Downloads last month
4
Edit dataset card