feat: add k-mer sharing estimation and Poisson-binomial null model
Add a new `estimate --index` command to compare observed k-mer sharing against a random-sequence model using a Poisson-binomial distribution. Introduce the `row_presence_histogram` API to support this analysis across various matrix types. Update documentation and dependencies accordingly. - Add `src/obikstats/src/null_model.rs` implementing `SharingNullModel` and `SharingRow` for computing cumulative probabilities and false discovery rates based on a Poisson-binomial distribution. - Add `src/obikstats/src/sharing.rs` defining `GenomeSharing` and `SharingSpectrum` to compute k-mer sharing spectra using parallel map-reduce. - Add `src/obikmer/src/cmd/estimate/sharing.rs` with `run` and `write_csv` to execute sharing estimation and output CSV results containing observed, expected, and deviation metrics. - Modify `src/obikmer/src/cmd/estimate/mod.rs` to support the new `--index` subcommand, adding `EstimateArgs` fields for index path, presence threshold, and output file. - Add `src/obicompactvec/src/row_histogram.rs` implementing `row_presence_histogram` for `PersistentIntMatrix`, `PersistentBitMatrix`, and sparse matrices to count rows present in exactly $j$ columns. - Update `src/obikindex/src/layer/content_layer.rs` and `src/obikindex/src/layer/typed_layer.rs` to expose the new `row_presence_histogram` method, dispatching based on layer type. - Add tests in `src/obicompactvec/src/tests/bitmatrix.rs`, `intmatrix.rs`, and `sparse.rs` to verify `count_geq` and `row_presence_histogram` against naive implementations for various matrix structures. - Update `UserDocMD/theory/kmer_indexing/kmers.md` to document the Poisson-binomial approach, $D_r$ bounds, and FDR calculations, replacing previous binomial approximations. - Update `UserDocMD/usage/estimate.md` to describe the two uses of `estimate`: parameter estimation and index comparison via `--index`. - Add `wiki` target to `Makefile` for regenerating documentation from user docs. - Bump `obikmer` package version from 1.4.5 to 1.4.6 in `Cargo.toml` and `Cargo.lock`.
This commit is contained in:
1 parent
6d6d5e5e53
commit
36c7247acb
17 files changed
+970
-378
No files matched your search
@@ -10,6 +10,10 @@
|
||||
//! `run`), built on `obikidxcache::IndexCache` rather than hand-opening
|
||||
//! each layer's files.
|
||||
|
||||
mod null_model;
|
||||
mod sharing;
|
||||
mod stats;
|
||||
|
||||
pub use null_model::{SharingNullModel, SharingRow};
|
||||
pub use sharing::{GenomeSharing, SharingSpectrum};
|
||||
pub use stats::{BitsPerKmer, GenomeKmerCounts, IndexBitsPerKmer};
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Random-sequence null model for k-mer sharing (`kmers.md`, "Distinguishing
|
||||
//! random from non-random k-mer sharing").
|
||||
//!
|
||||
//! Each genome `i` is modelled as a uniform random set of `N_i` distinct
|
||||
//! canonical k-mers drawn from the `M = 4^k / 2` canonical k-mers (exact for
|
||||
//! odd `k`: no k-mer is its own reverse complement). A given k-mer is then in
|
||||
//! genome `i` with probability `p_i = N_i / M`, independently across genomes,
|
||||
//! so the number `X` of genomes holding it is Poisson-binomial.
|
||||
|
||||
use crate::SharingSpectrum;
|
||||
|
||||
/// One row of the comparison between observed and expected sharing.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct SharingRow {
|
||||
pub r: usize,
|
||||
/// `k_r`: k-mers present in at least `r` genomes.
|
||||
pub k_r: u64,
|
||||
/// `O_r = k_r / k_1`.
|
||||
pub observed: f64,
|
||||
/// `q_r = P(X >= r | X >= 1)` under the null model.
|
||||
pub expected: f64,
|
||||
/// `D_r = O_r - q_r`.
|
||||
pub deviation: f64,
|
||||
/// `M_k P_null(X >= r)`: k-mers expected to reach `r` genomes by chance
|
||||
/// over the whole canonical k-mer space.
|
||||
pub expected_false_positives: f64,
|
||||
/// `FDR(r)`: 1 when `k_r = 0`, else `min(1, M_k P_null(X >= r) / k_r)`.
|
||||
pub fdr: f64,
|
||||
}
|
||||
|
||||
/// Poisson-binomial law of the number of genomes holding a random k-mer.
|
||||
pub struct SharingNullModel {
|
||||
/// Size `M_k = 4^k / 2` of the canonical k-mer space.
|
||||
m: f64,
|
||||
p: Vec<f64>,
|
||||
}
|
||||
|
||||
impl SharingNullModel {
|
||||
/// `genome_kmers[i]` is `N_i`; `k` is the (indexed) k-mer size, odd.
|
||||
pub fn new(genome_kmers: &[u64], k: usize) -> Self {
|
||||
let m = 4f64.powi(k as i32) / 2.0;
|
||||
Self { m, p: genome_kmers.iter().map(|&n| (n as f64 / m).min(1.0)).collect() }
|
||||
}
|
||||
|
||||
/// `P(X >= r)` for `r = 0..=S`, by the dynamic programme of `kmers.md`
|
||||
/// (genomes added one at a time, `O(S^2)`), then summed from the upper
|
||||
/// end so that tiny tail probabilities keep their precision (no
|
||||
/// `1 - Σ` cancellation).
|
||||
pub fn tail(&self) -> Vec<f64> {
|
||||
let s = self.p.len();
|
||||
let mut dist = vec![0.0f64; s + 1];
|
||||
dist[0] = 1.0;
|
||||
for (i, &p) in self.p.iter().enumerate() {
|
||||
for j in (1..=i + 1).rev() {
|
||||
dist[j] = dist[j] * (1.0 - p) + dist[j - 1] * p;
|
||||
}
|
||||
dist[0] *= 1.0 - p;
|
||||
}
|
||||
let mut acc = 0.0;
|
||||
for v in dist.iter_mut().rev() {
|
||||
acc += *v;
|
||||
*v = acc;
|
||||
}
|
||||
dist
|
||||
}
|
||||
|
||||
/// The rows `r = 1..=S` of observed against expected sharing.
|
||||
///
|
||||
/// Errors when the index records no k-mer (`k_1 = 0`): `O_r` is undefined.
|
||||
/// `q_r` is taken as 0 when `P(X >= 1)` underflows to 0 (no genome can
|
||||
/// hold anything).
|
||||
pub fn compare(&self, spectrum: &SharingSpectrum) -> Result<Vec<SharingRow>, String> {
|
||||
let k_at_least = spectrum.k_at_least();
|
||||
let k1 = *k_at_least.get(1).ok_or("the index has no genome")?;
|
||||
if k1 == 0 {
|
||||
return Err("the index records no k-mer present in any genome".into());
|
||||
}
|
||||
let tail = self.tail();
|
||||
let p1 = tail[1];
|
||||
Ok((1..tail.len())
|
||||
.map(|r| {
|
||||
let observed = k_at_least[r] as f64 / k1 as f64;
|
||||
let expected = if p1 > 0.0 { tail[r] / p1 } else { 0.0 };
|
||||
let k_r = k_at_least[r];
|
||||
let expected_false_positives = self.m * tail[r];
|
||||
let fdr = if k_r == 0 { 1.0 } else { (expected_false_positives / k_r as f64).min(1.0) };
|
||||
SharingRow {
|
||||
r,
|
||||
k_r,
|
||||
observed,
|
||||
expected,
|
||||
deviation: observed - expected,
|
||||
expected_false_positives,
|
||||
fdr,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn binom(n: usize, k: usize) -> f64 {
|
||||
(1..=k).fold(1.0, |a, i| a * (n + 1 - i) as f64 / i as f64)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_probabilities_give_the_binomial_tail() {
|
||||
// k = 3: M = 32, N_i = 8 → p = 0.25 for all four genomes.
|
||||
let m = SharingNullModel::new(&[8, 8, 8, 8], 3);
|
||||
let tail = m.tail();
|
||||
let (p, s) = (0.25f64, 4usize);
|
||||
for r in 0..=s {
|
||||
let expected: f64 =
|
||||
(r..=s).map(|j| binom(s, j) * p.powi(j as i32) * (1.0 - p).powi((s - j) as i32)).sum();
|
||||
assert!((tail[r] - expected).abs() < 1e-12, "r={r}: {} vs {expected}", tail[r]);
|
||||
}
|
||||
assert!((tail[0] - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_probabilities_two_genomes() {
|
||||
// p = (0.5, 0.25): P(X>=1) = 1 - 0.5*0.75, P(X>=2) = 0.125.
|
||||
let m = SharingNullModel { m: 1.0, p: vec![0.5, 0.25] };
|
||||
let t = m.tail();
|
||||
assert!((t[1] - 0.625).abs() < 1e-15);
|
||||
assert!((t[2] - 0.125).abs() < 1e-15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiny_tail_keeps_its_precision() {
|
||||
// k = 31, N = 1e9: p ≈ 2.2e-10; P(X>=3) over 3 genomes = p^3 ≈ 1e-29,
|
||||
// far below what `1 - Σ` could resolve.
|
||||
let m = SharingNullModel::new(&[1_000_000_000; 3], 31);
|
||||
let p = 1e9 / (4f64.powi(31) / 2.0);
|
||||
assert!((m.tail()[3] / p.powi(3) - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_first_row_has_zero_deviation() {
|
||||
let spectrum = SharingSpectrum { genome_kmers: vec![10, 10], hist: vec![0, 15, 5] };
|
||||
let rows = SharingNullModel::new(&spectrum.genome_kmers, 11).compare(&spectrum).unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(rows[0].k_r, 20);
|
||||
assert_eq!(rows[1].k_r, 5);
|
||||
assert!((rows[0].observed - 1.0).abs() < 1e-15);
|
||||
assert!(rows[0].deviation.abs() < 1e-12); // D_1 = 0 by construction
|
||||
assert!((rows[1].observed - 0.25).abs() < 1e-15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fdr_is_expected_false_positives_over_k_r_capped_at_one() {
|
||||
// k = 3: M = 32; N = (8, 8) → p = 0.25 each; P(X>=2) = 0.0625.
|
||||
let model = SharingNullModel::new(&[8, 8], 3);
|
||||
// 10 k-mers in exactly 1 genome, 2 in both → k_1 = 12, k_2 = 2.
|
||||
let spectrum = SharingSpectrum { genome_kmers: vec![8, 8], hist: vec![0, 10, 2] };
|
||||
let rows = model.compare(&spectrum).unwrap();
|
||||
// r = 2: FP = 32 * 0.0625 = 2; FDR = 2 / 2 = 1 (not below the cap).
|
||||
assert!((rows[1].expected_false_positives - 2.0).abs() < 1e-12);
|
||||
assert!((rows[1].fdr - 1.0).abs() < 1e-12);
|
||||
// r = 1: FP = 32 * (1 - 0.75^2) = 14 > k_1 = 12 → capped at 1.
|
||||
assert!((rows[0].expected_false_positives - 14.0).abs() < 1e-12);
|
||||
assert!((rows[0].fdr - 1.0).abs() < 1e-12);
|
||||
// Fewer expected false positives than observed: 20 of 22 k-mers shared.
|
||||
let spectrum = SharingSpectrum { genome_kmers: vec![8, 8], hist: vec![0, 2, 20] };
|
||||
let rows = model.compare(&spectrum).unwrap();
|
||||
assert!((rows[1].fdr - 2.0 / 20.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fdr_is_one_when_no_kmer_reaches_r() {
|
||||
let model = SharingNullModel::new(&[8, 8, 8], 3);
|
||||
let spectrum = SharingSpectrum { genome_kmers: vec![8, 8, 8], hist: vec![0, 12, 0, 0] };
|
||||
let rows = model.compare(&spectrum).unwrap();
|
||||
assert_eq!(rows[2].k_r, 0);
|
||||
assert_eq!(rows[2].fdr, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_index_is_an_error() {
|
||||
let spectrum = SharingSpectrum { genome_kmers: vec![0, 0], hist: vec![0, 0, 0] };
|
||||
assert!(SharingNullModel::new(&spectrum.genome_kmers, 11).compare(&spectrum).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! How the k-mers of an index are shared across its genomes — the data the
|
||||
//! null-model comparison of `DevDocMD`/`UserDocMD` `kmers.md` needs: the
|
||||
//! number `N_i` of distinct k-mers of each genome and the number `k_r` of
|
||||
//! k-mers present in at least `r` genomes.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use obikalgorithm::Algorithm;
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikindex::KmerIndex;
|
||||
|
||||
/// Layers scanned at once per `par_map_reduce` call — see
|
||||
/// `obikidxcache::IndexCache::par_map_reduce`'s own docs.
|
||||
const MAX_CONCURRENT_LAYERS: usize = 8;
|
||||
|
||||
/// Result of [`GenomeSharing`].
|
||||
pub struct SharingSpectrum {
|
||||
/// `N_i`: distinct k-mers present in genome `i`, one entry per genome.
|
||||
pub genome_kmers: Vec<u64>,
|
||||
/// `hist[j]`: number of k-mers present in exactly `j` genomes;
|
||||
/// `n_genomes + 1` entries. `hist[0]` is non-zero only when the presence
|
||||
/// threshold discards every occurrence of some k-mer.
|
||||
pub hist: Vec<u64>,
|
||||
}
|
||||
|
||||
impl SharingSpectrum {
|
||||
pub fn n_genomes(&self) -> usize {
|
||||
self.genome_kmers.len()
|
||||
}
|
||||
|
||||
/// `k_r` for `r = 0..=n_genomes`: number of k-mers present in at least
|
||||
/// `r` genomes. `k_at_least()[1]` is `k_1`, the number of k-mers
|
||||
/// present in at least one genome.
|
||||
pub fn k_at_least(&self) -> Vec<u64> {
|
||||
let mut k = vec![0u64; self.hist.len()];
|
||||
let mut acc = 0u64;
|
||||
for r in (0..self.hist.len()).rev() {
|
||||
acc += self.hist[r];
|
||||
k[r] = acc;
|
||||
}
|
||||
k
|
||||
}
|
||||
}
|
||||
|
||||
/// Single pass over every layer computing a [`SharingSpectrum`]. A k-mer is
|
||||
/// present in a genome when its value reaches `threshold` (on a presence
|
||||
/// index every recorded k-mer is present, whatever `threshold`), so both `N_i`
|
||||
/// and the histogram are taken at the same threshold. A k-mer lives in a
|
||||
/// single layer of its partition, so per-layer results add up exactly.
|
||||
pub struct GenomeSharing {
|
||||
index: Arc<KmerIndex>,
|
||||
threshold: u32,
|
||||
}
|
||||
|
||||
impl GenomeSharing {
|
||||
pub fn new(index: Arc<KmerIndex>, threshold: u32) -> Self {
|
||||
Self { index, threshold }
|
||||
}
|
||||
}
|
||||
|
||||
/// `acc[i] += add[i]`, growing `acc` when `add` is longer.
|
||||
fn add_into(acc: &mut Vec<u64>, add: &[u64]) {
|
||||
if acc.len() < add.len() {
|
||||
acc.resize(add.len(), 0);
|
||||
}
|
||||
for (a, b) in acc.iter_mut().zip(add) {
|
||||
*a += b;
|
||||
}
|
||||
}
|
||||
|
||||
type Partial = obikalgorithm::Result<(Vec<u64>, Vec<u64>)>;
|
||||
|
||||
impl Algorithm for GenomeSharing {
|
||||
type Output = SharingSpectrum;
|
||||
|
||||
fn run(&mut self) -> obikalgorithm::Result<SharingSpectrum> {
|
||||
let n_genomes = self.index.meta().genomes()?.len();
|
||||
let threshold = self.threshold;
|
||||
let cache = IndexCache::new(Arc::clone(&self.index), None);
|
||||
|
||||
let (genome_kmers, hist) = cache.par_map_reduce(
|
||||
MAX_CONCURRENT_LAYERS,
|
||||
|| -> Partial { Ok((Vec::new(), Vec::new())) },
|
||||
|layer| -> Partial {
|
||||
let per_genome = layer.count_geq(threshold).to_vec();
|
||||
let hist = layer.row_presence_histogram(threshold)?;
|
||||
Ok((per_genome, hist))
|
||||
},
|
||||
|a, b| -> Partial {
|
||||
let (mut ga, mut ha) = a?;
|
||||
let (gb, hb) = b?;
|
||||
add_into(&mut ga, &gb);
|
||||
add_into(&mut ha, &hb);
|
||||
Ok((ga, ha))
|
||||
},
|
||||
)?;
|
||||
|
||||
let mut genome_kmers = genome_kmers;
|
||||
let mut hist = hist;
|
||||
if genome_kmers.len() > n_genomes || hist.len() > n_genomes + 1 {
|
||||
return Err(format!(
|
||||
"a layer has more genome columns than the index declares ({n_genomes} genomes)"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// A layer may carry fewer columns than the index has genomes (and an
|
||||
// index may have no layer at all): the missing columns are absent.
|
||||
genome_kmers.resize(n_genomes, 0);
|
||||
hist.resize(n_genomes + 1, 0);
|
||||
Ok(SharingSpectrum { genome_kmers, hist })
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user