Implement advanced sampling and family annex logic
Introduces complex sampling mechanisms including quartet filtering, pair balance weighting, and entropy bias. Enforces the `--no-ambiguity` convention for family counting and updates annex storage for scalar data. This includes new logic for calculating family weights based on overlap, quota-based layer determination, and filtering families based on quartet informativeness. Updates also include argument parsing for `--n-sites` and improved handling of family overlap files.
This commit is contained in:
1 parent
0d12494f1a
commit
f29dcbcfb8
25 files changed
+1471
-486
No files matched your search
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "obikmer"
|
||||
version = "1.3.5"
|
||||
version = "1.3.6"
|
||||
edition = "2024"
|
||||
|
||||
[[bin]]
|
||||
|
||||
@@ -32,6 +32,36 @@ fn parse_gamma_shape(s: &str) -> Result<GammaShapeArg, String> {
|
||||
.map_err(|_| format!("invalid --gamma-shape value {s:?}: expected a positive number or \"auto\"/\"estimate\""))
|
||||
}
|
||||
|
||||
/// `--n-sites` CLI value: a number of sites to draw, or `all` for every site
|
||||
/// — the draw then keeps every variable family that passes the other filters,
|
||||
/// with no sampling involved. Its own tiny type (like [`GammaShapeArg`]) so
|
||||
/// the two cases stay distinct up to the call that needs the target, instead
|
||||
/// of an in-band sentinel (a negative number, `0`, ...) that a typo could hit.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NSitesArg {
|
||||
All,
|
||||
N(usize),
|
||||
}
|
||||
|
||||
impl NSitesArg {
|
||||
/// The target to hand to the sampler: `None` = exhaustive.
|
||||
pub fn target(self) -> Option<usize> {
|
||||
match self {
|
||||
NSitesArg::All => None,
|
||||
NSitesArg::N(n) => Some(n),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_n_sites(s: &str) -> Result<NSitesArg, String> {
|
||||
if s.eq_ignore_ascii_case("all") {
|
||||
return Ok(NSitesArg::All);
|
||||
}
|
||||
s.parse::<usize>()
|
||||
.map(NSitesArg::N)
|
||||
.map_err(|_| format!("invalid --n-sites value {s:?}: expected a non-negative integer or \"all\""))
|
||||
}
|
||||
|
||||
/// `--distance` value — either one of `obikphylo::DistanceMetric`'s
|
||||
/// whole-index metrics (routed to `IndexCache::distance`) or one of
|
||||
/// `obikphylo::SnpDistanceKind`'s `snp-*` corrections (routed to
|
||||
@@ -108,7 +138,7 @@ impl DistanceArg {
|
||||
/// (classic metrics + `snp-*` corrections/NJ/UPGMA), annex construction
|
||||
/// (`--sibling-annex`), annex diagnostics (`--sibling-stats`,
|
||||
/// `--sibling-hist`), entropy reporting (`--shannon`), SNP pseudo-alignment
|
||||
/// sampling (`--pseudo-alignment`, `--subsample`, `--free-loss`,
|
||||
/// sampling (`--pseudo-alignment`, `--n-sites`, `--free-loss`,
|
||||
/// `--no-ambiguity`, `--entropy`/`--entropy-sd`), Sankoff cost-matrix
|
||||
/// calibration (`--sankoff`, `--sankoff-ratio-ceiling`) and its TNT/PhyG/
|
||||
/// IQ-TREE exports (`--tnt`, `--phyg`, `--iqtree`/`--iqtree-min-freq`,
|
||||
@@ -180,26 +210,25 @@ 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). Always a full, unsampled scan of
|
||||
/// every family (`--subsample`/`--entropy`/`--entropy-sd` below only
|
||||
/// every family (`--n-sites`/`--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
|
||||
/// `--n-sites <N|all>` 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`/`--sankoff` (mandatory for both) and for a
|
||||
/// `snp-*` `--distance` value (optional there: omitted means exhaustive
|
||||
/// — every non-monomorphic minorant of the whole index, not an
|
||||
/// approximation) — a target, not a guarantee when given (proportional
|
||||
/// per-layer sampling; see `obikphylo::siblings::sampled_scan`'s own
|
||||
/// docs).
|
||||
#[arg(long)]
|
||||
pub subsample: Option<usize>,
|
||||
/// Number of variable sites to draw index-wide, or `all` for every site
|
||||
/// that passes the other filters (no sampling then). Mandatory for
|
||||
/// `--pseudo-alignment`/`--sankoff`; optional for a `snp-*`
|
||||
/// `--distance` value, where omitting it also means every site. A
|
||||
/// number is a target, not a guarantee (proportional per-layer
|
||||
/// sampling; see `obikphylo::siblings::sampled_scan`'s own docs).
|
||||
#[arg(long = "n-sites", value_name = "N|all", value_parser = parse_n_sites)]
|
||||
pub n_sites: Option<NSitesArg>,
|
||||
|
||||
/// In `--pseudo-alignment`, treat a genome carrying none of a family's
|
||||
/// observed members (`∅`) as missing data (`?`) rather than a real
|
||||
@@ -213,6 +242,24 @@ pub struct PhyloArgs {
|
||||
#[arg(long)]
|
||||
pub no_ambiguity: bool,
|
||||
|
||||
/// In `--pseudo-alignment`/`--sankoff`/`snp-*` `--distance`, keep only
|
||||
/// the families that can separate two pairs of genomes from each other
|
||||
/// (a bipartition): at least two distinct called states, each carried
|
||||
/// by at least two genomes. A singleton variant, or a family carried by
|
||||
/// fewer than four genomes, fits every topology and tells a tree
|
||||
/// nothing. Which genomes count as carriers follows `--no-ambiguity`.
|
||||
#[arg(long)]
|
||||
pub quartet: bool,
|
||||
|
||||
/// In `--pseudo-alignment`/`--sankoff`/`snp-*` `--distance`, favour the
|
||||
/// families that cover the pairs of genomes sharing the fewest families
|
||||
/// across the index: each family is weighted by the mean, over the pairs
|
||||
/// of genomes carrying it, of 1 / (number of families the pair shares).
|
||||
/// Evens out how well each pair of genomes is represented in the sample.
|
||||
/// Which genomes count as carriers follows `--no-ambiguity`.
|
||||
#[arg(long)]
|
||||
pub pair_balance: 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.
|
||||
@@ -227,7 +274,7 @@ pub struct PhyloArgs {
|
||||
/// Persist the `snp-*` `--distance` sample (the pairwise substitution
|
||||
/// tally) in `DIR` across separate `obikmer phylo` invocations: a later
|
||||
/// run against the same index with the exact same
|
||||
/// `--subsample`/`--free-loss`/`--no-ambiguity`/`--exclude-genome`/
|
||||
/// `--n-sites`/`--free-loss`/`--no-ambiguity`/`--quartet`/`--exclude-genome`/
|
||||
/// `--min-shared-family`/`--entropy`/`--entropy-sd` restores it instead
|
||||
/// of resampling. `DIR` is created if it doesn't exist. If it already
|
||||
/// holds a sample built under *different* selection parameters, this
|
||||
@@ -247,7 +294,7 @@ pub struct PhyloArgs {
|
||||
|
||||
/// Calibrate a 16-state Sankoff cost matrix (and its matching
|
||||
/// pseudo-alignment) from an already-built sibling annex — requires
|
||||
/// `--subsample <N>`, and shares `--free-loss`/`--no-ambiguity`/
|
||||
/// `--n-sites <N|all>`, and shares `--free-loss`/`--no-ambiguity`/`--quartet`/
|
||||
/// `--entropy`/`--entropy-sd` with `--pseudo-alignment` (one draw, same
|
||||
/// selection feeds both the alignment and every calibration tally).
|
||||
#[arg(long)]
|
||||
|
||||
@@ -11,13 +11,14 @@ use std::sync::Arc;
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikindex::KmerIndex;
|
||||
use obikphylo::siblings::{
|
||||
EntropyBias, GammaShape, SiblingExt, cardinality_transition_probs,
|
||||
EntropyBias, GammaShape, SamplingSpec, SiblingExt, cardinality_transition_probs,
|
||||
composition_transition_probs, pairwise_cost_matrix,
|
||||
};
|
||||
use obikphylo::{Metrics, neighbor_joining, upgma};
|
||||
use obisys::{Reporter, Stage};
|
||||
use tracing::info;
|
||||
|
||||
use args::NSitesArg;
|
||||
use iqtree::write_iqtree;
|
||||
use phyg::write_sankoff_phyg;
|
||||
use phylip::write_phylip_relaxed;
|
||||
@@ -154,7 +155,7 @@ pub fn run(args: PhyloArgs) {
|
||||
// ── Family Overlap matrix (`--family-overlap`) ──────────────────────────────
|
||||
if args.family_overlap {
|
||||
let t = Stage::start("family_overlap");
|
||||
let overlap = cache.family_overlap().unwrap_or_else(|e| {
|
||||
let overlap = cache.family_overlap(args.no_ambiguity).unwrap_or_else(|e| {
|
||||
eprintln!("error computing family overlap: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
@@ -201,7 +202,7 @@ pub fn run(args: PhyloArgs) {
|
||||
// `args::PhyloArgs::min_shared_family`'s own docs on why).
|
||||
let snp_exclude_mask: Vec<bool> = match args.min_shared_family {
|
||||
Some(threshold) => {
|
||||
let overlap = cache.family_overlap().unwrap_or_else(|e| {
|
||||
let overlap = cache.family_overlap(args.no_ambiguity).unwrap_or_else(|e| {
|
||||
eprintln!("error computing family overlap: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
@@ -235,6 +236,13 @@ pub fn run(args: PhyloArgs) {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let sampling = SamplingSpec {
|
||||
free_loss: args.free_loss,
|
||||
no_ambiguity: args.no_ambiguity,
|
||||
quartet: args.quartet,
|
||||
pair_balance: args.pair_balance,
|
||||
entropy_bias,
|
||||
};
|
||||
|
||||
// ── `--session` ──────────────────────────────────────────────────────────
|
||||
// Temporarily unavailable: the per-driver checkpoint/resume plumbing
|
||||
@@ -253,7 +261,7 @@ pub fn run(args: PhyloArgs) {
|
||||
|
||||
// ── Sampled SNP scan (`--pseudo-alignment`, Sankoff group, `snp-*` `--distance`) ──
|
||||
// All three consume exactly the same selection parameters
|
||||
// (`--subsample`/`--free-loss`/`--no-ambiguity`/`--exclude-genome`/
|
||||
// (`--n-sites`/`--free-loss`/`--no-ambiguity`/`--quartet`/`--exclude-genome`/
|
||||
// `--min-shared-family`/`--entropy`/`--entropy-sd`), and must draw from
|
||||
// the *same* random sample when combined in one invocation — so
|
||||
// whichever of them are requested here share exactly one
|
||||
@@ -265,13 +273,15 @@ pub fn run(args: PhyloArgs) {
|
||||
let snp_kind = args.distance.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)
|
||||
let target = args.n_sites.and_then(NSitesArg::target);
|
||||
|
||||
if args.pseudo_alignment && args.subsample.is_none() {
|
||||
eprintln!("error: --pseudo-alignment requires --subsample <N>");
|
||||
if args.pseudo_alignment && args.n_sites.is_none() {
|
||||
eprintln!("error: --pseudo-alignment requires --n-sites <N|all>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
if sankoff_requested && args.subsample.is_none() {
|
||||
eprintln!("error: --sankoff requires --subsample <N>");
|
||||
if sankoff_requested && args.n_sites.is_none() {
|
||||
eprintln!("error: --sankoff requires --n-sites <N|all>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
@@ -290,13 +300,13 @@ pub fn run(args: PhyloArgs) {
|
||||
|
||||
info!(
|
||||
"sampling SNP sites{}",
|
||||
match args.subsample {
|
||||
match target {
|
||||
Some(n) => format!(" (target {n} site(s))"),
|
||||
None => " (exhaustive)".into(),
|
||||
}
|
||||
);
|
||||
let t = Stage::start("sampled_scan");
|
||||
obikphylo::siblings::sampled_scan(&cache, args.subsample, args.free_loss, args.no_ambiguity, &snp_exclude_mask, entropy_bias, &mut reducers)
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user