use std::fs;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use clap::Parser;
use rsomics_common::{CommonFlags, Result, RsomicsError, Tool, ToolMeta};
use rsomics_help::{Example, FlagSpec, HelpSpec, Origin, Section};
use rsomics_phylo_tree::Tree;
use rsomics_tree_tipdist::tip_tip_distances;
pub const META: ToolMeta = ToolMeta {
name: env!("CARGO_PKG_NAME"),
version: env!("CARGO_PKG_VERSION"),
};
#[derive(Parser, Debug)]
#[command(name = "rsomics-tree-tipdist", version, about, long_about = None, disable_help_flag = true)]
pub struct Cli {
#[arg(default_value = "-")]
input: PathBuf,
#[arg(long, default_value_t = false)]
count: bool,
#[arg(short = 'o', long, default_value = "-")]
output: String,
#[command(flatten)]
pub common: CommonFlags,
}
impl Tool for Cli {
fn meta() -> ToolMeta {
META
}
fn common(&self) -> &CommonFlags {
&self.common
}
fn execute(self) -> Result<()> {
let newick = if self.input.as_os_str() == "-" {
std::io::read_to_string(std::io::stdin().lock()).map_err(RsomicsError::Io)?
} else {
fs::read_to_string(&self.input)
.map_err(|e| RsomicsError::InvalidInput(format!("{}: {e}", self.input.display())))?
};
let tree = Tree::from_newick(&newick)
.map_err(|e| RsomicsError::InvalidInput(format!("newick parse: {e}")))?;
let dm = tip_tip_distances(&tree, !self.count)
.map_err(|e| RsomicsError::InvalidInput(e.to_string()))?;
let mut out: Box<dyn Write> = if self.output == "-" {
Box::new(BufWriter::new(std::io::stdout().lock()))
} else {
Box::new(BufWriter::new(
fs::File::create(&self.output).map_err(RsomicsError::Io)?,
))
};
dm.write_lsmat(&mut out).map_err(RsomicsError::Io)?;
out.flush().map_err(RsomicsError::Io)
}
}
pub static HELP: HelpSpec = HelpSpec {
name: env!("CARGO_PKG_NAME"),
version: env!("CARGO_PKG_VERSION"),
tagline: "Patristic tip-to-tip distance matrix from a phylogenetic tree.",
origin: Some(Origin {
upstream: "scikit-bio skbio.tree.TreeNode.cophenet / tip_tip_distances",
upstream_license: "BSD-3-Clause",
our_license: "MIT OR Apache-2.0",
paper_doi: Some("10.1186/1471-2148-6-1"),
}),
usage_lines: &["[tree.nwk] [-o dm.tsv]"],
sections: &[Section {
title: "OPTIONS",
flags: &[
FlagSpec {
short: None,
long: "count",
aliases: &[],
value: None,
type_hint: None,
required: false,
default: Some("false"),
description: "Count branches between tips instead of summing lengths.",
why_default: None,
},
FlagSpec {
short: Some('o'),
long: "output",
aliases: &[],
value: Some("<path>"),
type_hint: Some("path"),
required: false,
default: Some("-"),
description: "Output path (- for stdout).",
why_default: None,
},
],
}],
examples: &[
Example {
description: "Cophenetic distance matrix to stdout",
command: "rsomics-tree-tipdist tree.nwk",
},
Example {
description: "From stdin, branch counts, to a file",
command: "cat tree.nwk | rsomics-tree-tipdist --count -o dm.tsv",
},
],
json_result_schema_doc: None,
};
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
#[test]
fn cli_debug_assert() {
Cli::command().debug_assert();
}
}