seqtk_rs/
subsample.rs

1use crate::io_utils::{FaReader, FqReader, FxWriter};
2use crate::sub_cli::SampleArgs;
3use rand::rngs::StdRng;
4use rand::{Rng, SeedableRng};
5
6/// Parses FASTQ/A file and sampling according to the seed and fraction.
7/// Outputs the results to [`std::io::stdout()`].
8///
9/// # Arguments
10///
11/// Check the arguments by `--help`
12///
13/// # Errors
14///
15/// Return an error if the operation cannot be completed.
16pub fn subsample_fastx(
17    fx_path: &str,
18    sparas: &SampleArgs,
19    is_fasta: bool,
20) -> Result<(), std::io::Error> {
21    let rand_seed = sparas.random_seed.unwrap_or(11) as u64;
22    let sampling_frac = sparas.sample_fraction.unwrap_or(1.0);
23    let mut rng = StdRng::seed_from_u64(rand_seed);
24
25    if is_fasta {
26        let fa_iter = FaReader::new(fx_path)?;
27        let mut fx_writer = FxWriter::new(is_fasta);
28        for record in fa_iter.records() {
29            if rng.random::<f64>() <= sampling_frac {
30                let read = record.unwrap();
31                fx_writer.write(read.id(), read.seq(), None, &[])?;
32            }
33        }
34    } else {
35        let fq_iter = FqReader::new(fx_path)?;
36        let mut fx_writer = FxWriter::new(is_fasta);
37        for record in fq_iter.records() {
38            if rng.random::<f64>() <= sampling_frac {
39                let read = record.unwrap();
40                fx_writer.write(read.id(), read.seq(), read.desc(), read.qual())?;
41            }
42        }
43    }
44    Ok(())
45}