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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Summary writer for alignment files
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::{Context, Ok, Result};
use colored::Colorize;

use crate::helper::alphabet;
use crate::helper::types::{DataType, TaxonRecords};
use crate::helper::utils;
use crate::stats::sequence::{CharMatrix, CharSummary, Completeness, SiteSummary, Sites, Taxa};
use crate::writer::FileWriter;

trait Alphabet {
    fn match_alphabet(&self, datatype: &DataType) -> &str {
        match datatype {
            DataType::Dna => alphabet::DNA_STR_UPPERCASE,
            DataType::Aa => alphabet::AA_STR_UPPERCASE,
            _ => unreachable!("Invalid data types! Use dna or aa only"),
        }
    }
}

impl Alphabet for CsvWriter<'_> {}
impl FileWriter for CsvWriter<'_> {}

pub struct CsvWriter<'a> {
    output: &'a Path,
    prefix: Option<&'a str>,
    datatype: &'a DataType,
}

impl<'a> CsvWriter<'a> {
    pub fn new(output: &'a Path, prefix: Option<&'a str>, datatype: &'a DataType) -> Self {
        Self {
            output,
            prefix,
            datatype,
        }
    }

    pub fn write_per_locus_summary(&self, file: &Path, summary: &Taxa) -> Result<()> {
        let default_prefix = file
            .file_stem()
            .and_then(OsStr::to_str)
            .expect("Failed to parse input file stem");
        let output = self.create_output_fname(default_prefix);
        let mut writer = self.create_output_file(&output)?;
        write!(
            writer,
            "taxon,\
        total_chars, \
        missing_data,\
        proportion_missing_data\
    "
        )?;
        if DataType::Dna == *self.datatype {
            write!(
                writer,
                ",gc_content\
                ,at_content\
                ,nucleotides"
            )?;
        }
        let alphabet = self.match_alphabet(self.datatype);
        self.write_alphabet_header(&mut writer, alphabet)?;
        summary.records.iter().for_each(|(taxon, chars)| {
            write!(
                writer,
                "{},{},{}",
                taxon, chars.total_chars, chars.missing_data
            )
            .expect("Failed taxon summary stats");
            write!(
                writer,
                ",{}",
                chars.missing_data as f64 / chars.total_chars as f64
            )
            .expect("Failed to write taxon summary stats");
            if DataType::Dna == *self.datatype {
                write!(
                    writer,
                    ",{},{},{}",
                    chars.gc_count as f64 / chars.total_chars as f64,
                    chars.at_count as f64 / chars.total_chars as f64,
                    chars.nucleotides as f64 / chars.total_chars as f64
                )
                .expect("Failed to write taxon summary stats");
            }
            alphabet.chars().for_each(|ch| {
                write!(writer, ",{}", chars.chars.get(&ch).unwrap_or(&0))
                    .expect("Failed getting character summary stats");
            });
            writeln!(writer).expect("Failed writing per locus summary stats");
        });
        Ok(())
    }

    pub fn write_taxon_summary(
        &self,
        taxon_summary: &BTreeMap<String, TaxonRecords>,
    ) -> Result<()> {
        let default_prefix = "taxon_summary";
        let output = self.create_output_fname(default_prefix);
        let mut writer = self.create_output_file(&output)?;
        write!(
            writer,
            "taxon,\
        locus_counts, \
        total_chars, \
        missing_data,\
        proportion_missing_data\
    "
        )?;
        if DataType::Dna == *self.datatype {
            write!(
                writer,
                ",gc_content\
            ,at_content\
            ,nucleotides"
            )?;
        }
        let alphabet = self.match_alphabet(self.datatype);
        self.write_alphabet_header(&mut writer, alphabet)?;
        taxon_summary.iter().for_each(|(taxon, counts)| {
            write!(
                writer,
                "{},{},{},{}",
                taxon, counts.locus_counts, counts.total_chars, counts.missing_data
            )
            .expect("Failed taxon summary stats");
            write!(
                writer,
                ",{}",
                counts.missing_data as f64 / counts.total_chars as f64
            )
            .expect("Failed to write taxon summary stats");
            if DataType::Dna == *self.datatype {
                write!(
                    writer,
                    ",{},{},{}",
                    counts.gc_count as f64 / counts.total_chars as f64,
                    counts.at_count as f64 / counts.total_chars as f64,
                    counts.nucleotides as f64 / counts.total_chars as f64
                )
                .expect("Failed to write taxon summary stats");
            }
            alphabet.chars().for_each(|ch| {
                write!(writer, ",{}", counts.char_counts.get(&ch).unwrap_or(&0))
                    .expect("Failed taxon summary stats");
            });
            writeln!(writer).expect("Failed taxon summary stats");
        });
        writer.flush()?;
        Ok(())
    }

    pub fn write_locus_summary(&self, stats: &[(Sites, CharMatrix, Taxa)]) -> Result<()> {
        let default_prefix = "locus_summary";
        let output = self.create_output_fname(default_prefix);
        let mut writer = self.create_output_file(&output)?;
        let alphabet = self.match_alphabet(self.datatype);
        self.write_locus_header(&mut writer, alphabet)?;
        stats.iter().for_each(|(site, chars, _)| {
            self.write_locus_content(&mut writer, site, chars, alphabet)
                .unwrap();
        });
        writer.flush()?;
        log::info!("{}", "Output".yellow());
        log::info!("{:18}: {}", "Output dir", self.output.display());

        Ok(())
    }

    fn create_output_fname(&self, default_prefix: &str) -> PathBuf {
        match self.prefix {
            Some(fname) => {
                let out_name = format!("{}_{}", fname, default_prefix);
                self.output.join(out_name).with_extension("csv")
            }
            None => self.output.join(default_prefix).with_extension("csv"),
        }
    }

    fn write_locus_header<W: Write>(&self, writer: &mut W, alphabet: &str) -> Result<()> {
        write!(
            writer,
            "path,\
            locus,\
            ntax,\
            chars_count,\
            site_count,\
            conserved_sites,\
            proportion_cons_sites,\
            variable_sites,\
            proportion_var_sites,\
            parsimony_informative_sites,\
            proportion_pars_inf_sites,\
            missing_data,\
            proportion_missing_data\
        "
        )?;
        if DataType::Dna == *self.datatype {
            write!(
                writer,
                ",GC_content\
                ,AT_content\
                ,nucleotides"
            )?;
        }
        self.write_alphabet_header(writer, alphabet)?;
        Ok(())
    }

    fn write_alphabet_header<W: Write>(&self, writer: &mut W, alphabet: &str) -> Result<()> {
        alphabet
            .chars()
            .for_each(|ch| write!(writer, ",{}", ch).unwrap());
        writeln!(writer)?;
        Ok(())
    }

    fn write_locus_content<W: Write>(
        &self,
        writer: &mut W,
        site: &Sites,
        chars: &CharMatrix,
        alphabet: &str,
    ) -> Result<()> {
        write!(
            writer,
            "{},{},{},{},",
            site.path.display(),
            site.path
                .file_stem()
                .and_then(OsStr::to_str)
                .with_context(|| format!(
                    "Failed getting locus name for {}",
                    site.path.display()
                ))?,
            chars.ntax,
            chars.chars.total_chars
        )?;

        // Site stats
        write!(
            writer,
            "{},{},{},{},{},{},{},",
            site.counts,
            site.conserved,
            site.prop_cons,
            site.variable,
            site.prop_var,
            site.pars_inf,
            site.prop_pinf
        )?;

        // Missing data
        write!(writer, "{},", chars.chars.missing_data)?;
        write!(writer, "{}", chars.chars.prop_missing_data)?;

        // We move comma position for accurate printing
        if DataType::Dna == *self.datatype {
            // GC content
            write!(
                writer,
                ",{}",
                chars.chars.gc_count as f64 / chars.chars.total_chars as f64
            )?;
            // AT content
            write!(
                writer,
                ",{}",
                chars.chars.at_count as f64 / chars.chars.total_chars as f64
            )?;
            write!(writer, ",{}", chars.chars.nucleotides)?;
        }

        // Characters
        alphabet.chars().for_each(|ch| {
            write!(writer, ",{}", chars.chars.chars.get(&ch).unwrap_or(&0)).unwrap();
        });
        writeln!(writer)?;
        Ok(())
    }
}

impl Alphabet for SummaryWriter<'_> {}

pub struct SummaryWriter<'s> {
    site: &'s SiteSummary,
    chars: &'s CharSummary,
    complete: &'s Completeness,
    datatype: &'s DataType,
}

impl FileWriter for SummaryWriter<'_> {}

impl<'s> SummaryWriter<'s> {
    pub fn new(
        site: &'s SiteSummary,
        chars: &'s CharSummary,
        complete: &'s Completeness,
        datatype: &'s DataType,
    ) -> Self {
        Self {
            site,
            chars,
            complete,
            datatype,
        }
    }

    pub fn write(&self, output_path: &Path, prefix: Option<&str>) -> Result<()> {
        let default_prefix = "alignment_summary";
        let output = match prefix {
            Some(fname) => {
                let out_name = format!("{}_{}", fname, default_prefix);
                output_path.join(out_name).with_extension("txt")
            }
            None => output_path.join(default_prefix).with_extension("txt"),
        };
        let mut writer = self.create_output_file(&output)?;
        self.write_to_file(&mut writer)?;
        writer.flush()?;
        Ok(())
    }

    fn write_to_file<W: Write>(&self, writer: &mut W) -> Result<()> {
        self.write_gen_sum(writer)?;
        self.write_aln_sum(writer)?;
        self.write_tax_sum(writer)?;
        self.write_char_count(writer)?;
        self.write_matrix_comp(writer)?;
        self.write_cons_seq(writer)?;
        self.write_var_seq(writer)?;
        self.write_pars_inf(writer)?;
        Ok(())
    }

    fn write_gen_sum<W: Write>(&self, writer: &mut W) -> Result<()> {
        let summary = "General Summary";
        writeln!(writer, "{}", summary)?;
        let total_taxa = format!(
            "{:18}: {}",
            "Total taxa",
            utils::fmt_num(&self.complete.total_tax)
        );
        writeln!(writer, "{}", total_taxa)?;

        let total_loci = format!(
            "{:18}: {}",
            "Total loci",
            utils::fmt_num(&self.site.total_loci)
        );
        writeln!(writer, "{}", total_loci)?;

        let total_sites = format!(
            "{:18}: {}",
            "Total sites",
            utils::fmt_num(&self.site.total_sites)
        );

        writeln!(writer, "{}", total_sites)?;

        let total_chars = format!(
            "{:18}: {}",
            "Total characters",
            utils::fmt_num(&self.chars.total_chars)
        );
        writeln!(writer, "{}", total_chars)?;

        let missing_data = format!(
            "{:18}: {}",
            "Missing data",
            utils::fmt_num(&self.chars.missing_data)
        );
        writeln!(writer, "{}", missing_data)?;
        let prop_missing_data = format!(
            "{:18}: {:.2}%",
            "%Missing data",
            self.chars.prop_missing_data * 100.0
        );
        writeln!(writer, "{}", prop_missing_data)?;

        match self.datatype {
            DataType::Dna => self.write_dna_sum(writer)?,
            DataType::Aa => self.write_aa_sum(writer)?,
            _ => unreachable!("Invalid data types! Use dna or aa only"),
        };

        Ok(())
    }

    fn write_aa_sum<W: Write>(&self, writer: &mut W) -> Result<()> {
        let characters = format!(
            "{:18}: {}",
            "Characters",
            utils::fmt_num(&self.chars.total_chars)
        );
        writeln!(writer, "{}", characters)?;

        Ok(())
    }

    fn write_dna_sum<W: Write>(&self, writer: &mut W) -> Result<()> {
        let gc_content = format!("{:18}: {:.2}", "GC content", self.chars.gc_content);
        writeln!(writer, "{}", gc_content)?;

        let at_content = format!("{:18}: {:.2}", "AT content", self.chars.at_content);

        writeln!(writer, "{}", at_content)?;

        let characters = format!(
            "{:18}: {}",
            "Characters",
            utils::fmt_num(&self.chars.total_chars)
        );
        writeln!(writer, "{}", characters)?;

        let nucleotides = format!(
            "{:18}: {}",
            "Nucleotides",
            utils::fmt_num(&self.chars.total_nucleotides)
        );
        writeln!(writer, "{}", nucleotides)?;

        Ok(())
    }

    fn write_aln_sum<W: Write>(&self, writer: &mut W) -> Result<()> {
        let aln_summary = "Alignment Summary";
        writeln!(writer, "\n{}", aln_summary)?;

        let min_site = format!(
            "{:18}: {} bp",
            "Min length",
            utils::fmt_num(&self.site.min_sites)
        );
        writeln!(writer, "{}", min_site)?;

        let max_site = format!(
            "{:18}: {} bp",
            "Max length",
            utils::fmt_num(&self.site.max_sites)
        );
        writeln!(writer, "{}", max_site)?;

        let mean_site = format!("{:18}: {:.2} bp", "Mean length", &self.site.mean_sites);

        writeln!(writer, "{}", mean_site)?;

        Ok(())
    }

    fn write_tax_sum<W: Write>(&self, writer: &mut W) -> Result<()> {
        let taxon_summary = "Taxon Summary";
        writeln!(writer, "\n{}", taxon_summary)?;

        let min_tax = format!("{:18}: {}", "Min taxa", utils::fmt_num(&self.chars.min_tax));
        writeln!(writer, "{}", min_tax)?;

        let max_tax = format!("{:18}: {}", "Max taxa", utils::fmt_num(&self.chars.max_tax));
        writeln!(writer, "{}", max_tax)?;

        let mean_tax = format!("{:18}: {:.2}", "Mean taxa", self.chars.mean_tax);
        writeln!(writer, "{}", mean_tax)?;

        Ok(())
    }

    fn write_char_count<W: Write>(&self, writer: &mut W) -> Result<()> {
        let char_count = "Character Count";
        writeln!(writer, "\n{}", char_count)?;
        let alphabet = self.match_alphabet(self.datatype);

        for ch in alphabet.chars() {
            if let Some(count) = self.chars.chars.get(&ch) {
                let count = format!("{:18}: {}", ch, utils::fmt_num(count));
                writeln!(writer, "{}", count)?;
            }
        }
        Ok(())
    }

    fn write_matrix_comp<W: Write>(&self, writer: &mut W) -> Result<()> {
        let matrix_summary = "Matrix Completeness";
        writeln!(writer, "\n{}", matrix_summary)?;
        self.complete
            .completeness
            .iter()
            .for_each(|(percent, ntax)| {
                let percent_str = format!("{}% taxa", percent);
                let percent_str = format!("{:18}: {}", percent_str, utils::fmt_num(ntax));
                writeln!(writer, "{}", percent_str).expect("Failed to write matrix completeness");
            });
        Ok(())
    }

    fn write_cons_seq<W: Write>(&self, writer: &mut W) -> Result<()> {
        let conserved_seq = "Conserved Sequences";
        writeln!(writer, "\n{}", conserved_seq)?;

        let conserved_loci = format!(
            "{:18}: {}",
            "Conserved loci",
            utils::fmt_num(&self.site.cons_loci)
        );

        writeln!(writer, "{}", conserved_loci)?;

        let prop_cons_loci = format!(
            "{:18}: {:.2}%",
            "%Con. loci",
            self.site.prop_cons_loci * 100.0
        );

        writeln!(writer, "{}", prop_cons_loci)?;

        let conserved_sites = format!(
            "{:18}: {}",
            "Conserved sites",
            utils::fmt_num(&self.site.total_cons_site)
        );

        writeln!(writer, "{}", conserved_sites)?;

        let prop_cons_sites = format!(
            "{:18}: {:.2}%",
            "%Con. sites",
            &self.site.prop_cons_site * 100.0
        );

        writeln!(writer, "{}", prop_cons_sites)?;

        let min_cons_site = format!(
            "{:18}: {}",
            "Min con. sites",
            utils::fmt_num(&self.site.min_cons_site)
        );

        writeln!(writer, "{}", min_cons_site)?;

        let max_cons_site = format!(
            "{:18}: {}",
            "Max con. sites",
            utils::fmt_num(&self.site.max_cons_site)
        );

        writeln!(writer, "{}", max_cons_site)?;

        let mean_cons_site = format!("{:18}: {:.2}", "Mean con. sites", &self.site.mean_cons_site);

        writeln!(writer, "{}", mean_cons_site)?;

        Ok(())
    }

    fn write_var_seq<W: Write>(&self, writer: &mut W) -> Result<()> {
        let var_seq = "Variable Sequences";

        writeln!(writer, "\n{}", var_seq)?;

        let var_loci = format!(
            "{:18}: {}",
            "Var. loci",
            utils::fmt_num(&self.site.var_loci)
        );

        writeln!(writer, "{}", var_loci)?;

        let prop_var_loci = format!(
            "{:18}: {:.2}%",
            "%Var. loci",
            self.site.prop_var_loci * 100.0
        );

        writeln!(writer, "{}", prop_var_loci)?;

        let var_sites = format!(
            "{:18}: {}",
            "Var. sites",
            utils::fmt_num(&self.site.total_var_site)
        );

        writeln!(writer, "{}", var_sites)?;

        let prop_var_sites = format!(
            "{:18}: {:.2}%",
            "%Var. sites",
            &self.site.prop_var_site * 100.0
        );

        writeln!(writer, "{}", prop_var_sites)?;

        let min_var_site = format!(
            "{:18}: {}",
            "Min var. sites",
            utils::fmt_num(&self.site.min_var_site)
        );

        writeln!(writer, "{}", min_var_site)?;

        let max_var_site = format!(
            "{:18}: {}",
            "Max var. sites",
            utils::fmt_num(&self.site.max_var_site)
        );

        writeln!(writer, "{}", max_var_site)?;

        let mean_var_site = format!("{:18}: {:.2}", "Mean var. sites", &self.site.mean_var_site);

        writeln!(writer, "{}", mean_var_site)?;

        Ok(())
    }

    fn write_pars_inf<W: Write>(&self, writer: &mut W) -> Result<()> {
        let pars_inf = "Parsimony Informative";
        writeln!(writer, "\n{}", pars_inf)?;

        let inf_loci = format!(
            "{:18}: {}",
            "Inf. loci",
            utils::fmt_num(&self.site.inf_loci)
        );

        writeln!(writer, "{}", inf_loci)?;

        let prop_inf_loci = format!(
            "{:18}: {:.2}%",
            "%Inf. loci",
            self.site.prop_inf_loci * 100.0
        );

        writeln!(writer, "{}", prop_inf_loci)?;

        let inf_sites = format!(
            "{:18}: {}",
            "Inf. sites",
            utils::fmt_num(&self.site.total_inf_site)
        );

        writeln!(writer, "{}", inf_sites)?;

        let prop_inf_sites = format!(
            "{:18}: {:.2}%",
            "%Inf. sites",
            self.site.prop_inf_site * 100.0
        );

        writeln!(writer, "{}", prop_inf_sites)?;

        let min_inf_site = format!(
            "{:18}: {}",
            "Min inf. sites",
            utils::fmt_num(&self.site.min_inf_site)
        );

        writeln!(writer, "{}", min_inf_site)?;

        let max_inf_site = format!(
            "{:18}: {}",
            "Max inf. sites",
            utils::fmt_num(&self.site.max_inf_site)
        );

        writeln!(writer, "{}", max_inf_site)?;

        let mean_inf_site = format!("{:18}: {:.2}", "Mean inf. sites", &self.site.mean_inf_site);
        writeln!(writer, "{}", mean_inf_site)?;

        log::info!("");

        Ok(())
    }
}