fastars 0.1.0

Ultra-fast QC and trimming for short and long reads
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! Split writer for dividing FASTQ output into multiple files.
//!
//! This module provides writers that can split output into multiple files
//! either by file count or by line count.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

use super::{CompressionType, FastqWriter, OwnedRecord};
use crate::cli::{SplitConfig, SplitMode};

// ============================================================================
// Single-End Split Writer
// ============================================================================

/// Writer that splits single-end output into multiple files.
///
/// Files are named with a numeric suffix: base_0001.fastq.gz, base_0002.fastq.gz, etc.
pub struct SplitWriter {
    /// Base path for output files (without extension).
    base_path: PathBuf,
    /// Split configuration.
    config: SplitConfig,
    /// Compression type for output files.
    compression: CompressionType,
    /// Current file index (0-based).
    current_file_idx: usize,
    /// Current writer.
    current_writer: Option<FastqWriter>,
    /// Total records written to current file.
    records_in_current_file: usize,
    /// Total records written overall.
    total_records_written: usize,
    /// Records per file (for ByFile mode).
    records_per_file: Option<usize>,
}

impl SplitWriter {
    /// Create a new split writer.
    ///
    /// # Arguments
    /// - `base_path`: Base path for output files (without numeric suffix)
    /// - `config`: Split configuration
    /// - `total_records`: Total number of records (required for ByFile mode)
    ///
    /// For ByFile mode, `total_records` is used to calculate records per file.
    /// For ByLines mode, it's not used (pass None).
    pub fn new(
        base_path: impl AsRef<Path>,
        config: SplitConfig,
        total_records: Option<usize>,
    ) -> Result<Self> {
        let base_path = base_path.as_ref().to_path_buf();
        let compression = CompressionType::from_path(&base_path);

        // Calculate records per file for ByFile mode
        let records_per_file = match config.mode {
            SplitMode::ByFile(n_files) => {
                let total = total_records.ok_or_else(|| {
                    anyhow::anyhow!("total_records required for ByFile split mode")
                })?;
                Some((total + n_files - 1) / n_files) // Ceiling division
            }
            SplitMode::ByLines(_) => None,
        };

        Ok(Self {
            base_path,
            config,
            compression,
            current_file_idx: 0,
            current_writer: None,
            records_in_current_file: 0,
            total_records_written: 0,
            records_per_file,
        })
    }

    /// Write a single record, handling file switching as needed.
    pub fn write_record(&mut self, record: &OwnedRecord) -> Result<()> {
        // Check if we need to switch to a new file
        if self.should_switch_file() {
            self.switch_to_next_file()?;
        }

        // Ensure we have a writer
        if self.current_writer.is_none() {
            self.switch_to_next_file()?;
        }

        // Write the record
        if let Some(writer) = &mut self.current_writer {
            writer
                .write_record(record)
                .context("Failed to write record")?;
        }

        self.records_in_current_file += 1;
        self.total_records_written += 1;

        Ok(())
    }

    /// Write a batch of records.
    pub fn write_batch(&mut self, records: &[OwnedRecord]) -> Result<()> {
        for record in records {
            self.write_record(record)?;
        }
        Ok(())
    }

    /// Check if we should switch to a new file.
    fn should_switch_file(&self) -> bool {
        match self.config.mode {
            SplitMode::ByFile(_) => {
                if let Some(per_file) = self.records_per_file {
                    self.records_in_current_file >= per_file
                } else {
                    false
                }
            }
            SplitMode::ByLines(lines) => {
                let records_per_file = lines / 4;
                self.records_in_current_file >= records_per_file
            }
        }
    }

    /// Switch to the next output file.
    fn switch_to_next_file(&mut self) -> Result<()> {
        // Flush and close current writer
        if let Some(mut writer) = self.current_writer.take() {
            writer.flush()?;
        }

        // Generate the new file path
        let file_path = self.generate_file_path(self.current_file_idx);

        // Create a new writer
        let writer = FastqWriter::new(&file_path, self.compression)
            .with_context(|| format!("Failed to create split file: {}", file_path.display()))?;

        self.current_writer = Some(writer);
        self.current_file_idx += 1;
        self.records_in_current_file = 0;

        Ok(())
    }

    /// Generate the file path for a given file index.
    fn generate_file_path(&self, idx: usize) -> PathBuf {
        let suffix = format!("{:0width$}", idx + 1, width = self.config.prefix_digits);

        // Extract base name and parent directory
        let parent = self.base_path.parent().unwrap_or(Path::new(""));
        let stem = self
            .base_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("output");

        // Determine extension based on compression type
        let extension = match self.compression {
            CompressionType::Gzip | CompressionType::ParallelGzip => "fastq.gz",
            CompressionType::None => "fastq",
        };

        parent.join(format!("{}_{}.{}", stem, suffix, extension))
    }

    /// Finalize all files.
    pub fn finish(&mut self) -> Result<()> {
        if let Some(mut writer) = self.current_writer.take() {
            writer.flush()?;
        }
        Ok(())
    }

    /// Get the total number of records written.
    pub fn total_records_written(&self) -> usize {
        self.total_records_written
    }

    /// Get the number of output files created.
    pub fn num_files_created(&self) -> usize {
        self.current_file_idx
    }

    /// Get all created file paths.
    pub fn get_output_files(&self) -> Vec<PathBuf> {
        (0..self.current_file_idx)
            .map(|idx| self.generate_file_path(idx))
            .collect()
    }
}

impl Drop for SplitWriter {
    fn drop(&mut self) {
        let _ = self.finish();
    }
}

// ============================================================================
// Paired-End Split Writer
// ============================================================================

/// Writer that splits paired-end output into multiple file pairs.
///
/// Both R1 and R2 files are split synchronously with the same record counts.
/// Files are named: base_0001.R1.fastq.gz, base_0001.R2.fastq.gz, etc.
pub struct PairedSplitWriter {
    /// Base path for output files.
    base_path: PathBuf,
    /// Split configuration.
    config: SplitConfig,
    /// Compression type.
    compression: CompressionType,
    /// Current file index.
    current_file_idx: usize,
    /// Current R1 writer.
    current_r1_writer: Option<FastqWriter>,
    /// Current R2 writer.
    current_r2_writer: Option<FastqWriter>,
    /// Records in current file.
    records_in_current_file: usize,
    /// Total records written.
    total_records_written: usize,
    /// Records per file (for ByFile mode).
    records_per_file: Option<usize>,
}

impl PairedSplitWriter {
    /// Create a new paired split writer.
    pub fn new(
        base_path: impl AsRef<Path>,
        config: SplitConfig,
        total_records: Option<usize>,
    ) -> Result<Self> {
        let base_path = base_path.as_ref().to_path_buf();
        let compression = CompressionType::from_path(&base_path);

        let records_per_file = match config.mode {
            SplitMode::ByFile(n_files) => {
                let total = total_records.ok_or_else(|| {
                    anyhow::anyhow!("total_records required for ByFile split mode")
                })?;
                Some((total + n_files - 1) / n_files)
            }
            SplitMode::ByLines(_) => None,
        };

        Ok(Self {
            base_path,
            config,
            compression,
            current_file_idx: 0,
            current_r1_writer: None,
            current_r2_writer: None,
            records_in_current_file: 0,
            total_records_written: 0,
            records_per_file,
        })
    }

    /// Write a pair of records.
    pub fn write_pair(&mut self, r1: &OwnedRecord, r2: &OwnedRecord) -> Result<()> {
        // Check if we need to switch files
        if self.should_switch_file() {
            self.switch_to_next_file()?;
        }

        // Ensure we have writers
        if self.current_r1_writer.is_none() || self.current_r2_writer.is_none() {
            self.switch_to_next_file()?;
        }

        // Write both records
        if let (Some(r1_writer), Some(r2_writer)) =
            (&mut self.current_r1_writer, &mut self.current_r2_writer)
        {
            r1_writer
                .write_record(r1)
                .context("Failed to write R1 record")?;
            r2_writer
                .write_record(r2)
                .context("Failed to write R2 record")?;
        }

        self.records_in_current_file += 1;
        self.total_records_written += 1;

        Ok(())
    }

    /// Write a batch of paired records.
    pub fn write_batch(&mut self, pairs: &[(OwnedRecord, OwnedRecord)]) -> Result<()> {
        for (r1, r2) in pairs {
            self.write_pair(r1, r2)?;
        }
        Ok(())
    }

    /// Check if we should switch files.
    fn should_switch_file(&self) -> bool {
        match self.config.mode {
            SplitMode::ByFile(_) => {
                if let Some(per_file) = self.records_per_file {
                    self.records_in_current_file >= per_file
                } else {
                    false
                }
            }
            SplitMode::ByLines(lines) => {
                let records_per_file = lines / 4;
                self.records_in_current_file >= records_per_file
            }
        }
    }

    /// Switch to the next output file pair.
    fn switch_to_next_file(&mut self) -> Result<()> {
        // Flush and close current writers
        if let Some(mut writer) = self.current_r1_writer.take() {
            writer.flush()?;
        }
        if let Some(mut writer) = self.current_r2_writer.take() {
            writer.flush()?;
        }

        // Generate new file paths
        let (r1_path, r2_path) = self.generate_file_paths(self.current_file_idx);

        // Create new writers
        let r1_writer = FastqWriter::new(&r1_path, self.compression)
            .with_context(|| format!("Failed to create split file: {}", r1_path.display()))?;
        let r2_writer = FastqWriter::new(&r2_path, self.compression)
            .with_context(|| format!("Failed to create split file: {}", r2_path.display()))?;

        self.current_r1_writer = Some(r1_writer);
        self.current_r2_writer = Some(r2_writer);
        self.current_file_idx += 1;
        self.records_in_current_file = 0;

        Ok(())
    }

    /// Generate file paths for R1 and R2.
    fn generate_file_paths(&self, idx: usize) -> (PathBuf, PathBuf) {
        let suffix = format!("{:0width$}", idx + 1, width = self.config.prefix_digits);

        let parent = self.base_path.parent().unwrap_or(Path::new(""));
        let stem = self
            .base_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("output");

        let extension = match self.compression {
            CompressionType::Gzip | CompressionType::ParallelGzip => "fastq.gz",
            CompressionType::None => "fastq",
        };

        let r1_path = parent.join(format!("{}_{}.R1.{}", stem, suffix, extension));
        let r2_path = parent.join(format!("{}_{}.R2.{}", stem, suffix, extension));

        (r1_path, r2_path)
    }

    /// Finalize all files.
    pub fn finish(&mut self) -> Result<()> {
        if let Some(mut writer) = self.current_r1_writer.take() {
            writer.flush()?;
        }
        if let Some(mut writer) = self.current_r2_writer.take() {
            writer.flush()?;
        }
        Ok(())
    }

    /// Get the total number of records written.
    pub fn total_records_written(&self) -> usize {
        self.total_records_written
    }

    /// Get the number of output file pairs created.
    pub fn num_files_created(&self) -> usize {
        self.current_file_idx
    }

    /// Get all created file paths (R1 and R2).
    pub fn get_output_files(&self) -> Vec<PathBuf> {
        let mut files = Vec::new();
        for idx in 0..self.current_file_idx {
            let (r1, r2) = self.generate_file_paths(idx);
            files.push(r1);
            files.push(r2);
        }
        files
    }
}

impl Drop for PairedSplitWriter {
    fn drop(&mut self) {
        let _ = self.finish();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::SplitMode;
    use tempfile::tempdir;

    fn make_record(name: &str, seq: &str) -> OwnedRecord {
        let qual = vec![b'I'; seq.len()];
        OwnedRecord::new(name.as_bytes().to_vec(), seq.as_bytes().to_vec(), qual)
    }

    #[test]
    fn test_split_writer_by_file() {
        let dir = tempdir().unwrap();
        let base_path = dir.path().join("output");

        let config = SplitConfig {
            mode: SplitMode::ByFile(2),
            prefix_digits: 4,
        };

        let mut writer = SplitWriter::new(&base_path, config, Some(10)).unwrap();

        // Write 10 records
        for i in 0..10 {
            let record = make_record(&format!("read{}", i), "ACGTACGTACGT");
            writer.write_record(&record).unwrap();
        }

        writer.finish().unwrap();

        assert_eq!(writer.num_files_created(), 2);
        assert_eq!(writer.total_records_written(), 10);

        // Check that files exist (no .gz extension since base_path has no extension)
        assert!(dir.path().join("output_0001.fastq").exists());
        assert!(dir.path().join("output_0002.fastq").exists());
    }

    #[test]
    fn test_split_writer_by_lines() {
        let dir = tempdir().unwrap();
        let base_path = dir.path().join("output");

        let config = SplitConfig {
            mode: SplitMode::ByLines(8), // 2 records per file
            prefix_digits: 3,
        };

        let mut writer = SplitWriter::new(&base_path, config, None).unwrap();

        // Write 6 records
        for i in 0..6 {
            let record = make_record(&format!("read{}", i), "ACGTACGTACGT");
            writer.write_record(&record).unwrap();
        }

        writer.finish().unwrap();

        assert_eq!(writer.num_files_created(), 3);
        assert_eq!(writer.total_records_written(), 6);

        // Check file naming (no .gz extension since base_path has no extension)
        assert!(dir.path().join("output_001.fastq").exists());
        assert!(dir.path().join("output_002.fastq").exists());
        assert!(dir.path().join("output_003.fastq").exists());
    }

    #[test]
    fn test_paired_split_writer() {
        let dir = tempdir().unwrap();
        let base_path = dir.path().join("output");

        let config = SplitConfig {
            mode: SplitMode::ByFile(2),
            prefix_digits: 4,
        };

        let mut writer = PairedSplitWriter::new(&base_path, config, Some(6)).unwrap();

        // Write 6 pairs
        for i in 0..6 {
            let r1 = make_record(&format!("read{}/1", i), "ACGTACGTACGT");
            let r2 = make_record(&format!("read{}/2", i), "TGCATGCATGCA");
            writer.write_pair(&r1, &r2).unwrap();
        }

        writer.finish().unwrap();

        assert_eq!(writer.num_files_created(), 2);
        assert_eq!(writer.total_records_written(), 6);

        // Check that both R1 and R2 files exist (no .gz extension since base_path has no extension)
        assert!(dir.path().join("output_0001.R1.fastq").exists());
        assert!(dir.path().join("output_0001.R2.fastq").exists());
        assert!(dir.path().join("output_0002.R1.fastq").exists());
        assert!(dir.path().join("output_0002.R2.fastq").exists());
    }

    #[test]
    fn test_write_batch() {
        let dir = tempdir().unwrap();
        let base_path = dir.path().join("output");

        let config = SplitConfig {
            mode: SplitMode::ByLines(8),
            prefix_digits: 4,
        };

        let mut writer = SplitWriter::new(&base_path, config, None).unwrap();

        let records: Vec<_> = (0..4)
            .map(|i| make_record(&format!("read{}", i), "ACGTACGT"))
            .collect();

        writer.write_batch(&records).unwrap();
        writer.finish().unwrap();

        assert_eq!(writer.total_records_written(), 4);
    }
}