Refactor sampling logic and introduce diagnostic outputs
This commit introduces new features for sampling, including detailed `SamplePlan` generation, Shannon entropy summaries, and site statistics reporting. It formalizes conditional distance matrix computation and clarifies the logic for family weighting and site selection.
This commit is contained in:
1 parent
2232628e58
commit
cb5fc202b6
13 files changed
+799
-122
No files matched your search
@@ -101,6 +101,51 @@ pub enum DistanceArg {
|
||||
SnpTv,
|
||||
}
|
||||
|
||||
/// The distance matrix this invocation must compute, if any: the one asked for
|
||||
/// with `--distance`, else `jaccard` when `--nj`, `--upgma` or
|
||||
/// `--shared-kmers` needs a matrix to work from, else none — a matrix is never
|
||||
/// computed (nor written) just because nothing said otherwise.
|
||||
pub fn distance_to_compute(
|
||||
distance: Option<DistanceArg>,
|
||||
nj: bool,
|
||||
upgma: bool,
|
||||
shared_kmers: bool,
|
||||
) -> Option<DistanceArg> {
|
||||
distance.or_else(|| (nj || upgma || shared_kmers).then_some(DistanceArg::Jaccard))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod distance_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nothing_asked_nothing_computed() {
|
||||
assert!(distance_to_compute(None, false, false, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_and_shared_kmer_outputs_imply_jaccard() {
|
||||
for (nj, upgma, shared) in [(true, false, false), (false, true, false), (false, false, true)] {
|
||||
assert!(matches!(
|
||||
distance_to_compute(None, nj, upgma, shared),
|
||||
Some(DistanceArg::Jaccard)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_distance_wins() {
|
||||
assert!(matches!(
|
||||
distance_to_compute(Some(DistanceArg::Mash), true, true, true),
|
||||
Some(DistanceArg::Mash)
|
||||
));
|
||||
assert!(matches!(
|
||||
distance_to_compute(Some(DistanceArg::SnpJc), false, false, false),
|
||||
Some(DistanceArg::SnpJc)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
impl DistanceArg {
|
||||
/// `Some` for the whole-index metrics, `None` for `snp-*` values.
|
||||
pub fn as_classic(self) -> Option<DistanceMetric> {
|
||||
@@ -215,6 +260,15 @@ pub struct PhyloArgs {
|
||||
#[arg(long)]
|
||||
pub shannon: bool,
|
||||
|
||||
/// Write the same entropy scan as `--shannon` as a distribution
|
||||
/// (`<prefix>_shannon_summary.csv`): the number of families per entropy
|
||||
/// kind, number of genomes carrying the family, number of those without
|
||||
/// ambiguity and 0.05-bit entropy bin — a few hundred thousand lines at
|
||||
/// most, whatever the size of the index, instead of one line per family.
|
||||
/// Requires an already-built sibling annex, like `--shannon`.
|
||||
#[arg(long)]
|
||||
pub shannon_summary: bool,
|
||||
|
||||
/// Write a SNP-only pseudo-alignment (FASTA) — requires
|
||||
/// `--n-sites <N|all>` and an already-built sibling annex
|
||||
/// (`--sibling-annex` first, in this invocation or an earlier one).
|
||||
@@ -260,6 +314,24 @@ pub struct PhyloArgs {
|
||||
#[arg(long)]
|
||||
pub pair_balance: bool,
|
||||
|
||||
/// Write what the draw contains, from the very sites it kept
|
||||
/// (requires `--pseudo-alignment`, `--sankoff` or a `snp-*`
|
||||
/// `--distance`): `<prefix>_sample_genomes.csv` (per genome, the sites it
|
||||
/// has a call in and the informative sites it takes part in),
|
||||
/// `<prefix>_sample_carriers.csv` (sites and informative sites per number
|
||||
/// of carriers) and `<prefix>_sample_overlap.csv` (the sample's own
|
||||
/// genome × genome overlap matrix, to compare with `--family-overlap`).
|
||||
#[arg(long)]
|
||||
pub sample_stats: bool,
|
||||
|
||||
/// Write how the draw was spread over the layers of the index
|
||||
/// (requires `--pseudo-alignment`, `--sankoff` or a `snp-*`
|
||||
/// `--distance`): `<prefix>_sample_plan.csv`, one line per layer with the
|
||||
/// families eligible, their total weight, the layer's quota, the families
|
||||
/// drawn and the ones kept after masking.
|
||||
#[arg(long)]
|
||||
pub sample_plan: 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.
|
||||
@@ -371,7 +443,10 @@ pub struct PhyloArgs {
|
||||
#[arg(long, default_value = "100")]
|
||||
pub sankoff_cost_scale: f64,
|
||||
|
||||
/// Distance to compute — either a whole-index metric (`jaccard`,
|
||||
/// Distance matrix to compute and write — none is computed unless this
|
||||
/// is given, or `--nj`/`--upgma`/`--shared-kmers` is (they need a matrix
|
||||
/// and use `jaccard` then, see [`distance_to_compute`]). Either a
|
||||
/// whole-index metric (`jaccard`,
|
||||
/// `mash`, `hamming`, `bray-curtis`, ...) or a `snp-*` correction over
|
||||
/// the central-position SNP substitution spectrum (`snp-raw`, `snp-jc`,
|
||||
/// `snp-k2p`, `snp-k81`, `snp-f81`, `snp-t92`, `snp-tn93`, `snp-tv`) —
|
||||
@@ -381,8 +456,8 @@ pub struct PhyloArgs {
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`, "`--distance`
|
||||
/// unification" for the full catalog and why LogDet/Tajima-Nei/F84/
|
||||
/// HKY85 aren't offered yet).
|
||||
#[arg(long, value_enum, default_value = "jaccard")]
|
||||
pub distance: DistanceArg,
|
||||
#[arg(long, value_enum)]
|
||||
pub distance: Option<DistanceArg>,
|
||||
|
||||
/// Rate-heterogeneity correction (Jin-Nei gamma shape parameter `α`)
|
||||
/// for `snp-*` `--distance` values that support it
|
||||
|
||||
@@ -3,6 +3,7 @@ mod iqtree;
|
||||
mod phyg;
|
||||
mod phylip;
|
||||
mod sankoff;
|
||||
mod stats;
|
||||
mod tnt;
|
||||
|
||||
use std::io::{self, BufWriter, Write};
|
||||
@@ -18,9 +19,10 @@ use obikphylo::{Metrics, neighbor_joining, upgma};
|
||||
use obisys::{Reporter, Stage};
|
||||
use tracing::info;
|
||||
|
||||
use args::NSitesArg;
|
||||
use args::{DistanceArg, NSitesArg, distance_to_compute};
|
||||
use iqtree::write_iqtree;
|
||||
use phyg::write_sankoff_phyg;
|
||||
use stats::{write_sample_plan, write_sample_stats};
|
||||
use phylip::write_phylip_relaxed;
|
||||
use sankoff::{write_sankoff_alignment_fasta, write_sankoff_matrix_csv, write_sankoff_params};
|
||||
use tnt::write_sankoff_tnt;
|
||||
@@ -194,6 +196,21 @@ pub fn run(args: PhyloArgs) {
|
||||
info!("entropy report → {path}");
|
||||
}
|
||||
|
||||
// ── Shannon entropy distribution (`--shannon-summary`) ──────────────────────
|
||||
if args.shannon_summary {
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_shannon_summary.csv", p.display()))
|
||||
.unwrap_or_else(|| "shannon_summary.csv".into());
|
||||
info!("summarising per-family Shannon entropy");
|
||||
let t = Stage::start("shannon_summary");
|
||||
cache.shannon_entropy_summary(std::path::Path::new(&path)).unwrap_or_else(|e| {
|
||||
eprintln!("error summarising Shannon entropy: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
info!("entropy summary → {path}");
|
||||
}
|
||||
|
||||
// ── `--min-shared-family` auto-exclusion ────────────────────────────────────
|
||||
// Layered on top of `--exclude-genome`, not instead of it — a separate
|
||||
// mask (not folded into `exclude_mask` itself) since it must reach
|
||||
@@ -270,7 +287,8 @@ pub fn run(args: PhyloArgs) {
|
||||
// different sample per flag — see `obikphylo::siblings::LayerReducer`'s
|
||||
// own module docs).
|
||||
let sankoff_requested = args.sankoff || args.tnt || args.phyg || args.iqtree;
|
||||
let snp_kind = args.distance.as_snp();
|
||||
let distance = distance_to_compute(args.distance, args.nj, args.upgma, args.shared_kmers);
|
||||
let snp_kind = distance.and_then(DistanceArg::as_snp);
|
||||
let need_alignment = args.pseudo_alignment || sankoff_requested;
|
||||
let need_pairwise = sankoff_requested || snp_kind.is_some();
|
||||
// `None` = every site (`--n-sites all`, or `--n-sites` omitted where it is optional)
|
||||
@@ -284,10 +302,20 @@ pub fn run(args: PhyloArgs) {
|
||||
eprintln!("error: --sankoff requires --n-sites <N|all>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
if (args.sample_stats || args.sample_plan) && !(need_alignment || need_pairwise) {
|
||||
eprintln!(
|
||||
"error: --sample-stats/--sample-plan describe a draw: they need --pseudo-alignment, \
|
||||
--sankoff or a snp-* --distance"
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let mut alignment_reducer =
|
||||
need_alignment.then(|| obikphylo::siblings::AlignmentReducer::new(&cache, &snp_exclude_mask));
|
||||
let mut pairwise_reducer = need_pairwise.then(|| obikphylo::siblings::PairwiseReducer::new(n));
|
||||
let mut stats_reducer =
|
||||
args.sample_stats.then(|| obikphylo::siblings::SampleStatsReducer::new(n, &snp_exclude_mask));
|
||||
let mut sample_plan = None;
|
||||
|
||||
if need_alignment || need_pairwise {
|
||||
let mut reducers: Vec<&mut dyn obikphylo::siblings::LayerReducer> = Vec::new();
|
||||
@@ -297,6 +325,9 @@ pub fn run(args: PhyloArgs) {
|
||||
if let Some(r) = pairwise_reducer.as_mut() {
|
||||
reducers.push(r);
|
||||
}
|
||||
if let Some(r) = stats_reducer.as_mut() {
|
||||
reducers.push(r);
|
||||
}
|
||||
|
||||
info!(
|
||||
"sampling SNP sites{}",
|
||||
@@ -306,14 +337,24 @@ pub fn run(args: PhyloArgs) {
|
||||
}
|
||||
);
|
||||
let t = Stage::start("sampled_scan");
|
||||
obikphylo::siblings::sampled_scan(&cache, target, sampling, &snp_exclude_mask, &mut reducers)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error sampling SNP sites: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
sample_plan = Some(
|
||||
obikphylo::siblings::sampled_scan(&cache, target, sampling, &snp_exclude_mask, &mut reducers)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error sampling SNP sites: {e}");
|
||||
std::process::exit(1);
|
||||
}),
|
||||
);
|
||||
rep.push(t.stop());
|
||||
}
|
||||
|
||||
// ── What the draw contains and how it was spread (`--sample-stats`/`--sample-plan`) ──
|
||||
if let Some(reducer) = stats_reducer {
|
||||
write_sample_stats(&reducer.finish(), &labels, &snp_exclude_mask, &args.output);
|
||||
}
|
||||
if args.sample_plan {
|
||||
write_sample_plan(&sample_plan.expect("scanned above: need_alignment || need_pairwise"), &args.output);
|
||||
}
|
||||
|
||||
// Finished once here (not left as reducers) so `--pseudo-alignment`
|
||||
// and the Sankoff group can each read it below without fighting over
|
||||
// which one consumes it — see `SankoffBundle::finish`'s own docs.
|
||||
@@ -396,9 +437,17 @@ pub fn run(args: PhyloArgs) {
|
||||
}
|
||||
|
||||
// ── Distance computation: classic whole-index metric vs. `snp-*` ───────────
|
||||
// Nothing below (matrix, shared-kmer matrix, NJ/UPGMA trees) is wanted
|
||||
// unless a distance was asked for (`--distance`) or implied
|
||||
// (`--nj`/`--upgma`/`--shared-kmers`): stop here rather than compute and
|
||||
// write a matrix nobody requested.
|
||||
let Some(distance) = distance else {
|
||||
rep.print();
|
||||
return;
|
||||
};
|
||||
// Two genuinely different code paths behind one `--distance` value — see
|
||||
// `args::DistanceArg`'s own docs.
|
||||
let (matrix, shared_kmers) = match args.distance.as_classic() {
|
||||
let (matrix, shared_kmers) = match distance.as_classic() {
|
||||
Some(metric) => {
|
||||
info!("computing {metric:?} distances for {n} genome(s)");
|
||||
let need_shared = args.shared_kmers || args.nj || args.upgma;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
// Diagnostic CSV outputs of a draw — `--sample-stats`, `--sample-plan` — kept
|
||||
// out of `mod.rs` (already long) the way `tnt.rs`/`phyg.rs` hold their own
|
||||
// writers. Each writer only formats what `obikphylo` computed; none of them
|
||||
// decides anything.
|
||||
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use obikphylo::siblings::{SamplePlan, SampleStats};
|
||||
use tracing::info;
|
||||
|
||||
/// `<prefix>_<suffix>`, or `<suffix>` alone without `-o` — the convention of
|
||||
/// every other file `phylo` writes.
|
||||
fn output_path(output: &Option<PathBuf>, suffix: &str) -> String {
|
||||
match output {
|
||||
Some(prefix) => format!("{}_{suffix}", prefix.display()),
|
||||
None => suffix.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn create(path: &str) -> BufWriter<std::fs::File> {
|
||||
BufWriter::new(std::fs::File::create(path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}))
|
||||
}
|
||||
|
||||
/// `--sample-stats`: three CSV files describing what the draw contains.
|
||||
///
|
||||
/// - `_sample_genomes.csv`: per genome, the sampled sites it has a call in,
|
||||
/// their share of all sampled sites, and the informative sites in which it
|
||||
/// takes part in the bipartition; `excluded` genomes are listed with zeros.
|
||||
/// - `_sample_carriers.csv`: per number of carriers, the sampled sites and how
|
||||
/// many of them are informative.
|
||||
/// - `_sample_overlap.csv`: the sample's own genome × genome overlap matrix
|
||||
/// (sampled sites both genomes have a call in), same layout as
|
||||
/// `--family-overlap`, to set against the index's.
|
||||
pub fn write_sample_stats(
|
||||
stats: &SampleStats,
|
||||
labels: &[String],
|
||||
excluded: &[bool],
|
||||
output: &Option<PathBuf>,
|
||||
) {
|
||||
let n = stats.n_genomes;
|
||||
|
||||
let path = output_path(output, "sample_genomes.csv");
|
||||
let mut f = create(&path);
|
||||
writeln!(f, "genome,excluded,sites_with_call,share_of_sites,informative_sites").unwrap();
|
||||
for g in 0..n {
|
||||
let share = if stats.n_sites == 0 { 0.0 } else { stats.calls[g] as f64 / stats.n_sites as f64 };
|
||||
writeln!(
|
||||
f,
|
||||
"{},{},{},{:.6},{}",
|
||||
labels[g],
|
||||
excluded.get(g).copied().unwrap_or(false),
|
||||
stats.calls[g],
|
||||
share,
|
||||
stats.informative_calls[g]
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
info!("sample genomes → {path}");
|
||||
|
||||
let path = output_path(output, "sample_carriers.csv");
|
||||
let mut f = create(&path);
|
||||
writeln!(f, "n_carriers,sites,informative_sites").unwrap();
|
||||
for (carriers, (&sites, &informative)) in
|
||||
stats.sites_by_carriers.iter().zip(&stats.informative_by_carriers).enumerate()
|
||||
{
|
||||
if sites > 0 {
|
||||
writeln!(f, "{carriers},{sites},{informative}").unwrap();
|
||||
}
|
||||
}
|
||||
info!("sample carriers → {path}");
|
||||
|
||||
let path = output_path(output, "sample_overlap.csv");
|
||||
let mut f = create(&path);
|
||||
write!(f, "genome").unwrap();
|
||||
for label in labels.iter().take(n) {
|
||||
write!(f, ",{label}").unwrap();
|
||||
}
|
||||
writeln!(f).unwrap();
|
||||
for i in 0..n {
|
||||
write!(f, "{}", labels[i]).unwrap();
|
||||
for j in 0..n {
|
||||
write!(f, ",{}", stats.overlap(i, j)).unwrap();
|
||||
}
|
||||
writeln!(f).unwrap();
|
||||
}
|
||||
info!("sample overlap matrix → {path}");
|
||||
}
|
||||
|
||||
/// `--sample-plan`: `_sample_plan.csv`, one line per layer in the order the
|
||||
/// draw visited them — the families eligible, their total weight, the layer's
|
||||
/// quota, how many families were drawn and resolved, and how many survived
|
||||
/// masking. Only layer lines (a column sum is one `awk` away); the target and
|
||||
/// the total kept are logged.
|
||||
pub fn write_sample_plan(plan: &SamplePlan, output: &Option<PathBuf>) {
|
||||
let path = output_path(output, "sample_plan.csv");
|
||||
let mut f = create(&path);
|
||||
writeln!(f, "partition,layer,eligible,mass,quota,resolved,kept").unwrap();
|
||||
for layer in &plan.layers {
|
||||
writeln!(
|
||||
f,
|
||||
"{},{},{},{:.6},{},{},{}",
|
||||
layer.partition, layer.layer, layer.eligible, layer.mass, layer.quota, layer.resolved, layer.kept
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
info!(
|
||||
"sample plan ({} layer(s), target {}, kept {}) → {path}",
|
||||
plan.layers.len(),
|
||||
plan.target,
|
||||
plan.kept()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user