Migrate index state tracking from filesystem sentinel files to an on-disk JSON schema within `index.meta`. The `IndexMeta` struct is now wrapped in an `Arc` with internal locking, exposing only fallible methods for genome and state access. In-memory mutation capabilities have been removed, requiring callers to handle I/O errors explicitly and pass immutable references to downstream components like `PartitionRouter`. Public sentinel constants have been removed from exports.
133 lines
5.8 KiB
Rust
133 lines
5.8 KiB
Rust
use std::sync::Arc;
|
|
|
|
use ndarray::Array2;
|
|
|
|
use obisys::progress_bar;
|
|
|
|
use obikindex::KmerIndex;
|
|
use obikindex::{OKIError, OKIResult};
|
|
|
|
use super::cache::PartitionCache;
|
|
use super::distance::RawSnpDistanceOutput;
|
|
use super::family_scan::{Selection, scan_layer_families};
|
|
|
|
/// See [`KmerIndex::cardinality_tally`].
|
|
pub struct CardinalityTally {
|
|
/// `counts[a][b] == counts[b][a]` = number of family sites, pooled over
|
|
/// included genome pairs, where one genome's family cardinality
|
|
/// (popcount of its presence mask, `0..=4`) is `a` and the other's is
|
|
/// `b`. Diagonal is real data here (both genomes at the same
|
|
/// cardinality), unlike [`super::distance::BasePairTally::counts`].
|
|
pub counts: [[u64; 5]; 5],
|
|
}
|
|
|
|
/// Adds [`cardinality_tally`](Self::cardinality_tally) to `KmerIndex`.
|
|
pub trait CardinalityExt {
|
|
/// Cardinality co-occurrence, pooled only over genome pairs whose
|
|
/// overall SNP ratio in `raw` is at or below `ratio_ceiling` — same
|
|
/// saturation/no-data exclusion discipline as
|
|
/// [`base_pair_tally`](Self::base_pair_tally). Unlike
|
|
/// `scan_family_pairs` (which resolves each genome to a single form and
|
|
/// silently drops any genome carrying more than one member of the
|
|
/// family), this needs the *full* per-genome presence mask — a family
|
|
/// member count of 2, 3 or 4 is exactly the signal being tallied, not
|
|
/// noise to discard — so it re-implements the traversal rather than
|
|
/// reusing that helper.
|
|
///
|
|
/// Restricted to variable families (`family_size() >= 2`), matching
|
|
/// `snp_pseudo_alignment`'s own scope — briefly removed, then
|
|
/// reinstated: without it, the diagonal is dominated by genome-wide
|
|
/// invariant background (family_size()<2 loci vastly outnumber the
|
|
/// ones that ever vary anywhere), which is inconsistent with the
|
|
/// `+ASC`-corrected alignment this matrix is ultimately used with —
|
|
/// `+ASC` exists specifically because the likelihood only ever sees
|
|
/// variable sites, so a rate model calibrated mostly from invariant
|
|
/// background sites doesn't describe the population it's applied to.
|
|
/// Verified empirically: removing the filter measurably worsened a
|
|
/// real IQ-TREE run (log-likelihood dropped, `NNI search needs
|
|
/// unusual large number of steps to converge` warnings appeared) — see
|
|
/// `DevDocMD/theory/evolutionary_distances.md` for the full account.
|
|
/// [`base_pair_tally`](Self::base_pair_tally)'s own diagonal (`same`)
|
|
/// gets the matching restriction via `scan_family_pairs`'s new
|
|
/// `variable` flag, rather than a `family_size()` check of its own (it
|
|
/// doesn't have direct access to the family's mask).
|
|
fn cardinality_tally(
|
|
&self,
|
|
raw: &RawSnpDistanceOutput,
|
|
ratio_ceiling: f64,
|
|
) -> OKIResult<CardinalityTally>;
|
|
}
|
|
|
|
impl CardinalityExt for KmerIndex {
|
|
fn cardinality_tally(
|
|
&self,
|
|
raw: &RawSnpDistanceOutput,
|
|
ratio_ceiling: f64,
|
|
) -> OKIResult<CardinalityTally> {
|
|
let n_parts = self.n_partitions();
|
|
let n_genomes = self.meta().genomes().map_err(OKIError::Io)?.len();
|
|
let with_counts = self.meta().config.with_counts;
|
|
let k = self.kmer_size();
|
|
let included = Array2::from_shape_fn((n_genomes, n_genomes), |(i, j)| {
|
|
if i == j {
|
|
return false;
|
|
}
|
|
let snp = raw.snp[[i, j]];
|
|
let total = snp + raw.shared[[i, j]];
|
|
total > 0 && (snp as f64 / total as f64) <= ratio_ceiling
|
|
});
|
|
|
|
let cache = Arc::new(PartitionCache::build(self, n_parts, with_counts)?);
|
|
let layer_dirs = super::family_scan::sibling_layer_dirs(self)?;
|
|
|
|
let pb = progress_bar("cardinality_tally", layer_dirs.len() as u64, "layers");
|
|
// One layer at a time — see `snp_pseudo_alignment`'s comment for why
|
|
// `par_iter()` over layers would defeat `scan_layer_families`'s
|
|
// partition-grouped locality. Tallied straight into `total` as each
|
|
// family comes back — no per-layer buffer.
|
|
let mut total = [[0u64; 5]; 5];
|
|
for layer_dir in &layer_dirs {
|
|
scan_layer_families(
|
|
layer_dir,
|
|
n_parts,
|
|
n_genomes,
|
|
with_counts,
|
|
k,
|
|
&cache,
|
|
&Selection::All,
|
|
|_family_idx, mask, genome_mask| {
|
|
if mask.family_size() < 2 {
|
|
// Fully invariant family (never varies anywhere in
|
|
// the index) — genome-wide background, not
|
|
// SNP-adjacent signal; would otherwise swamp the
|
|
// diagonal (`c=1/c=1` etc.), which needs to reflect
|
|
// the same variable-families-only population the
|
|
// `+ASC`-corrected alignment/likelihood actually
|
|
// models. See `base_pair_tally`'s `variable` gate
|
|
// on its own `same` diagonal for the matching fix.
|
|
return;
|
|
}
|
|
|
|
for i in 0..n_genomes {
|
|
let card_i = genome_mask[i].count_ones() as usize;
|
|
for j in (i + 1)..n_genomes {
|
|
if !included[[i, j]] {
|
|
continue;
|
|
}
|
|
let card_j = genome_mask[j].count_ones() as usize;
|
|
total[card_i][card_j] += 1;
|
|
if card_i != card_j {
|
|
total[card_j][card_i] += 1;
|
|
}
|
|
}
|
|
}
|
|
},
|
|
)?;
|
|
pb.inc(1);
|
|
}
|
|
pb.finish_and_clear();
|
|
|
|
Ok(CardinalityTally { counts: total })
|
|
}
|
|
}
|