segul 0.23.2

An ultrafast and memory-efficient tool for phylogenomics
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
530
531
532
//! Add sequence to a file.
//!
//! Support adding many sequences at once.
//! The destination file and the sequences can
//! be in different formats, but the file name,
//! excluding the extension, (file stem) must be the same.
//! Input sequences can also be an alignment files.
//! However, SEGUL will output unaligned sequences
//! by excluding the gaps and missing data
//! from the the resulting file.
use std::{
    collections::{HashMap, HashSet},
    path::{Path, PathBuf},
    sync::{Mutex, RwLock},
};

use colored::Colorize;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};

use crate::{
    core::OutputPrint,
    helper::{
        files,
        sequence::SeqParser,
        types::{DataType, Header, InputFmt, OutputFmt, SeqMatrix},
        utils,
    },
    writer::sequences::SeqWriter,
};

pub struct SequenceAddition<'a> {
    /// Input sequence files to be added.
    input_files: &'a [PathBuf],
    /// Input sequence file format.
    input_fmt: &'a InputFmt,
    /// Data type of the sequences.
    datatype: &'a DataType,
    /// Destination file to add the sequences.
    output: &'a Path,
    /// Output file format.
    output_fmt: &'a OutputFmt,
    /// Include or not include skipped files.
    /// If true, skipped files will be written to the output.
    /// in the same format as the output.
    added_only: bool,
}

impl Default for SequenceAddition<'_> {
    fn default() -> Self {
        Self {
            input_files: &[],
            input_fmt: &InputFmt::Auto,
            datatype: &DataType::Dna,
            output: Path::new("output"),
            output_fmt: &OutputFmt::Fasta,
            added_only: false,
        }
    }
}

impl OutputPrint for SequenceAddition<'_> {}

impl<'a> SequenceAddition<'a> {
    pub fn new(
        input_files: &'a [PathBuf],
        input_fmt: &'a InputFmt,
        datatype: &'a DataType,
        output: &'a Path,
        output_fmt: &'a OutputFmt,
        added_only: bool,
    ) -> Self {
        Self {
            input_files,
            input_fmt,
            datatype,
            output,
            output_fmt,
            added_only,
        }
    }

    pub fn add(&self, dest_file: &[PathBuf], dest_fmt: &InputFmt) {
        let spinner = utils::set_spinner();
        spinner.set_message("Adding sequences...");
        let counter = self.add_sequences(dest_file, dest_fmt);
        spinner.finish_with_message("Finished adding sequences.\n");
        let mut total_written = 0;
        if !self.added_only {
            let skipped_files = self.get_skipped_files(&counter, dest_file);
            total_written = self.write_skip_files(&skipped_files);
        }
        self.print_multi_sequence_info(&counter, total_written);
    }

    pub fn add_single(&self, dest_file: &Path, include_filename: bool) {
        let spinner = utils::set_spinner();
        spinner.set_message("Adding sequences...");
        let to_matrix = Mutex::new(SeqMatrix::new());
        let counter = Mutex::new(SingleSequenceCounter::new());
        self.input_files.par_iter().for_each(|input| {
            let input_matrix = self.get_matrix(input, self.input_fmt);
            input_matrix.iter().for_each(|(name, sequence)| {
                let sequence_name = if include_filename {
                    let input_stem = self.get_file_stem(input);
                    format!("{}_{}", name, input_stem)
                } else {
                    name.to_string()
                };
                let mut to_matrix = to_matrix.lock().expect("Failed to lock to_matrix.");
                if to_matrix.contains_key(&sequence_name) {
                    counter.lock().expect("Failed to lock counter.").skip();
                } else {
                    to_matrix.insert(sequence_name, sequence.to_string());
                    counter
                        .lock()
                        .expect("Failed to lock counter.")
                        .add(sequence);
                }
            });
        });
        spinner.finish_with_message("Finished adding sequences.\n");
        let mut to_matrix = to_matrix.into_inner().expect("Failed to get to_matrix.");
        self.clean_missing_data(&mut to_matrix);
        if to_matrix.is_empty() {
            log::warn!("No sequences to add. Exiting...");
            return;
        }
        self.write_output(&to_matrix, dest_file);
        self.print_single_sequence_info(&counter.into_inner().expect("Failed to get counter."));
    }

    fn add_sequences(&self, dest_file: &[PathBuf], dest_fmt: &InputFmt) -> SequenceCounter {
        let dest_collection = self.create_dest_library(dest_file);
        let counter = Mutex::new(SequenceCounter::new(
            self.input_files.len(),
            dest_file.len(),
        ));
        self.input_files.par_iter().for_each(|input| {
            let input_stem = self.get_file_stem(input);
            match dest_collection.get(&input_stem) {
                Some(dest_file) => {
                    let input_matrix = self.get_matrix(input, self.input_fmt);
                    let dest_matrix =
                        self.create_final_matrix(input_matrix, dest_file, dest_fmt, &counter);
                    match dest_matrix {
                        Some(matrix) => {
                            self.write_output(&matrix, dest_file);
                            counter
                                .lock()
                                .expect("Failed to lock counter.")
                                .add_file(&input_stem);
                        }
                        None => {
                            counter
                                .lock()
                                .expect("Failed to lock counter.")
                                .skip_file(&input_stem);
                        }
                    }
                }
                None => {
                    log::warn!("No destination file found for {}. Skipping...", &input_stem);
                    counter
                        .lock()
                        .expect("Failed to lock counter.")
                        .skip_file(&input_stem);
                }
            };
        });
        let mut counter = counter.into_inner().expect("Failed to get counter.");
        counter.calculate_mean();
        counter
    }

    fn get_skipped_files(&self, counter: &SequenceCounter, dest_files: &[PathBuf]) -> Vec<PathBuf> {
        dest_files
            .iter()
            .filter(|file| !counter.added_files.contains(&self.get_file_stem(file)))
            .cloned()
            .collect()
    }

    fn write_skip_files(&self, skipped_files: &[PathBuf]) -> usize {
        let counter = RwLock::new(0);
        skipped_files.par_iter().for_each(|file| {
            let final_matrix = self.get_matrix(file, self.input_fmt);
            self.write_output(&final_matrix, file);
            *counter.write().expect("Failed to write counter.") += 1;
        });
        let counter = *counter.read().expect("Failed to read counter.");
        counter
    }

    fn create_final_matrix(
        &self,
        input_matrix: SeqMatrix,
        dest_file: &Path,
        dest_fmt: &InputFmt,
        counter: &Mutex<SequenceCounter>,
    ) -> Option<SeqMatrix> {
        let mut dest_matrix = self.get_matrix(dest_file, dest_fmt);
        let mut added_count = 0;
        input_matrix.iter().for_each(|(name, sequence)| {
            if dest_matrix.contains_key(name) {
                counter
                    .lock()
                    .expect("Failed to lock counter.")
                    .skip_sequence(sequence);
            } else {
                dest_matrix.insert(name.to_string(), sequence.to_string());
                counter
                    .lock()
                    .expect("Failed to lock counter.")
                    .add_sequence(sequence);
                added_count += 1;
            }
        });
        if added_count > 0 {
            self.clean_missing_data(&mut dest_matrix);
            Some(dest_matrix)
        } else {
            None
        }
    }

    fn create_dest_library(&self, dest_file: &[PathBuf]) -> HashMap<String, PathBuf> {
        let dest_collection: Mutex<HashMap<String, PathBuf>> = Mutex::new(HashMap::new());
        dest_file.par_iter().for_each(|file| {
            let file_stem = self.get_file_stem(file);
            let mut dest_collection = dest_collection
                .lock()
                .expect("Failed to lock dest_collection.");
            dest_collection.insert(file_stem, file.clone());
        });
        dest_collection
            .into_inner()
            .expect("Failed to get dest_collection.")
    }

    fn get_file_stem(&self, file: &Path) -> String {
        file.file_stem()
            .expect("Failed to get file stem.")
            .to_string_lossy()
            .to_string()
    }

    fn get_matrix(&self, input: &Path, input_fmt: &InputFmt) -> SeqMatrix {
        let (seq, _) = SeqParser::new(input, self.datatype).parse(input_fmt);
        seq
    }

    fn clean_missing_data(&self, matrix: &mut SeqMatrix) {
        matrix.values_mut().for_each(|seq| {
            *seq = seq.replace(['?', '-'], "");
        });
    }

    fn write_output(&self, final_matrix: &SeqMatrix, file: &Path) {
        let output_path = files::create_output_fname(self.output, file, self.output_fmt);
        let mut header: Header = Header::new();
        header.from_seq_matrix(final_matrix, false);
        let mut writer = SeqWriter::new(&output_path, final_matrix, &header);
        writer
            .write_sequence(self.output_fmt)
            .expect("Failed to write sequences.");
    }

    fn print_multi_sequence_info(&self, counter: &SequenceCounter, total_written: usize) {
        self.print_output();
        log::info!("\n{}", "File Summary".yellow());
        log::info!("{:18}: {}", "Total input files", counter.total_input_files);
        log::info!(
            "{:18}: {}",
            "Total dest files",
            counter.total_destination_files
        );
        log::info!("{:18}: {}", "Files skipped", counter.skipped_file_counts);
        log::info!("{:18}: {}", "Files added", counter.total_file_added);
        log::info!(
            "{:18}: {}\n",
            "Files written",
            counter.total_file_added + total_written
        );
        log::info!("{}", "Sequences Summary".yellow());
        log::info!(
            "{:18}: {}",
            "Total sequences",
            counter.total_sequence_counts
        );
        log::info!("{:18}: {}", "Sequence skipped", counter.skipped_sequences);
        log::info!("{:18}: {}", "Sequence added", counter.total_sequence_added);
        log::info!("{:18}: {:.2}", "Mean length", counter.mean_length);
        if counter.total_sequence_added > 0 {
            log::info!("{:18}: {:.2}", "Mean added", counter.mean_added_sequences);
            log::info!(
                "{:18}: {:.2}",
                "Mean added length",
                counter.mean_added_length
            );
        }
    }

    fn print_single_sequence_info(&self, counter: &SingleSequenceCounter) {
        self.print_output();
        log::info!("\n{}", "File Summary".yellow());
        log::info!("{:18}: {}", "Total input files", self.input_files.len());
        log::info!(
            "{:18}: {}",
            "Files skipped",
            counter.skipped_sequence_counts
        );
        log::info!("{:18}: {}", "Files added", counter.sequence_counts);
        log::info!("{:18}: {:.2}", "Mean length", counter.mean_length_added);
    }

    fn print_output(&self) {
        log::info!("{}", "Output".yellow());
        log::info!("{:18}: {}", "Directory", self.output.display());
        self.print_output_fmt(self.output_fmt);
    }
}

struct SingleSequenceCounter {
    /// Total sequence added
    sequence_counts: usize,
    /// Skipped sequence counts
    skipped_sequence_counts: usize,
    /// Mean length of the sequence
    mean_length_added: f64,
    /// Total length of the sequence
    total_length_added: usize,
}

impl SingleSequenceCounter {
    fn new() -> Self {
        Self {
            sequence_counts: 0,
            skipped_sequence_counts: 0,
            mean_length_added: 0.0,
            total_length_added: 0,
        }
    }

    fn add(&mut self, sequence: &str) {
        self.sequence_counts += 1;
        self.total_length_added += sequence.len();
        self.calculate_mean();
    }

    fn skip(&mut self) {
        self.skipped_sequence_counts += 1;
    }

    fn calculate_mean(&mut self) {
        if self.sequence_counts > 0 {
            self.mean_length_added = self.total_length_added as f64 / self.sequence_counts as f64;
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct SequenceCounter {
    total_input_files: usize,
    total_destination_files: usize,
    total_file_added: usize,
    /// Store file stem
    added_files: HashSet<String>,
    /// Store file stem
    skipped_files: Vec<String>,
    skipped_file_counts: usize,
    skipped_sequences: usize,
    total_sequence_counts: usize,
    total_sequence_added: usize,
    mean_added_sequences: f64,
    mean_length: f64,
    total_length: usize,
    total_added_length: usize,
    mean_added_length: f64,
}

impl SequenceCounter {
    fn new(total_input_files: usize, total_destination_files: usize) -> Self {
        Self {
            total_input_files,
            total_destination_files,
            total_file_added: 0,
            added_files: HashSet::new(),
            skipped_files: Vec::new(),
            skipped_file_counts: 0,
            total_sequence_added: 0,
            skipped_sequences: 0,
            total_sequence_counts: 0,
            mean_added_sequences: 0.0,
            mean_length: 0.0,
            total_length: 0,
            total_added_length: 0,
            mean_added_length: 0.0,
        }
    }

    fn calculate_mean(&mut self) {
        if self.total_file_added > 0 {
            self.mean_added_sequences =
                self.total_sequence_added as f64 / self.total_sequence_counts as f64;
            self.mean_added_length =
                self.total_added_length as f64 / self.total_sequence_added as f64;
        }
        self.mean_length = self.total_length as f64 / self.total_sequence_counts as f64;
    }

    fn add_sequence(&mut self, sequence: &str) {
        self.total_sequence_counts += 1;
        self.total_sequence_added += 1;
        self.total_length += sequence.len();
        self.total_added_length += sequence.len();
    }

    fn skip_sequence(&mut self, sequence: &str) {
        self.total_sequence_counts += 1;
        self.skipped_sequences += 1;
        self.total_length += sequence.len();
    }

    fn skip_file(&mut self, file_stem: &str) {
        self.skipped_file_counts += 1;
        self.skipped_files.push(file_stem.to_string());
    }

    fn add_file(&mut self, file_stem: &str) {
        self.total_file_added += 1;
        self.added_files.insert(file_stem.to_string());
    }
}

#[cfg(test)]
mod tests {
    use tempdir::TempDir;

    use super::*;

    #[test]
    fn test_stat_counter() {
        let mut counter = SequenceCounter::new(2, 2);
        counter.add_sequence("ATCG");
        counter.add_sequence("ATCG");
        counter.skip_sequence("ATCG");
        counter.skip_sequence("ATCG");
        counter.add_file("file");
        counter.calculate_mean();
        assert_eq!(counter.total_input_files, 2);
        assert_eq!(counter.total_sequence_counts, 4);
        assert_eq!(counter.total_sequence_added, 2);
        assert_eq!(counter.skipped_sequences, 2);
        assert_eq!(counter.total_file_added, 1);
        assert_eq!(counter.skipped_file_counts, 0);
        assert_eq!(counter.mean_added_sequences, 0.5);
        assert_eq!(counter.mean_length, 4.0);
        assert_eq!(counter.total_length, 16);
        assert_eq!(counter.total_added_length, 8);
        assert_eq!(counter.mean_added_length, 4.0);
    }

    #[test]
    fn test_sequence_addition() {
        let input_files = vec![
            PathBuf::from("tests/files/gappy/gene_1.nex"),
            PathBuf::from("tests/files/gappy/gene_2.nex"),
        ];
        let dest_files = vec![
            PathBuf::from("tests/files/alignments/gene_1.nex"),
            PathBuf::from("tests/files/alignments/gene_2.nex"),
        ];
        let output = TempDir::new("temp").unwrap();
        let addition = SequenceAddition::new(
            &input_files,
            &InputFmt::Auto,
            &DataType::Dna,
            output.path(),
            &OutputFmt::Fasta,
            false,
        );
        let counter = addition.add_sequences(&dest_files, &InputFmt::Auto);
        assert_eq!(counter.total_input_files, 2);
        assert_eq!(counter.total_sequence_added, 2);
        assert_eq!(counter.skipped_sequences, 3);
        let output_files = output.path().read_dir().unwrap();
        assert_eq!(output_files.count(), 2);
        output.close().unwrap();
    }

    #[test]
    fn test_finding_skipped_files() {
        let mut counter = SequenceCounter::new(2, 3);
        counter.add_file("gene_1");
        let dest_files = vec![
            PathBuf::from("tests/files/alignments/gene_1.nex"),
            PathBuf::from("tests/files/alignments/gene_2.nex"),
            PathBuf::from("tests/files/alignments/gene_3.nex"),
        ];
        let addition = SequenceAddition::default();
        let skipped_files = addition.get_skipped_files(&counter, &dest_files);
        assert_eq!(skipped_files.len(), 2);
    }

    #[test]
    fn test_adding_single_file() {
        let input_files = vec![
            PathBuf::from("tests/files/gappy/gene_1.nex"),
            PathBuf::from("tests/files/gappy/gene_2.nex"),
        ];
        let output = TempDir::new("temp").unwrap();
        let addition = SequenceAddition::new(
            &input_files,
            &InputFmt::Auto,
            &DataType::Dna,
            output.path(),
            &OutputFmt::Fasta,
            false,
        );
        let dest_file = PathBuf::from("uce");
        addition.add_single(&dest_file, true);
        let output_files = output.path().read_dir().unwrap();
        assert_eq!(output_files.count(), 1);
        assert_eq!(
            output.path().join("uce.fas").exists(),
            true,
            "Output file does not exist"
        );
        output.close().unwrap();
    }
}