feat: add phylogenetic sampling, masking, and plain FASTA writer
Introduces configurable phylogenetic sampling and masking controls via new CLI flags (`--subsample`, `--entropy`, `--exclude-genome`, etc.). Adds a complete SNP pseudo-alignment pipeline featuring entropy-biased Gaussian sampling, post-hoc state masking, and proportional per-layer filtering. Extends the FASTA writer with a `write_plain_record` API for bare-header output without JSON annotations.
This commit is contained in:
1 parent
5a0b71d105
commit
beb2951c20
12 files changed
+768
-27
No files matched your search
@@ -36,15 +36,28 @@ impl From<MetricArg> for DistanceMetric {
|
||||
}
|
||||
|
||||
/// Partial transfer of `obikmer`'s `phylo` command: the plain distance-metric
|
||||
/// path (`--metric`/NJ/UPGMA) plus annex construction (`--sibling-annex`) —
|
||||
/// everything else sibling-annex-based (`--snp`, `--sankoff`,
|
||||
/// `--tnt`/`--phyg`/`--iqtree`, stats, ...) stays in `obikmer` until the rest
|
||||
/// of `obikphylo::siblings` is reconnected (see the project memory on this).
|
||||
/// path (`--metric`/NJ/UPGMA), annex construction (`--sibling-annex`),
|
||||
/// entropy reporting (`--shannon`) and SNP pseudo-alignment sampling
|
||||
/// (`--pseudo-alignment`, `--subsample`, `--free-loss`, `--no-ambiguity`,
|
||||
/// `--entropy`/`--entropy-sd`) — everything else sibling-annex-based
|
||||
/// (`--sankoff`, `--tnt`/`--phyg`/`--iqtree`, stats, ...) stays in `obikmer`
|
||||
/// until the rest of `obikphylo::siblings` is reconnected (see the project
|
||||
/// memory on this).
|
||||
#[derive(Args)]
|
||||
pub struct PhyloArgs {
|
||||
/// Index directory
|
||||
pub index: PathBuf,
|
||||
|
||||
/// Exclude a genome (by its exact label) — from `--pseudo-alignment`'s
|
||||
/// sampling (a family whose only polymorphism lived in an excluded
|
||||
/// genome is discarded during sampling, not filtered afterward — see
|
||||
/// `obikphylo::siblings::extensions::SiblingExt::snp_pseudo_alignment`'s
|
||||
/// own docs) and from the distance matrix / shared-kmer matrix CSV
|
||||
/// output (row and column both dropped; the underlying computation
|
||||
/// itself is unaffected). Repeatable.
|
||||
#[arg(long = "exclude-genome", value_name = "LABEL")]
|
||||
pub exclude_genome: Vec<String>,
|
||||
|
||||
/// Build (or rebuild) the sibling-count/minorant annex — independent of
|
||||
/// the distance metric below, meant to be run routinely, ahead of any
|
||||
/// SNP-family distance computation that will later consume it.
|
||||
@@ -53,11 +66,48 @@ pub struct PhyloArgs {
|
||||
|
||||
/// Write a per-family Shannon entropy report (CSV) — requires an
|
||||
/// already-built sibling annex (`--sibling-annex` first, in this
|
||||
/// invocation or an earlier one). Full, unsampled scan of every family;
|
||||
/// no `--subsample`/`--entropy-bias` yet.
|
||||
/// invocation or an earlier one). Always a full, unsampled scan of
|
||||
/// every family (`--subsample`/`--entropy`/`--entropy-sd` below only
|
||||
/// apply to `--pseudo-alignment`, not this).
|
||||
#[arg(long)]
|
||||
pub shannon: bool,
|
||||
|
||||
/// Write a SNP-only pseudo-alignment (FASTA) — requires
|
||||
/// `--subsample <N>` and an already-built sibling annex
|
||||
/// (`--sibling-annex` first, in this invocation or an earlier one).
|
||||
#[arg(long)]
|
||||
pub pseudo_alignment: bool,
|
||||
|
||||
/// Target number of variable sites to sample index-wide for
|
||||
/// `--pseudo-alignment` — a target, not a guarantee (proportional
|
||||
/// per-layer sampling; see `obikphylo::siblings::SiblingExt::snp_pseudo_alignment`'s
|
||||
/// own docs).
|
||||
#[arg(long)]
|
||||
pub subsample: Option<usize>,
|
||||
|
||||
/// In `--pseudo-alignment`, treat a genome carrying none of a family's
|
||||
/// observed members (`∅`) as missing data (`?`) rather than a real
|
||||
/// character state.
|
||||
#[arg(long)]
|
||||
pub free_loss: bool,
|
||||
|
||||
/// In `--pseudo-alignment`, treat a genome carrying more than one
|
||||
/// member of a family (ambiguous) as missing data (`?`) rather than an
|
||||
/// IUPAC ambiguity code.
|
||||
#[arg(long)]
|
||||
pub no_ambiguity: bool,
|
||||
|
||||
/// Entropy-biased sampling target (Gaussian kernel mean) for
|
||||
/// `--pseudo-alignment` — activates biasing as soon as this or
|
||||
/// `--entropy-sd` is given; the other defaults to 1.0/0.5.
|
||||
#[arg(long)]
|
||||
pub entropy: Option<f64>,
|
||||
|
||||
/// Entropy-biased sampling kernel width (Gaussian standard deviation)
|
||||
/// for `--pseudo-alignment` — see `--entropy`.
|
||||
#[arg(long)]
|
||||
pub entropy_sd: Option<f64>,
|
||||
|
||||
/// Distance metric to compute
|
||||
#[arg(long, value_enum, default_value = "jaccard")]
|
||||
pub metric: MetricArg,
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikindex::KmerIndex;
|
||||
use obikphylo::siblings::SiblingExt;
|
||||
use obikphylo::siblings::{EntropyBias, SiblingExt};
|
||||
use obikphylo::{Metrics, neighbor_joining, upgma};
|
||||
use obisys::{Reporter, Stage};
|
||||
use tracing::info;
|
||||
@@ -30,6 +30,25 @@ pub fn run(args: PhyloArgs) {
|
||||
.collect();
|
||||
let n = labels.len();
|
||||
|
||||
// ── Genome exclusion (`--exclude-genome`) ───────────────────────────────────
|
||||
// Resolved once, up front: `snp_pseudo_alignment` needs it baked into
|
||||
// sampling itself (see its own docs), and the distance/shared-kmer CSV
|
||||
// writers below just skip these rows/columns at write time — the
|
||||
// underlying `cache.distance(...)` computation is unaffected either way.
|
||||
let exclude_mask: Vec<bool> = {
|
||||
let mut mask = vec![false; n];
|
||||
for label in &args.exclude_genome {
|
||||
match labels.iter().position(|l| l == label) {
|
||||
Some(i) => mask[i] = true,
|
||||
None => {
|
||||
eprintln!("error: --exclude-genome {label:?} does not match any genome in this index");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
mask
|
||||
};
|
||||
|
||||
let mut rep = Reporter::new();
|
||||
|
||||
// Every partition/layer this needs is opened once, up front, and
|
||||
@@ -73,6 +92,48 @@ pub fn run(args: PhyloArgs) {
|
||||
info!("entropy report → {path}");
|
||||
}
|
||||
|
||||
// ── SNP pseudo-alignment (`--pseudo-alignment`) ─────────────────────────────
|
||||
if args.pseudo_alignment {
|
||||
let Some(subsample_n) = args.subsample else {
|
||||
eprintln!("error: --pseudo-alignment requires --subsample <N>");
|
||||
std::process::exit(1);
|
||||
};
|
||||
// Same activation rule as `--shannon`'s own entropy-biased path
|
||||
// would use: either flag given activates biasing, the other
|
||||
// defaults to 1.0/0.5.
|
||||
let entropy_bias = if args.entropy.is_some() || args.entropy_sd.is_some() {
|
||||
Some(EntropyBias {
|
||||
mu: args.entropy.unwrap_or(1.0),
|
||||
sigma: args.entropy_sd.unwrap_or(0.5),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
info!("sampling SNP pseudo-alignment (target {subsample_n} site(s))");
|
||||
let t = Stage::start("pseudo_alignment");
|
||||
let alignment = cache
|
||||
.snp_pseudo_alignment(subsample_n, args.free_loss, args.no_ambiguity, &exclude_mask, entropy_bias)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error building pseudo-alignment: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_alignment.fasta", p.display()))
|
||||
.unwrap_or_else(|| "alignment.fasta".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let n_sites = alignment.sequences.first().map_or(0, Vec::len);
|
||||
for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) {
|
||||
obifastwrite::write_plain_record(seq, &labels[g], &mut f).unwrap();
|
||||
}
|
||||
info!("pseudo-alignment ({n_sites} site(s), {} genome(s)) → {path}", alignment.genome_indices.len());
|
||||
}
|
||||
|
||||
info!("computing {:?} distances for {} genome(s)", args.metric, n);
|
||||
|
||||
let need_shared = args.shared_kmers || args.nj || args.upgma;
|
||||
@@ -85,14 +146,19 @@ pub fn run(args: PhyloArgs) {
|
||||
});
|
||||
rep.push(t.stop());
|
||||
|
||||
// Rows/columns kept in every matrix CSV below — `cache.distance(...)`
|
||||
// above is computed over every genome regardless; only the writers skip
|
||||
// excluded ones.
|
||||
let kept: Vec<usize> = (0..n).filter(|&i| !exclude_mask[i]).collect();
|
||||
|
||||
// ── Distance matrix → CSV ─────────────────────────────────────────────────
|
||||
let write_dist_csv = |w: &mut dyn Write| {
|
||||
write!(w, "genome").unwrap();
|
||||
for g in &labels { write!(w, ",{g}").unwrap(); }
|
||||
for &j in &kept { write!(w, ",{}", labels[j]).unwrap(); }
|
||||
writeln!(w).unwrap();
|
||||
for (i, g) in labels.iter().enumerate() {
|
||||
write!(w, "{g}").unwrap();
|
||||
for j in 0..n {
|
||||
for &i in &kept {
|
||||
write!(w, "{}", labels[i]).unwrap();
|
||||
for &j in &kept {
|
||||
write!(w, ",{:.6}", result.matrix[[i, j]]).unwrap();
|
||||
}
|
||||
writeln!(w).unwrap();
|
||||
@@ -127,11 +193,11 @@ pub fn run(args: PhyloArgs) {
|
||||
std::process::exit(1);
|
||||
}));
|
||||
write!(f, "genome").unwrap();
|
||||
for g in &labels { write!(f, ",{g}").unwrap(); }
|
||||
for &j in &kept { write!(f, ",{}", labels[j]).unwrap(); }
|
||||
writeln!(f).unwrap();
|
||||
for (i, g) in labels.iter().enumerate() {
|
||||
write!(f, "{g}").unwrap();
|
||||
for j in 0..n { write!(f, ",{}", shared[[i, j]]).unwrap(); }
|
||||
for &i in &kept {
|
||||
write!(f, "{}", labels[i]).unwrap();
|
||||
for &j in &kept { write!(f, ",{}", shared[[i, j]]).unwrap(); }
|
||||
writeln!(f).unwrap();
|
||||
}
|
||||
info!("shared-kmer matrix → {path}");
|
||||
|
||||
Reference in new issue
Block a user