Refactor algorithms for unified sampling and reduction

Introduces a unified sampling trunk, new reducer traits, and refined logic for SNP distance calculation and session handling. Enforces strict parameter sharing across all algorithms to ensure consistent sampling.
This commit is contained in:
Eric Coissac committed 2026-10-13 08:43:06 +02:00
1 parent 0d1ecac233
commit 1702addbf9
12 files changed
+320 -760

No files matched your search

+83 -130
View File
@@ -24,43 +24,6 @@ use phylip::write_phylip_relaxed;
use sankoff::{write_sankoff_alignment_fasta, write_sankoff_matrix_csv, write_sankoff_params};
use tnt::write_sankoff_tnt;
/// Deterministic byte encoding of the `snp-*` `--distance` selection
/// parameters, for `obiksession::Session::open`'s params-conflict check.
/// `obiksession` treats this as an opaque blob (see its own crate docs) —
/// only this module needs to know the layout, and only well enough to
/// produce/compare it, never to pretty-print a per-field diff (v1 keeps
/// the conflict message generic rather than decoding both sides field by
/// field — see its use in `run` below).
fn session_params_blob(
n: Option<usize>,
free_loss: bool,
no_ambiguity: bool,
excluded: &[bool],
entropy_bias: Option<EntropyBias>,
) -> Vec<u8> {
let mut buf = Vec::new();
match n {
Some(v) => {
buf.push(1);
buf.extend_from_slice(&(v as u64).to_le_bytes());
}
None => buf.push(0),
}
buf.push(free_loss as u8);
buf.push(no_ambiguity as u8);
buf.extend_from_slice(&(excluded.len() as u64).to_le_bytes());
buf.extend(excluded.iter().map(|&b| b as u8));
match entropy_bias {
Some(EntropyBias { mu, sigma }) => {
buf.push(1);
buf.extend_from_slice(&mu.to_le_bytes());
buf.extend_from_slice(&sigma.to_le_bytes());
}
None => buf.push(0),
}
buf
}
pub use args::PhyloArgs;
pub fn run(args: PhyloArgs) {
@@ -273,63 +236,83 @@ pub fn run(args: PhyloArgs) {
None
};
// ── `--session`: persist the snp-* sample across separate invocations ──
// Only covers `snp-*` `--distance` today (see `--session`'s own docs);
// `None` when `--session` isn't given, matching today's always-resample
// default exactly.
let session = args.session.as_ref().map(|dir| {
let params = session_params_blob(
args.subsample,
args.free_loss,
args.no_ambiguity,
&snp_exclude_mask,
entropy_bias,
// ── `--session` ──────────────────────────────────────────────────────────
// Temporarily unavailable: the per-driver checkpoint/resume plumbing
// it relied on (`algorithms::session_cache`) was removed along with
// the three independent sampling drivers it patched over (see
// `algorithms::scan`'s own module docs) — persistence needs to be
// rebuilt on top of the new single `sampled_scan` trunk instead of
// silently becoming a no-op.
if args.session.is_some() {
eprintln!(
"error: --session is temporarily unavailable (being rebuilt on top of the unified \
sampling trunk) — rerun without --session/--session-force"
);
match obiksession::Session::open(dir, &params, args.session_force) {
Ok(Ok(session)) => {
match session.outcome() {
obiksession::SessionOutcome::Created => {
info!("--session {}: starting fresh", dir.display());
}
obiksession::SessionOutcome::Reused => {
info!("--session {}: found, will reuse its cached sample if present", dir.display());
}
}
session
}
Ok(Err(_conflict)) => {
eprintln!(
"error: --session {} was built with different selection parameters \
(--subsample/--free-loss/--no-ambiguity/--exclude-genome/--min-shared-family/\
--entropy/--entropy-sd) than this run — pass --session-force to discard its \
cached sample and start fresh, or point --session at a different directory",
dir.display()
);
std::process::exit(1);
}
Err(e) => {
eprintln!("error opening --session {}: {e}", dir.display());
std::process::exit(1);
}
}
std::process::exit(1);
}
// ── Sampled SNP scan (`--pseudo-alignment`, Sankoff group, `snp-*` `--distance`) ──
// All three consume exactly the same selection parameters
// (`--subsample`/`--free-loss`/`--no-ambiguity`/`--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
// `sampled_scan` call, each contributing only the reducer(s) it needs,
// instead of each running its own scan (which used to silently draw a
// 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 need_alignment = args.pseudo_alignment || sankoff_requested;
let need_pairwise = sankoff_requested || snp_kind.is_some();
if args.pseudo_alignment && args.subsample.is_none() {
eprintln!("error: --pseudo-alignment requires --subsample <N>");
std::process::exit(1);
}
if sankoff_requested && args.subsample.is_none() {
eprintln!("error: --sankoff requires --subsample <N>");
std::process::exit(1);
}
let mut alignment_reducer = need_alignment.then(|| {
obikphylo::siblings::AlignmentReducer::new(&cache, &snp_exclude_mask, args.free_loss, args.no_ambiguity)
});
let mut pairwise_reducer = need_pairwise.then(|| obikphylo::siblings::PairwiseReducer::new(n));
// ── 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);
};
if need_alignment || need_pairwise {
let mut reducers: Vec<&mut dyn obikphylo::siblings::LayerReducer> = Vec::new();
if let Some(r) = alignment_reducer.as_mut() {
reducers.push(r);
}
if let Some(r) = pairwise_reducer.as_mut() {
reducers.push(r);
}
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, &snp_exclude_mask, entropy_bias)
info!(
"sampling SNP sites{}",
match args.subsample {
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)
.unwrap_or_else(|e| {
eprintln!("error building pseudo-alignment: {e}");
eprintln!("error sampling SNP sites: {e}");
std::process::exit(1);
});
rep.push(t.stop());
}
// 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.
let alignment = alignment_reducer.map(obikphylo::siblings::AlignmentReducer::finish);
// ── SNP pseudo-alignment (`--pseudo-alignment`) ─────────────────────────────
if args.pseudo_alignment {
let alignment = alignment.as_ref().expect("scanned above: need_alignment");
let path = args.output.as_ref()
.map(|p| format!("{}_alignment.fasta", p.display()))
@@ -350,33 +333,17 @@ pub fn run(args: PhyloArgs) {
// `snp-*` `--distance` branch below can reuse its already-sampled
// tally instead of resampling — see `SankoffBundle::snp_distance`'s own
// docs for why that's required for correctness, not just speed, when
// both are requested in the same invocation (they always share the
// same `n`/`free_loss`/`no_ambiguity`/excluded-set/`entropy_bias`: the
// CLI has no way to give them different values in one run).
// both are requested in the same invocation.
let mut bundle = None;
if args.sankoff || args.tnt || args.phyg || args.iqtree {
let Some(subsample_n) = args.subsample else {
eprintln!("error: --sankoff requires --subsample <N>");
std::process::exit(1);
};
info!("sampling Sankoff calibration bundle (target {subsample_n} site(s))");
let t = Stage::start("sankoff_bundle");
let b = cache
.sankoff_bundle(
subsample_n,
args.free_loss,
args.no_ambiguity,
&snp_exclude_mask,
entropy_bias,
args.sankoff_ratio_ceiling,
session.as_ref(),
)
.unwrap_or_else(|e| {
eprintln!("error computing Sankoff calibration bundle: {e}");
std::process::exit(1);
});
rep.push(t.stop());
if sankoff_requested {
let alignment = alignment.clone().expect("scanned above: need_alignment");
let pairwise = pairwise_reducer.take().expect("scanned above: need_pairwise");
let b = obikphylo::siblings::SankoffBundle::finish(
alignment,
pairwise,
args.sankoff_ratio_ceiling,
&snp_exclude_mask,
);
let p_card = cardinality_transition_probs(&b.cardinality_tally);
let p_comp = composition_transition_probs(&b.base_pair_tally);
@@ -441,7 +408,7 @@ pub fn run(args: PhyloArgs) {
eprintln!("error: --shared-kmers has no meaning for a snp-* --distance value");
std::process::exit(1);
}
let kind = args.distance.as_snp().expect("DistanceArg is always classic or snp");
let kind = snp_kind.expect("DistanceArg is always classic or snp");
let gamma_shape = args.gamma_shape.map_or(GammaShape::Disabled, Into::into);
let t = Stage::start("snp_distance");
let matrix = match &bundle {
@@ -453,23 +420,9 @@ pub fn run(args: PhyloArgs) {
b.snp_distance(kind, gamma_shape)
}
None => {
info!(
"computing {kind:?} SNP distance for {n} genome(s){}",
match args.subsample {
Some(n) => format!(" (subsampled, target {n} site(s))"),
None => " (exhaustive)".into(),
}
);
cache.snp_distance(
kind,
args.subsample,
args.free_loss,
args.no_ambiguity,
&snp_exclude_mask,
entropy_bias,
gamma_shape,
session.as_ref(),
)
info!("computing {kind:?} SNP distance for {n} genome(s) (reusing the sampled scan above)");
let (tally, dispersion) = pairwise_reducer.take().expect("scanned above: need_pairwise").finish();
obikphylo::siblings::distance_matrix(&tally, &dispersion, kind, gamma_shape)
}
}
.unwrap_or_else(|e| {