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
Generated
+1
-1
@@ -1531,7 +1531,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "obikmer"
|
||||
version = "1.4.5"
|
||||
version = "1.4.6"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"csv",
|
||||
|
||||
@@ -14,6 +14,7 @@ mod meta;
|
||||
mod mmap_file;
|
||||
mod rankselect;
|
||||
mod reader;
|
||||
mod row_histogram;
|
||||
mod sparse_intmatrix;
|
||||
mod sparse_intmatrix_columnar;
|
||||
mod storage_kind;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Row-wise presence histogram — how many k-mers (matrix rows) are present
|
||||
//! in exactly `j` genomes (columns), for every `j`.
|
||||
//!
|
||||
//! Row-major for `Sparse` (no on-disk column representation: a `col_view`
|
||||
//! there is a deliberate `panic!`, so a column could only be synthesised by
|
||||
//! scanning every row anyway), column-major otherwise — same split, same
|
||||
//! reasons as [`crate::batch_presence_counts`] and
|
||||
//! [`crate::batch_int_group_stats`], which this reuses and mirrors.
|
||||
//!
|
||||
//! The result is additive across layers and partitions: summing the vectors
|
||||
//! gives the histogram of the whole index.
|
||||
|
||||
use std::io;
|
||||
|
||||
use crate::bitmatrix::batch_presence_counts;
|
||||
use crate::colgroup::{ColGroup, chunked_presence_count};
|
||||
use crate::intmatrix::PersistentIntMatrix;
|
||||
use crate::tempintvec::TempCompactIntVec;
|
||||
use crate::PersistentBitMatrix;
|
||||
|
||||
/// Tallies a per-row presence-count vector into `hist[j]` = number of rows
|
||||
/// whose count is `j`. `hist` has `n_cols + 1` entries.
|
||||
fn tally(counts: &TempCompactIntVec, n_cols: usize) -> Vec<u64> {
|
||||
let mut hist = vec![0u64; n_cols + 1];
|
||||
for c in counts.view().iter() {
|
||||
hist[c as usize] += 1;
|
||||
}
|
||||
hist
|
||||
}
|
||||
|
||||
impl PersistentIntMatrix {
|
||||
/// `hist[j]` = number of rows (k-mers) present in exactly `j` columns
|
||||
/// (genomes), a cell being present when its count reaches `threshold`.
|
||||
/// Length `n_cols() + 1`; `hist[0]` counts rows present nowhere, which
|
||||
/// is possible when `threshold > 1`. `threshold == 0` makes every cell
|
||||
/// present: all rows land in `hist[n_cols()]`.
|
||||
pub fn row_presence_histogram(&self, threshold: u32) -> io::Result<Vec<u64>> {
|
||||
let n_cols = self.n_cols();
|
||||
if threshold == 0 {
|
||||
let mut hist = vec![0u64; n_cols + 1];
|
||||
hist[n_cols] = self.n() as u64;
|
||||
return Ok(hist);
|
||||
}
|
||||
match self {
|
||||
Self::Sparse(m) => {
|
||||
let mut hist = vec![0u64; n_cols + 1];
|
||||
for slot in 0..m.n() {
|
||||
let mut present = 0usize;
|
||||
m.for_each_cell_in_row(slot, |_, v| present += usize::from(v >= threshold));
|
||||
hist[present] += 1;
|
||||
}
|
||||
Ok(hist)
|
||||
}
|
||||
Self::Columnar(_) | Self::Packed(_) => {
|
||||
let cols: Vec<usize> = (0..n_cols).collect();
|
||||
let counts = chunked_presence_count(self.n(), &cols, |b, c| {
|
||||
b.inc_predicate_fast(self.col_view(c), |v| v >= threshold)
|
||||
})?;
|
||||
Ok(tally(&counts, n_cols))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PersistentBitMatrix {
|
||||
/// `hist[j]` = number of rows (k-mers) present in exactly `j` columns
|
||||
/// (genomes). Length `n_cols() + 1`. A presence matrix holds no counts,
|
||||
/// so there is no threshold: every set bit is present.
|
||||
pub fn row_presence_histogram(&self) -> io::Result<Vec<u64>> {
|
||||
let n_cols = self.n_cols();
|
||||
let all = ColGroup::new("all", (0..n_cols).collect());
|
||||
let counts = batch_presence_counts(self, std::slice::from_ref(&all))?
|
||||
.pop()
|
||||
.expect("one group in, one count vector out");
|
||||
Ok(tally(&counts, n_cols))
|
||||
}
|
||||
}
|
||||
@@ -304,3 +304,31 @@ fn col_view_packed_matches_columnar() {
|
||||
}
|
||||
drop(dir_col);
|
||||
}
|
||||
|
||||
// ── count_geq (ColumnWeights) ─────────────────────────────────────────────────
|
||||
|
||||
/// A presence matrix holds no counts: `count_geq` is `count_ones` for any
|
||||
/// threshold, so a presence index is unaffected by `--presence-threshold`.
|
||||
#[test]
|
||||
fn count_geq_ignores_threshold() {
|
||||
use crate::traits::ColumnWeights;
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true, true],
|
||||
&[false, false, false, false],
|
||||
&[true, true, true, false],
|
||||
]);
|
||||
for t in [0u32, 1, 2, 100] {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), vec![3, 0, 3], "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_presence_histogram_dense() {
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true, true],
|
||||
&[false, false, true, false],
|
||||
&[true, false, true, false],
|
||||
]);
|
||||
// Rows carry 2, 0, 3, 1 genomes.
|
||||
assert_eq!(m.row_presence_histogram().unwrap(), vec![1, 1, 1, 1]);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use tempfile::tempdir;
|
||||
|
||||
use crate::traits::CountPartials;
|
||||
use crate::traits::{ColumnWeights, CountPartials};
|
||||
use crate::{
|
||||
PersistentCompactIntMatrixBuilder, PersistentCompactIntVec, PersistentCompactIntVecBuilder,
|
||||
PersistentIntMatrix, StorageKind, pack_compact_int_matrix, pack_sparse_compact_int_matrix,
|
||||
@@ -682,3 +682,133 @@ fn intslice_view_collect_slots_values() {
|
||||
assert_eq!(view.collect_slots_values(&[0, 1, 2]), vec![10, 255, 300]);
|
||||
assert_eq!(view.collect_slots_values(&[3, 1]), vec![1000, 255]);
|
||||
}
|
||||
|
||||
// ── count_geq (ColumnWeights) ─────────────────────────────────────────────────
|
||||
|
||||
/// Naive per-column `count(v >= threshold)` over column-major `data`.
|
||||
fn naive_count_geq(data: &[&[u32]], threshold: u32) -> Vec<u64> {
|
||||
data.iter().map(|col| col.iter().filter(|&&v| v >= threshold).count() as u64).collect()
|
||||
}
|
||||
|
||||
/// Thresholds straddling 0, 1, the primary-byte limit (255) and the overflow values.
|
||||
const GEQ_THRESHOLDS: [u32; 10] = [0, 1, 2, 5, 10, 254, 255, 256, 500, 1001];
|
||||
|
||||
#[test]
|
||||
fn count_geq_columnar_matches_naive() {
|
||||
let data: &[&[u32]] = &[&[0, 1, 2, 300, 255], &[5, 0, 0, 0, 1000], &[0, 0, 0, 0, 0]];
|
||||
let (_d, m) = make_matrix(data);
|
||||
assert_eq!(m.storage_kind(), StorageKind::Columnar);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_geq_packed_matches_naive() {
|
||||
let data: &[&[u32]] = &[&[10, 300, 500, 0], &[200, 50, 1000, 1]];
|
||||
let (dir, _col) = make_matrix(data);
|
||||
pack_compact_int_matrix(&dir.path().join("counts")).unwrap();
|
||||
let m = PersistentIntMatrix::open(dir.path()).unwrap();
|
||||
assert_eq!(m.storage_kind(), StorageKind::Packed);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_geq_sparse_enum_matches_naive() {
|
||||
let data: &[&[u32]] = &[&[0, 5, 0, 3, 700], &[2, 0, 0, 4, 0], &[0, 0, 9, 0, 1]];
|
||||
let (dir, _col) = make_matrix(data);
|
||||
pack_sparse_compact_int_matrix(&dir.path().join("counts")).unwrap();
|
||||
let m = PersistentIntMatrix::open(dir.path()).unwrap();
|
||||
assert_eq!(m.storage_kind(), StorageKind::Sparse);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_kmer_counts_is_count_geq_one() {
|
||||
let data: &[&[u32]] = &[&[0, 1, 2, 300], &[5, 0, 0, 0]];
|
||||
let (_d, m) = make_matrix(data);
|
||||
assert_eq!(m.partial_kmer_counts().to_vec(), m.count_nonzero().to_vec());
|
||||
assert_eq!(m.partial_kmer_counts().to_vec(), ColumnWeights::count_geq(&m, 1).to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pciv_count_geq_matches_naive() {
|
||||
let counts = [0u32, 1, 2, 254, 255, 256, 1000];
|
||||
let (_dir, v) = make_pciv(&counts);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
let expected = counts.iter().filter(|&&c| c >= t).count() as u64;
|
||||
assert_eq!(v.count_geq(t), expected, "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── row_presence_histogram ────────────────────────────────────────────────────
|
||||
|
||||
/// Naive reference: for each row, how many columns reach `threshold`.
|
||||
fn naive_row_hist(data: &[&[u32]], threshold: u32) -> Vec<u64> {
|
||||
let n = data[0].len();
|
||||
let mut hist = vec![0u64; data.len() + 1];
|
||||
for slot in 0..n {
|
||||
hist[data.iter().filter(|col| col[slot] >= threshold).count()] += 1;
|
||||
}
|
||||
hist
|
||||
}
|
||||
|
||||
const HIST_DATA: &[&[u32]] = &[
|
||||
&[0, 1, 2, 300, 255, 0],
|
||||
&[5, 0, 0, 0, 1000, 0],
|
||||
&[0, 7, 0, 3, 1, 0],
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn row_presence_histogram_columnar_matches_naive() {
|
||||
let (_d, m) = make_matrix(HIST_DATA);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_presence_histogram_packed_matches_naive() {
|
||||
let (dir, _m) = make_matrix(HIST_DATA);
|
||||
pack_compact_int_matrix(&dir.path().join("counts")).unwrap();
|
||||
let m = PersistentIntMatrix::open(dir.path()).unwrap();
|
||||
assert_eq!(m.storage_kind(), StorageKind::Packed);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_presence_histogram_sparse_matches_naive() {
|
||||
let (dir, _m) = make_matrix(HIST_DATA);
|
||||
pack_sparse_compact_int_matrix(&dir.path().join("counts")).unwrap();
|
||||
let m = PersistentIntMatrix::open(dir.path()).unwrap();
|
||||
assert_eq!(m.storage_kind(), StorageKind::Sparse);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// More than 254 columns exercises `chunked_presence_count`'s chunked path
|
||||
/// (per-row counts above the `u8` primary range).
|
||||
#[test]
|
||||
fn row_presence_histogram_many_columns() {
|
||||
// 300 columns × 4 rows: row r is present (value 1) in the first
|
||||
// [0, 300, 7, 255] columns respectively.
|
||||
let present = [0usize, 300, 7, 255];
|
||||
let cols: Vec<Vec<u32>> = (0..300)
|
||||
.map(|c| present.iter().map(|&p| u32::from(c < p)).collect())
|
||||
.collect();
|
||||
let col_refs: Vec<&[u32]> = cols.iter().map(Vec::as_slice).collect();
|
||||
let (_d, m) = make_matrix(&col_refs);
|
||||
let hist = m.row_presence_histogram(1).unwrap();
|
||||
assert_eq!(hist.len(), 301);
|
||||
for p in present {
|
||||
assert_eq!(hist[p], 1, "rows present in {p} columns");
|
||||
}
|
||||
assert_eq!(hist.iter().sum::<u64>(), 4);
|
||||
}
|
||||
@@ -443,3 +443,30 @@ fn build_permuted_follows_the_permutation() {
|
||||
assert_eq!(row_as_bool(&permuted, new), row_as_bool(&src, old as usize), "new row {new}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_count_geq_ignores_threshold() {
|
||||
use crate::traits::ColumnWeights;
|
||||
let rows: &[&[bool]] = &[&[true, false, true], &[false, false, true], &[true, false, false]];
|
||||
let (_d, m) = make_sparse(rows, 3);
|
||||
for t in [0u32, 1, 2, 100] {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), vec![2, 0, 2], "threshold {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_row_presence_histogram_matches_dense() {
|
||||
let cols: &[&[bool]] = &[
|
||||
&[true, false, true, true, false],
|
||||
&[false, false, true, false, false],
|
||||
&[true, false, true, false, false],
|
||||
];
|
||||
let (_dd, dense) = make_dense(cols);
|
||||
let rows: Vec<Vec<bool>> = (0..5).map(|s| cols.iter().map(|c| c[s]).collect()).collect();
|
||||
let row_refs: Vec<&[bool]> = rows.iter().map(Vec::as_slice).collect();
|
||||
let (_ds, sparse) = make_sparse(&row_refs, 3);
|
||||
let sparse = PersistentBitMatrix::Sparse(sparse);
|
||||
assert_eq!(sparse.row_presence_histogram().unwrap(), dense.row_presence_histogram().unwrap());
|
||||
// Rows carry 2, 0, 3, 1, 0 genomes.
|
||||
assert_eq!(sparse.row_presence_histogram().unwrap(), vec![2, 1, 1, 1]);
|
||||
}
|
||||
@@ -266,6 +266,18 @@ impl KmerLayer {
|
||||
}
|
||||
}
|
||||
|
||||
/// `hist[j]` = number of k-mers of this layer present in exactly `j`
|
||||
/// genomes (length `n_cols() + 1`), a k-mer being present when its count
|
||||
/// reaches `threshold` — presence layers hold no counts, so `threshold`
|
||||
/// has no effect there. Additive across layers.
|
||||
pub fn row_presence_histogram(&self, threshold: u32) -> OKIResult<Vec<u64>> {
|
||||
match self {
|
||||
KmerLayer::Count { layer, .. } => layer.row_presence_histogram(threshold),
|
||||
KmerLayer::Presence { layer, .. } => layer.row_presence_histogram(),
|
||||
KmerLayer::Empty { .. } => panic!("Layer::row_presence_histogram() called on an Empty layer"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Batch, genome-major "carries" for a set of `slots` — `out[g][i]` =
|
||||
/// whether genome `g` (0..`out.len()`) carries `slots[i]`. `out` must
|
||||
/// have one entry per genome column, each resized to `slots.len()`.
|
||||
|
||||
@@ -395,6 +395,13 @@ impl TypedLayer<PersistentIntMatrix> {
|
||||
self.data.n_cols()
|
||||
}
|
||||
|
||||
/// `hist[j]` = number of k-mers of this layer present in exactly `j`
|
||||
/// genomes, a k-mer being present in a genome when its count reaches
|
||||
/// `threshold` (see `PersistentIntMatrix::row_presence_histogram`).
|
||||
pub fn row_presence_histogram(&self, threshold: u32) -> OKIResult<Vec<u64>> {
|
||||
self.data.row_presence_histogram(threshold).map_err(OKIError::Io)
|
||||
}
|
||||
|
||||
/// Extract a sub-matrix of counts for the rows at `slots`.
|
||||
///
|
||||
/// Returns a column-first `Vec<Vec<u32>>`: one inner `Vec` per genome
|
||||
@@ -518,6 +525,12 @@ impl<D: LayerData<Item = Box<[bool]>> + BinaryMatrix + obicompactvec::ColumnWeig
|
||||
}
|
||||
|
||||
impl TypedLayer<PersistentBitMatrix> {
|
||||
/// `hist[j]` = number of k-mers of this layer present in exactly `j`
|
||||
/// genomes (see `PersistentBitMatrix::row_presence_histogram`).
|
||||
pub fn row_presence_histogram(&self) -> OKIResult<Vec<u64>> {
|
||||
self.data.row_presence_histogram().map_err(OKIError::Io)
|
||||
}
|
||||
|
||||
/// Every nonzero `(idx into slots, col, value)` triple among `slots` —
|
||||
/// delegates to `PersistentBitMatrix::nonzero_iter`.
|
||||
pub fn nonzero_iter<'a>(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "obikmer"
|
||||
version = "1.4.5"
|
||||
version = "1.4.6"
|
||||
edition = "2024"
|
||||
|
||||
[[bin]]
|
||||
|
||||
@@ -1,9 +1,38 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
|
||||
use super::index::resolve_approx_params;
|
||||
|
||||
mod sharing;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct EstimateArgs {
|
||||
/// Compare the k-mer sharing of an index with a random-sequence model
|
||||
///
|
||||
/// Instead of the approximate-index report, reads INDEX and writes a CSV
|
||||
/// with one row per r = 1..S (S = number of genomes): `r`; `k_r`, the
|
||||
/// number of k-mers present in at least r genomes; `O_r = k_r/k_1`, the
|
||||
/// observed proportion; `q_r`, the proportion expected by chance when
|
||||
/// each genome is a random set of k-mers of its own size; and
|
||||
/// `D_r = O_r - q_r`, positive when k-mers are shared more than chance
|
||||
/// predicts. Cannot be combined with -k, -z, --evidence-bits or --fp.
|
||||
#[arg(long, value_name = "INDEX",
|
||||
conflicts_with_all = ["kmer_size", "findere_z", "evidence_bits", "fp"])]
|
||||
pub index: Option<PathBuf>,
|
||||
|
||||
/// Minimum k-mer count to count as present (with --index)
|
||||
///
|
||||
/// Same meaning as in `phylo`: on an index that stores counts, a k-mer
|
||||
/// is present in a genome only when its count reaches this threshold.
|
||||
/// It has no effect on indexes without counts.
|
||||
#[arg(long, default_value = "1", requires = "index")]
|
||||
pub presence_threshold: u32,
|
||||
|
||||
/// Write the CSV to this file instead of standard output (with --index)
|
||||
#[arg(short = 'o', long, value_name = "FILE", requires = "index")]
|
||||
pub output: Option<PathBuf>,
|
||||
|
||||
/// k-mer size used for querying (same as --kmer-size in index)
|
||||
#[arg(short = 'k', long, default_value_t = 31)]
|
||||
pub kmer_size: usize,
|
||||
@@ -23,6 +52,10 @@ pub struct EstimateArgs {
|
||||
}
|
||||
|
||||
pub fn run(args: EstimateArgs) {
|
||||
if let Some(index) = &args.index {
|
||||
sharing::run(index, args.presence_threshold, args.output.as_deref());
|
||||
return;
|
||||
}
|
||||
let (z, b, fp_window) = resolve_approx_params(args.findere_z, args.evidence_bits, args.fp);
|
||||
|
||||
let k_query = args.kmer_size;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! `estimate --index`: observed k-mer sharing against the random-sequence
|
||||
//! null model, as a CSV (see `DevDocMD`/`UserDocMD` `kmers.md`).
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufWriter, Write};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use obikalgorithm::Algorithm;
|
||||
use obikindex::KmerIndex;
|
||||
use obikstats::{GenomeSharing, SharingNullModel, SharingRow};
|
||||
use tracing::info;
|
||||
|
||||
pub(super) fn run(index_path: &Path, presence_threshold: u32, output: Option<&Path>) {
|
||||
let fail = |what: &str, e: &dyn std::fmt::Display| -> ! {
|
||||
eprintln!("error {what}: {e}");
|
||||
std::process::exit(1);
|
||||
};
|
||||
|
||||
let idx = Arc::new(KmerIndex::open(index_path).unwrap_or_else(|e| fail("opening index", &e)));
|
||||
let k = idx.kmer_size();
|
||||
let spectrum = GenomeSharing::new(Arc::clone(&idx), presence_threshold)
|
||||
.run()
|
||||
.unwrap_or_else(|e| fail("computing k-mer sharing", &e));
|
||||
let rows = SharingNullModel::new(&spectrum.genome_kmers, k)
|
||||
.compare(&spectrum)
|
||||
.unwrap_or_else(|e| fail("comparing with the null model", &e));
|
||||
|
||||
let result = match output {
|
||||
Some(path) => File::create(path)
|
||||
.and_then(|f| write_csv(&rows, BufWriter::new(f)))
|
||||
.map(|()| info!("sharing CSV written to {}", path.display())),
|
||||
None => write_csv(&rows, io::stdout().lock()),
|
||||
};
|
||||
result.unwrap_or_else(|e| fail("writing CSV", &e));
|
||||
}
|
||||
|
||||
pub(super) fn write_csv(rows: &[SharingRow], mut out: impl Write) -> io::Result<()> {
|
||||
writeln!(out, "r,k_r,O_r,q_r,D_r,FP_r,FDR_r")?;
|
||||
for row in rows {
|
||||
writeln!(
|
||||
out,
|
||||
"{},{},{:.6e},{:.6e},{:.6e},{:.6e},{:.6e}",
|
||||
row.r,
|
||||
row.k_r,
|
||||
row.observed,
|
||||
row.expected,
|
||||
row.deviation,
|
||||
row.expected_false_positives,
|
||||
row.fdr
|
||||
)?;
|
||||
}
|
||||
out.flush()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn csv_has_header_and_one_row_per_r() {
|
||||
let rows = vec![
|
||||
SharingRow { r: 1, k_r: 20, observed: 1.0, expected: 1.0, deviation: 0.0, expected_false_positives: 30.0, fdr: 1.0 },
|
||||
SharingRow { r: 2, k_r: 5, observed: 0.25, expected: 0.01, deviation: 0.24, expected_false_positives: 0.5, fdr: 0.1 },
|
||||
];
|
||||
let mut buf = Vec::new();
|
||||
write_csv(&rows, &mut buf).unwrap();
|
||||
let text = String::from_utf8(buf).unwrap();
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines[0], "r,k_r,O_r,q_r,D_r,FP_r,FDR_r");
|
||||
assert_eq!(lines.len(), 3);
|
||||
assert_eq!(lines[2], "2,5,2.500000e-1,1.000000e-2,2.400000e-1,5.000000e-1,1.000000e-1");
|
||||
}
|
||||
}
|
||||
@@ -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