rsomics-fasta-utils 0.1.1

FASTA utility toolkit — count, chroms, len, revcomp, rename, tab, wrap, unique, convert, and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::path::PathBuf;

use clap::{Parser, Subcommand};
use rsomics_common::{CommonFlags, Result, RsomicsError, Tool, ToolMeta};
use rsomics_help::{Example, HelpSpec, Origin};

use rsomics_fasta_utils::ops;

pub const META: ToolMeta = ToolMeta {
    name: env!("CARGO_PKG_NAME"),
    version: env!("CARGO_PKG_VERSION"),
};

#[derive(Parser)]
#[command(
    name = "rsomics-fasta-utils",
    version,
    about = "FASTA utility toolkit",
    disable_help_flag = true
)]
pub struct Cli {
    #[command(subcommand)]
    command: Command,
    #[command(flatten)]
    pub common: CommonFlags,
}

#[derive(Subcommand)]
enum Command {
    /// List unique sequence names (chromosomes)
    Chroms {
        input: PathBuf,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Nucleotide composition
    Composition { input: PathBuf },
    /// Count sequences
    Count { input: PathBuf },
    /// Deduplicate sequences (by sequence or name)
    Dedup {
        input: PathBuf,
        #[arg(short = 'n', long)]
        by_name: bool,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Extract sequences by name list
    Extract {
        input: PathBuf,
        #[arg(short = 'l', long)]
        list: PathBuf,
        #[arg(long)]
        exclude: bool,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Filter sequences by length
    Filter {
        input: PathBuf,
        #[arg(short = 'm', long, default_value_t = 0)]
        min_len: usize,
        #[arg(short = 'M', long, default_value_t = 0)]
        max_len: usize,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// GC content per sequence
    GcContent {
        input: PathBuf,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Filter records by name regex
    Grep {
        input: PathBuf,
        #[arg(short = 'p', long)]
        pattern: String,
        #[arg(long)]
        invert_match: bool,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Output the first N sequences
    Head {
        input: PathBuf,
        #[arg(short = 'n', long, default_value_t = 10)]
        num: u64,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Count k-mer frequencies
    Kmers {
        input: PathBuf,
        #[arg(short = 'k', default_value_t = 21)]
        k: usize,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Sequence lengths
    Len {
        input: PathBuf,
        #[arg(long)]
        tab: bool,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Rename sequences with prefix
    Rename {
        input: PathBuf,
        #[arg(short = 'p', long)]
        prefix: String,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Reverse complement
    Revcomp {
        input: PathBuf,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Random subsample of sequences
    Sample {
        input: PathBuf,
        #[arg(short = 'p', long, default_value_t = 0.1)]
        proportion: f64,
        #[arg(long, default_value_t = 42)]
        seed: u64,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Randomly shuffle sequence order
    Shuffle {
        input: PathBuf,
        #[arg(long, default_value_t = 42)]
        seed: u64,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Sort sequences by name or length
    Sort {
        input: PathBuf,
        #[arg(short = 'l', long)]
        by_length: bool,
        #[arg(short = 'L', long)]
        by_length_desc: bool,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Split into multiple files by sequence count
    Split {
        input: PathBuf,
        #[arg(long, default_value_t = 1000)]
        seqs_per_file: u64,
        #[arg(long, default_value = "split_")]
        prefix: String,
    },
    /// Convert to tab-separated (name\tsequence)
    Tab {
        input: PathBuf,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Convert to BED (one interval per sequence)
    ToBed {
        input: PathBuf,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Convert FASTA to FASTQ (with dummy quality)
    ToFastq {
        input: PathBuf,
        #[arg(long, default_value_t = b'I')]
        qual_char: u8,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Deduplicate sequences (keep unique only)
    Unique {
        input: PathBuf,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Convert to uppercase
    Upper {
        input: PathBuf,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Sliding-window GC statistics
    Window {
        input: PathBuf,
        #[arg(short = 'w', long, default_value_t = 10000)]
        window: usize,
        #[arg(short = 's', long, default_value_t = 5000)]
        step: usize,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
    /// Re-wrap sequences to fixed line width
    Wrap {
        input: PathBuf,
        #[arg(short = 'w', long, default_value_t = 80)]
        width: usize,
        #[arg(short = 'o', long, default_value = "-")]
        output: String,
    },
}

fn open_output(path: &str, json: bool) -> Result<Box<dyn std::io::Write>> {
    if path == "-" {
        if json {
            Ok(Box::new(std::io::sink()))
        } else {
            Ok(Box::new(std::io::stdout().lock()))
        }
    } else {
        Ok(Box::new(
            std::fs::File::create(path).map_err(RsomicsError::Io)?,
        ))
    }
}

impl Tool for Cli {
    fn meta() -> ToolMeta {
        META
    }

    fn common(&self) -> &CommonFlags {
        &self.common
    }

    #[allow(clippy::too_many_lines)]
    fn execute(self) -> Result<()> {
        let json = self.common.json;
        match self.command {
            Command::Chroms { input, output } => {
                let mut out = open_output(&output, json)?;
                ops::chroms::fasta_chroms(&input, &mut out)?;
            }
            Command::Composition { input } => {
                let c = ops::composition::fasta_composition(&input)?;
                if !json {
                    println!("A\t{}", c.a);
                    println!("C\t{}", c.c);
                    println!("G\t{}", c.g);
                    println!("T\t{}", c.t);
                    println!("N\t{}", c.n);
                    println!("other\t{}", c.other);
                    println!("total\t{}", c.total);
                }
            }
            Command::Count { input } => {
                let n = ops::count::count(&input)?;
                if !json {
                    println!("{n}");
                }
            }
            Command::Dedup {
                input,
                by_name,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::dedup::dedup_fasta(&input, &mut out, by_name)?;
            }
            Command::Extract {
                input,
                list,
                exclude,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::extract::extract_fasta(&input, &list, &mut out, exclude)?;
            }
            Command::Filter {
                input,
                min_len,
                max_len,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::filter::filter(&input, min_len, max_len, &mut out)?;
            }
            Command::GcContent { input, output } => {
                let mut out = open_output(&output, json)?;
                ops::gc_content::fasta_gc_content(&input, &mut out)?;
            }
            Command::Grep {
                input,
                pattern,
                invert_match,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::grep::grep(&input, &pattern, invert_match, &mut out)?;
            }
            Command::Head { input, num, output } => {
                let mut out = open_output(&output, json)?;
                ops::head::head(&input, num, &mut out)?;
            }
            Command::Kmers { input, k, output } => {
                let mut out = open_output(&output, json)?;
                ops::kmers::count_kmers(&input, &mut out, k)?;
            }
            Command::Len { input, tab, output } => {
                let mut out = open_output(&output, json)?;
                ops::len::lengths(&input, tab, &mut out)?;
            }
            Command::Rename {
                input,
                prefix,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::rename::rename(&input, &prefix, &mut out)?;
            }
            Command::Revcomp { input, output } => {
                let mut out = open_output(&output, json)?;
                ops::revcomp::revcomp(&input, &mut out)?;
            }
            Command::Sample {
                input,
                proportion,
                seed,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::sample::sample(&input, proportion, seed, &mut out)?;
            }
            Command::Shuffle {
                input,
                seed,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::shuffle::shuffle_fasta(&input, &mut out, seed)?;
            }
            Command::Sort {
                input,
                by_length,
                by_length_desc,
                output,
            } => {
                let key = if by_length_desc {
                    ops::sort::SortKey::LengthDesc
                } else if by_length {
                    ops::sort::SortKey::Length
                } else {
                    ops::sort::SortKey::Name
                };
                let mut out = open_output(&output, json)?;
                ops::sort::sort(&input, key, &mut out)?;
            }
            Command::Split {
                input,
                seqs_per_file,
                prefix,
            } => {
                let n = ops::split::split_by_count(&input, seqs_per_file, &prefix)?;
                eprintln!("{n} files written");
            }
            Command::Tab { input, output } => {
                let mut out = open_output(&output, json)?;
                ops::tab::fasta_to_tab(&input, &mut out)?;
            }
            Command::ToBed { input, output } => {
                let mut out = open_output(&output, json)?;
                ops::to_bed::fasta_to_bed(&input, &mut out)?;
            }
            Command::ToFastq {
                input,
                qual_char,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::to_fastq::convert(&input, qual_char, &mut out)?;
            }
            Command::Unique { input, output } => {
                let mut out = open_output(&output, json)?;
                let (total, unique) = ops::unique::unique_fasta(&input, &mut out)?;
                eprintln!("{total} total, {unique} unique");
            }
            Command::Upper { input, output } => {
                let mut out = open_output(&output, json)?;
                ops::upper::uppercase(&input, &mut out)?;
            }
            Command::Window {
                input,
                window,
                step,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::window::window_stats(&input, &mut out, window, step)?;
            }
            Command::Wrap {
                input,
                width,
                output,
            } => {
                let mut out = open_output(&output, json)?;
                ops::wrap::fasta_wrap(&input, &mut out, width)?;
            }
        }
        Ok(())
    }
}

pub static HELP: HelpSpec = HelpSpec {
    name: env!("CARGO_PKG_NAME"),
    version: env!("CARGO_PKG_VERSION"),
    tagline: "FASTA utility toolkit — count, chroms, len, revcomp, rename, tab, wrap, unique, convert, and more.",
    origin: Some(Origin {
        upstream: "seqkit / seqtk",
        upstream_license: "MIT",
        our_license: "MIT OR Apache-2.0",
        paper_doi: None,
    }),
    usage_lines: &["<COMMAND> [OPTIONS] <input>"],
    sections: &[],
    examples: &[
        Example {
            description: "Count sequences",
            command: "rsomics-fasta-utils count genome.fa",
        },
        Example {
            description: "Reverse complement all sequences",
            command: "rsomics-fasta-utils revcomp genome.fa -o rc.fa",
        },
        Example {
            description: "Subsample 10% of sequences",
            command: "rsomics-fasta-utils sample -p 0.1 genome.fa -o subset.fa",
        },
    ],
    json_result_schema_doc: None,
};

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    #[test]
    fn cli_debug_assert() {
        Cli::command().debug_assert();
    }
}