From 93ff24c4dd05a568d3a149da8dc2b4a2dfc70efe Mon Sep 17 00:00:00 2001 From: Eric Coissac Date: Wed, 2 Dec 2026 19:49:51 +0100 Subject: [PATCH] refactor: restructure sparse bit matrix handling and add compressed columns Refactor the sparse bit matrix implementation by splitting builder logic into dedicated modules and introducing a new `CompressedBitColumn` type for in-memory presence data. This change supports sparse output modes in merge operations, where presence data is compressed in RAM rather than written to disk immediately. - Move `PersistentSparseBitMatrixBuilder` and related functions from `src/obicompactvec/src/bitmatrix/sparse.rs` to `src/obicompactvec/src/bitmatrix/sparse/builder.rs` - Move `write_varint` from `src/obicompactvec/src/bitmatrix/sparse.rs` to `src/obicompactvec/src/bitmatrix/sparse/set_dict.rs` - Add `src/obicompactvec/src/compressed_column.rs` with `CompressedBitColumn` for in-memory compressed presence data - Add `src/obicompactvec/src/bitmatrix/sparse/append.rs` with `SparseBase`, `Source`, and `write_sparse_presence` functions - Update `src/obicompactvec/src/matrix_builder.rs` and `src/obicompactvec/src/mem_builder.rs` to support detached memory columns and compression - Add `src/obikmerge/src/partition_merge/output.rs` with `Target`, `Output`, and `Group` structs for managing merge output states - Add `MergeSpec` struct in `src/obikmerge/src/partition_merge/mod.rs` and update `merge_partition` to use it - Add tests in `src/obicompactvec/src/tests/sparse_append.rs` and `src/obikmerge/src/tests.rs` for sparse append and merge operations - Update `src/obiskim/Cargo.toml` and `src/Cargo.lock` to bump `obiskim` version to 1.4.11 - Add documentation in `DevDocMD/implementation/merge.md` detailing sparse presence output behavior --- DevDocMD/implementation/merge.md | 15 + ReleaseNotes/version-1.4.11.md | 15 + src/Cargo.lock | 2 +- src/obicompactvec/examples/genome_set_trie.rs | 5 +- src/obicompactvec/src/bitmatrix/mod.rs | 5 +- src/obicompactvec/src/bitmatrix/sparse.rs | 266 +----------------- .../src/bitmatrix/sparse/append.rs | 190 +++++++++++++ .../src/bitmatrix/sparse/builder.rs | 232 +++++++++++++++ .../src/bitmatrix/sparse/set_dict.rs | 136 +++++++++ .../src/bitmatrix/sparse_columnar.rs | 2 +- src/obicompactvec/src/compressed_column.rs | 126 +++++++++ src/obicompactvec/src/lib.rs | 6 +- src/obicompactvec/src/matrix_builder.rs | 21 +- src/obicompactvec/src/mem_builder.rs | 22 +- src/obicompactvec/src/tests/mod.rs | 1 + src/obicompactvec/src/tests/sparse_append.rs | 140 +++++++++ src/obikmerge/src/lib.rs | 3 + src/obikmerge/src/merge.rs | 13 +- src/obikmerge/src/partition_merge/mod.rs | 159 ++++++----- src/obikmerge/src/partition_merge/output.rs | 167 +++++++++++ src/obikmerge/src/tests.rs | 195 +++++++++++++ src/obiskim/Cargo.toml | 2 +- 22 files changed, 1379 insertions(+), 344 deletions(-) create mode 100644 ReleaseNotes/version-1.4.11.md create mode 100644 src/obicompactvec/src/bitmatrix/sparse/append.rs create mode 100644 src/obicompactvec/src/bitmatrix/sparse/builder.rs create mode 100644 src/obicompactvec/src/bitmatrix/sparse/set_dict.rs create mode 100644 src/obicompactvec/src/compressed_column.rs create mode 100644 src/obicompactvec/src/tests/sparse_append.rs create mode 100644 src/obikmerge/src/partition_merge/output.rs create mode 100644 src/obikmerge/src/tests.rs diff --git a/DevDocMD/implementation/merge.md b/DevDocMD/implementation/merge.md index 06d8ba82..421af32f 100644 --- a/DevDocMD/implementation/merge.md +++ b/DevDocMD/implementation/merge.md @@ -101,6 +101,21 @@ Only one group's source layers and destination columns are alive at a time, so t --- +## Sparse presence output: no column files + +In presence mode with the sparse output (the default), pass 2 creates no +`col_*.pbiv` file for the added genomes. Each filled column is compressed in +RAM (`CompressedBitColumn`: blocks of 4096 rows, stored as varint gaps between +set bits, or as the raw bitmap when that is not larger). Once all source groups +of a partition are done, `write_sparse_presence` transposes the base columns +and the compressed ones, a window of rows at a time, and writes each layer's +sparse matrix once. `finalize` then finds the layers already packed. + +All compressed columns of a partition stay in RAM until its matrices are +written (their size is logged at `debug` level); there is no disk spill. Count +mode and `--dense` still append column files and pack them afterwards. The +sections below that describe column files apply to those two paths. + ## `append_genome_column` Defined on two concrete specialisations of `Layer`: diff --git a/ReleaseNotes/version-1.4.11.md b/ReleaseNotes/version-1.4.11.md new file mode 100644 index 00000000..8f72eb8d --- /dev/null +++ b/ReleaseNotes/version-1.4.11.md @@ -0,0 +1,15 @@ +# Release Notes for obiskim (Rust k-mer genomics tool) 1.4.11 + +## Features + +- **Genome Set Trie Example**: Added `src/obicompactvec/examples/genome_set_trie.rs` demonstrating the construction and measurement of a set trie using `PersistentBitMatrix`. Includes helper structs (`SetTrie`, `Node`, `EdgeHasher`, `StepStats`) and validation against a naive implementation. + +## Internal + +- **Sparse Bit Matrix Refactoring**: Restructured sparse bit matrix handling to support sparse output modes in merge operations, where presence data is compressed in RAM rather than written to disk immediately. + - Introduced `CompressedBitColumn` for in-memory compressed presence data. + - Split builder logic into dedicated modules: `sparse/builder.rs`, `sparse/set_dict.rs`, and `sparse/append.rs`. + - Updated `matrix_builder.rs` and `mem_builder.rs` to support detached memory columns and compression. +- **Merge Operations**: Added `MergeSpec` struct and updated `merge_partition` to utilize it. Introduced `Target`, `Output`, and `Group` structs in `partition_merge/output.rs` for managing merge output states. +- **Documentation**: Added `DevDocMD/implementation/merge.md` detailing sparse presence output behavior. +- **Tests**: Added tests for sparse append and merge operations in `obicompactvec` and `obikmerge`. diff --git a/src/Cargo.lock b/src/Cargo.lock index 45bbdcdb..c24fffb5 100644 --- a/src/Cargo.lock +++ b/src/Cargo.lock @@ -1690,7 +1690,7 @@ dependencies = [ [[package]] name = "obiskim" -version = "1.4.10" +version = "1.4.11" dependencies = [ "clap", "csv", diff --git a/src/obicompactvec/examples/genome_set_trie.rs b/src/obicompactvec/examples/genome_set_trie.rs index 69c5e9ab..79472799 100644 --- a/src/obicompactvec/examples/genome_set_trie.rs +++ b/src/obicompactvec/examples/genome_set_trie.rs @@ -336,6 +336,9 @@ mod tests { 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}"); + assert!( + meta.contains(&format!("\"n_distinct_multi\":{n_dict}")), + "{meta}" + ); } } diff --git a/src/obicompactvec/src/bitmatrix/mod.rs b/src/obicompactvec/src/bitmatrix/mod.rs index 1e0185a3..411a5fbb 100644 --- a/src/obicompactvec/src/bitmatrix/mod.rs +++ b/src/obicompactvec/src/bitmatrix/mod.rs @@ -25,8 +25,11 @@ pub use group_ops::batch_presence_counts; pub use packed::pack_bit_matrix; pub use persistent::PersistentBitMatrix; pub(crate) use sparse::RowRank; +#[cfg(test)] +pub(crate) use sparse::write_sparse_presence_with; pub use sparse::{ - PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder, pack_sparse_bit_matrix, + PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder, SparseBase, + pack_sparse_bit_matrix, write_sparse_presence, }; pub(crate) use pairwise::{ diff --git a/src/obicompactvec/src/bitmatrix/sparse.rs b/src/obicompactvec/src/bitmatrix/sparse.rs index 0d0601b1..af955daa 100644 --- a/src/obicompactvec/src/bitmatrix/sparse.rs +++ b/src/obicompactvec/src/bitmatrix/sparse.rs @@ -20,7 +20,6 @@ //! `dict_values[dict_offsets[dict_id]..dict_offsets[dict_id+1]]` is its //! varint-encoded genome list. -use std::collections::HashMap; use std::fs; use std::io; use std::path::{Path, PathBuf}; @@ -28,17 +27,20 @@ use std::path::{Path, PathBuf}; use memmap2::Mmap; use ndarray::{Array1, Array2}; -use crate::eliasfano::{EliasFano, EliasFanoBuilder}; -use crate::fixedintvec::{ - PersistentFixedIntVec, PersistentFixedIntVecBuilder, bit_width_for_range, -}; -use crate::meta::{MatrixMeta, field}; -use crate::rankselect::{PersistentRankSelectBitVec, PersistentRankSelectBitVecBuilder}; +use crate::eliasfano::EliasFano; +use crate::fixedintvec::PersistentFixedIntVec; +use crate::meta::field; +use crate::rankselect::PersistentRankSelectBitVec; use crate::traits::{BitPartials, ColumnWeights}; -use super::PersistentBitMatrix; -use super::col_path; -use super::packed::{PackedBitMatrix, pack_bit_matrix, packed_bit_matrix_n_cols}; +mod append; +mod builder; +mod set_dict; + +#[cfg(test)] +pub(crate) use append::write_sparse_presence_with; +pub use append::{SparseBase, write_sparse_presence}; +pub use builder::{PersistentSparseBitMatrixBuilder, pack_sparse_bit_matrix}; fn is_multi_path(dir: &Path) -> PathBuf { dir.join("is_multi.prsb") @@ -98,19 +100,7 @@ impl SparseMeta { } } -// ── varint (LEB128-style) ──────────────────────────────────────────────────── - -fn write_varint(buf: &mut Vec, mut v: u32) { - loop { - let byte = (v & 0x7F) as u8; - v >>= 7; - if v == 0 { - buf.push(byte); - break; - } - buf.push(byte | 0x80); - } -} +// ── varint (LEB128-style, written by `set_dict`) ──────────────────────────────────────────────────── fn read_varint(data: &[u8], pos: &mut usize) -> u32 { let mut result = 0u32; @@ -157,7 +147,7 @@ pub(crate) enum RowRank { /// /// The dictionary itself is `dict_offsets`/`dict_values`: each distinct /// multi-genome set is varint-encoded (ascending genome indices, delta -/// isn't taken — see [`write_varint`]/[`read_varint`]) as a byte run in +/// isn't taken — see [`read_varint`]) as a byte run in /// `dict_values`, and `dict_offsets` (an [`EliasFano`] over the /// `n_distinct_multi` sets' *byte* offsets — monotone by construction, one /// entry per `dict_id`) gives `dict_entry_range(dict_id)`'s `[start, end)` @@ -428,190 +418,6 @@ impl crate::traits::BinaryMatrix for PersistentSparseBitMatrix { } } -// ── PersistentSparseBitMatrixBuilder ──────────────────────────────────────── - -/// Row batch size for [`PersistentSparseBitMatrixBuilder::build_from_dense`]. -const BUILD_FROM_DENSE_BATCH: usize = 4096; - -pub struct PersistentSparseBitMatrixBuilder { - dir: PathBuf, - n_cols: usize, - is_multi: Vec, - singleton_values: Vec, - multi_dict_ids: Vec, - dedup: HashMap, u32>, - dict_sets_in_order: Vec>, -} - -impl PersistentSparseBitMatrixBuilder { - pub fn new(n: usize, n_cols: usize, dir: &Path) -> io::Result { - fs::create_dir_all(dir)?; - Ok(Self { - dir: dir.to_path_buf(), - n_cols, - is_multi: Vec::with_capacity(n), - singleton_values: Vec::new(), - multi_dict_ids: Vec::new(), - dedup: HashMap::new(), - dict_sets_in_order: Vec::new(), - }) - } - - /// Appends one row's genome set — `genomes` sorted ascending, each - /// `< n_cols`. Rows must be pushed in slot order (0, 1, 2, ...), one - /// call per k-mer slot of the layer being converted/built. - /// - /// Cardinality 0 (no genome present — not expected on a real built - /// index, every slot has at least one, but handled correctly rather - /// than assumed away) routes through the dictionary path as a genuine - /// empty entry, *not* the singleton shortcut: a placeholder singleton - /// value would be indistinguishable from a real singleton at that same - /// genome index on read-back. - pub fn push_row(&mut self, genomes: &[u32]) { - match genomes.len() { - 1 => { - self.is_multi.push(false); - self.singleton_values.push(genomes[0]); - } - _ => { - self.is_multi.push(true); - let id = if let Some(&id) = self.dedup.get(genomes) { - id - } else { - let id = self.dict_sets_in_order.len() as u32; - self.dict_sets_in_order.push(genomes.to_vec()); - self.dedup.insert(genomes.to_vec(), id); - id - }; - self.multi_dict_ids.push(id); - } - } - } - - pub fn close(self) -> io::Result<()> { - let n = self.is_multi.len(); - let n_singleton = self.singleton_values.len(); - let n_multi = self.multi_dict_ids.len(); - let n_distinct_multi = self.dict_sets_in_order.len(); - - let mut is_multi_b = PersistentRankSelectBitVecBuilder::new(n, &is_multi_path(&self.dir))?; - for (i, &v) in self.is_multi.iter().enumerate() { - is_multi_b.set(i, v); - } - is_multi_b.close()?; - - let singleton_width = bit_width_for_range(self.n_cols as u64); - let mut singleton_b = PersistentFixedIntVecBuilder::new( - n_singleton, - singleton_width, - &singleton_path(&self.dir), - )?; - for (i, &v) in self.singleton_values.iter().enumerate() { - singleton_b.set(i, v as u64); - } - singleton_b.close()?; - - let multi_width = bit_width_for_range(n_distinct_multi as u64); - let mut multi_b = - PersistentFixedIntVecBuilder::new(n_multi, multi_width, &multi_path(&self.dir))?; - for (i, &v) in self.multi_dict_ids.iter().enumerate() { - multi_b.set(i, v as u64); - } - multi_b.close()?; - - let mut dict_values = Vec::new(); - let mut offsets: Vec = Vec::with_capacity(n_distinct_multi); - for set in &self.dict_sets_in_order { - offsets.push(dict_values.len() as u64); - for &g in set { - write_varint(&mut dict_values, g); - } - } - let universe = dict_values.len() as u64 + 1; - let mut offsets_b = - EliasFanoBuilder::new(offsets.len(), universe, &dict_offsets_base(&self.dir))?; - for &o in &offsets { - offsets_b.push(o); - } - offsets_b.close()?; - fs::write(dict_values_path(&self.dir), &dict_values)?; - - SparseMeta { - n, - n_cols: self.n_cols, - n_singleton, - n_multi, - n_distinct_multi, - } - .save(&self.dir)?; - Ok(()) - } - - pub fn finish(self) -> io::Result { - let dir = self.dir.clone(); - self.close()?; - PersistentSparseBitMatrix::open(&dir) - } - - /// Builds a sparse matrix from an already-built dense - /// [`PersistentBitMatrix`] (`Columnar` or `Packed`), for migrating an - /// existing index. - /// - /// Processes rows in batches of [`BUILD_FROM_DENSE_BATCH`] instead of - /// one row at a time: [`BitSliceView::for_each_set_in`] walks each - /// column *once per batch*, word by word, visiting only the set bits — - /// rather than `fill_row`'s row-major loop, which re-reads every column - /// with one `get()` per cell and jumps between all `n_cols` columns on - /// every single row. Columns are visited in ascending order, so each - /// row's genome list comes out sorted, as `push_row` requires. - pub fn build_from_dense(dense: &PersistentBitMatrix, dir: &Path) -> io::Result { - let n = dense.n(); - let n_cols = dense.n_cols(); - let mut builder = Self::new(n, n_cols, dir)?; - let mut row_buffers: Vec> = vec![Vec::new(); BUILD_FROM_DENSE_BATCH]; - let mut start = 0; - while start < n { - let end = (start + BUILD_FROM_DENSE_BATCH).min(n); - for c in 0..n_cols { - dense.col_view(c).for_each_set_in(start..end, |slot| { - row_buffers[slot - start].push(c as u32); - }); - } - for buf in row_buffers.iter_mut().take(end - start) { - builder.push_row(buf); - buf.clear(); - } - start = end; - } - Ok(builder) - } - - /// Builds the row-permuted copy of `src` into `dir`: row `s` of the - /// result is row `new_to_old[s]` of `src`. `new_to_old` must have - /// `src.n()` entries and be a permutation of `0..src.n()` — the caller - /// proves that, this only reads `src` at those slots. - /// - /// Needed whenever the slot numbering of a layer changes (its MPHF is - /// rebuilt) while the data attached to each k-mer must follow it. - /// Rows are read at arbitrary slots of `src`, so convert a dense source - /// to sparse first (`build_from_dense`) rather than permuting it - /// cell by cell. - pub fn build_permuted( - src: &PersistentSparseBitMatrix, - new_to_old: &[u32], - dir: &Path, - ) -> io::Result { - let mut builder = Self::new(new_to_old.len(), src.n_cols(), dir)?; - let mut genomes: Vec = Vec::new(); - for &old in new_to_old { - genomes.clear(); - src.for_each_genome_in_row(old as usize, |g| genomes.push(g as u32)); - builder.push_row(&genomes); - } - Ok(builder) - } -} - // ── Trait impls ─────────────────────────────────────────────────────────────── impl ColumnWeights for PersistentSparseBitMatrix { @@ -678,47 +484,3 @@ impl BitPartials for PersistentSparseBitMatrix { m } } - -/// Converts a layer's presence matrix (columnar `col_*.pbiv` or dense -/// `matrix.pbmx`) to the sparse on-disk format in place. Old-format files -/// are removed only after the new format is fully written, so a crash -/// mid-conversion leaves a previous, still valid format. Idempotent: does -/// nothing if `is_multi.prsb` already exists. -/// -/// Columnar data is transposed straight into the sparse format, a window of -/// rows at a time, one column file open at a time -/// ([`PersistentSparseBitMatrixBuilder::build_from_columnar`]): no dense -/// intermediate is written, and a worker holds no mapping of the columns -/// whatever their number. A dense `matrix.pbmx` is only read when it is the -/// current form of the layer: no columnar data pending, or a `matrix.pbmx` -/// that already has as many columns as the columnar metadata says. -pub fn pack_sparse_bit_matrix(dir: &Path) -> io::Result<()> { - if is_multi_path(dir).exists() { - return Ok(()); - } - let packed_path = dir.join("matrix.pbmx"); - - if let Ok(meta) = MatrixMeta::load(dir) - && packed_bit_matrix_n_cols(&packed_path).ok() != Some(meta.n_cols) - { - // Columnar data is the freshest form (any `matrix.pbmx` here is - // stale, e.g. copied from a merge base before the layer was - // widened): transpose it directly. - PersistentSparseBitMatrixBuilder::build_from_columnar(dir, &meta)?.close()?; - for c in 0..meta.n_cols { - fs::remove_file(col_path(dir, c))?; - } - fs::remove_file(dir.join("meta.json"))?; - let _ = fs::remove_file(&packed_path); - return Ok(()); - } - - // Dense packed form is the current one. `pack_bit_matrix` is a no-op when - // there is no columnar data left, and otherwise only drops the - // now-redundant column files. - pack_bit_matrix(dir)?; - let dense = PersistentBitMatrix::Packed(PackedBitMatrix::open(&packed_path)?); - PersistentSparseBitMatrixBuilder::build_from_dense(&dense, dir)?.close()?; - drop(dense); - fs::remove_file(&packed_path) -} diff --git a/src/obicompactvec/src/bitmatrix/sparse/append.rs b/src/obicompactvec/src/bitmatrix/sparse/append.rs new file mode 100644 index 00000000..32233cc5 --- /dev/null +++ b/src/obicompactvec/src/bitmatrix/sparse/append.rs @@ -0,0 +1,190 @@ +//! Building a layer's sparse presence matrix from the columns it already has +//! followed by new columns held compressed in RAM, without ever writing a +//! column file. See [`crate::transpose`]. + +use std::fs; +use std::io; +use std::path::Path; + +use crate::compressed_column::CompressedBitColumn; +use crate::meta::MatrixMeta; +use crate::transpose::{DEFAULT_MAX_HITS, DEFAULT_WINDOW_ROWS, Hit, transpose_windows}; + +use super::super::sparse_columnar::read_bit_window; +use super::super::{PersistentBitMatrix, col_path}; +use super::{PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder}; + +/// The columns of a layer that precede the added ones. +#[derive(Debug, Clone, Copy)] +pub enum SparseBase { + /// A new layer: this many columns, all absent. + Absent(usize), + /// Whatever presence matrix the layer holds: implicit (one column, all + /// present), columnar or sparse. It must have `n_cols` columns. + Layer { n_cols: usize }, +} + +enum Source { + Absent(usize), + Implicit, + Columnar(MatrixMeta), + Sparse(Box), +} + +impl Source { + fn n_cols(&self) -> usize { + match self { + Source::Absent(k) => *k, + Source::Implicit => 1, + Source::Columnar(meta) => meta.n_cols, + Source::Sparse(m) => m.n_cols(), + } + } +} + +/// Writes `layer_dir/presence/` in the sparse format: `n` rows, the columns of +/// `base`, then `added`. Any previous matrix there is replaced once the new +/// one is complete. +pub fn write_sparse_presence( + layer_dir: &Path, + base: SparseBase, + n: usize, + added: &[CompressedBitColumn], +) -> io::Result<()> { + write_sparse_presence_with( + layer_dir, + base, + n, + added, + DEFAULT_WINDOW_ROWS, + DEFAULT_MAX_HITS, + ) +} + +/// [`write_sparse_presence`] with explicit window size and non-zero-cell cap. +pub(crate) fn write_sparse_presence_with( + layer_dir: &Path, + base: SparseBase, + n: usize, + added: &[CompressedBitColumn], + window_rows: usize, + max_hits: usize, +) -> io::Result<()> { + let presence = layer_dir.join("presence"); + let source = match base { + SparseBase::Absent(k) => Source::Absent(k), + SparseBase::Layer { n_cols } => { + let source = open_source(layer_dir, n)?; + if source.n_cols() != n_cols { + return Err(invalid( + layer_dir, + &format!("{} columns, expected {n_cols}", source.n_cols()), + )); + } + source + } + }; + if let Some(c) = added.iter().find(|c| c.len() != n) { + return Err(invalid( + layer_dir, + &format!("added column of {} rows, expected {n}", c.len()), + )); + } + let k = source.n_cols(); + // A sparse base is read row by row while its rows are completed; every + // other base takes part in the transposition as `k` columns. + let skipped = if matches!(source, Source::Sparse(_)) { + k + } else { + 0 + }; + + let tmp = layer_dir.join("presence.new"); + if tmp.exists() { + fs::remove_dir_all(&tmp)?; + } + let mut builder = PersistentSparseBitMatrixBuilder::new(n, k + added.len(), &tmp)?; + let mut bytes: Vec = Vec::new(); + let mut words: Vec = Vec::new(); + let mut row: Vec = Vec::new(); + transpose_windows( + n, + k + added.len() - skipped, + window_rows, + max_hits, + (), + |t, start, end, hits: &mut Vec>| { + let c = t + skipped; + let mut hit = |r: usize| hits.push((r as u32, t as u32, ())); + if c >= k { + added[c - k].for_each_set_in(start, end, |slot| hit(slot - start)); + return Ok(()); + } + match &source { + Source::Absent(_) | Source::Sparse(_) => {} + Source::Implicit => (0..end - start).for_each(hit), + Source::Columnar(_) => { + read_bit_window( + &col_path(&presence, c), + n, + start, + end, + &mut bytes, + &mut words, + )?; + crate::views::BitSliceView::new(&words, end - start) + .for_each_set_in(0..end - start, hit); + } + } + Ok(()) + }, + |start, batch| { + for i in 0..batch.len() { + match &source { + Source::Sparse(m) => { + row.clear(); + m.for_each_genome_in_row(start + i, |g| row.push(g as u32)); + row.extend(batch.cols(i).iter().map(|&c| c + k as u32)); + builder.push_row(&row); + } + _ => builder.push_row(batch.cols(i)), + } + } + Ok(()) + }, + )?; + builder.close()?; + drop(source); + if presence.exists() { + fs::remove_dir_all(&presence)?; + } + fs::rename(&tmp, &presence) +} + +fn open_source(layer_dir: &Path, n: usize) -> io::Result { + let matrix = PersistentBitMatrix::open(layer_dir)?; + if matrix.n() != n { + return Err(invalid( + layer_dir, + &format!("presence matrix of {} rows, expected {n}", matrix.n()), + )); + } + match matrix { + PersistentBitMatrix::Implicit { .. } => Ok(Source::Implicit), + PersistentBitMatrix::Columnar(_) => Ok(Source::Columnar(MatrixMeta::load( + &layer_dir.join("presence"), + )?)), + PersistentBitMatrix::Sparse(m) => Ok(Source::Sparse(Box::new(m))), + PersistentBitMatrix::Packed(_) => Err(invalid( + layer_dir, + "a dense packed presence matrix cannot be extended", + )), + } +} + +fn invalid(dir: &Path, what: &str) -> io::Error { + io::Error::new( + io::ErrorKind::InvalidData, + format!("{}: {what}", dir.display()), + ) +} diff --git a/src/obicompactvec/src/bitmatrix/sparse/builder.rs b/src/obicompactvec/src/bitmatrix/sparse/builder.rs new file mode 100644 index 00000000..73f6c32f --- /dev/null +++ b/src/obicompactvec/src/bitmatrix/sparse/builder.rs @@ -0,0 +1,232 @@ +//! [`PersistentSparseBitMatrixBuilder`] (rows pushed in slot order) and +//! [`pack_sparse_bit_matrix`], the in-place conversion of a layer. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use crate::eliasfano::EliasFanoBuilder; +use crate::fixedintvec::{PersistentFixedIntVecBuilder, bit_width_for_range}; +use crate::meta::MatrixMeta; +use crate::rankselect::PersistentRankSelectBitVecBuilder; + +use super::super::PersistentBitMatrix; +use super::super::col_path; +use super::super::packed::{PackedBitMatrix, pack_bit_matrix, packed_bit_matrix_n_cols}; +use super::set_dict::SetDict; +use super::{ + PersistentSparseBitMatrix, SparseMeta, dict_offsets_base, dict_values_path, is_multi_path, + multi_path, singleton_path, +}; + +// ── PersistentSparseBitMatrixBuilder ──────────────────────────────────────── + +/// Row batch size for [`PersistentSparseBitMatrixBuilder::build_from_dense`]. +const BUILD_FROM_DENSE_BATCH: usize = 4096; + +pub struct PersistentSparseBitMatrixBuilder { + dir: PathBuf, + n_cols: usize, + is_multi: Vec, + singleton_values: Vec, + multi_dict_ids: Vec, + dict: SetDict, +} + +impl PersistentSparseBitMatrixBuilder { + pub fn new(n: usize, n_cols: usize, dir: &Path) -> io::Result { + fs::create_dir_all(dir)?; + Ok(Self { + dir: dir.to_path_buf(), + n_cols, + is_multi: Vec::with_capacity(n), + singleton_values: Vec::new(), + multi_dict_ids: Vec::new(), + dict: SetDict::new(), + }) + } + + /// Appends one row's genome set — `genomes` sorted ascending, each + /// `< n_cols`. Rows must be pushed in slot order (0, 1, 2, ...), one + /// call per k-mer slot of the layer being converted/built. + /// + /// Cardinality 0 (no genome present — not expected on a real built + /// index, every slot has at least one, but handled correctly rather + /// than assumed away) routes through the dictionary path as a genuine + /// empty entry, *not* the singleton shortcut: a placeholder singleton + /// value would be indistinguishable from a real singleton at that same + /// genome index on read-back. + pub fn push_row(&mut self, genomes: &[u32]) { + match genomes.len() { + 1 => { + self.is_multi.push(false); + self.singleton_values.push(genomes[0]); + } + _ => { + self.is_multi.push(true); + let id = self.dict.intern(genomes); + self.multi_dict_ids.push(id); + } + } + } + + pub fn close(self) -> io::Result<()> { + let n = self.is_multi.len(); + let n_singleton = self.singleton_values.len(); + let n_multi = self.multi_dict_ids.len(); + let n_distinct_multi = self.dict.len(); + + let mut is_multi_b = PersistentRankSelectBitVecBuilder::new(n, &is_multi_path(&self.dir))?; + for (i, &v) in self.is_multi.iter().enumerate() { + is_multi_b.set(i, v); + } + is_multi_b.close()?; + + let singleton_width = bit_width_for_range(self.n_cols as u64); + let mut singleton_b = PersistentFixedIntVecBuilder::new( + n_singleton, + singleton_width, + &singleton_path(&self.dir), + )?; + for (i, &v) in self.singleton_values.iter().enumerate() { + singleton_b.set(i, v as u64); + } + singleton_b.close()?; + + let multi_width = bit_width_for_range(n_distinct_multi as u64); + let mut multi_b = + PersistentFixedIntVecBuilder::new(n_multi, multi_width, &multi_path(&self.dir))?; + for (i, &v) in self.multi_dict_ids.iter().enumerate() { + multi_b.set(i, v as u64); + } + multi_b.close()?; + + let (dict_values, offsets) = self.dict.parts(); + let universe = dict_values.len() as u64 + 1; + let mut offsets_b = + EliasFanoBuilder::new(offsets.len(), universe, &dict_offsets_base(&self.dir))?; + for &o in offsets { + offsets_b.push(o); + } + offsets_b.close()?; + fs::write(dict_values_path(&self.dir), dict_values)?; + + SparseMeta { + n, + n_cols: self.n_cols, + n_singleton, + n_multi, + n_distinct_multi, + } + .save(&self.dir)?; + Ok(()) + } + + pub fn finish(self) -> io::Result { + let dir = self.dir.clone(); + self.close()?; + PersistentSparseBitMatrix::open(&dir) + } + + /// Builds a sparse matrix from an already-built dense + /// [`PersistentBitMatrix`] (`Columnar` or `Packed`), for migrating an + /// existing index. + /// + /// Processes rows in batches of [`BUILD_FROM_DENSE_BATCH`] instead of + /// one row at a time: [`BitSliceView::for_each_set_in`] walks each + /// column *once per batch*, word by word, visiting only the set bits — + /// rather than `fill_row`'s row-major loop, which re-reads every column + /// with one `get()` per cell and jumps between all `n_cols` columns on + /// every single row. Columns are visited in ascending order, so each + /// row's genome list comes out sorted, as `push_row` requires. + pub fn build_from_dense(dense: &PersistentBitMatrix, dir: &Path) -> io::Result { + let n = dense.n(); + let n_cols = dense.n_cols(); + let mut builder = Self::new(n, n_cols, dir)?; + let mut row_buffers: Vec> = vec![Vec::new(); BUILD_FROM_DENSE_BATCH]; + let mut start = 0; + while start < n { + let end = (start + BUILD_FROM_DENSE_BATCH).min(n); + for c in 0..n_cols { + dense.col_view(c).for_each_set_in(start..end, |slot| { + row_buffers[slot - start].push(c as u32); + }); + } + for buf in row_buffers.iter_mut().take(end - start) { + builder.push_row(buf); + buf.clear(); + } + start = end; + } + Ok(builder) + } + + /// Builds the row-permuted copy of `src` into `dir`: row `s` of the + /// result is row `new_to_old[s]` of `src`. `new_to_old` must have + /// `src.n()` entries and be a permutation of `0..src.n()` — the caller + /// proves that, this only reads `src` at those slots. + /// + /// Needed whenever the slot numbering of a layer changes (its MPHF is + /// rebuilt) while the data attached to each k-mer must follow it. + /// Rows are read at arbitrary slots of `src`, so convert a dense source + /// to sparse first (`build_from_dense`) rather than permuting it + /// cell by cell. + pub fn build_permuted( + src: &PersistentSparseBitMatrix, + new_to_old: &[u32], + dir: &Path, + ) -> io::Result { + let mut builder = Self::new(new_to_old.len(), src.n_cols(), dir)?; + let mut genomes: Vec = Vec::new(); + for &old in new_to_old { + genomes.clear(); + src.for_each_genome_in_row(old as usize, |g| genomes.push(g as u32)); + builder.push_row(&genomes); + } + Ok(builder) + } +} + +/// Converts a layer's presence matrix (columnar `col_*.pbiv` or dense +/// `matrix.pbmx`) to the sparse on-disk format in place. Old-format files +/// are removed only after the new format is fully written, so a crash +/// mid-conversion leaves a previous, still valid format. Idempotent: does +/// nothing if `is_multi.prsb` already exists. +/// +/// Columnar data is transposed straight into the sparse format, a window of +/// rows at a time, one column file open at a time +/// ([`PersistentSparseBitMatrixBuilder::build_from_columnar`]): no dense +/// intermediate is written, and a worker holds no mapping of the columns +/// whatever their number. A dense `matrix.pbmx` is only read when it is the +/// current form of the layer: no columnar data pending, or a `matrix.pbmx` +/// that already has as many columns as the columnar metadata says. +pub fn pack_sparse_bit_matrix(dir: &Path) -> io::Result<()> { + if is_multi_path(dir).exists() { + return Ok(()); + } + let packed_path = dir.join("matrix.pbmx"); + + if let Ok(meta) = MatrixMeta::load(dir) + && packed_bit_matrix_n_cols(&packed_path).ok() != Some(meta.n_cols) + { + // Columnar data is the freshest form (any `matrix.pbmx` here is + // stale, e.g. copied from a merge base before the layer was + // widened): transpose it directly. + PersistentSparseBitMatrixBuilder::build_from_columnar(dir, &meta)?.close()?; + for c in 0..meta.n_cols { + fs::remove_file(col_path(dir, c))?; + } + fs::remove_file(dir.join("meta.json"))?; + let _ = fs::remove_file(&packed_path); + return Ok(()); + } + + // Dense packed form is the current one. `pack_bit_matrix` is a no-op when + // there is no columnar data left, and otherwise only drops the + // now-redundant column files. + pack_bit_matrix(dir)?; + let dense = PersistentBitMatrix::Packed(PackedBitMatrix::open(&packed_path)?); + PersistentSparseBitMatrixBuilder::build_from_dense(&dense, dir)?.close()?; + drop(dense); + fs::remove_file(&packed_path) +} diff --git a/src/obicompactvec/src/bitmatrix/sparse/set_dict.rs b/src/obicompactvec/src/bitmatrix/sparse/set_dict.rs new file mode 100644 index 00000000..9c814b02 --- /dev/null +++ b/src/obicompactvec/src/bitmatrix/sparse/set_dict.rs @@ -0,0 +1,136 @@ +//! Deduplicated dictionary of genome sets, each stored once, as the very +//! bytes written to `dict_values.bin`. + +use std::collections::HashMap; +use std::hash::{BuildHasher, RandomState}; + +/// End of a same-hash chain. +const NONE: u32 = u32::MAX; + +fn write_varint(buf: &mut Vec, mut v: u32) { + loop { + let byte = (v & 0x7F) as u8; + v >>= 7; + if v == 0 { + buf.push(byte); + break; + } + buf.push(byte | 0x80); + } +} + +/// Ids are dense and follow first insertion. A set is found by the hash of +/// its encoded bytes; sets sharing a hash are chained through `same_hash`, +/// so the index never holds a copy of a set. +pub(super) struct SetDict { + /// Encoded sets, concatenated in id order. + values: Vec, + /// Start of each set in `values`. + offsets: Vec, + /// Per id: the previous id with the same hash, or [`NONE`]. + same_hash: Vec, + /// Hash → latest id carrying it. + heads: HashMap, + hasher: RandomState, + /// Applied to every hash; narrowed by tests to force collisions. + hash_mask: u64, + scratch: Vec, +} + +impl SetDict { + pub(super) fn new() -> Self { + Self::with_hash_mask(u64::MAX) + } + + fn with_hash_mask(hash_mask: u64) -> Self { + Self { + values: Vec::new(), + offsets: Vec::new(), + same_hash: Vec::new(), + heads: HashMap::new(), + hasher: RandomState::new(), + hash_mask, + scratch: Vec::new(), + } + } + + /// Number of distinct sets. + pub(super) fn len(&self) -> usize { + self.offsets.len() + } + + /// The encoded sets and the start offset of each. + pub(super) fn parts(&self) -> (&[u8], &[u64]) { + (&self.values, &self.offsets) + } + + fn entry(&self, id: usize) -> &[u8] { + let end = self + .offsets + .get(id + 1) + .map_or(self.values.len(), |&o| o as usize); + &self.values[self.offsets[id] as usize..end] + } + + /// Id of `genomes`, adding it if new. + pub(super) fn intern(&mut self, genomes: &[u32]) -> u32 { + self.scratch.clear(); + for &g in genomes { + write_varint(&mut self.scratch, g); + } + let hash = self.hasher.hash_one(self.scratch.as_slice()) & self.hash_mask; + let head = self.heads.get(&hash).copied().unwrap_or(NONE); + let mut id = head; + while id != NONE { + if self.entry(id as usize) == self.scratch.as_slice() { + return id; + } + id = self.same_hash[id as usize]; + } + let new = u32::try_from(self.len()) + .ok() + .filter(|&i| i != NONE) + .expect("too many distinct genome sets"); + self.offsets.push(self.values.len() as u64); + self.values.extend_from_slice(&self.scratch); + self.same_hash.push(head); + self.heads.insert(hash, new); + new + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sets() -> Vec> { + vec![ + vec![0, 1], + vec![], + vec![0, 1, 2], + vec![200, 70_000], + vec![0], + vec![1, 2], + ] + } + + #[test] + fn colliding_hashes_keep_sets_distinct() { + for mask in [0, 1, u64::MAX] { + let mut dict = SetDict::with_hash_mask(mask); + for round in 0..2 { + for (i, set) in sets().iter().enumerate() { + assert_eq!(dict.intern(set), i as u32, "mask {mask} round {round}"); + } + } + assert_eq!(dict.len(), sets().len()); + let mut expected = Vec::new(); + for set in sets() { + for g in set { + write_varint(&mut expected, g); + } + } + assert_eq!(dict.parts().0, expected); + } + } +} diff --git a/src/obicompactvec/src/bitmatrix/sparse_columnar.rs b/src/obicompactvec/src/bitmatrix/sparse_columnar.rs index f508458a..e2b9ec34 100644 --- a/src/obicompactvec/src/bitmatrix/sparse_columnar.rs +++ b/src/obicompactvec/src/bitmatrix/sparse_columnar.rs @@ -23,7 +23,7 @@ const PBIV_HEADER: usize = 16; /// Reads the bits of `path` for rows `start..end` (`start` a multiple of 64) /// into `words`, after checking the header against `n`. -fn read_bit_window( +pub(super) fn read_bit_window( path: &Path, n: usize, start: usize, diff --git a/src/obicompactvec/src/compressed_column.rs b/src/obicompactvec/src/compressed_column.rs new file mode 100644 index 00000000..831bc147 --- /dev/null +++ b/src/obicompactvec/src/compressed_column.rs @@ -0,0 +1,126 @@ +//! A presence column held compressed in RAM, between the moment it has been +//! filled in random slot order (as a plain bitmap) and the moment it is read +//! back, in row windows, to build the sparse matrix. +//! +//! Rows are cut into blocks of [`BLOCK_ROWS`]. Each block is stored as the +//! varint gaps between its set bits, or as its raw bitmap when that is not +//! larger, so a column never costs more than its bitmap plus the 4-byte-per- +//! block index. Any block can be decoded on its own. + +/// Rows per block; a multiple of 64. +const BLOCK_ROWS: usize = 4096; +const BLOCK_WORDS: usize = BLOCK_ROWS / 64; + +pub struct CompressedBitColumn { + n: usize, + bytes: Vec, + /// Start of each block in `bytes`, plus the total length. + offsets: Vec, +} + +impl CompressedBitColumn { + /// Compresses the first `n` bits of `words`; bits beyond `n` must be 0. + pub(crate) fn from_words(words: &[u64], n: usize) -> Self { + let mut bytes = Vec::new(); + let mut offsets = Vec::with_capacity(n.div_ceil(BLOCK_ROWS) + 1); + offsets.push(0); + for block in words[..n.div_ceil(64)].chunks(BLOCK_WORDS) { + encode_block(block, &mut bytes); + offsets.push(u32::try_from(bytes.len()).expect("compressed column over 4 GiB")); + } + bytes.shrink_to_fit(); + Self { n, bytes, offsets } + } + + /// Number of rows. + pub fn len(&self) -> usize { + self.n + } + + pub fn is_empty(&self) -> bool { + self.n == 0 + } + + /// Heap bytes held: encoded blocks and block index. + pub fn byte_size(&self) -> usize { + self.bytes.len() + self.offsets.len() * size_of::() + } + + /// Calls `f(row)` for every set bit of rows `start..end`, ascending. + pub fn for_each_set_in(&self, start: usize, end: usize, mut f: impl FnMut(usize)) { + assert!(start <= end && end <= self.n); + for b in start / BLOCK_ROWS..end.div_ceil(BLOCK_ROWS) { + let base = b * BLOCK_ROWS; + let data = &self.bytes[self.offsets[b] as usize..self.offsets[b + 1] as usize]; + let mut emit = |row: usize| { + if row >= start && row < end { + f(row); + } + }; + if data.len() == bitmap_len((self.n - base).min(BLOCK_ROWS)) { + for (w, chunk) in data.as_chunks::<8>().0.iter().enumerate() { + let mut word = u64::from_le_bytes(*chunk); + while word != 0 { + emit(base + w * 64 + word.trailing_zeros() as usize); + word &= word - 1; + } + } + } else { + let mut next = 0usize; + let mut pos = 0usize; + while pos < data.len() { + let mut gap = 0usize; + let mut shift = 0; + loop { + let byte = data[pos]; + pos += 1; + gap |= usize::from(byte & 0x7F) << shift; + if byte & 0x80 == 0 { + break; + } + shift += 7; + } + next += gap; + emit(base + next); + next += 1; + } + } + } + } +} + +/// Bytes of the raw bitmap of a block of `rows` rows. +fn bitmap_len(rows: usize) -> usize { + rows.div_ceil(64) * 8 +} + +/// Appends one block: gaps if strictly shorter than the bitmap (the length is +/// what tells the two apart), the bitmap otherwise. +fn encode_block(words: &[u64], out: &mut Vec) { + let start = out.len(); + let limit = words.len() * 8; + let mut next = 0usize; + 'gaps: for (w, &word) in words.iter().enumerate() { + let mut rest = word; + while rest != 0 { + let row = w * 64 + rest.trailing_zeros() as usize; + let mut gap = row - next; + while gap >= 0x80 { + out.push(gap as u8 | 0x80); + gap >>= 7; + } + out.push(gap as u8); + next = row + 1; + rest &= rest - 1; + if out.len() - start >= limit { + break 'gaps; + } + } + } + if out.len() - start >= limit { + out.truncate(start); + for word in words { + out.extend_from_slice(&word.to_le_bytes()); + } + } +} diff --git a/src/obicompactvec/src/lib.rs b/src/obicompactvec/src/lib.rs index ea79a7db..1eacff3d 100644 --- a/src/obicompactvec/src/lib.rs +++ b/src/obicompactvec/src/lib.rs @@ -2,6 +2,7 @@ mod bitmatrix; mod bitvec; mod builder; mod colgroup; +mod compressed_column; mod eliasfano; mod fixedintvec; mod format; @@ -27,12 +28,13 @@ mod views_scan; pub use bitmatrix::{ PersistentBitMatrix, PersistentBitMatrixBuilder, PersistentSparseBitMatrix, - PersistentSparseBitMatrixBuilder, batch_presence_counts, pack_bit_matrix, - pack_sparse_bit_matrix, + PersistentSparseBitMatrixBuilder, SparseBase, batch_presence_counts, pack_bit_matrix, + pack_sparse_bit_matrix, write_sparse_presence, }; pub use bitvec::{BitIter, PersistentBitVec, PersistentBitVecBuilder}; pub use builder::PersistentCompactIntVecBuilder; pub use colgroup::{ColGroup, FilterMask, MatrixGroupOps, eval_filter_mask}; +pub use compressed_column::CompressedBitColumn; pub use eliasfano::{EliasFano, EliasFanoBuilder}; pub use fixedintvec::{PersistentFixedIntVec, PersistentFixedIntVecBuilder, bit_width_for_range}; pub use int_group_ops::{IntGroupStats, batch_int_group_stats}; diff --git a/src/obicompactvec/src/matrix_builder.rs b/src/obicompactvec/src/matrix_builder.rs index 26d48158..2a325129 100644 --- a/src/obicompactvec/src/matrix_builder.rs +++ b/src/obicompactvec/src/matrix_builder.rs @@ -8,7 +8,9 @@ use std::io; use std::path::Path; -use crate::{MemBitVecBuilder, MemCompactIntVecBuilder, TempBitVec, TempCompactIntVec}; +use crate::{ + CompressedBitColumn, MemBitVecBuilder, MemCompactIntVecBuilder, TempBitVec, TempCompactIntVec, +}; use crate::{PersistentBitMatrixBuilder as BitMB, PersistentBitVecBuilder}; use crate::{PersistentCompactIntMatrixBuilder as IntMB, PersistentCompactIntVecBuilder}; @@ -35,6 +37,23 @@ impl ColBuilder { } } + /// A presence column of `n` slots held in RAM, belonging to no matrix: + /// finished with [`into_compressed`](Self::into_compressed). + pub fn detached_bit(n: usize) -> Self { + ColBuilder::MemBit(MemBitVecBuilder::detached(n)) + } + + /// The column compressed in RAM, without writing it. In-memory presence + /// columns only. + pub fn into_compressed(self) -> io::Result { + match self { + ColBuilder::MemBit(b) => Ok(b.compress()), + _ => Err(io::Error::other( + "only an in-memory presence column can be compressed", + )), + } + } + pub fn close(self) -> io::Result<()> { match self { ColBuilder::Bit(b) => b.close(), diff --git a/src/obicompactvec/src/mem_builder.rs b/src/obicompactvec/src/mem_builder.rs index 8d304dc9..041a9082 100644 --- a/src/obicompactvec/src/mem_builder.rs +++ b/src/obicompactvec/src/mem_builder.rs @@ -15,6 +15,7 @@ use std::io::{self, Write}; use std::path::{Path, PathBuf}; use crate::bitvec::{MAGIC as PBIV_MAGIC, n_words}; +use crate::compressed_column::CompressedBitColumn; use crate::format::{write_pciv_header, write_pciv_tail}; use crate::mmap_file::{write_built, write_std_header}; @@ -24,7 +25,8 @@ use crate::mmap_file::{write_built, write_std_header}; pub struct MemBitVecBuilder { words: Vec, n: usize, - path: PathBuf, + /// `None` for a detached column, which is only ever compressed. + path: Option, } impl MemBitVecBuilder { @@ -33,10 +35,25 @@ impl MemBitVecBuilder { Self { words: vec![0u64; n_words(n)], n, - path: path.to_path_buf(), + path: Some(path.to_path_buf()), } } + /// All-false vector of `n` bits with no file behind it: its only outlet + /// is [`compress`](Self::compress). + pub fn detached(n: usize) -> Self { + Self { + words: vec![0u64; n_words(n)], + n, + path: None, + } + } + + /// The column, compressed in RAM; nothing is written. + pub fn compress(self) -> CompressedBitColumn { + CompressedBitColumn::from_words(&self.words, self.n) + } + #[inline] pub fn len(&self) -> usize { self.n @@ -62,6 +79,7 @@ impl MemBitVecBuilder { /// exactly as the mmap-backed builder lays them out — and publishes it. pub fn close(self) -> io::Result<()> { let Self { words, n, path } = self; + let path = path.ok_or_else(|| io::Error::other("a detached column has no file"))?; write_built(&path, |w| { write_std_header(w, PBIV_MAGIC, [0u8; 4], n)?; for word in &words { diff --git a/src/obicompactvec/src/tests/mod.rs b/src/obicompactvec/src/tests/mod.rs index e8581bf7..70777a56 100644 --- a/src/obicompactvec/src/tests/mod.rs +++ b/src/obicompactvec/src/tests/mod.rs @@ -9,6 +9,7 @@ mod matrix_builder; mod mem_builder; mod rankselect; mod sparse; +mod sparse_append; mod sparse_intmatrix; mod transpose_columnar; mod views_scan; diff --git a/src/obicompactvec/src/tests/sparse_append.rs b/src/obicompactvec/src/tests/sparse_append.rs new file mode 100644 index 00000000..395391bc --- /dev/null +++ b/src/obicompactvec/src/tests/sparse_append.rs @@ -0,0 +1,140 @@ +//! Compressed in-memory columns, and the sparse matrix built from a base plus +//! such columns: same bytes as the dense route on the equivalent matrix. + +use std::collections::BTreeMap; +use std::fs; +use std::path::Path; + +use tempfile::tempdir; + +use crate::bitmatrix::write_sparse_presence_with; +use crate::{ + ColBuilder, CompressedBitColumn, LayerMeta, PersistentBitMatrix, PersistentBitMatrixBuilder, + PersistentSparseBitMatrixBuilder, SparseBase, pack_sparse_bit_matrix, +}; + +const N: usize = 3 * 4096 + 37; + +fn mix(x: usize) -> u64 { + (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 33 +} + +/// Columns of very different densities, including empty and full blocks. +fn bit(c: usize, slot: usize) -> bool { + let r = mix(slot * 31 + c); + match c % 6 { + 0 => r.is_multiple_of(2), + 1 => r.is_multiple_of(97), + 2 => r.is_multiple_of(7), + 3 => slot < 4096 || slot == N - 1, + 4 => slot % 5000 == 4999, + _ => false, + } +} + +fn compressed(f: impl Fn(usize) -> bool, n: usize) -> CompressedBitColumn { + let mut b = ColBuilder::detached_bit(n); + for slot in 0..n { + b.set_val(slot, u32::from(f(slot))); + } + b.into_compressed().unwrap() +} + +#[test] +fn compressed_column_roundtrips_and_never_exceeds_its_bitmap() { + for c in 0..6 { + for n in [0, 1, 64, 4096, 4097, N] { + let col = compressed(|s| bit(c, s), n); + let index = (n.div_ceil(4096) + 1) * 4; + assert!(col.byte_size() <= n.div_ceil(64) * 8 + index, "c={c} n={n}"); + for (start, end) in [(0, n), (n / 3, n), (n / 2, n / 2 + (n - n / 2) / 3)] { + let mut got = Vec::new(); + col.for_each_set_in(start, end, |r| got.push(r)); + let want: Vec = (start..end).filter(|&s| bit(c, s)).collect(); + assert_eq!(got, want, "c={c} n={n} {start}..{end}"); + } + } + } +} + +fn files(dir: &Path) -> BTreeMap> { + fs::read_dir(dir) + .unwrap() + .map(|e| { + let e = e.unwrap(); + let name = e.file_name().into_string().unwrap(); + (name, fs::read(e.path()).unwrap()) + }) + .collect() +} + +fn columnar(layer: &Path, n_cols: usize, f: impl Fn(usize, usize) -> bool) { + let mut b = PersistentBitMatrixBuilder::new(N, &layer.join("presence")).unwrap(); + for c in 0..n_cols { + let mut col = b.add_col().unwrap(); + for slot in 0..N { + col.set(slot, f(c, slot)); + } + col.close().unwrap(); + } + b.close().unwrap(); +} + +/// Base of `k` columns whose content is `f`, plus `added` further columns: +/// compare with the dense route for several window shapes. +fn check(k: usize, added: usize, f: &dyn Fn(usize, usize) -> bool, prepare: &dyn Fn(&Path)) { + let reference = tempdir().unwrap(); + columnar(reference.path(), k + added, f); + let dense = PersistentBitMatrix::open(reference.path()).unwrap(); + let expected = tempdir().unwrap(); + PersistentSparseBitMatrixBuilder::build_from_dense(&dense, expected.path()) + .unwrap() + .close() + .unwrap(); + let expected = files(expected.path()); + + let cols: Vec = + (k..k + added).map(|c| compressed(|s| f(c, s), N)).collect(); + for (window, max_hits) in [(1 << 21, 4 << 20), (64, 1 << 20), (4096, 200)] { + let layer = tempdir().unwrap(); + LayerMeta::save(layer.path(), N).unwrap(); + prepare(layer.path()); + let base = if layer.path().join("absent").exists() { + SparseBase::Absent(k) + } else { + SparseBase::Layer { n_cols: k } + }; + write_sparse_presence_with(layer.path(), base, N, &cols, window, max_hits).unwrap(); + assert_eq!( + files(&layer.path().join("presence")), + expected, + "window {window}" + ); + assert!(!layer.path().join("presence.new").exists()); + } +} + +#[test] +fn absent_base_matches_dense() { + check(3, 7, &|c, s| c >= 3 && bit(c, s), &|layer| { + fs::write(layer.join("absent"), b"").unwrap() + }); +} + +#[test] +fn implicit_base_matches_dense() { + check(1, 7, &|c, s| c == 0 || bit(c, s), &|_| {}); +} + +#[test] +fn columnar_base_matches_dense() { + check(4, 5, &bit, &|layer| columnar(layer, 4, bit)); +} + +#[test] +fn sparse_base_matches_dense() { + check(4, 5, &bit, &|layer| { + columnar(layer, 4, bit); + pack_sparse_bit_matrix(&layer.join("presence")).unwrap(); + }); +} diff --git a/src/obikmerge/src/lib.rs b/src/obikmerge/src/lib.rs index 8f30fd03..b265bc59 100644 --- a/src/obikmerge/src/lib.rs +++ b/src/obikmerge/src/lib.rs @@ -17,3 +17,6 @@ mod merge; mod partition_merge; pub use merge::{Merge, MergeMode}; + +#[cfg(test)] +mod tests; diff --git a/src/obikmerge/src/merge.rs b/src/obikmerge/src/merge.rs index 0698ab1d..c7102725 100644 --- a/src/obikmerge/src/merge.rs +++ b/src/obikmerge/src/merge.rs @@ -12,7 +12,7 @@ use obikindex::{GenomeInfo, IndexBuilder, IndexState, KmerIndex}; use obisys::{PartitionRunner, Progress, Reporter, Stage}; use tracing::{debug, info}; -use crate::partition_merge::merge_partition; +use crate::partition_merge::{MergeSpec, merge_partition}; // ── MergeMode ───────────────────────────────────────────────────────────────── @@ -312,6 +312,15 @@ impl Algorithm for Merge<'_> { let srcs = &srcs; let evidence = &evidence; let mode = self.mode; + let spec = &MergeSpec { + dst: &dst, + sources: srcs, + mode, + sparse: self.sparse, + n_dst_genomes, + block_bits, + evidence, + }; let runner = PartitionRunner::new(); let mut part_stats: Vec = Vec::with_capacity(n_partitions); @@ -321,7 +330,7 @@ impl Algorithm for Merge<'_> { runner .run( &order, - |i| merge_partition(&dst, i, srcs, mode, n_dst_genomes, block_bits, evidence), + |i| merge_partition(spec, i), |i, g_len, dur| { done += 1; if let Some(cb) = on_progress.as_mut() { diff --git a/src/obikmerge/src/partition_merge/mod.rs b/src/obikmerge/src/partition_merge/mod.rs index d2eb97ac..c989d880 100644 --- a/src/obikmerge/src/partition_merge/mod.rs +++ b/src/obikmerge/src/partition_merge/mod.rs @@ -7,8 +7,9 @@ //! //! Split: this file orchestrates one partition (pass 1, new-layer setup, //! loop over source groups); [`pass2`] holds the per-group column-fill -//! pipeline. +//! pipeline and [`output`] the destination of the filled columns. +mod output; mod pass2; use std::fs; @@ -17,13 +18,14 @@ use std::sync::Arc; use tracing::debug; -use obicompactvec::{ColBuilder, MatrixBuilder}; +use obicompactvec::{MatrixBuilder, SparseBase}; use obikindex::layer::{IndexMode, KmerLayer, TypedLayer}; use obikindex::{KmerIndex, OKIError, OKIResult}; use obikindexer::{build_graph, materialize_layer}; use obiskio::UnitigFileReader; use crate::MergeMode; +use output::{Output, Target}; use pass2::run_pass2; // `MatrixBuilder::new`/`resume` take a `presence: bool` — `MergeMode` maps @@ -34,7 +36,7 @@ fn presence(mode: MergeMode) -> bool { // ── merge_partition ──────────────────────────────────────────────────────── -/// Merge `sources` into destination partition `i`. +/// What every partition of one merge shares. /// /// Each entry in `sources` is `(index, n_genomes)` where `n_genomes` is the /// number of genome columns that source contributes. A merged index @@ -42,17 +44,31 @@ fn presence(mode: MergeMode) -> bool { /// destination is `sum(n_genomes)`. /// /// `n_dst_genomes` is the number of genome columns already in the -/// destination matrices (copied from the bootstrap source before this -/// call). -pub(crate) fn merge_partition( - dst: &KmerIndex, - i: usize, - sources: &[(&KmerIndex, usize)], - mode: MergeMode, - n_dst_genomes: usize, - block_bits: u8, - evidence: &IndexMode, -) -> OKIResult { +/// destination matrices (copied from the bootstrap source before the +/// partitions are merged). With `sparse`, a presence merge writes the sparse +/// matrices directly (see [`output`]). +pub(crate) struct MergeSpec<'a> { + pub(crate) dst: &'a KmerIndex, + pub(crate) sources: &'a [(&'a KmerIndex, usize)], + pub(crate) mode: MergeMode, + pub(crate) sparse: bool, + pub(crate) n_dst_genomes: usize, + pub(crate) block_bits: u8, + pub(crate) evidence: &'a IndexMode, +} + +/// Merge the sources of `spec` into destination partition `i`. +pub(crate) fn merge_partition(spec: &MergeSpec<'_>, i: usize) -> OKIResult { + let &MergeSpec { + dst, + sources, + mode, + sparse, + n_dst_genomes, + block_bits, + evidence, + } = spec; + let sparse_output = sparse && mode == MergeMode::Presence; let dst_partition = dst.partition(i)?; let n_dst_layers = dst_partition.n_layers(); @@ -60,7 +76,8 @@ pub(crate) fn merge_partition( // presence matrices on existing layers (all slots true — every kmer in // those layers belongs to genome_0) so a resumed builder can append // source columns onto them below. - if n_dst_genomes == 1 && mode == MergeMode::Presence { + // The sparse output reads an implicit matrix as it is. + if n_dst_genomes == 1 && mode == MergeMode::Presence && !sparse_output { for l in 0..n_dst_layers { let layer = dst_partition.layer(l)?.open()?; TypedLayer::<()>::init_presence_matrix(layer.dir(), layer.n())?; @@ -159,22 +176,42 @@ pub(crate) fn merge_partition( MergeMode::Count => layer_dir.join("counts"), }; - // ── New layer matrix: absent (dst-genome) columns only ──────────────── - // Created and closed here; every source group below resumes it and - // appends its own columns, exactly like the existing dst layers. - let new_data_dir: Option = if any_new { - let data_dir = matrix_dir(&new_layer_dir); - fs::create_dir_all(&data_dir)?; - let mut mb = MatrixBuilder::new(presence(mode), n_new, &data_dir).map_err(OKIError::Io)?; - for _ in 0..n_dst_genomes { - mb.add_absent_col().map_err(OKIError::Io)?; - } - mb.close().map_err(OKIError::Io)?; - Some(data_dir) + // ── Destination of the columns ──────────────────────────────────────── + // The new layer starts with the dst genomes' columns, all absent. + let mut output = if sparse_output { + let base = SparseBase::Layer { + n_cols: n_dst_genomes, + }; + let exist = dst_layers + .iter() + .map(|l| Target::new(l.dir(), l.n(), base)) + .collect(); + let new = + any_new.then(|| Target::new(&new_layer_dir, n_new, SparseBase::Absent(n_dst_genomes))); + Output::Sparse { exist, new } } else { - None + // New layer matrix: created and closed here; every source group + // below resumes it and appends its own columns, exactly like the + // existing dst layers. + let new_dir: Option = if any_new { + let data_dir = matrix_dir(&new_layer_dir); + fs::create_dir_all(&data_dir)?; + let mut mb = + MatrixBuilder::new(presence(mode), n_new, &data_dir).map_err(OKIError::Io)?; + for _ in 0..n_dst_genomes { + mb.add_absent_col().map_err(OKIError::Io)?; + } + mb.close().map_err(OKIError::Io)?; + Some(data_dir) + } else { + None + }; + Output::Files { + presence: presence(mode), + exist_dirs: dst_layers.iter().map(|l| matrix_dir(l.dir())).collect(), + new_dir, + } }; - let exist_data_dirs: Vec = dst_layers.iter().map(|l| matrix_dir(l.dir())).collect(); // ── Pass 2, by consecutive groups of sources ────────────────────────── // @@ -190,14 +227,15 @@ pub(crate) fn merge_partition( // `g` of a source is `n_dst_genomes + col_base + offset_local + g` — // the same column as when every source was processed in one session. // - // Memory: the group's columns are built in RAM (`add_mem_col`), at most + // Memory: the group's columns are built in RAM, at most // `SRC_GROUP × src_n × (L_dst + 1)` live columns per partition, each of // `n_layer / 8` bytes (presence) or `n_layer` bytes + overflow (counts): // about `SRC_GROUP × src_n × N_part × (1/8 | 1)` bytes, `N_part` being // the partition's k-mer count over all dst layers. For mono-genome // sources this stays below pass 1's de Bruijn graph (≥ ~19 B per new // k-mer) unless the new layer is tiny next to the existing ones - // (incremental merge into a large index). + // (incremental merge into a large index). The sparse output additionally + // keeps every finished column compressed until the partition is written. const SRC_GROUP: usize = 2; let t_pass2 = std::time::Instant::now(); let mut col_base = 0usize; @@ -221,64 +259,20 @@ pub(crate) fn merge_partition( col_offset += src_n; } - let expected_cols = n_dst_genomes + col_base; - let open_group = |data_dir: &Path| -> OKIResult<(MatrixBuilder, Vec)> { - let mut mb = MatrixBuilder::resume(presence(mode), data_dir).map_err(OKIError::Io)?; - if mb.n_cols() != expected_cols { - return Err(OKIError::InvalidData { - context: "merge pass2", - detail: format!( - "{}: {} columns, expected {expected_cols}", - data_dir.display(), - mb.n_cols() - ), - }); - } - // In-memory columns: no sparse file / `MmapMut` on the write - // path, so a block the FS cannot allocate is an `io::Error` at - // `close`, not a SIGBUS (see `MatrixBuilder::add_mem_col`). - let cols = (0..group_n).map(|_| mb.add_mem_col()).collect(); - Ok((mb, cols)) - }; - - let (exist_mbs, exist_cols): (Vec, Vec>) = exist_data_dirs - .iter() - .map(|d| open_group(d)) - .collect::>>()? - .into_iter() - .unzip(); - let (new_mb, new_cols) = match &new_data_dir { - Some(d) => { - let (mb, cols) = open_group(d)?; - (Some(mb), cols) - } - None => (None, vec![]), - }; + let mut columns = output.open_group(group_n, n_dst_genomes + col_base)?; // `items` (and with it this group's source layers) is consumed by // the pipeline and dropped when it returns. - let (exist_cols, new_cols) = run_pass2( + (columns.exist, columns.new) = run_pass2( items, &dst_layers, &new_mphf, - exist_cols, - new_cols, + std::mem::take(&mut columns.exist), + std::mem::take(&mut columns.new), n_workers, max_open, )?; - - for (mb, cols) in exist_mbs.into_iter().zip(exist_cols) { - for c in cols { - c.close()?; - } - mb.close().map_err(OKIError::Io)?; - } - for c in new_cols { - c.close()?; - } - if let Some(mb) = new_mb { - mb.close().map_err(OKIError::Io)?; - } + output.close_group(columns)?; col_base += group_n; } @@ -287,5 +281,10 @@ pub(crate) fn merge_partition( t_pass2.elapsed().as_secs_f64() ); + // The dst layers' matrices are about to be replaced: unmap them first. + drop(dst_layers); + drop(new_mphf); + output.finish(i)?; + Ok(n_new) } diff --git a/src/obikmerge/src/partition_merge/output.rs b/src/obikmerge/src/partition_merge/output.rs new file mode 100644 index 00000000..a105df9b --- /dev/null +++ b/src/obikmerge/src/partition_merge/output.rs @@ -0,0 +1,167 @@ +//! Where pass 2's columns go, group after group. +//! +//! Counts and dense presence append column files to each destination matrix. +//! Sparse presence keeps every added column compressed in RAM and writes each +//! destination matrix once, in its final format, when all groups are done: no +//! column file is created. + +use std::path::{Path, PathBuf}; + +use rayon::prelude::*; +use tracing::debug; + +use obicompactvec::{ + ColBuilder, CompressedBitColumn, MatrixBuilder, SparseBase, write_sparse_presence, +}; +use obikindex::{OKIError, OKIResult}; + +/// A destination matrix written at the end, in sparse form. +pub(super) struct Target { + layer_dir: PathBuf, + n: usize, + base: SparseBase, + added: Vec, +} + +impl Target { + pub(super) fn new(layer_dir: &Path, n: usize, base: SparseBase) -> Self { + Self { + layer_dir: layer_dir.to_path_buf(), + n, + base, + added: Vec::new(), + } + } +} + +pub(super) enum Output { + /// Column files appended to the matrices in `exist_dirs` / `new_dir`. + Files { + presence: bool, + exist_dirs: Vec, + new_dir: Option, + }, + /// Sparse presence, written by [`Output::finish`]. + Sparse { + exist: Vec, + new: Option, + }, +} + +/// One group's open columns: per existing dst layer, then the new layer. +pub(super) struct Group { + pub(super) exist: Vec>, + pub(super) new: Vec, + /// The resumed matrices, existing layers then new one (`Files` only). + matrices: Vec, +} + +impl Output { + /// `n_cols` fresh columns per destination. `expected_cols` is the number + /// of columns each destination matrix file already holds. + pub(super) fn open_group(&self, n_cols: usize, expected_cols: usize) -> OKIResult { + match self { + Output::Files { + presence, + exist_dirs, + new_dir, + } => { + let mut matrices = Vec::new(); + let mut open = |dir: &Path| -> OKIResult> { + let mut mb = MatrixBuilder::resume(*presence, dir).map_err(OKIError::Io)?; + if mb.n_cols() != expected_cols { + return Err(OKIError::InvalidData { + context: "merge pass2", + detail: format!( + "{}: {} columns, expected {expected_cols}", + dir.display(), + mb.n_cols() + ), + }); + } + // In-memory columns: no sparse file / `MmapMut` on the + // write path, so a block the FS cannot allocate is an + // `io::Error` at `close`, not a SIGBUS (see + // `MatrixBuilder::add_mem_col`). + let cols = (0..n_cols).map(|_| mb.add_mem_col()).collect(); + matrices.push(mb); + Ok(cols) + }; + let exist = exist_dirs + .iter() + .map(|d| open(d)) + .collect::>()?; + let new = match new_dir { + Some(d) => open(d)?, + None => Vec::new(), + }; + Ok(Group { + exist, + new, + matrices, + }) + } + Output::Sparse { exist, new } => { + let open = |t: &Target| -> Vec { + (0..n_cols).map(|_| ColBuilder::detached_bit(t.n)).collect() + }; + Ok(Group { + exist: exist.iter().map(open).collect(), + new: new.as_ref().map(open).unwrap_or_default(), + matrices: Vec::new(), + }) + } + } + } + + /// Takes back a filled group. + pub(super) fn close_group(&mut self, group: Group) -> OKIResult<()> { + match self { + Output::Files { .. } => { + for c in group.exist.into_iter().flatten().chain(group.new) { + c.close()?; + } + for mb in group.matrices { + mb.close().map_err(OKIError::Io)?; + } + } + Output::Sparse { exist, new } => { + let compress = |t: &mut Target, cols: Vec| -> OKIResult<()> { + let cols = cols + .into_par_iter() + .map(ColBuilder::into_compressed) + .collect::>>() + .map_err(OKIError::Io)?; + t.added.extend(cols); + Ok(()) + }; + for (t, cols) in exist.iter_mut().zip(group.exist) { + compress(t, cols)?; + } + if let Some(t) = new { + compress(t, group.new)?; + } + } + } + Ok(()) + } + + /// Writes what is still only in RAM, releasing each layer's columns as + /// soon as its matrix is written. + pub(super) fn finish(self, partition: usize) -> OKIResult<()> { + let Output::Sparse { exist, new } = self else { + return Ok(()); + }; + let targets: Vec = exist.into_iter().chain(new).collect(); + let bytes: usize = targets + .iter() + .flat_map(|t| &t.added) + .map(CompressedBitColumn::byte_size) + .sum(); + debug!("partition {partition}: compressed presence columns: {bytes} bytes"); + for t in targets { + write_sparse_presence(&t.layer_dir, t.base, t.n, &t.added).map_err(OKIError::Io)?; + } + Ok(()) + } +} diff --git a/src/obikmerge/src/tests.rs b/src/obikmerge/src/tests.rs new file mode 100644 index 00000000..2c1939ab --- /dev/null +++ b/src/obikmerge/src/tests.rs @@ -0,0 +1,195 @@ +//! Presence merge of small mono-genome indexes: the sparse output written +//! directly must be what the column-by-column route followed by a sparse +//! pack produces, and must give every k-mer its genomes. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +use obicompactvec::{ + PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder, +}; +use obikalgorithm::Algorithm; +use obikindex::layer::{IndexMode, KmerLayer}; +use obikindex::{GenomeInfo, IndexBuilder, IndexConfig, KmerIndex}; +use obikindexer::build_layer_from_kmers; +use obikseq::{CanonicalKmer, Kmer, Sequence}; +use obisys::Reporter; + +use crate::{Merge, MergeMode}; + +const K: usize = 21; +const PARTITION_BITS: usize = 1; +const GENOMES: usize = 7; + +fn dna(seed: u64, len: usize) -> Vec { + let mut s = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + (0..len) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + b"ACGT"[(s >> 32) as usize % 4] + }) + .collect() +} + +fn kmers_of(seq: &[u8]) -> impl Iterator { + seq.windows(K) + .map(|w| Kmer::from_ascii(w).unwrap().canonical()) +} + +/// Genome `g`: a core shared by all, a stretch shared with its parity group, +/// and a private one. The first is the longest, so it becomes the base. +fn genome(g: usize) -> BTreeSet { + let private = if g == 0 { 900 } else { 300 }; + [ + dna(1, 800), + dna(10 + (g % 2) as u64, 400), + dna(100 + g as u64, private), + ] + .iter() + .flat_map(|s| kmers_of(s)) + .collect() +} + +/// The test's own routing: any function of the k-mer will do, as long as all +/// sources share it. +fn partition_of(kmer: &CanonicalKmer) -> usize { + let ascii = kmer.to_ascii(); + ascii.iter().map(|&b| usize::from(b)).sum::() % (1 << PARTITION_BITS) +} + +fn build_index(path: &Path, g: usize) -> KmerIndex { + let config = IndexConfig { + kmer_size: K, + minimizer_size: 11, + n_bits: PARTITION_BITS, + with_counts: false, + evidence: IndexMode::default(), + block_bits: 0, + }; + let idx = KmerIndex::create(path, config, Some(GenomeInfo::new(format!("g{g}")))).unwrap(); + for i in 0..idx.n_partitions() { + let partition = idx.partition(i).unwrap(); + let layer_dir = KmerLayer::new(&partition, 0).dir().to_path_buf(); + fs::create_dir_all(&layer_dir).unwrap(); + let kmers = genome(g).into_iter().filter(|k| partition_of(k) == i); + build_layer_from_kmers(kmers, &layer_dir, 0, &IndexMode::default()).unwrap(); + } + drop(idx); + KmerIndex::finalize_indexed(path, &mut Reporter::new(), false).unwrap() +} + +fn layer_dirs(idx: &KmerIndex, i: usize) -> Vec { + let partition = idx.partition(i).unwrap(); + (0..partition.n_layers()) + .map(|l| KmerLayer::new(&partition, l).dir().to_path_buf()) + .collect() +} + +fn files(dir: &Path) -> BTreeMap> { + fs::read_dir(dir) + .unwrap() + .map(|e| { + let e = e.unwrap(); + let name = e.file_name().into_string().unwrap(); + (name, fs::read(e.path()).unwrap()) + }) + .collect() +} + +/// Writes into `out` the new layer's matrix of `from`, partition `i`, with its +/// rows in the slot order of the same layer of `to`. +fn renumber(to: &KmerIndex, from: &KmerIndex, i: usize, out: &Path) { + let open = |idx: &KmerIndex| idx.partition(i).unwrap().layer(1).unwrap().open().unwrap(); + let (to_layer, from_layer) = (open(to), open(from)); + let source = PersistentSparseBitMatrix::open(&layer_dirs(from, i)[1].join("presence")).unwrap(); + let mut new_to_old = vec![u32::MAX; source.n()]; + for kmer in (0..GENOMES).flat_map(genome) { + if partition_of(&kmer) == i + && let Some(slot) = to_layer.find_slot(kmer) + { + new_to_old[slot] = from_layer.find_slot(kmer).unwrap() as u32; + } + } + PersistentSparseBitMatrixBuilder::build_permuted(&source, &new_to_old, out) + .unwrap() + .close() + .unwrap(); +} + +/// Every k-mer of every genome is in exactly one layer, with its genome set. +fn check_content(idx: &KmerIndex) { + let mut expected: BTreeMap> = BTreeMap::new(); + // The merge puts its base first; here the base is genome 0 and the other + // sources keep their order. + for g in 0..GENOMES { + for kmer in genome(g) { + expected.entry(kmer).or_insert_with(|| vec![false; GENOMES])[g] = true; + } + } + for i in 0..idx.n_partitions() { + let layers: Vec<(KmerLayer, PersistentBitMatrix)> = layer_dirs(idx, i) + .iter() + .enumerate() + .map(|(l, dir)| { + let layer = idx.partition(i).unwrap().layer(l).unwrap().open().unwrap(); + (layer, PersistentBitMatrix::open(dir).unwrap()) + }) + .collect(); + for (kmer, row) in expected.iter().filter(|(k, _)| partition_of(k) == i) { + let found: Vec> = layers + .iter() + .filter_map(|(layer, m)| layer.find_slot(*kmer).map(|s| m.row(s).into_vec())) + .collect(); + assert_eq!(found, std::slice::from_ref(row), "partition {i}"); + } + } +} + +#[test] +fn direct_sparse_presence_merge_matches_columnar_then_pack() { + let root = std::env::temp_dir().join(format!("obikmerge-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + + let sources: Vec = (0..GENOMES) + .map(|g| build_index(&root.join(format!("g{g}")), g)) + .collect(); + let refs: Vec<&KmerIndex> = sources.iter().collect(); + + let direct = Merge::new(&refs, root.join("direct"), MergeMode::Presence) + .run() + .unwrap(); + let columnar = Merge::new(&refs, root.join("columnar"), MergeMode::Presence) + .sparse(false) + .run() + .unwrap(); + columnar.pack_matrices(true).unwrap(); + + check_content(&direct); + check_content(&columnar); + for i in 0..direct.n_partitions() { + let (a, b) = (layer_dirs(&direct, i), layer_dirs(&columnar, i)); + assert_eq!(a.len(), 2, "base layer and new layer"); + assert_eq!(a.len(), b.len()); + for a in &a { + let direct_files = files(&a.join("presence")); + assert!(direct_files.contains_key("sparse_meta.json")); + assert!(!direct_files.keys().any(|n| n.starts_with("col_"))); + assert!(!a.join("presence.new").exists()); + } + // Layer 0 is the base's, copied: same slots in both outputs. The new + // layer's MPHF is built from a graph filled in parallel, so its slot + // numbering may differ from one run to the next: renumber the + // reference into the direct output's slots before comparing bytes. + assert!(files(&a[0].join("presence")) == files(&b[0].join("presence"))); + let renumbered = root.join(format!("renumbered{i}")); + renumber(&direct, &columnar, i, &renumbered); + assert!(files(&a[1].join("presence")) == files(&renumbered)); + } + + drop((direct, columnar, sources)); + fs::remove_dir_all(&root).unwrap(); +} diff --git a/src/obiskim/Cargo.toml b/src/obiskim/Cargo.toml index 6f52a9d0..543bd29e 100644 --- a/src/obiskim/Cargo.toml +++ b/src/obiskim/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "obiskim" -version = "1.4.10" +version = "1.4.11" edition = "2024" license = "CECILL-2.1" repository = "https://forge.metabarcoding.org/obi/obiskim"