From bfb9289abebdf5f12f0ffe5185edd9ae2aa3e42d Mon Sep 17 00:00:00 2001 From: Eric Coissac Date: Wed, 2 Dec 2026 19:37:41 +0100 Subject: [PATCH] feat: add genome set trie example to obicompactvec Introduce a new example demonstrating the construction and measurement of a set trie using `PersistentBitMatrix`. This includes helper structs for trie nodes and step statistics, along with a naive implementation for validation. - Add `src/obicompactvec/examples/genome_set_trie.rs` with `SetTrie`, `Node`, `EdgeHasher`, and `StepStats` structs for trie management - Implement `SetTrie` methods including `new`, `add_row`, `end_step`, `finish`, and `stats` to build and analyze the trie structure - Add `measure` function to calculate step statistics from a `PersistentBitMatrix` and `naive` function for baseline comparison - Include `counts_match_naive_on_every_format` test to validate trie counts against the naive implementation across formats - Update `src/Cargo.lock` to bump `obiskim` dependency from 1.4.9 to 1.4.10 --- src/Cargo.lock | 2 +- src/obicompactvec/examples/genome_set_trie.rs | 341 ++++++++++++++++++ 2 files changed, 342 insertions(+), 1 deletion(-) create mode 100644 src/obicompactvec/examples/genome_set_trie.rs diff --git a/src/Cargo.lock b/src/Cargo.lock index 404f70b4..45bbdcdb 100644 --- a/src/Cargo.lock +++ b/src/Cargo.lock @@ -1690,7 +1690,7 @@ dependencies = [ [[package]] name = "obiskim" -version = "1.4.9" +version = "1.4.10" dependencies = [ "clap", "csv", diff --git a/src/obicompactvec/examples/genome_set_trie.rs b/src/obicompactvec/examples/genome_set_trie.rs new file mode 100644 index 00000000..69c5e9ab --- /dev/null +++ b/src/obicompactvec/examples/genome_set_trie.rs @@ -0,0 +1,341 @@ +//! Read-only measurement: how large would the prefix trie of genome sets be +//! for existing presence layers? +//! +//! Each row's genome set, taken in ascending genome order, is a path in a trie +//! whose nodes are `(parent, genome)`. This is the structure a merge would +//! maintain to write the sparse format without a columnar intermediate. +//! +//! ```text +//! cargo run --release -p obicompactvec --example genome_set_trie -- LAYER_DIR... +//! ``` +//! +//! `LAYER_DIR` is the directory *holding* `presence/`. One tab-separated line +//! is printed per layer and per step `k`, "step `k`" meaning the matrix +//! restricted to its first `k` genomes. All steps come from a single pass: the +//! trie of the first `k` genomes is exactly the nodes labelled `< k`. + +use std::collections::HashMap; +use std::hash::{BuildHasherDefault, Hasher}; +use std::io; +use std::path::Path; +use std::time::Instant; + +use obicompactvec::PersistentBitMatrix; + +/// Rows decoded per call. +const BATCH: usize = 4096; +const FIRST_STEP: usize = 25; + +// ── hashing ───────────────────────────────────────────────────────────────── + +/// Multiplicative mix for the single `u64` edge key. +#[derive(Default)] +struct EdgeHasher(u64); + +impl Hasher for EdgeHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, _: &[u8]) { + unreachable!("only u64 keys are hashed") + } + fn write_u64(&mut self, k: u64) { + let x = k.wrapping_mul(0x9E37_79B9_7F4A_7C15); + self.0 = x ^ (x >> 32); + } +} + +// ── trie ──────────────────────────────────────────────────────────────────── + +#[derive(Clone, Copy)] +struct Node { + genome: u32, + depth: u32, + /// Bit `s` set: some row's set restricted to `steps[s]` genomes ends here. + ends: u32, +} + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +struct StepStats { + genomes: usize, + rows: u64, + /// Rows with no genome among the first `genomes`. + empty_rows: u64, + /// Set bits. + cells: u64, + /// Distinct non-empty sets. + distinct: u64, + /// Distinct sets of two genomes or more. + distinct_multi: u64, + /// Sum of the sizes of the distinct sets. + set_length: u64, + nodes: u64, +} + +struct SetTrie { + steps: Vec, + edges: HashMap>, + /// Node 0 is the root (empty set). + nodes: Vec, + rows: u64, + empty_rows: Vec, + cells: Vec, +} + +/// `FIRST_STEP`, doubling while below `n_cols`, then `n_cols` itself. +fn steps_for(n_cols: usize) -> Vec { + let mut steps: Vec = std::iter::successors(Some(FIRST_STEP), |k| k.checked_mul(2)) + .take_while(|&k| k < n_cols) + .collect(); + steps.push(n_cols); + steps +} + +impl SetTrie { + fn new(n_cols: usize) -> Self { + let steps = steps_for(n_cols); + assert!(steps.len() <= 32, "too many steps for the u32 mask"); + let root = Node { + genome: 0, + depth: 0, + ends: 0, + }; + Self { + edges: HashMap::default(), + nodes: vec![root], + rows: 0, + empty_rows: vec![0; steps.len()], + cells: vec![0; steps.len()], + steps, + } + } + + /// Adds one row; `genomes` sorted ascending, without duplicates. + fn add_row(&mut self, genomes: &[u32]) { + self.rows += 1; + let mut node = 0u32; + let mut s = 0usize; + for (depth, &g) in genomes.iter().enumerate() { + while g as usize >= self.steps[s] { + self.end_step(s, node, depth); + s += 1; + } + let key = (u64::from(node) << 32) | u64::from(g); + let next = u32::try_from(self.nodes.len()).expect("more than u32::MAX nodes"); + node = *self.edges.entry(key).or_insert(next); + if node == next { + self.nodes.push(Node { + genome: g, + depth: depth as u32 + 1, + ends: 0, + }); + } + } + for s in s..self.steps.len() { + self.end_step(s, node, genomes.len()); + } + } + + /// The current row, restricted to step `s`, is the `len`-genome set `node`. + fn end_step(&mut self, s: usize, node: u32, len: usize) { + self.cells[s] += len as u64; + if len == 0 { + self.empty_rows[s] += 1; + } else { + self.nodes[node as usize].ends |= 1 << s; + } + } + + fn stats(&self) -> Vec { + let mut out: Vec = self + .steps + .iter() + .enumerate() + .map(|(s, &k)| StepStats { + genomes: k, + rows: self.rows, + empty_rows: self.empty_rows[s], + cells: self.cells[s], + ..StepStats::default() + }) + .collect(); + for node in &self.nodes[1..] { + for (s, st) in out.iter_mut().enumerate() { + st.nodes += u64::from((node.genome as usize) < st.genomes); + if node.ends & (1 << s) != 0 { + st.distinct += 1; + st.distinct_multi += u64::from(node.depth > 1); + st.set_length += u64::from(node.depth); + } + } + } + out + } +} + +// ── reading a layer ───────────────────────────────────────────────────────── + +fn measure(layer_dir: &Path) -> io::Result<(PersistentBitMatrix, Vec)> { + let matrix = PersistentBitMatrix::open(layer_dir)?; + let n = matrix.n(); + let mut trie = SetTrie::new(matrix.n_cols()); + let mut rows: Vec> = vec![Vec::new(); BATCH]; + let mut slots: Vec = Vec::with_capacity(BATCH); + for start in (0..n).step_by(BATCH) { + slots.clear(); + slots.extend(start..(start + BATCH).min(n)); + for (i, c, v) in matrix.nonzero_iter(&slots) { + if v != 0 { + rows[i].push(c as u32); + } + } + for row in rows.iter_mut().take(slots.len()) { + row.sort_unstable(); + trie.add_row(row); + row.clear(); + } + } + let stats = trie.stats(); + Ok((matrix, stats)) +} + +fn main() -> io::Result<()> { + let dirs: Vec = std::env::args().skip(1).collect(); + if dirs.is_empty() { + eprintln!("usage: genome_set_trie LAYER_DIR... (directories holding presence/)"); + std::process::exit(2); + } + println!( + "layer\tformat\tgenomes\trows\tempty_rows\tcells\tdensity\tdistinct\tdistinct_multi\t\ + set_length\tnodes\tnodes_per_row\tcolumns_bytes\tids_bytes" + ); + for dir in &dirs { + let t = Instant::now(); + let (matrix, stats) = measure(Path::new(dir))?; + for s in &stats { + let per_row = |x: u64| x as f64 / s.rows.max(1) as f64; + println!( + "{dir}\t{:?}\t{}\t{}\t{}\t{}\t{:.4}\t{}\t{}\t{}\t{}\t{:.4}\t{}\t{}", + matrix.storage_kind(), + s.genomes, + s.rows, + s.empty_rows, + s.cells, + per_row(s.cells) / s.genomes.max(1) as f64, + s.distinct, + s.distinct_multi, + s.set_length, + s.nodes, + per_row(s.nodes), + s.rows.div_ceil(8) * s.genomes as u64, + s.rows * 4, + ); + } + eprintln!("{dir}: {:.1}s", t.elapsed().as_secs_f64()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + use std::fs; + + use obicompactvec::{PersistentBitMatrixBuilder, pack_bit_matrix, pack_sparse_bit_matrix}; + + use super::*; + + const N: usize = 10_000; + const G: usize = 60; + + /// Deterministic matrix mixing a few shared sets, singletons, noise and + /// empty rows. + fn row_of(slot: usize) -> Vec { + let mix = |x: usize| (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40; + (0..G) + .filter(|&g| match slot % 5 { + 0 => g % (2 + slot % 7) == 0, + 1 => g == slot % G, + 2 => mix(slot * G + g) % 3 == 0, + 3 => g < slot % 40, + _ => false, + }) + .map(|g| g as u32) + .collect() + } + + fn naive(k: usize) -> StepStats { + let mut sets = HashSet::new(); + let mut prefixes = HashSet::new(); + let mut st = StepStats { + genomes: k, + rows: N as u64, + ..StepStats::default() + }; + for slot in 0..N { + let mut row = row_of(slot); + row.retain(|&g| (g as usize) < k); + st.cells += row.len() as u64; + if row.is_empty() { + st.empty_rows += 1; + continue; + } + for len in 1..=row.len() { + prefixes.insert(row[..len].to_vec()); + } + sets.insert(row); + } + st.distinct = sets.len() as u64; + st.distinct_multi = sets.iter().filter(|s| s.len() > 1).count() as u64; + st.set_length = sets.iter().map(|s| s.len() as u64).sum(); + st.nodes = prefixes.len() as u64; + st + } + + #[test] + fn counts_match_naive_on_every_format() { + let layer = tempfile::tempdir().unwrap(); + let presence = layer.path().join("presence"); + fs::create_dir_all(&presence).unwrap(); + let mut mb = PersistentBitMatrixBuilder::new(N, &presence).unwrap(); + for g in 0..G { + let mut col = mb.add_col().unwrap(); + for slot in 0..N { + col.set(slot, row_of(slot).contains(&(g as u32))); + } + col.close().unwrap(); + } + mb.close().unwrap(); + + let expected: Vec = steps_for(G).into_iter().map(naive).collect(); + assert_eq!(expected.len(), 3); + let check = |format: &str| { + let (matrix, stats) = measure(layer.path()).unwrap(); + assert_eq!(format!("{:?}", matrix.storage_kind()), format); + assert_eq!(stats, expected, "{format}"); + }; + check("Columnar"); + pack_bit_matrix(&presence).unwrap(); + check("Packed"); + fs::remove_file(presence.join("matrix.pbmx")).unwrap(); + + // Rebuild the columnar form, then go sparse. + let mut mb = PersistentBitMatrixBuilder::new(N, &presence).unwrap(); + for g in 0..G { + let mut col = mb.add_col().unwrap(); + for slot in 0..N { + col.set(slot, row_of(slot).contains(&(g as u32))); + } + col.close().unwrap(); + } + mb.close().unwrap(); + pack_sparse_bit_matrix(&presence).unwrap(); + check("Sparse"); + + // The sparse dictionary also holds one entry for the empty set. + let meta = fs::read_to_string(presence.join("sparse_meta.json")).unwrap(); + let full = expected.last().unwrap(); + let n_dict = full.distinct_multi + u64::from(full.empty_rows > 0); + assert!(meta.contains(&format!("\"n_distinct_multi\":{n_dict}")), "{meta}"); + } +}