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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Find input files and parse IDs from input files.

use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;

use glob::glob;
use indexmap::IndexSet;
use lazy_static::lazy_static;
use rayon::prelude::*;
use regex::Regex;
use walkdir::WalkDir;

use crate::helper::types::SeqReadFmt;
use crate::helper::types::{DataType, InputFmt};
use crate::parser::fasta;
use crate::parser::nexus::Nexus;
use crate::parser::phylip::Phylip;

use super::types::{self, ContigFmt};

macro_rules! id_non_fasta {
    ($self:ident,  $type: ident, $datatype:ident) => {{
        let (sender, receiver) = channel();
        $self.files.par_iter().for_each_with(sender, |s, file| {
            s.send($type::new(file, $self.$datatype).parse_only_id())
                .expect("Failed parallel processing IDs");
        });
        receiver.iter().collect()
    }};
}

macro_rules! walk_dir {
    ($self:ident, $match: ident) => {{
        WalkDir::new($self.dir)
            .into_iter()
            .filter_map(|ok| ok.ok())
            .filter(|e| e.file_type().is_file())
            .filter(|e| $match(e.file_name().to_str().expect("Failed parsing file name")))
            .map(|e| e.into_path())
            .collect()
    }};
}

trait FileFinder {
    fn glob_files(&self, pattern: &str) -> Vec<PathBuf> {
        glob(pattern)
            .expect("Failed finding files with matching pattern")
            .filter_map(|ok| ok.ok())
            .collect::<Vec<PathBuf>>()
    }

    fn check_results(&self, files: &[PathBuf]) {
        if files.is_empty() {
            panic!(
                "No input files found. \
                    Please check your input directory and file format."
            );
        }
    }
}

impl FileFinder for SeqReadFinder<'_> {}

/// Find high-throughput sequencing read files.
/// Supported file formats uncompressed FASTQ and
/// compressed GZIP FASTQ.
pub struct SeqReadFinder<'a> {
    /// Input directory.
    dir: &'a Path,
    /// Glob pattern.
    pattern: String,
}

impl<'a> SeqReadFinder<'a> {
    pub fn new(dir: &'a Path) -> Self {
        Self {
            dir,
            pattern: String::new(),
        }
    }

    /// Find input files for raw reads.
    /// Return a vector of input files.
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::types::SeqReadFmt;
    /// use segul::helper::finder::SeqReadFinder;
    ///
    /// let dir = Path::new("tests/files/raw");
    /// let input_fmt = SeqReadFmt::Fastq;
    /// let files = SeqReadFinder::new(&dir).find(&input_fmt);
    /// assert_eq!(files.len(), 4);
    pub fn find(&mut self, input_fmt: &'a SeqReadFmt) -> Vec<PathBuf> {
        let files = if SeqReadFmt::Auto == *input_fmt {
            self.find_recursive()
        } else {
            self.raw_pattern(input_fmt);
            self.glob_files(&self.pattern)
        };

        self.check_results(&files);

        files
    }

    /// Find input files for raw reads, recursively.
    /// Return a vector of input files.
    ///
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::types::SeqReadFmt;
    /// use segul::helper::finder::SeqReadFinder;
    ///
    /// let dir = Path::new("tests/files/raw");
    /// let files = SeqReadFinder::new(&dir).find_recursive();
    /// assert_eq!(files.len(), 4);
    /// ```
    pub fn find_recursive(&self) -> Vec<PathBuf> {
        walk_dir!(self, re_matches_fastq_lazy)
    }

    fn raw_pattern(&mut self, input_fmt: &'a SeqReadFmt) {
        self.pattern = match input_fmt {
            SeqReadFmt::Fastq => format!("{}/*.f*q", self.dir.display()),
            SeqReadFmt::Gzip => format!("{}/*.f*q.gz*", self.dir.display()),
            SeqReadFmt::Auto => unreachable!("Unsupported input format"),
        };
    }
}

pub struct ContigFileFinder<'a> {
    /// Input directory.
    dir: &'a Path,
    /// Glob pattern.
    pattern: String,
}

impl FileFinder for ContigFileFinder<'_> {}

impl<'a> ContigFileFinder<'a> {
    pub fn new(dir: &'a Path) -> Self {
        Self {
            dir,
            pattern: String::new(),
        }
    }

    /// Find input files for contiguous sequences.
    /// Return a vector of input files.
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::types::ContigFmt;
    /// use segul::helper::finder::ContigFileFinder;
    ///
    /// let dir = Path::new("tests/files/contigs");
    /// let input_fmt = ContigFmt::Fasta;
    /// let files = ContigFileFinder::new(&dir).find(&input_fmt);
    /// assert_eq!(files.len(), 2);
    pub fn find(&mut self, input_fmt: &'a ContigFmt) -> Vec<PathBuf> {
        let files = if ContigFmt::Auto == *input_fmt {
            self.find_recursive()
        } else {
            self.contig_pattern(input_fmt);
            self.glob_files(&self.pattern)
        };

        self.check_results(&files);

        files
    }

    /// Find input files for contiguous sequences, recursively.
    /// Return a vector of input files.
    ///
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::types::InputFmt;
    /// use segul::helper::finder::ContigFileFinder;
    ///
    /// let dir = Path::new("tests/files/contigs");
    /// let files = ContigFileFinder::new(&dir).find_recursive();
    /// assert_eq!(files.len(), 2);
    /// ```
    pub fn find_recursive(&self) -> Vec<PathBuf> {
        walk_dir!(self, re_matches_fasta_lazy)
    }

    fn contig_pattern(&mut self, input_fmt: &'a ContigFmt) {
        self.pattern = match input_fmt {
            ContigFmt::Fasta => format!("{}/*.f*a", self.dir.display()),
            ContigFmt::Gzip => format!("{}/*.f*a.gz*", self.dir.display()),
            ContigFmt::Auto => unreachable!("Unsupported input format"),
        };
    }
}

pub struct MafFileFinder<'a> {
    /// Input directory.
    dir: &'a Path,
    /// Glob pattern.
    pattern: String,
}

impl FileFinder for MafFileFinder<'_> {}

impl<'a> MafFileFinder<'a> {
    pub fn new(dir: &'a Path) -> Self {
        Self {
            dir,
            pattern: String::new(),
        }
    }

    /// Find input files for multiple alignment format.
    /// Return a vector of input files.
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::finder::MafFileFinder;
    ///
    /// let dir = Path::new("tests/files/maf");
    /// let files = MafFileFinder::new(&dir).find();
    /// assert_eq!(files.len(), 1);
    pub fn find(&mut self) -> Vec<PathBuf> {
        self.maf_pattern();
        let files = self.glob_files(&self.pattern);
        self.check_results(&files);

        files
    }

    /// Find input files for multiple alignment format, recursively.
    /// Return a vector of input files.
    ///
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::finder::MafFileFinder;
    ///
    /// let dir = Path::new("tests/files/maf");
    /// let files = MafFileFinder::new(&dir).find_recursive();
    /// assert_eq!(files.len(), 1);
    pub fn find_recursive(&self) -> Vec<PathBuf> {
        walk_dir!(self, re_matches_maf_lazy)
    }

    fn maf_pattern(&mut self) {
        self.pattern = format!("{}/*.maf", self.dir.display());
    }
}

/// Find sequence files from a directory.
/// Supported file formats are FASTA, PHYLIP, and NEXUS.
/// include support for interleaved and sequential formats.
pub struct SeqFileFinder<'a> {
    /// Input directory.
    dir: &'a Path,
    /// Glob pattern.
    pattern: String,
}

impl FileFinder for SeqFileFinder<'_> {}

impl<'a> SeqFileFinder<'a> {
    /// Create a new `Files` instance.
    pub fn new(dir: &'a Path) -> Self {
        Self {
            dir,
            pattern: String::new(),
        }
    }

    /// Find input files for sequence and alignment.
    /// Return a vector of input files.
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::types::InputFmt;
    /// use segul::helper::finder::SeqFileFinder;
    ///
    /// let dir = Path::new("tests/files/alignments");
    /// let input_fmt = InputFmt::Nexus;
    /// let files = SeqFileFinder::new(&dir).find(&input_fmt);
    /// assert_eq!(files.len(), 4);
    /// ```
    pub fn find(&mut self, input_fmt: &'a InputFmt) -> Vec<PathBuf> {
        let files = if InputFmt::Auto == *input_fmt {
            self.find_recursive()
        } else {
            self.pattern(input_fmt);
            self.glob_files(&self.pattern)
        };
        self.check_results(&files);

        files
    }

    /// Find input files for sequence and alignment, recursively.
    /// Return a vector of input files.
    ///
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::finder::SeqFileFinder;
    ///
    /// let dir = Path::new("tests/files/alignments");
    /// let files = SeqFileFinder::new(&dir).find_recursive();
    /// assert_eq!(files.len(), 4);
    /// ```
    pub fn find_recursive(&self) -> Vec<PathBuf> {
        walk_dir!(self, re_match_sequence_lazy)
    }

    /// Find input files for sequence and alignment, recursively.
    /// Limit search to only the input format.
    ///
    /// # Example
    /// ```
    /// use std::path::Path;
    /// use segul::helper::types::InputFmt;
    /// use segul::helper::finder::SeqFileFinder;
    ///
    /// let dir = Path::new("tests/files/alignments");
    /// let files = SeqFileFinder::new(&dir).find_recursive_only(&InputFmt::Nexus);
    /// assert_eq!(files.len(), 4);
    pub fn find_recursive_only(&self, input_fmt: &'a InputFmt) -> Vec<PathBuf> {
        match input_fmt {
            InputFmt::Fasta => walk_dir!(self, re_matches_fasta_lazy),
            InputFmt::Nexus => walk_dir!(self, re_match_nexus_lazy),
            InputFmt::Phylip => walk_dir!(self, re_match_phylip_lazy),
            _ => unreachable!(),
        }
    }

    fn check_results(&self, files: &[PathBuf]) {
        if files.is_empty() {
            panic!(
                "Failed finding input files using {}. \
                Check the input directory and the input format.",
                self.pattern
            );
        }
    }

    fn pattern(&mut self, input_fmt: &'a InputFmt) {
        self.pattern = match input_fmt {
            InputFmt::Fasta => format!("{}/*.fa*", self.dir.display()),
            InputFmt::Nexus => format!("{}/*.nex*", self.dir.display()),
            InputFmt::Phylip => format!("{}/*.phy*", self.dir.display()),
            InputFmt::Auto => unreachable!("Unsupported input format"),
        };
    }
}

fn re_matches_fastq_lazy(fname: &str) -> bool {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"(?i)(.fq|.fastq)(?:.*)").unwrap();
    }

    RE.is_match(fname)
}

fn re_matches_fasta_lazy(fname: &str) -> bool {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"(?i)(.fa*)(?:.*)").unwrap();
    }

    RE.is_match(fname)
}

fn re_matches_maf_lazy(fname: &str) -> bool {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"(?i)(.maf)").unwrap();
    }

    RE.is_match(fname)
}

fn re_match_sequence_lazy(fname: &str) -> bool {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"(?i)(.nex*|.nxs|.phy*|.fna|.fa*)(?:.*)").unwrap();
    }

    RE.is_match(fname)
}

fn re_match_nexus_lazy(fname: &str) -> bool {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"(?i)(.nex*|.nxs)(?:.*)").unwrap();
    }

    RE.is_match(fname)
}

fn re_match_phylip_lazy(fname: &str) -> bool {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"(?i)(.phy*|.fna|.fa*)(?:.*)").unwrap();
    }

    RE.is_match(fname)
}

/// Parse IDs from input sequence files.
/// # Example
/// ```
/// use std::path::PathBuf;
/// use segul::helper::types::{DataType, InputFmt};
/// use segul::helper::finder::IDs;
/// use indexmap::IndexSet;
///
/// let files = vec![
///    PathBuf::from("tests/files/alignments/gene_1.nex"),
///    PathBuf::from("tests/files/alignments/gene_2.nex"),
/// ];
///
/// let input_fmt = InputFmt::Nexus;
/// let datatype = DataType::Dna;
/// let ids = IDs::new(&files, &input_fmt, &datatype).id_unique();
/// assert_eq!(ids.len(), 2);
/// ```
pub struct IDs<'a> {
    /// Input files.
    files: &'a [PathBuf],
    /// Input format.
    input_fmt: &'a InputFmt,
    /// Input data type.
    datatype: &'a DataType,
}

impl<'a> IDs<'a> {
    /// Create a new `IDs` instance.
    pub fn new(files: &'a [PathBuf], input_fmt: &'a InputFmt, datatype: &'a DataType) -> Self {
        Self {
            files,
            input_fmt,
            datatype,
        }
    }

    /// Parse IDs in sequence files.
    /// Return a unique set of IDs.
    pub fn id_unique(&self) -> IndexSet<String> {
        let all_ids = self.parse_id();
        self.filter_unique(&all_ids)
    }

    fn filter_unique(&self, all_ids: &[IndexSet<String>]) -> IndexSet<String> {
        let mut id = IndexSet::new();
        all_ids.iter().for_each(|ids| {
            ids.iter().for_each(|val| {
                if !id.contains(val) {
                    id.insert(val.to_string());
                }
            });
        });

        id
    }

    fn parse_id(&self) -> Vec<IndexSet<String>> {
        match self.input_fmt {
            InputFmt::Nexus => id_non_fasta!(self, Nexus, datatype),
            InputFmt::Phylip => id_non_fasta!(self, Phylip, datatype),
            InputFmt::Fasta => self.id_from_fasta(),
            InputFmt::Auto => self.id_auto(),
        }
    }

    fn id_auto(&self) -> Vec<IndexSet<String>> {
        let (sender, receiver) = channel();
        self.files.par_iter().for_each_with(sender, |s, file| {
            let input_fmt = types::infer_input_auto(file);
            match input_fmt {
                InputFmt::Fasta => s.send(fasta::parse_only_id(file)).unwrap(),
                InputFmt::Nexus => s
                    .send(Nexus::new(file, self.datatype).parse_only_id())
                    .unwrap(),
                InputFmt::Phylip => s
                    .send(Phylip::new(file, self.datatype).parse_only_id())
                    .unwrap(),
                _ => unreachable!(),
            }
        });
        receiver.iter().collect()
    }

    fn id_from_fasta(&self) -> Vec<IndexSet<String>> {
        let (sender, receiver) = channel();
        self.files.par_iter().for_each_with(sender, |s, file| {
            s.send(fasta::parse_only_id(file)).unwrap();
        });
        receiver.iter().collect()
    }
}

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

    macro_rules! input {
        ($files: ident) => {
            let path = Path::new("tests/files/alignments");

            let mut $files = SeqFileFinder::new(path);
        };
    }

    #[test]
    fn test_files() {
        input!(finder);
        let fmt = InputFmt::Nexus;
        let files = finder.find(&fmt);
        assert_eq!(4, files.len());
    }

    #[test]
    fn test_files_recursive() {
        input!(finder);
        let fmt = InputFmt::Auto;
        let files = finder.find(&fmt);
        assert_eq!(4, files.len());
    }

    #[test]
    fn test_raw_pattern() {
        let path = Path::new("tests/files/raw");
        let fmt = SeqReadFmt::Fastq;
        let mut files = SeqReadFinder::new(path);
        let found_files = files.find(&fmt);
        assert_eq!(4, found_files.len());
        assert_eq!("tests/files/raw/*.f*q", files.pattern);
    }

    #[test]
    fn test_contig_file_pattern() {
        let path = Path::new("tests/files/contigs");
        let fmt = ContigFmt::Fasta;
        let mut files = ContigFileFinder::new(path);
        let found_files = files.find(&fmt);
        assert_eq!(2, found_files.len());
        assert_eq!("tests/files/contigs/*.f*a", files.pattern);
    }

    #[test]
    fn test_pattern() {
        input!(files);
        let fmt = InputFmt::Nexus;
        files.pattern(&fmt);
        assert_eq!("tests/files/alignments/*.nex*", files.pattern);
    }

    #[test]
    #[should_panic]
    fn test_check_empty_files() {
        let path = Path::new("tests/files/empty/");
        let mut finder = SeqFileFinder::new(path);
        let files = finder.find(&InputFmt::Nexus);
        finder.check_results(&files);
    }

    #[test]
    fn test_id() {
        input!(finder);
        let input_fmt = InputFmt::Nexus;
        let datatype = DataType::Dna;
        let files = finder.find(&input_fmt);
        let id = IDs::new(&files, &input_fmt, &datatype);
        let ids = id.id_unique();
        assert_eq!(3, ids.len());
    }

    #[test]
    fn match_fastq() {
        let fname = "test.fastq";
        assert!(re_matches_fastq_lazy(fname));
    }

    #[test]
    fn match_fasta() {
        let fname = "test.fasta";
        let fname2 = "test.fa";
        let fname3 = "test.fas";
        assert!(re_matches_fasta_lazy(fname));
        assert!(re_matches_fasta_lazy(fname2));
        assert!(re_matches_fasta_lazy(fname3));
    }

    #[test]
    fn match_sequence_fmt() {
        let fname = "test.fasta";
        let fname2 = "test.nex";
        let fname3 = "test.phy";
        let fname4 = "test.nexus";
        assert!(re_match_sequence_lazy(fname));
        assert!(re_match_sequence_lazy(fname2));
        assert!(re_match_sequence_lazy(fname3));
        assert!(re_match_sequence_lazy(fname4));
    }
}