Files
obiskim/src/obikphylo/src/siblings/algorithms/subsample.rs
T
Eric Coissac fdfc1eb3dd Refactor siblings module and enhance sampling logic
Introduces filtering for scan families, handles genome exclusion arguments, refactors the `siblings` module architecture, and clarifies invariants for statistical calculations.
2026-10-13 08:45:26 +02:00

372 lines
16 KiB
Rust

//! Proportional per-layer sampling of non-monomorphic minorants, bounded to
//! `n` sites index-wide — a cross-partition-resolution-cost bound, not a
//! full scan (see `DevDocMD/architecture/siblings.md`, "`--subsample`/
//! `--shannon`").
//!
//! Per layer: a quota proportional to that layer's own non-monomorphic
//! minorant count (`quota = round(n * count_layer / total_count)`), reached
//! by walking [`minorant_selection::eligible_bitset_layer`]'s bit vector
//! circularly from a random start, in the same natural (physical, locality-
//! friendly) order the rest of this crate already batches through — never a
//! full random permutation, which would scatter access across the whole
//! layer instead of keeping nearby reads nearby.
//!
//! For each eligible family visited: a Bernoulli(`p`) draw decides whether
//! to *attempt* it this round — `p = p0` (`quota / count_layer`) uniformly,
//! or `p = p0 * kernel(entropy)` when [`EntropyBias`] is given (an
//! unnormalised Gaussian kernel over that family's already-built entropy
//! value — `1` exactly at `entropy == mu`, decaying smoothly away from it,
//! no hard cutoff). Entropy is read by zipping the round's own circular
//! index sequence against [`super::entropy::iter_full_entropy`]'s streamed
//! values (rotated to start at the same point, via
//! [`circular_entropy_values`]) — never a `HashMap`/`Vec` materialised
//! up front, just two more small mmap opens per round (cheap: page cache,
//! not real re-reads) — so biasing costs nothing beyond the plain uniform
//! path's own annex-bits work; the uniform path skips this stream
//! entirely. Rejected families stay eligible (bit untouched, may be drawn
//! again on a later lap); accepted ones are cleared immediately (bit set to
//! `false`) regardless of what happens next — once a family has been
//! resolved once, it is never revisited, whether it turned out to survive
//! post-hoc masking (`algorithms::masking`) or not.
//!
//! Accepted families are *not* resolved one at a time: `scan_layer_families`
//! re-reads a whole layer's k-mer stream on every call, so resolving in
//! small per-family increments would repeatedly re-pay that cost. Instead,
//! each round gathers a batch of accepted candidates (sized from the
//! previous round's observed survival rate, or optimistically `remaining`
//! on the first round) and resolves the whole batch in one
//! `scan_layer_families` call, bounded to
//! [`MAX_TOPUP_ROUNDS`] rounds per layer — a layer that still hasn't
//! reached its quota after that many rounds (or has exhausted its whole
//! circular walk) simply contributes fewer than its share; `n` sites
//! index-wide is a target, never a guarantee (see the project discussion
//! this implements).
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;
use obicompactvec::TempBitVecBuilder;
use obikidxcache::index_cache::IndexCache;
use obikindex::OKIResult;
use rand::RngExt;
use super::entropy::iter_full_entropy;
use super::family_scan::{Selection, scan_layer_families};
use super::is_fast_mode;
use super::masking::{masked_state, survives_masking};
use super::minorant_selection::eligible_bitset_layer;
use crate::siblings::FamilyMask;
use crate::siblings::extensions::SiblingBuilder;
/// Resolution rounds a single layer's sampling may take before giving up on
/// reaching its own quota — see the module docs on why a round batches many
/// accepted families rather than resolving them one at a time.
const MAX_TOPUP_ROUNDS: usize = 5;
/// One surviving family — already drawn (Bernoulli/entropy-bias), already
/// resolved (`scan_layer_families`), already passed post-hoc masking
/// (`super::masking::survives_masking`). `masked[g]` is genome `g`'s
/// [`super::masking::masked_state`] result — computed exactly once, here,
/// from the raw (per-family, per-genome) resolved state, *before*
/// `--free-loss`/`--no-ambiguity` are applied — never the raw state
/// itself: every consumer downstream (this family's own survival check,
/// its eventual alignment column, its contribution to the pairwise tally)
/// needs the masked view, and computing it once and sharing it is what
/// guarantees they can never disagree about what a genome's state was at
/// this site (see `algorithms::pairwise::reduce_pairwise`'s own docs for
/// the inconsistency that arose from each consumer masking independently).
/// An owned `Vec`: the borrowed slice `scan_layer_families` hands its own
/// callback doesn't outlive that callback, but a `SurvivingFamily` is meant
/// to be handed to [`sample_index`]'s caller as part of a whole layer's
/// batch, well after that callback returns.
pub struct SurvivingFamily {
pub family_idx: usize,
pub mask: FamilyMask,
pub masked: Vec<Option<u8>>,
}
/// Gaussian-kernel entropy bias parameters — `mu`/`sigma` are the
/// `--entropy`/`--entropy-sd` CLI values (defaulted by the caller, not
/// here). `pub`, not `pub(crate)`: part of the public signature of
/// [`super::scan::sampled_scan`].
#[derive(Clone, Copy)]
pub struct EntropyBias {
pub mu: f64,
pub sigma: f64,
}
/// [`iter_full_entropy`], rotated to start at `start` and wrap once back to
/// it — the same `family_idx` order [`sample_layer`]'s own circular index
/// sequence walks, so the two can be `.zip()`-ed directly. Two more streamed
/// passes over the layer's (small) annex/entropy files, not a materialised
/// `Vec`/`HashMap` — `iter_full_entropy` itself never allocates more than
/// its own iterator state.
fn circular_entropy_values(
layer_dir: &Path,
start: usize,
) -> OKIResult<impl Iterator<Item = f32> + use<>> {
let head = iter_full_entropy(layer_dir)?.skip(start);
let tail = iter_full_entropy(layer_dir)?.take(start);
Ok(head.chain(tail))
}
/// Samples up to `n` non-monomorphic families index-wide, proportionally
/// per layer, calling `on_layer(partition, layer, survivors)` once per
/// cached layer that contributed anything, with every family from that
/// layer that was both drawn *and* still carries real polymorphism after
/// `free_loss`/`no_ambiguity`/`excluded` masking
/// (`algorithms::masking::survives_masking`) — i.e. every
/// [`SurvivingFamily`] this produces is already a usable alignment site, no
/// second resolution pass needed by the caller. `excluded[g]` (see
/// `survives_masking`'s own docs) never counts genome `g` toward that check
/// — `SurvivingFamily::masked` itself still carries every genome's own
/// masked state, excluded or not, so a caller building per-genome output
/// (e.g. an alignment row) must apply the same exclusion itself when
/// consuming it.
///
/// `survivors` is a single `Arc<Vec<SurvivingFamily>>` — one allocation per
/// layer (bounded by that layer's own quota, never the whole index), handed
/// out already shared: a caller that wants several independent reduces over
/// the same batch (an alignment builder, a tally builder, ...) just clones
/// the `Arc` once per reduce (an `O(1)` refcount bump, no data copy) instead
/// of re-deriving or re-resolving anything — including handing a clone to
/// its own `rayon::join`/`scope` worker, since `Arc` (unlike a plain
/// borrowed slice) satisfies the `Send + 'static` those need.
///
/// `skip_layers`: the number of (partition, layer) pairs, in this
/// function's own iteration order (`cache.partitions()` then `0..n_layer`,
/// both deterministic for an unchanged index), to skip *entirely* —
/// neither their (cheap) eligibility-bitset lookup's `sample_layer` call
/// nor `on_layer` runs for them. Built for checkpointed-resume support
/// (quotas are computed from `total_eligible`, summed over *every* layer
/// regardless of `skip_layers`, so a resumed run reproduces the exact same
/// *per-layer quotas* an uninterrupted one would have — i.e. how many
/// sites each remaining layer contributes stays correct — without
/// reproducing the exact same *sample*: `sample_layer`'s draws come from
/// `rand::rng()`, a per-process, OS-seeded generator with no continuity
/// across a process boundary). No current caller passes anything but `0`:
/// the `--session`-based resume mechanism this was built for was removed
/// (see `algorithms::scan`'s own module docs) pending a rebuild on top of
/// [`sampled_scan`](super::scan::sampled_scan) — the parameter stays, as
/// the seam a future resume mechanism would hook into, rather than being
/// ripped out and re-added later.
///
/// Returns the actual number of *newly processed* sites kept (not
/// counting whatever `skip_layers` layers already contributed on an
/// earlier, interrupted call) — may be less than `n` (see the module
/// docs).
pub(crate) fn sample_index(
cache: &IndexCache,
n: usize,
free_loss: bool,
no_ambiguity: bool,
excluded: &[bool],
entropy_bias: Option<EntropyBias>,
skip_layers: usize,
mut on_layer: impl FnMut(usize, usize, usize, Arc<Vec<SurvivingFamily>>),
) -> OKIResult<usize> {
let n_genomes = cache.meta().genomes().len();
let fast_mode = is_fast_mode(cache);
// Entropy-biased mode reads each candidate's entropy from the entropy
// annex (`EntropyWeights::open`, per layer, below) — build any missing
// one now, once, rather than mid-walk.
if entropy_bias.is_some() {
cache.ensure_entropy_and_overlap_annexes()?;
}
// Every cached layer's eligibility bitset, built up front — annex-only,
// no cross-partition resolution, so cheap even summed over the whole
// index — needed before any layer's quota can be computed (each
// layer's share depends on every other layer's own count).
let mut layers: Vec<(usize, usize, TempBitVecBuilder, usize)> = Vec::new();
for part in cache.partitions() {
let n_layer = cache.n_layer(part).unwrap_or(0);
for l in 0..n_layer {
let layer = cache
.get_layer(part, l)
.expect("cache-consistent: n_layer(part) already bounds l");
let eligible = eligible_bitset_layer(layer.dir())?;
let n_minorants = eligible.view().len();
layers.push((part, l, eligible, n_minorants));
}
}
let total_eligible: u64 = layers
.iter()
.map(|(_, _, e, _)| e.view().count_ones())
.sum();
if total_eligible == 0 {
return Ok(0);
}
let mut total_kept = 0usize;
for (raw_index, (part, l, mut eligible, n_minorants)) in layers.into_iter().enumerate() {
if raw_index < skip_layers {
continue;
}
let count_layer = eligible.view().count_ones();
if count_layer == 0 {
continue;
}
let quota = ((n as u128 * count_layer as u128) / total_eligible as u128) as usize;
if quota == 0 {
continue;
}
total_kept += sample_layer(
cache,
part,
l,
raw_index,
&mut eligible,
n_minorants,
quota,
n_genomes,
fast_mode,
free_loss,
no_ambiguity,
excluded,
entropy_bias,
&mut on_layer,
)?;
}
Ok(total_kept)
}
/// One layer's share of [`sample_index`] — see the module docs for the
/// per-family accept/reject/mark rules and the round-batching scheme.
#[allow(clippy::too_many_arguments)]
fn sample_layer(
cache: &IndexCache,
partition: usize,
layer_idx: usize,
raw_index: usize,
eligible: &mut TempBitVecBuilder,
n_minorants: usize,
quota: usize,
n_genomes: usize,
fast_mode: bool,
free_loss: bool,
no_ambiguity: bool,
excluded: &[bool],
entropy_bias: Option<EntropyBias>,
on_layer: &mut impl FnMut(usize, usize, usize, Arc<Vec<SurvivingFamily>>),
) -> OKIResult<usize> {
if n_minorants == 0 {
return Ok(0);
}
let count_layer = eligible.view().count_ones() as usize;
if count_layer == 0 {
return Ok(0);
}
let p0 = (quota as f64 / count_layer as f64).min(1.0);
let layer_dir = cache
.get_layer(partition, layer_idx)
.expect("cache-consistent")
.dir()
.to_path_buf();
let mut rng = rand::rng();
let start = rng.random_range(0..n_minorants);
let mut visited = 0usize;
let mut kept = 0usize;
let mut resolved = 0usize; // total accepted (and resolved) so far, across every round
let mut survivors: Vec<SurvivingFamily> = Vec::new();
for _round in 0..MAX_TOPUP_ROUNDS {
// Stop on success (quota reached) or true exhaustion (every
// eligible family has been accepted at least once — rejected ones
// stay at `1` and keep getting fresh draws lap after lap, so this
// can only reach `0` once nothing is left to even attempt). Not
// bounded to one lap: `round_start` below already wraps past
// `n_minorants` correctly, so a layer with a low masking-survival
// rate can and does loop back around to retry earlier rejections,
// up to `MAX_TOPUP_ROUNDS` laps.
if kept >= quota || eligible.view().count_ones() == 0 {
break;
}
let remaining = quota - kept;
// Optimistic on the first round (assume every accepted family will
// survive masking); afterwards, size the next batch from the
// observed survival rate so a second round is likely to close the
// gap rather than needing all `MAX_TOPUP_ROUNDS`.
let survival_rate = if resolved == 0 {
1.0
} else {
(kept as f64 / resolved as f64).max(0.05)
};
let target_this_round = ((remaining as f64 / survival_rate).ceil() as usize).max(1);
// This round's own circular walk, resuming exactly where the
// previous round left off (`start + visited`, wrapped) — zipped
// against that same rotation of the entropy stream when biased, so
// each candidate's own kernel weight is read in lockstep, never via
// a separate lookup structure. Unbiased draws skip the entropy
// stream entirely (a flat `1.0` kernel), never touching the entropy
// annex.
let round_start = (start + visited) % n_minorants;
let entropies: Box<dyn Iterator<Item = f32>> = match entropy_bias {
Some(_) => Box::new(circular_entropy_values(&layer_dir, round_start)?),
None => Box::new(std::iter::repeat(0.0f32)), // never read: kernel forced to 1.0 below
};
let candidates = (round_start..n_minorants)
.chain(0..round_start)
.zip(entropies);
let mut accepted: HashSet<usize> = HashSet::new();
for (family_idx, entropy) in candidates {
visited += 1;
if !eligible.view().get(family_idx) {
continue;
}
let kernel = match entropy_bias {
Some(bias) => {
let d = (entropy as f64 - bias.mu) / bias.sigma;
(-0.5 * d * d).exp()
}
None => 1.0,
};
if rng.random::<f64>() < (p0 * kernel).min(1.0) {
eligible.set(family_idx, false);
accepted.insert(family_idx);
if accepted.len() >= target_this_round {
break;
}
}
}
if accepted.is_empty() {
break; // nothing left to try this lap
}
resolved += accepted.len();
scan_layer_families(
cache,
partition,
layer_idx,
n_genomes,
fast_mode,
&Selection::Some(&accepted),
|family_idx, mask, genome_mask| {
debug_assert!(
mask.family_size() >= 2,
"eligible bitset must only accept non-monomorphic minorants"
);
let masked: Vec<Option<u8>> =
genome_mask.iter().map(|&m| masked_state(m, free_loss, no_ambiguity)).collect();
if survives_masking(&masked, excluded) {
survivors.push(SurvivingFamily { family_idx, mask, masked });
kept += 1;
}
},
)?;
}
if !survivors.is_empty() {
on_layer(partition, layer_idx, raw_index, Arc::new(survivors));
}
Ok(kept)
}