refactor: overhaul compact vector storage, phylo algorithms, and CLI interfaces

Refactor the core compact vector library to support sparse matrices, overflow handling, and improved distance metrics. Update phylogenetic algorithms to handle ambiguity policies and quartet conventions, and standardize error handling and CLI argument parsing across all tools.

- `src/obicompactvec`: Add support for sparse bit matrices and overflow handling in compact vectors; update distance metrics (Jaccard, Bray, Euclidean) to accept explicit sums and thresholds; add `transpose` module and refine `PersistentBitMatrix`/`PersistentSparseBitMatrix` APIs.
- `src/obicompactvec/src/bitmatrix`: Implement `PersistentSparseBitMatrix` and `PersistentSparseBitMatrixBuilder`; update pairwise distance calculations to handle implicit and sparse types; add `partial_group_presence_count` for group operations.
- `src/obicompactvec/src/tests`: Update tests to use new sparse matrix APIs, explicit `.close().unwrap()` chains, and refined assertions for distance symmetry and diagonal checks.
- `src/obidebruinj`: Refactor De Bruijn graph traversal to use atomic fetch-or for visited masks and explicit direction checks in `unitig_nucleotides` and `for_each_unitig`.
- `src/obifastwrite`: Update `annotation` to accept slice of tuples; refine `write_scatter` and `write_count` output structures; improve ID extraction in `different_sequences_different_id`.
- `src/obikdump`: Refactor `dump` and `write_unitigs` to use parallel iterators (`rayon::into_par_iter`) and updated `IndexCache` imports for kmer partitioning.
- `src/obikentropy`: Update `emit_f64_2d` formatting; refine entropy tests to use `Kmer::from_ascii` directly and multi-line assertions for range checks.
- `src/obikfilter`: Add `MinComplexity` filter; update `passes` logic for ingroup/outgroup counts with explicit threshold checks; refactor `filter_partition` to use closures for kmer insertion.
- `src/obikidxcache`: Update `iter_partition` and `iter_indexed` to handle explicit partition arguments and collect layer cache keys before iteration.
- `src/obikindex`: Refactor `IndexBuilder` and `KmerIndex` to explicitly initialize `meta` and `lock`; update `OKIError` to include static context and string details; add `TypedLayer` row presence histogram support.
- `src/obikindexer`: Update `build_index_layer` to handle zero layers and flatten `mphf1.bin` loading; refactor `graph_pipeline` to explicitly define transformations and sinks for `KmerGraphData`.
- `src/obikmer`: Refactor CLI commands (`annotate`, `convert`, `dump`, `filter`, `pack`, `select`, `unitig`) to use explicit error handling with `unwrap_or_else` and updated metadata access; add `query` and `select` modules.
- `src/obikmer/src/cmd/phylo`: Update phylogenetic output writers (`iqtree`, `phyg`, `phylip`, `sankoff`, `tnt`) to handle explicit genome indices, sites, and alignment structures; add `shared` module for shared kmer writing.
- `src/obikmerge`: Refactor `merge` to validate source compatibility with specific error messages; update pass 2 logic to stream layer unitigs to column builders.
- `src/obikphylo`: Overhaul distance metrics to support ambiguity policies and quartet conventions; update `SnpAlignment` to include sites; refactor sibling algorithms to handle masking, entropy, and pair weights explicitly.
- `src/obikphylo/src/siblings`: Update `alignment`, `cardcomp`, `entropy`, `masking`, and `pairwise` algorithms to use explicit policy arguments and refined assertions; add `sample_stats` and `subsample` modules.
- `src/obikphylo/src/tree`: Refactor `neighbor_joining` and `upgma` to explicitly handle node creation, edge finding, and label cloning.
- `src/obikquery`: Add `partition_kmers`, `query_layer`, and `smer_index` modules; update `process_chunk` to use explicit iterator chaining for statistics; refine `from_records` to push kmer descriptions.
- `src/obikrebuild`: Refactor `compact_partition` and `reindex` to use explicit block structures and updated error mapping for metadata evidence.
- `src/obikselect`: Update `build_output_cols` to handle group operations and default aggregation; refine `select_partition` to explicitly pass thresholds and presence flags.
- `src/obikseq`: Update `Kmer` push methods to use bitwise operations with `PhantomData`; refine `PackedSeq` initialization and error handling; add `RoutableSuperKmer` to public API.
- `src/obiksession`: Update `Session` to accept `force` parameter for opening; refine `Memoize` to use `get_or_compute_with_key` and explicit byte conversion.
- `src/obikstats`: Refactor `SharingNullModel` to directly construct probability vectors; update tests to use fixed `SharingSpectrum` definitions.
- `src/obipipeline`: Refactor scheduler macros to wrap transformations in `Box<dyn Fn>` with `Send + Sync`; update `Pipe` and `Pool` to handle explicit error signaling and stage indexing.
- `src/obiread`: Add `text/gbff` MIME type; update `read_sequence_chunks_sized` to use explicit `SeqChunkIter` constructors; refine `SeqRecord` initialization.
- `src/obiskbuilder`: Add `stream_iter` module for streaming superkmer iteration; update benchmarks to use direct `.count()` calls.
- `src/obiskio`: Refactor `SKError` to include static context and string details; update `UnitigFileReader`/`Writer` to use explicit error mapping and block offset handling.
- `src/obisys`: Refactor `DirLock` to use explicit `acquire_mode` and `promote`/`demote` logic; update `LockSlot` to handle exclusive/shared states with mutexes; refine `NodeConfig` and `effective_parallelism` tracing.
- `src/obitaxonomy`: Refactor `TaxPath` and `TaxPattern` parsing to handle segments and ranks explicitly; update error messages to include segment information; add `segment` and `segment_pattern` modules.
This commit is contained in:
Eric Coissac committed 2026-12-01 17:34:15 +01:00
1 parent 8159137f8b
commit ed0d563995
209 files changed
+4235 -1288

No files matched your search

@@ -10,26 +10,39 @@ use std::error::Error;
use std::path::Path; use std::path::Path;
use std::time::Instant; use std::time::Instant;
use obicompactvec::{PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder}; use obicompactvec::{
PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder,
};
fn main() -> Result<(), Box<dyn Error>> { fn main() -> Result<(), Box<dyn Error>> {
let layer_dir = std::env::args().nth(1).expect("usage: compare_sparse_dense <layer_dir>"); let layer_dir = std::env::args()
.nth(1)
.expect("usage: compare_sparse_dense <layer_dir>");
let layer_dir = Path::new(&layer_dir); let layer_dir = Path::new(&layer_dir);
let t0 = Instant::now(); let t0 = Instant::now();
let dense = PersistentBitMatrix::open(layer_dir)?; let dense = PersistentBitMatrix::open(layer_dir)?;
println!("dense ouverte en {:?} ({} lignes x {} colonnes)", t0.elapsed(), dense.n(), dense.n_cols()); println!(
"dense ouverte en {:?} ({} lignes x {} colonnes)",
t0.elapsed(),
dense.n(),
dense.n_cols()
);
let out_dir = tempfile::tempdir()?; let out_dir = tempfile::tempdir()?;
let t0 = Instant::now(); let t0 = Instant::now();
let sparse = PersistentSparseBitMatrixBuilder::build_from_dense(&dense, out_dir.path())?.finish()?; let sparse =
PersistentSparseBitMatrixBuilder::build_from_dense(&dense, out_dir.path())?.finish()?;
println!("build_from_dense: {:?}", t0.elapsed()); println!("build_from_dense: {:?}", t0.elapsed());
compare(&dense, &sparse) compare(&dense, &sparse)
} }
fn compare(dense: &PersistentBitMatrix, sparse: &PersistentSparseBitMatrix) -> Result<(), Box<dyn Error>> { fn compare(
dense: &PersistentBitMatrix,
sparse: &PersistentSparseBitMatrix,
) -> Result<(), Box<dyn Error>> {
let n = dense.n(); let n = dense.n();
let n_cols = dense.n_cols(); let n_cols = dense.n_cols();
assert_eq!(n, sparse.n(), "n mismatch"); assert_eq!(n, sparse.n(), "n mismatch");
@@ -56,7 +69,10 @@ fn compare(dense: &PersistentBitMatrix, sparse: &PersistentSparseBitMatrix) -> R
} }
} }
} }
println!("comparaison bit-a-bit: {:?} ({total_cells} cellules)", t0.elapsed()); println!(
"comparaison bit-a-bit: {:?} ({total_cells} cellules)",
t0.elapsed()
);
if let Some((slot, col, d, s)) = first_mismatch { if let Some((slot, col, d, s)) = first_mismatch {
eprintln!("PREMIER MISMATCH: slot={slot} col={col} dense={d} sparse={s}"); eprintln!("PREMIER MISMATCH: slot={slot} col={col} dense={d} sparse={s}");
@@ -13,20 +13,30 @@ use std::error::Error;
use std::path::Path; use std::path::Path;
use std::time::Instant; use std::time::Instant;
use obicompactvec::{PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder}; use obicompactvec::{
PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder,
};
fn main() -> Result<(), Box<dyn Error>> { fn main() -> Result<(), Box<dyn Error>> {
let layer_dir = std::env::args().nth(1).expect("usage: compare_sparse_dense_presence <layer_dir>"); let layer_dir = std::env::args()
.nth(1)
.expect("usage: compare_sparse_dense_presence <layer_dir>");
let layer_dir = Path::new(&layer_dir); let layer_dir = Path::new(&layer_dir);
let t0 = Instant::now(); let t0 = Instant::now();
let dense = PersistentBitMatrix::open(layer_dir)?; let dense = PersistentBitMatrix::open(layer_dir)?;
println!("dense ouverte en {:?} ({} lignes x {} colonnes)", t0.elapsed(), dense.n(), dense.n_cols()); println!(
"dense ouverte en {:?} ({} lignes x {} colonnes)",
t0.elapsed(),
dense.n(),
dense.n_cols()
);
let out_dir = tempfile::tempdir()?; let out_dir = tempfile::tempdir()?;
let t0 = Instant::now(); let t0 = Instant::now();
let sparse = PersistentSparseBitMatrixBuilder::build_from_dense(&dense, out_dir.path())?.finish()?; let sparse =
PersistentSparseBitMatrixBuilder::build_from_dense(&dense, out_dir.path())?.finish()?;
println!("build_from_dense: {:?}", t0.elapsed()); println!("build_from_dense: {:?}", t0.elapsed());
compare(&dense, &sparse)?; compare(&dense, &sparse)?;
@@ -36,7 +46,10 @@ fn main() -> Result<(), Box<dyn Error>> {
Ok(()) Ok(())
} }
fn compare(dense: &PersistentBitMatrix, sparse: &PersistentSparseBitMatrix) -> Result<(), Box<dyn Error>> { fn compare(
dense: &PersistentBitMatrix,
sparse: &PersistentSparseBitMatrix,
) -> Result<(), Box<dyn Error>> {
let n = dense.n(); let n = dense.n();
let n_cols = dense.n_cols(); let n_cols = dense.n_cols();
assert_eq!(n, sparse.n(), "n mismatch"); assert_eq!(n, sparse.n(), "n mismatch");
@@ -63,7 +76,10 @@ fn compare(dense: &PersistentBitMatrix, sparse: &PersistentSparseBitMatrix) -> R
} }
} }
} }
println!("comparaison case-a-case: {:?} ({total_cells} cellules)", t0.elapsed()); println!(
"comparaison case-a-case: {:?} ({total_cells} cellules)",
t0.elapsed()
);
if let Some((slot, col, d, s)) = first_mismatch { if let Some((slot, col, d, s)) = first_mismatch {
eprintln!("PREMIER MISMATCH: slot={slot} col={col} dense={d} sparse={s}"); eprintln!("PREMIER MISMATCH: slot={slot} col={col} dense={d} sparse={s}");
@@ -121,7 +137,11 @@ fn dir_size(dir: &Path) -> std::io::Result<u64> {
Ok(total) Ok(total)
} }
fn compaction_stats(dense_layer_dir: &Path, sparse_dir: &Path, dense: &PersistentBitMatrix) -> Result<(), Box<dyn Error>> { fn compaction_stats(
dense_layer_dir: &Path,
sparse_dir: &Path,
dense: &PersistentBitMatrix,
) -> Result<(), Box<dyn Error>> {
let dense_size = dir_size(&dense_layer_dir.join("presence"))?; let dense_size = dir_size(&dense_layer_dir.join("presence"))?;
let sparse_size = dir_size(sparse_dir)?; let sparse_size = dir_size(sparse_dir)?;
+21 -5
View File
@@ -21,7 +21,11 @@ pub struct PersistentBitMatrixBuilder {
impl PersistentBitMatrixBuilder { impl PersistentBitMatrixBuilder {
pub fn new(n: usize, dir: &Path) -> io::Result<Self> { pub fn new(n: usize, dir: &Path) -> io::Result<Self> {
fs::create_dir_all(dir)?; fs::create_dir_all(dir)?;
Ok(Self { dir: dir.to_path_buf(), n, n_cols: 0 }) Ok(Self {
dir: dir.to_path_buf(),
n,
n_cols: 0,
})
} }
/// Resume appending columns to a Columnar matrix directory already /// Resume appending columns to a Columnar matrix directory already
@@ -32,11 +36,19 @@ impl PersistentBitMatrixBuilder {
/// on-disk column naming or `MatrixMeta` themselves. /// on-disk column naming or `MatrixMeta` themselves.
pub fn resume(dir: &Path) -> io::Result<Self> { pub fn resume(dir: &Path) -> io::Result<Self> {
let meta = MatrixMeta::load(dir)?; let meta = MatrixMeta::load(dir)?;
Ok(Self { dir: dir.to_path_buf(), n: meta.n, n_cols: meta.n_cols }) Ok(Self {
dir: dir.to_path_buf(),
n: meta.n,
n_cols: meta.n_cols,
})
} }
pub fn n(&self) -> usize { self.n } pub fn n(&self) -> usize {
pub fn n_cols(&self) -> usize { self.n_cols } self.n
}
pub fn n_cols(&self) -> usize {
self.n_cols
}
pub fn add_col(&mut self) -> io::Result<PersistentBitVecBuilder> { pub fn add_col(&mut self) -> io::Result<PersistentBitVecBuilder> {
let path = col_path(&self.dir, self.n_cols); let path = col_path(&self.dir, self.n_cols);
@@ -73,6 +85,10 @@ impl PersistentBitMatrixBuilder {
} }
pub fn close(self) -> io::Result<()> { pub fn close(self) -> io::Result<()> {
MatrixMeta { n: self.n, n_cols: self.n_cols }.save(&self.dir) MatrixMeta {
n: self.n,
n_cols: self.n_cols,
}
.save(&self.dir)
} }
} }
+15 -5
View File
@@ -7,7 +7,9 @@ use crate::bitvec::{PersistentBitVec, PersistentBitVecBuilder};
use crate::meta::MatrixMeta; use crate::meta::MatrixMeta;
use super::col_path; use super::col_path;
use super::pairwise::{fill_row_generic, par_col_reduce, pairwise2_matrix, pairwise_matrix, row_generic}; use super::pairwise::{
fill_row_generic, pairwise_matrix, pairwise2_matrix, par_col_reduce, row_generic,
};
// ── ColumnarBitMatrix ───────────────────────────────────────────────────────── // ── ColumnarBitMatrix ─────────────────────────────────────────────────────────
@@ -27,11 +29,17 @@ impl ColumnarBitMatrix {
} }
#[inline] #[inline]
pub(crate) fn n(&self) -> usize { self.n } pub(crate) fn n(&self) -> usize {
self.n
}
#[inline] #[inline]
pub(crate) fn n_cols(&self) -> usize { self.cols.len() } pub(crate) fn n_cols(&self) -> usize {
self.cols.len()
}
#[inline] #[inline]
pub(crate) fn col(&self, c: usize) -> &PersistentBitVec { &self.cols[c] } pub(crate) fn col(&self, c: usize) -> &PersistentBitVec {
&self.cols[c]
}
#[inline] #[inline]
pub(crate) fn row(&self, slot: usize) -> Box<[bool]> { pub(crate) fn row(&self, slot: usize) -> Box<[bool]> {
@@ -48,7 +56,9 @@ impl ColumnarBitMatrix {
} }
pub(crate) fn partial_jaccard_dist_matrix(&self) -> (Array2<u64>, Array2<u64>) { pub(crate) fn partial_jaccard_dist_matrix(&self) -> (Array2<u64>, Array2<u64>) {
pairwise2_matrix(self.n_cols(), |i, j| self.col(i).partial_jaccard_dist(self.col(j))) pairwise2_matrix(self.n_cols(), |i, j| {
self.col(i).partial_jaccard_dist(self.col(j))
})
} }
pub(crate) fn partial_hamming_dist_matrix(&self) -> Array2<u64> { pub(crate) fn partial_hamming_dist_matrix(&self) -> Array2<u64> {
+12 -4
View File
@@ -1,7 +1,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::io; use std::io;
use crate::colgroup::{chunked_presence_count, ColGroup, MatrixGroupOps}; use crate::colgroup::{ColGroup, MatrixGroupOps, chunked_presence_count};
use crate::tempbitvec::{TempBitVec, TempBitVecBuilder}; use crate::tempbitvec::{TempBitVec, TempBitVecBuilder};
use crate::tempintvec::{TempCompactIntVec, TempCompactIntVecBuilder}; use crate::tempintvec::{TempCompactIntVec, TempCompactIntVecBuilder};
@@ -114,9 +114,15 @@ pub fn batch_presence_counts(
// ── MatrixGroupOps ──────────────────────────────────────────────────────────── // ── MatrixGroupOps ────────────────────────────────────────────────────────────
impl MatrixGroupOps for PersistentBitMatrix { impl MatrixGroupOps for PersistentBitMatrix {
fn partial_group_presence_count(&self, g: &ColGroup, _threshold: u32) -> io::Result<TempCompactIntVec> { fn partial_group_presence_count(
&self,
g: &ColGroup,
_threshold: u32,
) -> io::Result<TempCompactIntVec> {
// Bit matrices store 0/1 — threshold is structurally always 1. // Bit matrices store 0/1 — threshold is structurally always 1.
chunked_presence_count(self.n(), &g.indices, |b, c| b.inc_present_fast(self.col_view(c))) chunked_presence_count(self.n(), &g.indices, |b, c| {
b.inc_present_fast(self.col_view(c))
})
} }
fn partial_group_sum(&self, g: &ColGroup) -> io::Result<TempCompactIntVec> { fn partial_group_sum(&self, g: &ColGroup) -> io::Result<TempCompactIntVec> {
@@ -139,7 +145,9 @@ impl MatrixGroupOps for PersistentBitMatrix {
let mut result = TempCompactIntVecBuilder::new(n)?; let mut result = TempCompactIntVecBuilder::new(n)?;
if let Some((&first, rest)) = g.indices.split_first() { if let Some((&first, rest)) = g.indices.split_first() {
result.inc_present_fast(self.col_view(first)); result.inc_present_fast(self.col_view(first));
for &c in rest { result.mask_with(self.col_view(c)); } for &c in rest {
result.mask_with(self.col_view(c));
}
} }
result.freeze() result.freeze()
} }
+6 -2
View File
@@ -24,10 +24,14 @@ pub use builder::PersistentBitMatrixBuilder;
pub use group_ops::batch_presence_counts; pub use group_ops::batch_presence_counts;
pub use packed::pack_bit_matrix; pub use packed::pack_bit_matrix;
pub use persistent::PersistentBitMatrix; pub use persistent::PersistentBitMatrix;
pub use sparse::{PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder, pack_sparse_bit_matrix};
pub(crate) use sparse::RowRank; pub(crate) use sparse::RowRank;
pub use sparse::{
PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder, pack_sparse_bit_matrix,
};
pub(crate) use pairwise::{fill_row_generic, par_col_reduce, pairwise2_matrix, pairwise_matrix, row_generic}; pub(crate) use pairwise::{
fill_row_generic, pairwise_matrix, pairwise2_matrix, par_col_reduce, row_generic,
};
fn col_path(dir: &Path, col: usize) -> PathBuf { fn col_path(dir: &Path, col: usize) -> PathBuf {
dir.join(format!("col_{col:06}.pbiv")) dir.join(format!("col_{col:06}.pbiv"))
+24 -7
View File
@@ -10,7 +10,9 @@ use crate::meta::MatrixMeta;
use crate::views::BitSliceView; use crate::views::BitSliceView;
use super::col_path; use super::col_path;
use super::pairwise::{fill_row_generic, par_col_reduce, pairwise2_matrix, pairwise_matrix, row_generic}; use super::pairwise::{
fill_row_generic, pairwise_matrix, pairwise2_matrix, par_col_reduce, row_generic,
};
// ── PackedBitMatrix ─────────────────────────────────────────────────────────── // ── PackedBitMatrix ───────────────────────────────────────────────────────────
@@ -32,7 +34,10 @@ impl PackedBitMatrix {
pub(crate) fn open(path: &Path) -> io::Result<Self> { pub(crate) fn open(path: &Path) -> io::Result<Self> {
let mmap = unsafe { Mmap::map(&File::open(path)?)? }; let mmap = unsafe { Mmap::map(&File::open(path)?)? };
if mmap.len() < PBMX_HEADER { if mmap.len() < PBMX_HEADER {
return Err(io::Error::new(io::ErrorKind::InvalidData, "PBMX file too short")); return Err(io::Error::new(
io::ErrorKind::InvalidData,
"PBMX file too short",
));
} }
if &mmap[0..4] != &PBMX_MAGIC { if &mmap[0..4] != &PBMX_MAGIC {
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PBMX magic")); return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PBMX magic"));
@@ -43,11 +48,17 @@ impl PackedBitMatrix {
let mut data_offsets = Vec::with_capacity(n_cols); let mut data_offsets = Vec::with_capacity(n_cols);
for c in 0..n_cols { for c in 0..n_cols {
let off_pos = PBMX_HEADER + c * 8; let off_pos = PBMX_HEADER + c * 8;
let col_file_off = u64::from_le_bytes(mmap[off_pos..off_pos+8].try_into().unwrap()) as usize; let col_file_off =
u64::from_le_bytes(mmap[off_pos..off_pos + 8].try_into().unwrap()) as usize;
data_offsets.push(col_file_off + PBIV_HEADER); data_offsets.push(col_file_off + PBIV_HEADER);
} }
Ok(Self { mmap, n_rows, n_cols, data_offsets }) Ok(Self {
mmap,
n_rows,
n_cols,
data_offsets,
})
} }
#[inline] #[inline]
@@ -134,7 +145,9 @@ pub fn pack_bit_matrix(dir: &Path) -> io::Result<()> {
// the columnar files are newer and must be (re-)packed, overwriting the // the columnar files are newer and must be (re-)packed, overwriting the
// stale one — never silently discarded as "leftover cleanup". // stale one — never silently discarded as "leftover cleanup".
if packed_bit_matrix_n_cols(&packed_path).ok() == Some(meta.n_cols) { if packed_bit_matrix_n_cols(&packed_path).ok() == Some(meta.n_cols) {
for c in 0..meta.n_cols { let _ = fs::remove_file(col_path(dir, c)); } for c in 0..meta.n_cols {
let _ = fs::remove_file(col_path(dir, c));
}
let _ = fs::remove_file(dir.join("meta.json")); let _ = fs::remove_file(dir.join("meta.json"));
return Ok(()); return Ok(());
} }
@@ -162,7 +175,9 @@ pub fn pack_bit_matrix(dir: &Path) -> io::Result<()> {
out.write_all(&[0u8; 4])?; out.write_all(&[0u8; 4])?;
out.write_all(&(meta.n as u64).to_le_bytes())?; out.write_all(&(meta.n as u64).to_le_bytes())?;
out.write_all(&(n_cols as u64).to_le_bytes())?; out.write_all(&(n_cols as u64).to_le_bytes())?;
for &off in &offsets { out.write_all(&off.to_le_bytes())?; } for &off in &offsets {
out.write_all(&off.to_le_bytes())?;
}
for c in 0..n_cols { for c in 0..n_cols {
io::copy(&mut File::open(col_path(dir, c))?, &mut out)?; io::copy(&mut File::open(col_path(dir, c))?, &mut out)?;
} }
@@ -170,7 +185,9 @@ pub fn pack_bit_matrix(dir: &Path) -> io::Result<()> {
drop(out); drop(out);
fs::rename(&tmp_path, &packed_path)?; fs::rename(&tmp_path, &packed_path)?;
for c in 0..n_cols { fs::remove_file(col_path(dir, c))?; } for c in 0..n_cols {
fs::remove_file(col_path(dir, c))?;
}
fs::remove_file(dir.join("meta.json"))?; fs::remove_file(dir.join("meta.json"))?;
Ok(()) Ok(())
} }
+51 -15
View File
@@ -8,31 +8,51 @@ use rayon::prelude::*;
/// value at a slot — reused so the same `(0..n_cols).map(|c| get(c, /// value at a slot — reused so the same `(0..n_cols).map(|c| get(c,
/// slot))` loop isn't hand-written once per format, mirroring /// slot))` loop isn't hand-written once per format, mirroring
/// `views::nonzero_triples`'s reuse across the same backends. /// `views::nonzero_triples`'s reuse across the same backends.
pub(crate) fn row_generic<T: Copy>(slot: usize, n_cols: usize, get: impl Fn(usize, usize) -> T) -> Box<[T]> { pub(crate) fn row_generic<T: Copy>(
slot: usize,
n_cols: usize,
get: impl Fn(usize, usize) -> T,
) -> Box<[T]> {
(0..n_cols).map(|c| get(c, slot)).collect() (0..n_cols).map(|c| get(c, slot)).collect()
} }
/// Like [`row_generic`], filling a caller-provided buffer instead of allocating. /// Like [`row_generic`], filling a caller-provided buffer instead of allocating.
pub(crate) fn fill_row_generic<T: Copy>(slot: usize, buf: &mut [T], get: impl Fn(usize, usize) -> T) { pub(crate) fn fill_row_generic<T: Copy>(
for (c, out) in buf.iter_mut().enumerate() { *out = get(c, slot); } slot: usize,
buf: &mut [T],
get: impl Fn(usize, usize) -> T,
) {
for (c, out) in buf.iter_mut().enumerate() {
*out = get(c, slot);
}
} }
/// Shared per-column parallel reduction: `count_ones`/`sum`/`count_nonzero` /// Shared per-column parallel reduction: `count_ones`/`sum`/`count_nonzero`
/// all have this exact shape (`(0..n_cols).into_par_iter().map(f).collect()`) /// all have this exact shape (`(0..n_cols).into_par_iter().map(f).collect()`)
/// across every `Columnar`/`Packed` backend — written once here instead of /// across every `Columnar`/`Packed` backend — written once here instead of
/// once per format. /// once per format.
pub(crate) fn par_col_reduce<T: Send>(n_cols: usize, f: impl Fn(usize) -> T + Sync + Send) -> Array1<T> { pub(crate) fn par_col_reduce<T: Send>(
n_cols: usize,
f: impl Fn(usize) -> T + Sync + Send,
) -> Array1<T> {
Array1::from_vec((0..n_cols).into_par_iter().map(f).collect()) Array1::from_vec((0..n_cols).into_par_iter().map(f).collect())
} }
fn upper_pairs(n: usize) -> Vec<(usize, usize)> { fn upper_pairs(n: usize) -> Vec<(usize, usize)> {
(0..n).flat_map(|i| (i + 1..n).map(move |j| (i, j))).collect() (0..n)
.flat_map(|i| (i + 1..n).map(move |j| (i, j)))
.collect()
} }
fn fill_symmetric<T>(n: usize, vals: impl Iterator<Item = (usize, usize, T, T)>) -> Array2<T> fn fill_symmetric<T>(n: usize, vals: impl Iterator<Item = (usize, usize, T, T)>) -> Array2<T>
where T: Clone + Default { where
T: Clone + Default,
{
let mut m = Array2::from_elem((n, n), T::default()); let mut m = Array2::from_elem((n, n), T::default());
for (i, j, vij, vji) in vals { m[[i, j]] = vij; m[[j, i]] = vji; } for (i, j, vij, vji) in vals {
m[[i, j]] = vij;
m[[j, i]] = vji;
}
m m
} }
@@ -45,11 +65,17 @@ where T: Clone + Default {
/// see `pairwise2_matrix`), not zero. Distance finalisations that need a /// see `pairwise2_matrix`), not zero. Distance finalisations that need a
/// zero diagonal (self-distance) already overwrite it explicitly. /// zero diagonal (self-distance) already overwrite it explicitly.
pub(crate) fn pairwise_matrix<T>(n: usize, f: impl Fn(usize, usize) -> T + Sync) -> Array2<T> pub(crate) fn pairwise_matrix<T>(n: usize, f: impl Fn(usize, usize) -> T + Sync) -> Array2<T>
where T: Copy + Default + Send { where
T: Copy + Default + Send,
{
let results: Vec<(usize, usize, T)> = upper_pairs(n) let results: Vec<(usize, usize, T)> = upper_pairs(n)
.into_par_iter().map(|(i, j)| (i, j, f(i, j))).collect(); .into_par_iter()
.map(|(i, j)| (i, j, f(i, j)))
.collect();
let mut m = fill_symmetric(n, results.into_iter().map(|(i, j, v)| (i, j, v, v))); let mut m = fill_symmetric(n, results.into_iter().map(|(i, j, v)| (i, j, v, v)));
for i in 0..n { m[[i, i]] = f(i, i); } for i in 0..n {
m[[i, i]] = f(i, i);
}
m m
} }
@@ -57,17 +83,27 @@ where T: Copy + Default + Send {
/// symmetric matrices simultaneously (e.g. intersection + union for Jaccard). /// symmetric matrices simultaneously (e.g. intersection + union for Jaccard).
/// The diagonal is `f(i,i)` (e.g. a genome's kmer count intersected with /// The diagonal is `f(i,i)` (e.g. a genome's kmer count intersected with
/// itself), not `T::default()` — see `pairwise_matrix` for why that matters. /// itself), not `T::default()` — see `pairwise_matrix` for why that matters.
pub(crate) fn pairwise2_matrix<T>(n: usize, f: impl Fn(usize, usize) -> (T, T) + Sync) -> (Array2<T>, Array2<T>) pub(crate) fn pairwise2_matrix<T>(
where T: Copy + Default + Send { n: usize,
f: impl Fn(usize, usize) -> (T, T) + Sync,
) -> (Array2<T>, Array2<T>)
where
T: Copy + Default + Send,
{
let results: Vec<(usize, usize, T, T)> = upper_pairs(n) let results: Vec<(usize, usize, T, T)> = upper_pairs(n)
.into_par_iter() .into_par_iter()
.map(|(i, j)| { let (a, b) = f(i, j); (i, j, a, b) }) .map(|(i, j)| {
let (a, b) = f(i, j);
(i, j, a, b)
})
.collect(); .collect();
let mut m0 = Array2::from_elem((n, n), T::default()); let mut m0 = Array2::from_elem((n, n), T::default());
let mut m1 = Array2::from_elem((n, n), T::default()); let mut m1 = Array2::from_elem((n, n), T::default());
for (i, j, a, b) in results { for (i, j, a, b) in results {
m0[[i, j]] = a; m0[[j, i]] = a; m0[[i, j]] = a;
m1[[i, j]] = b; m1[[j, i]] = b; m0[[j, i]] = a;
m1[[i, j]] = b;
m1[[j, i]] = b;
} }
for i in 0..n { for i in 0..n {
let (a, b) = f(i, i); let (a, b) = f(i, i);
+67 -28
View File
@@ -8,7 +8,7 @@ use crate::layer_meta::LayerMeta;
use crate::meta::MatrixMeta; use crate::meta::MatrixMeta;
use crate::storage_kind::StorageKind; use crate::storage_kind::StorageKind;
use crate::traits::{BitPartials, ColumnWeights}; use crate::traits::{BitPartials, ColumnWeights};
use crate::views::{nonzero_triples, BitSliceView}; use crate::views::{BitSliceView, nonzero_triples};
use super::columnar::ColumnarBitMatrix; use super::columnar::ColumnarBitMatrix;
use super::packed::PackedBitMatrix; use super::packed::PackedBitMatrix;
@@ -42,7 +42,9 @@ impl PersistentBitMatrix {
let presence_dir = layer_dir.join("presence"); let presence_dir = layer_dir.join("presence");
if presence_dir.join("matrix.pbmx").exists() { if presence_dir.join("matrix.pbmx").exists() {
return Ok(Self::Packed(PackedBitMatrix::open(&presence_dir.join("matrix.pbmx"))?)); return Ok(Self::Packed(PackedBitMatrix::open(
&presence_dir.join("matrix.pbmx"),
)?));
} }
if MatrixMeta::load(&presence_dir).is_ok() { if MatrixMeta::load(&presence_dir).is_ok() {
@@ -50,18 +52,25 @@ impl PersistentBitMatrix {
} }
if presence_dir.join("sparse_meta.json").exists() { if presence_dir.join("sparse_meta.json").exists() {
return Ok(Self::Sparse(PersistentSparseBitMatrix::open(&presence_dir)?)); return Ok(Self::Sparse(PersistentSparseBitMatrix::open(
&presence_dir,
)?));
} }
// No presence matrix → Implicit; requires layer_meta.json // No presence matrix → Implicit; requires layer_meta.json
let meta = LayerMeta::load(layer_dir).map_err(|_| io::Error::new( let meta = LayerMeta::load(layer_dir).map_err(|_| {
io::Error::new(
io::ErrorKind::NotFound, io::ErrorKind::NotFound,
format!( format!(
"no presence matrix and no layer_meta.json in {} — run 'obikmer upgrade'", "no presence matrix and no layer_meta.json in {} — run 'obikmer upgrade'",
layer_dir.display() layer_dir.display()
), ),
))?; )
Ok(Self::Implicit { n_rows: meta.n, n_cols: 1 }) })?;
Ok(Self::Implicit {
n_rows: meta.n,
n_cols: 1,
})
} }
/// This already-open matrix's storage format — reads the discriminant /// This already-open matrix's storage format — reads the discriminant
@@ -96,7 +105,10 @@ impl PersistentBitMatrix {
} }
Err(io::Error::new( Err(io::Error::new(
io::ErrorKind::NotFound, io::ErrorKind::NotFound,
format!("cannot detect presence storage format in {}", layer_dir.display()), format!(
"cannot detect presence storage format in {}",
layer_dir.display()
),
)) ))
} }
@@ -134,7 +146,9 @@ impl PersistentBitMatrix {
Self::Columnar(m) => m.col(c).view(), Self::Columnar(m) => m.col(c).view(),
Self::Packed(m) => m.col_slice(c), Self::Packed(m) => m.col_slice(c),
Self::Sparse(_) => panic!("col_view() not available on Sparse PersistentBitMatrix"), Self::Sparse(_) => panic!("col_view() not available on Sparse PersistentBitMatrix"),
Self::Implicit { .. } => panic!("col_view() not available on Implicit PersistentBitMatrix"), Self::Implicit { .. } => {
panic!("col_view() not available on Implicit PersistentBitMatrix")
}
} }
} }
@@ -157,11 +171,11 @@ impl PersistentBitMatrix {
match self { match self {
Self::Columnar(m) => PersistentBitVecBuilder::build_from(m.col(c), path), Self::Columnar(m) => PersistentBitVecBuilder::build_from(m.col(c), path),
Self::Packed(m) => m.col_persist(c, path), Self::Packed(m) => m.col_persist(c, path),
Self::Sparse(_) => Err(io::Error::new(io::ErrorKind::Unsupported, Self::Sparse(_) => Err(io::Error::new(
"col_persist not available on Sparse PersistentBitMatrix")), io::ErrorKind::Unsupported,
Self::Implicit { n_rows, .. } => { "col_persist not available on Sparse PersistentBitMatrix",
PersistentBitVecBuilder::new_ones(*n_rows, path) )),
} Self::Implicit { n_rows, .. } => PersistentBitVecBuilder::new_ones(*n_rows, path),
} }
} }
@@ -244,15 +258,21 @@ impl PersistentBitMatrix {
/// constraint against it; the allocation is one `Box` per call, not /// constraint against it; the allocation is one `Box` per call, not
/// per cell — negligible next to what it replaces (a fresh `Vec` /// per cell — negligible next to what it replaces (a fresh `Vec`
/// allocated per single-cell `get` in the old `Sparse` path). /// allocated per single-cell `get` in the old `Sparse` path).
pub fn nonzero_iter<'a>(&'a self, slots: &'a [usize]) -> Box<dyn Iterator<Item = (usize, usize, u32)> + 'a> { pub fn nonzero_iter<'a>(
&'a self,
slots: &'a [usize],
) -> Box<dyn Iterator<Item = (usize, usize, u32)> + 'a> {
match self { match self {
Self::Sparse(m) => Box::new(m.nonzero_iter(slots)), Self::Sparse(m) => Box::new(m.nonzero_iter(slots)),
Self::Implicit { .. } => { Self::Implicit { .. } => {
Box::new(slots.iter().enumerate().map(|(i, _)| (i, 0usize, 1u32))) Box::new(slots.iter().enumerate().map(|(i, _)| (i, 0usize, 1u32)))
} }
Self::Columnar(_) | Self::Packed(_) => { Self::Columnar(_) | Self::Packed(_) => Box::new(nonzero_triples(
Box::new(nonzero_triples(slots, self.n_cols(), |c| self.col_view(c), false)) slots,
} self.n_cols(),
|c| self.col_view(c),
false,
)),
} }
} }
@@ -276,9 +296,12 @@ impl PersistentBitMatrix {
let n = *n_cols; let n = *n_cols;
let mut inter = Array2::zeros((n, n)); let mut inter = Array2::zeros((n, n));
let mut union = Array2::zeros((n, n)); let mut union = Array2::zeros((n, n));
for i in 0..n { for j in 0..n { for i in 0..n {
inter[[i, j]] = v; union[[i, j]] = v; for j in 0..n {
}} inter[[i, j]] = v;
union[[i, j]] = v;
}
}
(inter, union) (inter, union)
} }
} }
@@ -303,11 +326,15 @@ impl PersistentBitMatrix {
impl ColumnWeights for PersistentBitMatrix { impl ColumnWeights for PersistentBitMatrix {
#[inline] #[inline]
fn col_weights(&self) -> Array1<u64> { self.count_ones() } fn col_weights(&self) -> Array1<u64> {
self.count_ones()
}
/// A presence matrix holds no counts: a set bit is present whatever /// A presence matrix holds no counts: a set bit is present whatever
/// `threshold` is. /// `threshold` is.
#[inline] #[inline]
fn count_geq(&self, _threshold: u32) -> Array1<u64> { self.count_ones() } fn count_geq(&self, _threshold: u32) -> Array1<u64> {
self.count_ones()
}
} }
impl BitPartials for PersistentBitMatrix { impl BitPartials for PersistentBitMatrix {
@@ -323,15 +350,27 @@ impl BitPartials for PersistentBitMatrix {
impl crate::traits::BinaryMatrix for PersistentBitMatrix { impl crate::traits::BinaryMatrix for PersistentBitMatrix {
#[inline] #[inline]
fn n(&self) -> usize { self.n() } fn n(&self) -> usize {
self.n()
}
#[inline] #[inline]
fn n_cols(&self) -> usize { self.n_cols() } fn n_cols(&self) -> usize {
self.n_cols()
}
#[inline] #[inline]
fn row(&self, slot: usize) -> Box<[bool]> { self.row(slot) } fn row(&self, slot: usize) -> Box<[bool]> {
self.row(slot)
}
#[inline] #[inline]
fn fill_row(&self, slot: usize, buf: &mut [u32]) { self.fill_row(slot, buf) } fn fill_row(&self, slot: usize, buf: &mut [u32]) {
self.fill_row(slot, buf)
}
#[inline] #[inline]
fn fill_sub_matrix(&self, slots: &[usize], out: &mut [Vec<bool>]) { self.fill_sub_matrix(slots, out) } fn fill_sub_matrix(&self, slots: &[usize], out: &mut [Vec<bool>]) {
self.fill_sub_matrix(slots, out)
}
#[inline] #[inline]
fn count_ones(&self) -> Array1<u64> { self.count_ones() } fn count_ones(&self) -> Array1<u64> {
self.count_ones()
}
} }
+84 -25
View File
@@ -28,22 +28,36 @@ use std::path::{Path, PathBuf};
use memmap2::Mmap; use memmap2::Mmap;
use ndarray::{Array1, Array2}; use ndarray::{Array1, Array2};
use crate::traits::{BitPartials, ColumnWeights};
use crate::eliasfano::{EliasFano, EliasFanoBuilder}; use crate::eliasfano::{EliasFano, EliasFanoBuilder};
use crate::fixedintvec::{PersistentFixedIntVec, PersistentFixedIntVecBuilder, bit_width_for_range}; use crate::fixedintvec::{
PersistentFixedIntVec, PersistentFixedIntVecBuilder, bit_width_for_range,
};
use crate::meta::{MatrixMeta, field}; use crate::meta::{MatrixMeta, field};
use crate::rankselect::{PersistentRankSelectBitVec, PersistentRankSelectBitVecBuilder}; use crate::rankselect::{PersistentRankSelectBitVec, PersistentRankSelectBitVecBuilder};
use crate::traits::{BitPartials, ColumnWeights};
use super::PersistentBitMatrix; use super::PersistentBitMatrix;
use super::col_path; use super::col_path;
use super::packed::{PackedBitMatrix, pack_bit_matrix, packed_bit_matrix_n_cols}; use super::packed::{PackedBitMatrix, pack_bit_matrix, packed_bit_matrix_n_cols};
fn is_multi_path(dir: &Path) -> PathBuf { dir.join("is_multi.prsb") } fn is_multi_path(dir: &Path) -> PathBuf {
fn singleton_path(dir: &Path) -> PathBuf { dir.join("singleton.pfiv") } dir.join("is_multi.prsb")
fn multi_path(dir: &Path) -> PathBuf { dir.join("multi.pfiv") } }
fn dict_offsets_base(dir: &Path) -> PathBuf { dir.join("dict_offsets") } fn singleton_path(dir: &Path) -> PathBuf {
fn dict_values_path(dir: &Path) -> PathBuf { dir.join("dict_values.bin") } dir.join("singleton.pfiv")
fn meta_path(dir: &Path) -> PathBuf { dir.join("sparse_meta.json") } }
fn multi_path(dir: &Path) -> PathBuf {
dir.join("multi.pfiv")
}
fn dict_offsets_base(dir: &Path) -> PathBuf {
dir.join("dict_offsets")
}
fn dict_values_path(dir: &Path) -> PathBuf {
dir.join("dict_values.bin")
}
fn meta_path(dir: &Path) -> PathBuf {
dir.join("sparse_meta.json")
}
struct SparseMeta { struct SparseMeta {
n: usize, n: usize,
@@ -57,7 +71,12 @@ impl SparseMeta {
fn load(dir: &Path) -> io::Result<Self> { fn load(dir: &Path) -> io::Result<Self> {
let s = fs::read_to_string(meta_path(dir))?; let s = fs::read_to_string(meta_path(dir))?;
let get = |name: &str| { let get = |name: &str| {
field(&s, name).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("bad sparse_meta.json: missing {name}"))) field(&s, name).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("bad sparse_meta.json: missing {name}"),
)
})
}; };
Ok(Self { Ok(Self {
n: get("n")?, n: get("n")?,
@@ -175,15 +194,25 @@ impl PersistentSparseBitMatrix {
Some(unsafe { Mmap::map(&dict_file)? }) Some(unsafe { Mmap::map(&dict_file)? })
}; };
Ok(Self { Ok(Self {
is_multi, singleton, multi, dict_offsets, dict_values, is_multi,
n: meta.n, n_cols: meta.n_cols, n_distinct_multi: meta.n_distinct_multi, singleton,
multi,
dict_offsets,
dict_values,
n: meta.n,
n_cols: meta.n_cols,
n_distinct_multi: meta.n_distinct_multi,
}) })
} }
#[inline] #[inline]
pub fn n(&self) -> usize { self.n } pub fn n(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn n_cols(&self) -> usize { self.n_cols } pub fn n_cols(&self) -> usize {
self.n_cols
}
#[inline] #[inline]
fn dict_bytes(&self) -> &[u8] { fn dict_bytes(&self) -> &[u8] {
@@ -342,13 +371,17 @@ impl PersistentSparseBitMatrix {
/// `n_cols`-wide buffer, ever. See /// `n_cols`-wide buffer, ever. See
/// `DevDocMD/architecture/siblings.md`, "`query` never benefits from /// `DevDocMD/architecture/siblings.md`, "`query` never benefits from
/// sparse row-major access". /// sparse row-major access".
pub fn nonzero_iter<'a>(&'a self, slots: &'a [usize]) -> impl Iterator<Item = (usize, usize, u32)> + 'a { pub fn nonzero_iter<'a>(
&'a self,
slots: &'a [usize],
) -> impl Iterator<Item = (usize, usize, u32)> + 'a {
let mut next_slot = 0usize; let mut next_slot = 0usize;
let mut cur_idx = 0usize; let mut cur_idx = 0usize;
let mut buf: Vec<usize> = Vec::new(); let mut buf: Vec<usize> = Vec::new();
let mut buf_pos = 0usize; let mut buf_pos = 0usize;
std::iter::from_fn(move || loop { std::iter::from_fn(move || {
loop {
if buf_pos < buf.len() { if buf_pos < buf.len() {
let g = buf[buf_pos]; let g = buf[buf_pos];
buf_pos += 1; buf_pos += 1;
@@ -363,23 +396,36 @@ impl PersistentSparseBitMatrix {
buf.clear(); buf.clear();
self.for_each_genome_in_row(slot, |g| buf.push(g)); self.for_each_genome_in_row(slot, |g| buf.push(g));
buf_pos = 0; buf_pos = 0;
}
}) })
} }
} }
impl crate::traits::BinaryMatrix for PersistentSparseBitMatrix { impl crate::traits::BinaryMatrix for PersistentSparseBitMatrix {
#[inline] #[inline]
fn n(&self) -> usize { self.n() } fn n(&self) -> usize {
self.n()
}
#[inline] #[inline]
fn n_cols(&self) -> usize { self.n_cols() } fn n_cols(&self) -> usize {
self.n_cols()
}
#[inline] #[inline]
fn row(&self, slot: usize) -> Box<[bool]> { self.row(slot) } fn row(&self, slot: usize) -> Box<[bool]> {
self.row(slot)
}
#[inline] #[inline]
fn fill_row(&self, slot: usize, buf: &mut [u32]) { self.fill_row(slot, buf) } fn fill_row(&self, slot: usize, buf: &mut [u32]) {
self.fill_row(slot, buf)
}
#[inline] #[inline]
fn fill_sub_matrix(&self, slots: &[usize], out: &mut [Vec<bool>]) { self.fill_sub_matrix(slots, out) } fn fill_sub_matrix(&self, slots: &[usize], out: &mut [Vec<bool>]) {
self.fill_sub_matrix(slots, out)
}
#[inline] #[inline]
fn count_ones(&self) -> Array1<u64> { self.count_ones() } fn count_ones(&self) -> Array1<u64> {
self.count_ones()
}
} }
// ── PersistentSparseBitMatrixBuilder ──────────────────────────────────────── // ── PersistentSparseBitMatrixBuilder ────────────────────────────────────────
@@ -455,14 +501,19 @@ impl PersistentSparseBitMatrixBuilder {
is_multi_b.close()?; is_multi_b.close()?;
let singleton_width = bit_width_for_range(self.n_cols as u64); 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))?; let mut singleton_b = PersistentFixedIntVecBuilder::new(
n_singleton,
singleton_width,
&singleton_path(&self.dir),
)?;
for (i, &v) in self.singleton_values.iter().enumerate() { for (i, &v) in self.singleton_values.iter().enumerate() {
singleton_b.set(i, v as u64); singleton_b.set(i, v as u64);
} }
singleton_b.close()?; singleton_b.close()?;
let multi_width = bit_width_for_range(n_distinct_multi as u64); 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))?; let mut multi_b =
PersistentFixedIntVecBuilder::new(n_multi, multi_width, &multi_path(&self.dir))?;
for (i, &v) in self.multi_dict_ids.iter().enumerate() { for (i, &v) in self.multi_dict_ids.iter().enumerate() {
multi_b.set(i, v as u64); multi_b.set(i, v as u64);
} }
@@ -477,14 +528,22 @@ impl PersistentSparseBitMatrixBuilder {
} }
} }
let universe = dict_values.len() as u64 + 1; let universe = dict_values.len() as u64 + 1;
let mut offsets_b = EliasFanoBuilder::new(offsets.len(), universe, &dict_offsets_base(&self.dir))?; let mut offsets_b =
EliasFanoBuilder::new(offsets.len(), universe, &dict_offsets_base(&self.dir))?;
for &o in &offsets { for &o in &offsets {
offsets_b.push(o); offsets_b.push(o);
} }
offsets_b.close()?; offsets_b.close()?;
fs::write(dict_values_path(&self.dir), &dict_values)?; 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)?; SparseMeta {
n,
n_cols: self.n_cols,
n_singleton,
n_multi,
n_distinct_multi,
}
.save(&self.dir)?;
Ok(()) Ok(())
} }
@@ -46,7 +46,11 @@ fn read_bit_window(
bytes.resize(nw * 8, 0); bytes.resize(nw * 8, 0);
file.read_exact_at(bytes, (PBIV_HEADER + start / 8) as u64)?; file.read_exact_at(bytes, (PBIV_HEADER + start / 8) as u64)?;
words.clear(); words.clear();
words.extend(bytes.chunks_exact(8).map(|b| u64::from_le_bytes(b.try_into().unwrap()))); words.extend(
bytes
.chunks_exact(8)
.map(|b| u64::from_le_bytes(b.try_into().unwrap())),
);
Ok(()) Ok(())
} }
@@ -77,7 +81,14 @@ impl PersistentSparseBitMatrixBuilder {
max_hits, max_hits,
(), (),
|c, start, end, hits: &mut Vec<Hit<()>>| { |c, start, end, hits: &mut Vec<Hit<()>>| {
read_bit_window(&col_path(dir, c), meta.n, start, end, &mut bytes, &mut words)?; read_bit_window(
&col_path(dir, c),
meta.n,
start,
end,
&mut bytes,
&mut words,
)?;
BitSliceView::new(&words, end - start).for_each_set_in(0..end - start, |r| { BitSliceView::new(&words, end - start).for_each_set_in(0..end - start, |r| {
hits.push((r as u32, c as u32, ())); hits.push((r as u32, c as u32, ()));
}); });
+4 -1
View File
@@ -230,7 +230,10 @@ impl PersistentBitVecBuilder {
pub fn build_from(source: &PersistentBitVec, path: &Path) -> io::Result<Self> { pub fn build_from(source: &PersistentBitVec, path: &Path) -> io::Result<Self> {
fs::copy(source.path(), building_path(path))?; fs::copy(source.path(), building_path(path))?;
let file = OpenOptions::new().read(true).write(true).open(building_path(path))?; let file = OpenOptions::new()
.read(true)
.write(true)
.open(building_path(path))?;
let mmap = unsafe { MmapMut::map_mut(&file)? }; let mmap = unsafe { MmapMut::map_mut(&file)? };
let n = source.len(); let n = source.len();
Ok(Self { Ok(Self {
+118 -30
View File
@@ -5,7 +5,9 @@ use std::path::{Path, PathBuf};
use memmap2::MmapMut; use memmap2::MmapMut;
use crate::format::{byte_count_nonzero, byte_sum, HEADER_SIZE, finalize_pciv, parse_overflow_entry}; use crate::format::{
HEADER_SIZE, byte_count_nonzero, byte_sum, finalize_pciv, parse_overflow_entry,
};
use crate::reader::PersistentCompactIntVec; use crate::reader::PersistentCompactIntVec;
use crate::views::{BitSliceView, IntSliceView}; use crate::views::{BitSliceView, IntSliceView};
@@ -19,22 +21,42 @@ pub struct PersistentCompactIntVecBuilder {
impl PersistentCompactIntVecBuilder { impl PersistentCompactIntVecBuilder {
pub fn new(n: usize, path: &Path) -> io::Result<Self> { pub fn new(n: usize, path: &Path) -> io::Result<Self> {
let file = OpenOptions::new() let file = OpenOptions::new()
.read(true).write(true).create(true).truncate(true) .read(true)
.write(true)
.create(true)
.truncate(true)
.open(path)?; .open(path)?;
file.set_len((HEADER_SIZE + n) as u64)?; file.set_len((HEADER_SIZE + n) as u64)?;
let mmap = unsafe { MmapMut::map_mut(&file)? }; let mmap = unsafe { MmapMut::map_mut(&file)? };
Ok(Self { path: path.to_path_buf(), mmap, n, overflow: HashMap::new() }) Ok(Self {
path: path.to_path_buf(),
mmap,
n,
overflow: HashMap::new(),
})
} }
pub fn from_raw_primary(primary: &[u8], overflow: HashMap<usize, u32>, path: &Path) -> io::Result<Self> { pub fn from_raw_primary(
primary: &[u8],
overflow: HashMap<usize, u32>,
path: &Path,
) -> io::Result<Self> {
let n = primary.len(); let n = primary.len();
let file = OpenOptions::new() let file = OpenOptions::new()
.read(true).write(true).create(true).truncate(true) .read(true)
.write(true)
.create(true)
.truncate(true)
.open(path)?; .open(path)?;
file.set_len((HEADER_SIZE + n) as u64)?; file.set_len((HEADER_SIZE + n) as u64)?;
let mut mmap = unsafe { MmapMut::map_mut(&file)? }; let mut mmap = unsafe { MmapMut::map_mut(&file)? };
mmap[HEADER_SIZE..HEADER_SIZE + n].copy_from_slice(primary); mmap[HEADER_SIZE..HEADER_SIZE + n].copy_from_slice(primary);
Ok(Self { path: path.to_path_buf(), mmap, n, overflow }) Ok(Self {
path: path.to_path_buf(),
mmap,
n,
overflow,
})
} }
pub fn build_from(source: &PersistentCompactIntVec, path: &Path) -> io::Result<Self> { pub fn build_from(source: &PersistentCompactIntVec, path: &Path) -> io::Result<Self> {
@@ -49,13 +71,21 @@ impl PersistentCompactIntVecBuilder {
let (slot, value) = parse_overflow_entry(&mmap, data_offset, i); let (slot, value) = parse_overflow_entry(&mmap, data_offset, i);
overflow.insert(slot, value); overflow.insert(slot, value);
} }
Ok(Self { path: path.to_path_buf(), mmap, n, overflow }) Ok(Self {
path: path.to_path_buf(),
mmap,
n,
overflow,
})
} }
#[inline] #[inline]
pub fn get(&self, slot: usize) -> u32 { pub fn get(&self, slot: usize) -> u32 {
match self.mmap[HEADER_SIZE + slot] { match self.mmap[HEADER_SIZE + slot] {
255 => *self.overflow.get(&slot).expect("sentinel without overflow entry"), 255 => *self
.overflow
.get(&slot)
.expect("sentinel without overflow entry"),
v => v as u32, v => v as u32,
} }
} }
@@ -72,20 +102,33 @@ impl PersistentCompactIntVecBuilder {
} }
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
#[inline] #[inline]
pub fn primary_bytes(&self) -> &[u8] { &self.mmap[HEADER_SIZE..HEADER_SIZE + self.n] } pub fn primary_bytes(&self) -> &[u8] {
&self.mmap[HEADER_SIZE..HEADER_SIZE + self.n]
}
#[inline] #[inline]
pub fn primary_bytes_mut(&mut self) -> &mut [u8] { &mut self.mmap[HEADER_SIZE..HEADER_SIZE + self.n] } pub fn primary_bytes_mut(&mut self) -> &mut [u8] {
&mut self.mmap[HEADER_SIZE..HEADER_SIZE + self.n]
}
#[inline] #[inline]
pub fn clear_overflow(&mut self) { self.overflow.clear(); } pub fn clear_overflow(&mut self) {
self.overflow.clear();
}
#[inline] #[inline]
pub fn sum(&self) -> u64 { pub fn sum(&self) -> u64 {
byte_sum(&self.mmap[HEADER_SIZE..HEADER_SIZE + self.n], self.overflow.values().copied()) byte_sum(
&self.mmap[HEADER_SIZE..HEADER_SIZE + self.n],
self.overflow.values().copied(),
)
} }
#[inline] #[inline]
pub fn count_nonzero(&self) -> u64 { pub fn count_nonzero(&self) -> u64 {
@@ -121,12 +164,16 @@ impl PersistentCompactIntVecBuilder {
pub fn inc_present(&mut self, col: BitSliceView<'_>) { pub fn inc_present(&mut self, col: BitSliceView<'_>) {
let n = self.n; let n = self.n;
for (wi, &word) in col.words().iter().enumerate() { for (wi, &word) in col.words().iter().enumerate() {
if word == 0 { continue; } if word == 0 {
continue;
}
let mut w = word; let mut w = word;
while w != 0 { while w != 0 {
let bit = w.trailing_zeros() as usize; let bit = w.trailing_zeros() as usize;
let slot = wi * 64 + bit; let slot = wi * 64 + bit;
if slot < n { self.inc(slot); } if slot < n {
self.inc(slot);
}
w &= w - 1; w &= w - 1;
} }
} }
@@ -139,12 +186,16 @@ impl PersistentCompactIntVecBuilder {
let primary = self.primary_bytes_mut(); let primary = self.primary_bytes_mut();
let n = primary.len(); let n = primary.len();
for (wi, &word) in col.words().iter().enumerate() { for (wi, &word) in col.words().iter().enumerate() {
if word == 0 { continue; } if word == 0 {
continue;
}
let mut w = word; let mut w = word;
while w != 0 { while w != 0 {
let bit = w.trailing_zeros() as usize; let bit = w.trailing_zeros() as usize;
let s = wi * 64 + bit; let s = wi * 64 + bit;
if s < n { primary[s] += 1; } if s < n {
primary[s] += 1;
}
w &= w - 1; w &= w - 1;
} }
} }
@@ -166,7 +217,9 @@ impl PersistentCompactIntVecBuilder {
} }
} }
for (slot, val) in col.overflow_entries() { for (slot, val) in col.overflow_entries() {
if pred(val) { self.inc(slot); } if pred(val) {
self.inc(slot);
}
} }
} }
@@ -183,7 +236,9 @@ impl PersistentCompactIntVecBuilder {
} }
} }
for (slot, val) in col.overflow_entries() { for (slot, val) in col.overflow_entries() {
if pred(val) { self.primary_bytes_mut()[slot] += 1; } if pred(val) {
self.primary_bytes_mut()[slot] += 1;
}
} }
debug_assert!( debug_assert!(
!self.primary_bytes().contains(&255), !self.primary_bytes().contains(&255),
@@ -200,7 +255,12 @@ impl PersistentCompactIntVecBuilder {
// through this loop). // through this loop).
let mut newly_overflow: Vec<(usize, u32)> = Vec::new(); let mut newly_overflow: Vec<(usize, u32)> = Vec::new();
let mut already_overflow: Vec<usize> = Vec::new(); let mut already_overflow: Vec<usize> = Vec::new();
for (s, (a, &b)) in self.primary_bytes_mut().iter_mut().zip(other.primary_bytes()).enumerate() { for (s, (a, &b)) in self
.primary_bytes_mut()
.iter_mut()
.zip(other.primary_bytes())
.enumerate()
{
if *a < 255 && b < 255 { if *a < 255 && b < 255 {
let sum = *a as u32 + b as u32; let sum = *a as u32 + b as u32;
if sum < 255 { if sum < 255 {
@@ -213,7 +273,9 @@ impl PersistentCompactIntVecBuilder {
already_overflow.push(s); already_overflow.push(s);
} }
} }
for (s, sum) in newly_overflow { self.overflow.insert(s, sum); } for (s, sum) in newly_overflow {
self.overflow.insert(s, sum);
}
for s in already_overflow { for s in already_overflow {
let sv = self.get(s); let sv = self.get(s);
let ov = other.get(s); let ov = other.get(s);
@@ -225,8 +287,14 @@ impl PersistentCompactIntVecBuilder {
let self_ov: Vec<(usize, u32)> = self.overflow_entries().collect(); let self_ov: Vec<(usize, u32)> = self.overflow_entries().collect();
let other_ov: HashMap<usize, u32> = other.overflow_entries().collect(); let other_ov: HashMap<usize, u32> = other.overflow_entries().collect();
self.clear_overflow(); self.clear_overflow();
for (a, &b) in self.primary_bytes_mut().iter_mut().zip(other.primary_bytes()) { for (a, &b) in self
if b < *a { *a = b; } .primary_bytes_mut()
.iter_mut()
.zip(other.primary_bytes())
{
if b < *a {
*a = b;
}
} }
for (slot, self_val) in self_ov { for (slot, self_val) in self_ov {
if let Some(&other_val) = other_ov.get(&slot) { if let Some(&other_val) = other_ov.get(&slot) {
@@ -240,8 +308,14 @@ impl PersistentCompactIntVecBuilder {
let sv = self.get(slot); let sv = self.get(slot);
self.set(slot, sv.max(other_val)); self.set(slot, sv.max(other_val));
} }
for (a, &b) in self.primary_bytes_mut().iter_mut().zip(other.primary_bytes()) { for (a, &b) in self
if b > *a { *a = b; } .primary_bytes_mut()
.iter_mut()
.zip(other.primary_bytes())
{
if b > *a {
*a = b;
}
} }
} }
@@ -253,7 +327,12 @@ impl PersistentCompactIntVecBuilder {
// saturates to 0 without needing `other.get`. Only `self`-overflow // saturates to 0 without needing `other.get`. Only `self`-overflow
// slots need the overflow map, settled after the loop. // slots need the overflow map, settled after the loop.
let mut needs_full: Vec<usize> = Vec::new(); let mut needs_full: Vec<usize> = Vec::new();
for (s, (a, &b)) in self.primary_bytes_mut().iter_mut().zip(other.primary_bytes()).enumerate() { for (s, (a, &b)) in self
.primary_bytes_mut()
.iter_mut()
.zip(other.primary_bytes())
.enumerate()
{
if *a < 255 { if *a < 255 {
*a = if b < 255 { a.saturating_sub(b) } else { 0 }; *a = if b < 255 { a.saturating_sub(b) } else { 0 };
} else { } else {
@@ -271,14 +350,18 @@ impl PersistentCompactIntVecBuilder {
pub fn mask_with(&mut self, mask: BitSliceView<'_>) { pub fn mask_with(&mut self, mask: BitSliceView<'_>) {
let n = self.n; let n = self.n;
for (wi, &word) in mask.words().iter().enumerate() { for (wi, &word) in mask.words().iter().enumerate() {
if word == u64::MAX { continue; } if word == u64::MAX {
continue;
}
let mut zeros = !word; let mut zeros = !word;
while zeros != 0 { while zeros != 0 {
let bit = zeros.trailing_zeros() as usize; let bit = zeros.trailing_zeros() as usize;
let s = wi * 64 + bit; let s = wi * 64 + bit;
if s < n { if s < n {
let b = self.primary_bytes()[s]; let b = self.primary_bytes()[s];
if b != 0 { self.set(s, 0); } if b != 0 {
self.set(s, 0);
}
} }
zeros &= zeros - 1; zeros &= zeros - 1;
} }
@@ -287,7 +370,12 @@ impl PersistentCompactIntVecBuilder {
pub fn close(self) -> io::Result<()> { pub fn close(self) -> io::Result<()> {
self.mmap.flush()?; self.mmap.flush()?;
let Self { path, mmap, n, overflow } = self; let Self {
path,
mmap,
n,
overflow,
} = self;
drop(mmap); drop(mmap);
let mut entries: Vec<(usize, u32)> = overflow.into_iter().collect(); let mut entries: Vec<(usize, u32)> = overflow.into_iter().collect();
entries.sort_unstable_by_key(|&(slot, _)| slot); entries.sort_unstable_by_key(|&(slot, _)| slot);
+40 -9
View File
@@ -17,7 +17,10 @@ pub struct ColGroup {
impl ColGroup { impl ColGroup {
pub fn new(name: impl Into<String>, indices: Vec<usize>) -> Self { pub fn new(name: impl Into<String>, indices: Vec<usize>) -> Self {
Self { name: name.into(), indices } Self {
name: name.into(),
indices,
}
} }
} }
@@ -34,13 +37,17 @@ pub(crate) fn chunked_presence_count(
) -> io::Result<TempCompactIntVec> { ) -> io::Result<TempCompactIntVec> {
if indices.len() < 255 { if indices.len() < 255 {
let mut builder = TempCompactIntVecBuilder::new(n)?; let mut builder = TempCompactIntVecBuilder::new(n)?;
for &c in indices { inc(&mut builder, c); } for &c in indices {
inc(&mut builder, c);
}
builder.freeze() builder.freeze()
} else { } else {
let mut result = TempCompactIntVecBuilder::new(n)?; let mut result = TempCompactIntVecBuilder::new(n)?;
for chunk in indices.chunks(254) { for chunk in indices.chunks(254) {
let mut chunk_b = TempCompactIntVecBuilder::new(n)?; let mut chunk_b = TempCompactIntVecBuilder::new(n)?;
for &c in chunk { inc(&mut chunk_b, c); } for &c in chunk {
inc(&mut chunk_b, c);
}
let frozen = chunk_b.freeze()?; let frozen = chunk_b.freeze()?;
result.add(frozen.view()); result.add(frozen.view());
} }
@@ -60,7 +67,11 @@ pub(crate) fn chunked_presence_count(
/// derived from `partial_group_presence_count` and should rarely need overriding. /// derived from `partial_group_presence_count` and should rarely need overriding.
pub trait MatrixGroupOps { pub trait MatrixGroupOps {
/// Per-slot count of group columns whose value ≥ `threshold`. /// Per-slot count of group columns whose value ≥ `threshold`.
fn partial_group_presence_count(&self, g: &ColGroup, threshold: u32) -> io::Result<TempCompactIntVec>; fn partial_group_presence_count(
&self,
g: &ColGroup,
threshold: u32,
) -> io::Result<TempCompactIntVec>;
/// Per-slot sum of values across all group columns. /// Per-slot sum of values across all group columns.
fn partial_group_sum(&self, g: &ColGroup) -> io::Result<TempCompactIntVec>; fn partial_group_sum(&self, g: &ColGroup) -> io::Result<TempCompactIntVec>;
@@ -105,9 +116,17 @@ pub trait MatrixGroupOps {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum FilterMask { pub enum FilterMask {
/// Slot passes if count of columns in `indices` with value ≥ `threshold` is ≥ `min_count`. /// Slot passes if count of columns in `indices` with value ≥ `threshold` is ≥ `min_count`.
PresenceGeq { indices: Vec<usize>, threshold: u32, min_count: usize }, PresenceGeq {
indices: Vec<usize>,
threshold: u32,
min_count: usize,
},
/// Slot passes if count of columns in `indices` with value ≥ `threshold` is ≤ `max_count`. /// Slot passes if count of columns in `indices` with value ≥ `threshold` is ≤ `max_count`.
PresenceLeq { indices: Vec<usize>, threshold: u32, max_count: usize }, PresenceLeq {
indices: Vec<usize>,
threshold: u32,
max_count: usize,
},
/// Slot passes if sum of values across `indices` columns is ≥ `min_sum`. /// Slot passes if sum of values across `indices` columns is ≥ `min_sum`.
SumGeq { indices: Vec<usize>, min_sum: u32 }, SumGeq { indices: Vec<usize>, min_sum: u32 },
/// Slot passes if sum of values across `indices` columns is ≤ `max_sum`. /// Slot passes if sum of values across `indices` columns is ≤ `max_sum`.
@@ -118,9 +137,17 @@ pub enum FilterMask {
/// Evaluate a [`FilterMask`] against `mat`, returning a per-slot `TempBitVec` /// Evaluate a [`FilterMask`] against `mat`, returning a per-slot `TempBitVec`
/// where bit=1 means the slot passes the filter. /// where bit=1 means the slot passes the filter.
pub fn eval_filter_mask(expr: &FilterMask, mat: &dyn MatrixGroupOps, n: usize) -> io::Result<TempBitVec> { pub fn eval_filter_mask(
expr: &FilterMask,
mat: &dyn MatrixGroupOps,
n: usize,
) -> io::Result<TempBitVec> {
match expr { match expr {
FilterMask::PresenceGeq { indices, threshold, min_count } => { FilterMask::PresenceGeq {
indices,
threshold,
min_count,
} => {
let g = ColGroup::new("", indices.clone()); let g = ColGroup::new("", indices.clone());
let counts = mat.partial_group_presence_count(&g, *threshold)?; let counts = mat.partial_group_presence_count(&g, *threshold)?;
let mut b = TempBitVecBuilder::new(n)?; let mut b = TempBitVecBuilder::new(n)?;
@@ -128,7 +155,11 @@ pub fn eval_filter_mask(expr: &FilterMask, mat: &dyn MatrixGroupOps, n: usize) -
b.or_where(counts.view(), |v| v >= mc); b.or_where(counts.view(), |v| v >= mc);
b.freeze() b.freeze()
} }
FilterMask::PresenceLeq { indices, threshold, max_count } => { FilterMask::PresenceLeq {
indices,
threshold,
max_count,
} => {
let g = ColGroup::new("", indices.clone()); let g = ColGroup::new("", indices.clone());
let counts = mat.partial_group_presence_count(&g, *threshold)?; let counts = mat.partial_group_presence_count(&g, *threshold)?;
let mut b = TempBitVecBuilder::new(n)?; let mut b = TempBitVecBuilder::new(n)?;
+37 -8
View File
@@ -61,13 +61,22 @@ impl EliasFano {
let high = PersistentRankSelectBitVec::open(&high_path(base))?; let high = PersistentRankSelectBitVec::open(&high_path(base))?;
let n = low.len(); let n = low.len();
let low_width = low.width(); let low_width = low.width();
Ok(Self { low, high, n, low_width }) Ok(Self {
low,
high,
n,
low_width,
})
} }
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
/// The `i`-th value of the encoded sequence. /// The `i`-th value of the encoded sequence.
pub fn get(&self, i: usize) -> u64 { pub fn get(&self, i: usize) -> u64 {
@@ -167,19 +176,35 @@ impl EliasFanoBuilder {
// truth on reopen, no separate bookkeeping of `low_width` needed. // truth on reopen, no separate bookkeeping of `low_width` needed.
let low = PersistentFixedIntVecBuilder::new(n, low_width, &low_path(base))?; let low = PersistentFixedIntVecBuilder::new(n, low_width, &low_path(base))?;
let high = PersistentRankSelectBitVecBuilder::new(high_len, &high_path(base))?; let high = PersistentRankSelectBitVecBuilder::new(high_len, &high_path(base))?;
Ok(Self { low, high, low_width, n, next: 0, last_value: 0 }) Ok(Self {
low,
high,
low_width,
n,
next: 0,
last_value: 0,
})
} }
/// Appends the next value — must be `>= ` every previously pushed /// Appends the next value — must be `>= ` every previously pushed
/// value (monotone non-decreasing), and `< universe` as given to /// value (monotone non-decreasing), and `< universe` as given to
/// [`new`](Self::new). /// [`new`](Self::new).
pub fn push(&mut self, value: u64) { pub fn push(&mut self, value: u64) {
assert!(self.next < self.n, "push() called more than n={} times", self.n); assert!(
self.next < self.n,
"push() called more than n={} times",
self.n
);
assert!( assert!(
self.next == 0 || value >= self.last_value, self.next == 0 || value >= self.last_value,
"push({value}) breaks monotonicity: last value was {}", self.last_value "push({value}) breaks monotonicity: last value was {}",
self.last_value
); );
let low_mask = if self.low_width >= 64 { u64::MAX } else { (1u64 << self.low_width) - 1 }; let low_mask = if self.low_width >= 64 {
u64::MAX
} else {
(1u64 << self.low_width) - 1
};
self.low.set(self.next, value & low_mask); self.low.set(self.next, value & low_mask);
let high_part = value >> self.low_width; let high_part = value >> self.low_width;
self.high.set(high_part as usize + self.next, true); self.high.set(high_part as usize + self.next, true);
@@ -188,7 +213,11 @@ impl EliasFanoBuilder {
} }
pub fn close(self) -> io::Result<()> { pub fn close(self) -> io::Result<()> {
assert_eq!(self.next, self.n, "push() called {} times, expected n={}", self.next, self.n); assert_eq!(
self.next, self.n,
"push() called {} times, expected n={}",
self.next, self.n
);
self.low.close()?; self.low.close()?;
self.high.close() self.high.close()
} }
+42 -11
View File
@@ -45,7 +45,11 @@ fn n_words_for(n: usize, width: u32) -> usize {
#[inline] #[inline]
fn mask(width: u32) -> u64 { fn mask(width: u32) -> u64 {
if width >= 64 { u64::MAX } else { (1u64 << width) - 1 } if width >= 64 {
u64::MAX
} else {
(1u64 << width) - 1
}
} }
// ── PersistentFixedIntVec ─────────────────────────────────────────────────── // ── PersistentFixedIntVec ───────────────────────────────────────────────────
@@ -61,17 +65,30 @@ impl PersistentFixedIntVec {
pub fn open(path: &Path) -> io::Result<Self> { pub fn open(path: &Path) -> io::Result<Self> {
let (mmap, n) = open_mmap_file(path, MAGIC, HEADER_SIZE)?; let (mmap, n) = open_mmap_file(path, MAGIC, HEADER_SIZE)?;
let width = mmap[4] as u32; let width = mmap[4] as u32;
Ok(Self { mmap, n, width, path: path.to_path_buf() }) Ok(Self {
mmap,
n,
width,
path: path.to_path_buf(),
})
} }
#[inline] #[inline]
pub fn path(&self) -> &Path { &self.path } pub fn path(&self) -> &Path {
&self.path
}
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
#[inline] #[inline]
pub fn width(&self) -> u32 { self.width } pub fn width(&self) -> u32 {
self.width
}
// SAFETY: mmap is page-aligned, HEADER_SIZE=16 divisible by 8 → u64-aligned. // SAFETY: mmap is page-aligned, HEADER_SIZE=16 divisible by 8 → u64-aligned.
#[inline] #[inline]
@@ -106,7 +123,10 @@ fn get_packed(words: &[u64], slot: usize, width: u32) -> u64 {
#[inline] #[inline]
fn set_packed(words: &mut [u64], slot: usize, width: u32, value: u64) { fn set_packed(words: &mut [u64], slot: usize, width: u32, value: u64) {
let m = mask(width); let m = mask(width);
debug_assert!(value & !m == 0, "value {value} does not fit in {width} bits"); debug_assert!(
value & !m == 0,
"value {value} does not fit in {width} bits"
);
let bit_offset = slot as u64 * width as u64; let bit_offset = slot as u64 * width as u64;
let word_idx = (bit_offset / 64) as usize; let word_idx = (bit_offset / 64) as usize;
let bit_in_word = (bit_offset % 64) as u32; let bit_in_word = (bit_offset % 64) as u32;
@@ -140,15 +160,26 @@ impl PersistentFixedIntVecBuilder {
let file_size = HEADER_SIZE + n_words_for(n, width) * 8; let file_size = HEADER_SIZE + n_words_for(n, width) * 8;
let pad = [width as u8, 0, 0, 0]; let pad = [width as u8, 0, 0, 0];
let mmap = create_mmap_file(path, MAGIC, pad, n, 0, file_size)?; let mmap = create_mmap_file(path, MAGIC, pad, n, 0, file_size)?;
Ok(Self { mmap, n, width, path: path.to_path_buf() }) Ok(Self {
mmap,
n,
width,
path: path.to_path_buf(),
})
} }
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
#[inline] #[inline]
pub fn width(&self) -> u32 { self.width } pub fn width(&self) -> u32 {
self.width
}
#[inline] #[inline]
fn data_words_mut(&mut self) -> &mut [u64] { fn data_words_mut(&mut self) -> &mut [u64] {
+9 -5
View File
@@ -37,8 +37,8 @@ pub(crate) fn byte_count_nonzero(primary: &[u8]) -> u64 {
#[inline] #[inline]
pub fn parse_overflow_entry(data: &[u8], base: usize, i: usize) -> (usize, u32) { pub fn parse_overflow_entry(data: &[u8], base: usize, i: usize) -> (usize, u32) {
let off = base + i * OVERFLOW_ENTRY_SIZE; let off = base + i * OVERFLOW_ENTRY_SIZE;
let slot = u64::from_le_bytes(data[off..off+8].try_into().unwrap()) as usize; let slot = u64::from_le_bytes(data[off..off + 8].try_into().unwrap()) as usize;
let value = u32::from_le_bytes(data[off+8..off+12].try_into().unwrap()); let value = u32::from_le_bytes(data[off + 8..off + 12].try_into().unwrap());
(slot, value) (slot, value)
} }
@@ -46,8 +46,8 @@ pub fn parse_overflow_entry(data: &[u8], base: usize, i: usize) -> (usize, u32)
#[inline] #[inline]
pub fn parse_index_entry(data: &[u8], base: usize, i: usize) -> (usize, usize) { pub fn parse_index_entry(data: &[u8], base: usize, i: usize) -> (usize, usize) {
let off = base + i * INDEX_ENTRY_SIZE; let off = base + i * INDEX_ENTRY_SIZE;
let slot = u64::from_le_bytes(data[off..off+8].try_into().unwrap()) as usize; let slot = u64::from_le_bytes(data[off..off + 8].try_into().unwrap()) as usize;
let pos = u64::from_le_bytes(data[off+8..off+16].try_into().unwrap()) as usize; let pos = u64::from_le_bytes(data[off + 8..off + 16].try_into().unwrap()) as usize;
(slot, pos) (slot, pos)
} }
@@ -67,7 +67,11 @@ fn pciv_index_layout(n_overflow: usize) -> (usize, usize) {
/// Write the 40-byte PCIV header for a vector of `n` slots with /// Write the 40-byte PCIV header for a vector of `n` slots with
/// `n_overflow` overflow entries (index layout derived from it). /// `n_overflow` overflow entries (index layout derived from it).
pub(crate) fn write_pciv_header<W: Write>(w: &mut W, n: usize, n_overflow: usize) -> io::Result<()> { pub(crate) fn write_pciv_header<W: Write>(
w: &mut W,
n: usize,
n_overflow: usize,
) -> io::Result<()> {
let (step, n_index) = pciv_index_layout(n_overflow); let (step, n_index) = pciv_index_layout(n_overflow);
w.write_all(&MAGIC)?; w.write_all(&MAGIC)?;
w.write_all(&[0u8; 4])?; w.write_all(&[0u8; 4])?;
+2 -1
View File
@@ -73,7 +73,8 @@ impl GroupAccum {
let seen_before = self.present_count.get(slot); let seen_before = self.present_count.get(slot);
self.present_count.set(slot, seen_before + 1); self.present_count.set(slot, seen_before + 1);
if value >= threshold { if value >= threshold {
self.presence_count.set(slot, self.presence_count.get(slot) + 1); self.presence_count
.set(slot, self.presence_count.get(slot) + 1);
} }
self.sum.set(slot, self.sum.get(slot) + value); self.sum.set(slot, self.sum.get(slot) + value);
if seen_before == 0 || value < self.min.get(slot) { if seen_before == 0 || value < self.min.get(slot) {
+3 -1
View File
@@ -23,6 +23,8 @@ impl LayerMeta {
} }
fn parse(s: &str) -> Option<Self> { fn parse(s: &str) -> Option<Self> {
Some(Self { n: crate::meta::field(s, "n")? }) Some(Self {
n: crate::meta::field(s, "n")?,
})
} }
} }
+5 -4
View File
@@ -20,29 +20,30 @@ mod sparse_intmatrix_columnar;
mod storage_kind; mod storage_kind;
mod tempbitvec; mod tempbitvec;
mod tempintvec; mod tempintvec;
mod transpose;
pub mod traits; pub mod traits;
mod transpose;
mod views; mod views;
mod views_scan; mod views_scan;
pub use bitmatrix::{ pub use bitmatrix::{
PersistentBitMatrix, PersistentBitMatrixBuilder, PersistentSparseBitMatrix, PersistentBitMatrix, PersistentBitMatrixBuilder, PersistentSparseBitMatrix,
PersistentSparseBitMatrixBuilder, batch_presence_counts, pack_bit_matrix, pack_sparse_bit_matrix, PersistentSparseBitMatrixBuilder, batch_presence_counts, pack_bit_matrix,
pack_sparse_bit_matrix,
}; };
pub use bitvec::{BitIter, PersistentBitVec, PersistentBitVecBuilder}; pub use bitvec::{BitIter, PersistentBitVec, PersistentBitVecBuilder};
pub use builder::PersistentCompactIntVecBuilder; pub use builder::PersistentCompactIntVecBuilder;
pub use colgroup::{ColGroup, FilterMask, MatrixGroupOps, eval_filter_mask}; pub use colgroup::{ColGroup, FilterMask, MatrixGroupOps, eval_filter_mask};
pub use eliasfano::{EliasFano, EliasFanoBuilder}; pub use eliasfano::{EliasFano, EliasFanoBuilder};
pub use int_group_ops::{IntGroupStats, batch_int_group_stats};
pub use fixedintvec::{PersistentFixedIntVec, PersistentFixedIntVecBuilder, bit_width_for_range}; pub use fixedintvec::{PersistentFixedIntVec, PersistentFixedIntVecBuilder, bit_width_for_range};
pub use int_group_ops::{IntGroupStats, batch_int_group_stats};
pub use intmatrix::{ pub use intmatrix::{
PersistentCompactIntMatrixBuilder, PersistentIntMatrix, pack_compact_int_matrix, PersistentCompactIntMatrixBuilder, PersistentIntMatrix, pack_compact_int_matrix,
}; };
pub use layer_meta::LayerMeta; pub use layer_meta::LayerMeta;
pub use matrix_builder::{ColBuilder, MatrixBuilder};
pub use mem_builder::{MemBitVecBuilder, MemCompactIntVecBuilder}; pub use mem_builder::{MemBitVecBuilder, MemCompactIntVecBuilder};
pub use mmap_file::{building_path, publish_built}; pub use mmap_file::{building_path, publish_built};
pub use matrix_builder::{ColBuilder, MatrixBuilder};
pub use rankselect::{PersistentRankSelectBitVec, PersistentRankSelectBitVecBuilder}; pub use rankselect::{PersistentRankSelectBitVec, PersistentRankSelectBitVecBuilder};
pub use reader::{Iter as CompactIntVecIter, PersistentCompactIntVec}; pub use reader::{Iter as CompactIntVecIter, PersistentCompactIntVec};
pub use sparse_intmatrix::{ pub use sparse_intmatrix::{
+1 -1
View File
@@ -8,9 +8,9 @@
use std::io; use std::io;
use std::path::Path; use std::path::Path;
use crate::{MemBitVecBuilder, MemCompactIntVecBuilder, TempBitVec, TempCompactIntVec};
use crate::{PersistentBitMatrixBuilder as BitMB, PersistentBitVecBuilder}; use crate::{PersistentBitMatrixBuilder as BitMB, PersistentBitVecBuilder};
use crate::{PersistentCompactIntMatrixBuilder as IntMB, PersistentCompactIntVecBuilder}; use crate::{PersistentCompactIntMatrixBuilder as IntMB, PersistentCompactIntVecBuilder};
use crate::{MemBitVecBuilder, MemCompactIntVecBuilder, TempBitVec, TempCompactIntVec};
// ── ColBuilder ──────────────────────────────────────────────────────────────── // ── ColBuilder ────────────────────────────────────────────────────────────────
+18 -4
View File
@@ -14,7 +14,7 @@ use std::collections::HashMap;
use std::io::{self, Write}; use std::io::{self, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::bitvec::{n_words, MAGIC as PBIV_MAGIC}; use crate::bitvec::{MAGIC as PBIV_MAGIC, n_words};
use crate::format::{write_pciv_header, write_pciv_tail}; use crate::format::{write_pciv_header, write_pciv_tail};
use crate::mmap_file::{write_built, write_std_header}; use crate::mmap_file::{write_built, write_std_header};
@@ -30,7 +30,11 @@ pub struct MemBitVecBuilder {
impl MemBitVecBuilder { impl MemBitVecBuilder {
/// All-false vector of `n` bits, to be written at `path` by `close`. /// All-false vector of `n` bits, to be written at `path` by `close`.
pub fn new(n: usize, path: &Path) -> Self { pub fn new(n: usize, path: &Path) -> Self {
Self { words: vec![0u64; n_words(n)], n, path: path.to_path_buf() } Self {
words: vec![0u64; n_words(n)],
n,
path: path.to_path_buf(),
}
} }
#[inline] #[inline]
@@ -83,7 +87,12 @@ pub struct MemCompactIntVecBuilder {
impl MemCompactIntVecBuilder { impl MemCompactIntVecBuilder {
/// All-zero vector of `n` slots, to be written at `path` by `close`. /// All-zero vector of `n` slots, to be written at `path` by `close`.
pub fn new(n: usize, path: &Path) -> Self { pub fn new(n: usize, path: &Path) -> Self {
Self { primary: vec![0u8; n], overflow: HashMap::new(), n, path: path.to_path_buf() } Self {
primary: vec![0u8; n],
overflow: HashMap::new(),
n,
path: path.to_path_buf(),
}
} }
#[inline] #[inline]
@@ -110,7 +119,12 @@ impl MemCompactIntVecBuilder {
/// Writes the PCIV file — header, primary bytes, overflow entries sorted /// Writes the PCIV file — header, primary bytes, overflow entries sorted
/// by slot, sparse index — and publishes it. /// by slot, sparse index — and publishes it.
pub fn close(self) -> io::Result<()> { pub fn close(self) -> io::Result<()> {
let Self { primary, overflow, n, path } = self; let Self {
primary,
overflow,
n,
path,
} = self;
let mut entries: Vec<(usize, u32)> = overflow.into_iter().collect(); let mut entries: Vec<(usize, u32)> = overflow.into_iter().collect();
entries.sort_unstable_by_key(|&(slot, _)| slot); entries.sort_unstable_by_key(|&(slot, _)| slot);
write_built(&path, |w| { write_built(&path, |w| {
+7 -2
View File
@@ -20,13 +20,18 @@ impl MatrixMeta {
} }
fn parse(s: &str) -> Option<MatrixMeta> { fn parse(s: &str) -> Option<MatrixMeta> {
Some(MatrixMeta { n: field(s, "n")?, n_cols: field(s, "n_cols")? }) Some(MatrixMeta {
n: field(s, "n")?,
n_cols: field(s, "n_cols")?,
})
} }
pub(crate) fn field(s: &str, name: &str) -> Option<usize> { pub(crate) fn field(s: &str, name: &str) -> Option<usize> {
let key = format!("\"{}\":", name); let key = format!("\"{}\":", name);
let pos = s.find(&key)? + key.len(); let pos = s.find(&key)? + key.len();
let rest = s[pos..].trim_start(); let rest = s[pos..].trim_start();
let end = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len()); let end = rest
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(rest.len());
rest[..end].parse().ok() rest[..end].parse().ok()
} }
+19 -4
View File
@@ -38,7 +38,12 @@ pub fn publish_built(path: &Path) -> io::Result<()> {
} }
/// Writes the crate-wide standard header: `magic` + `pad` + `n as u64` (LE). /// Writes the crate-wide standard header: `magic` + `pad` + `n as u64` (LE).
pub(crate) fn write_std_header<W: Write>(w: &mut W, magic: [u8; 4], pad: [u8; 4], n: usize) -> io::Result<()> { pub(crate) fn write_std_header<W: Write>(
w: &mut W,
magic: [u8; 4],
pad: [u8; 4],
n: usize,
) -> io::Result<()> {
w.write_all(&magic)?; w.write_all(&magic)?;
w.write_all(&pad)?; w.write_all(&pad)?;
w.write_all(&(n as u64).to_le_bytes()) w.write_all(&(n as u64).to_le_bytes())
@@ -103,14 +108,24 @@ pub(crate) fn create_mmap_file(
/// Opens `path` read-only, validates it is at least `header_size` bytes /// Opens `path` read-only, validates it is at least `header_size` bytes
/// and starts with `magic`, and returns the mapping plus `n` (read from /// and starts with `magic`, and returns the mapping plus `n` (read from
/// bytes `[8, 16)`). /// bytes `[8, 16)`).
pub(crate) fn open_mmap_file(path: &Path, magic: [u8; 4], header_size: usize) -> io::Result<(Mmap, usize)> { pub(crate) fn open_mmap_file(
path: &Path,
magic: [u8; 4],
header_size: usize,
) -> io::Result<(Mmap, usize)> {
let mmap = unsafe { Mmap::map(&File::open(path)?)? }; let mmap = unsafe { Mmap::map(&File::open(path)?)? };
let tag = String::from_utf8_lossy(&magic).into_owned(); let tag = String::from_utf8_lossy(&magic).into_owned();
if mmap.len() < header_size { if mmap.len() < header_size {
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{tag} file too short"))); return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("{tag} file too short"),
));
} }
if mmap[0..4] != magic { if mmap[0..4] != magic {
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("bad {tag} magic"))); return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("bad {tag} magic"),
));
} }
let n = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize; let n = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize;
Ok((mmap, n)) Ok((mmap, n))
+62 -16
View File
@@ -65,19 +65,34 @@ impl PersistentRankSelectBitVec {
pub fn open(path: &Path) -> io::Result<Self> { pub fn open(path: &Path) -> io::Result<Self> {
let (mmap, n) = open_mmap_file(path, MAGIC, HEADER_SIZE)?; let (mmap, n) = open_mmap_file(path, MAGIC, HEADER_SIZE)?;
let total_ones = u64::from_le_bytes(mmap[16..24].try_into().unwrap()); let total_ones = u64::from_le_bytes(mmap[16..24].try_into().unwrap());
Ok(Self { mmap, n, total_ones, path: path.to_path_buf() }) Ok(Self {
mmap,
n,
total_ones,
path: path.to_path_buf(),
})
} }
#[inline] #[inline]
pub fn path(&self) -> &Path { &self.path } pub fn path(&self) -> &Path {
&self.path
}
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
#[inline] #[inline]
pub fn count_ones(&self) -> u64 { self.total_ones } pub fn count_ones(&self) -> u64 {
self.total_ones
}
#[inline] #[inline]
pub fn count_zeros(&self) -> u64 { self.n as u64 - self.total_ones } pub fn count_zeros(&self) -> u64 {
self.n as u64 - self.total_ones
}
// SAFETY: mmap is page-aligned, HEADER_SIZE=24 divisible by 8 → u64-aligned. // SAFETY: mmap is page-aligned, HEADER_SIZE=24 divisible by 8 → u64-aligned.
#[inline] #[inline]
@@ -118,7 +133,11 @@ impl PersistentRankSelectBitVec {
} }
let bit_in_word = pos - word_idx * 64; let bit_in_word = pos - word_idx * 64;
let last = words[word_idx]; let last = words[word_idx];
let masked = if bit_in_word >= 64 { last } else { last & ((1u64 << bit_in_word) - 1) }; let masked = if bit_in_word >= 64 {
last
} else {
last & ((1u64 << bit_in_word) - 1)
};
rank += masked.count_ones() as u64; rank += masked.count_ones() as u64;
rank rank
} }
@@ -132,7 +151,11 @@ impl PersistentRankSelectBitVec {
/// Position of the `k`-th (0-indexed) 1 bit. Panics if fewer than /// Position of the `k`-th (0-indexed) 1 bit. Panics if fewer than
/// `k + 1` ones exist. /// `k + 1` ones exist.
pub fn select1(&self, k: u64) -> usize { pub fn select1(&self, k: u64) -> usize {
assert!(k < self.total_ones, "select1({k}) out of range: only {} ones", self.total_ones); assert!(
k < self.total_ones,
"select1({k}) out of range: only {} ones",
self.total_ones
);
let block_ranks = self.block_ranks(); let block_ranks = self.block_ranks();
let words = self.bit_words(); let words = self.bit_words();
@@ -141,7 +164,11 @@ impl PersistentRankSelectBitVec {
let mut hi = block_ranks.len(); let mut hi = block_ranks.len();
while lo + 1 < hi { while lo + 1 < hi {
let mid = lo + (hi - lo) / 2; let mid = lo + (hi - lo) / 2;
if block_ranks[mid] <= k { lo = mid; } else { hi = mid; } if block_ranks[mid] <= k {
lo = mid;
} else {
hi = mid;
}
} }
let block_idx = lo; let block_idx = lo;
let mut remaining = k - block_ranks[block_idx]; let mut remaining = k - block_ranks[block_idx];
@@ -154,7 +181,9 @@ impl PersistentRankSelectBitVec {
} }
remaining -= c; remaining -= c;
} }
unreachable!("select1({k}): ran off the end of its own block — rank/select index inconsistent"); unreachable!(
"select1({k}): ran off the end of its own block — rank/select index inconsistent"
);
} }
/// Position of the `k`-th (0-indexed) 0 bit. Panics if fewer than /// Position of the `k`-th (0-indexed) 0 bit. Panics if fewer than
@@ -166,7 +195,10 @@ impl PersistentRankSelectBitVec {
/// exact bit within the winning word via `SelectInWord` on `!w`. /// exact bit within the winning word via `SelectInWord` on `!w`.
pub fn select0(&self, k: u64) -> usize { pub fn select0(&self, k: u64) -> usize {
let total_zeros = self.count_zeros(); let total_zeros = self.count_zeros();
assert!(k < total_zeros, "select0({k}) out of range: only {total_zeros} zeros"); assert!(
k < total_zeros,
"select0({k}) out of range: only {total_zeros} zeros"
);
let block_ranks = self.block_ranks(); let block_ranks = self.block_ranks();
let words = self.bit_words(); let words = self.bit_words();
@@ -176,7 +208,11 @@ impl PersistentRankSelectBitVec {
while lo + 1 < hi { while lo + 1 < hi {
let mid = lo + (hi - lo) / 2; let mid = lo + (hi - lo) / 2;
let zeros_at_mid = (mid * BLOCK_WORDS * 64) as u64 - block_ranks[mid]; let zeros_at_mid = (mid * BLOCK_WORDS * 64) as u64 - block_ranks[mid];
if zeros_at_mid <= k { lo = mid; } else { hi = mid; } if zeros_at_mid <= k {
lo = mid;
} else {
hi = mid;
}
} }
let block_idx = lo; let block_idx = lo;
let zeros_before_block = (block_idx * BLOCK_WORDS * 64) as u64 - block_ranks[block_idx]; let zeros_before_block = (block_idx * BLOCK_WORDS * 64) as u64 - block_ranks[block_idx];
@@ -191,7 +227,9 @@ impl PersistentRankSelectBitVec {
} }
remaining -= c; remaining -= c;
} }
unreachable!("select0({k}): ran off the end of its own block — rank/select index inconsistent"); unreachable!(
"select0({k}): ran off the end of its own block — rank/select index inconsistent"
);
} }
} }
@@ -208,13 +246,21 @@ impl PersistentRankSelectBitVecBuilder {
let file_size = HEADER_SIZE + bits_bytes(n) + blocks_bytes(n); let file_size = HEADER_SIZE + bits_bytes(n) + blocks_bytes(n);
// 8 extra header zero bytes: `total_ones`, patched in close(). // 8 extra header zero bytes: `total_ones`, patched in close().
let mmap = create_mmap_file(path, MAGIC, [0u8; 4], n, 8, file_size)?; let mmap = create_mmap_file(path, MAGIC, [0u8; 4], n, 8, file_size)?;
Ok(Self { mmap, n, path: path.to_path_buf() }) Ok(Self {
mmap,
n,
path: path.to_path_buf(),
})
} }
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
#[inline] #[inline]
fn bit_words_mut(&mut self) -> &mut [u64] { fn bit_words_mut(&mut self) -> &mut [u64] {
+79 -20
View File
@@ -4,7 +4,9 @@ use std::path::{Path, PathBuf};
use memmap2::Mmap; use memmap2::Mmap;
use crate::format::{byte_count_nonzero, byte_sum, HEADER_SIZE, MAGIC, OVERFLOW_ENTRY_SIZE, parse_index_entry}; use crate::format::{
HEADER_SIZE, MAGIC, OVERFLOW_ENTRY_SIZE, byte_count_nonzero, byte_sum, parse_index_entry,
};
use crate::views::IntSliceView; use crate::views::IntSliceView;
pub struct PersistentCompactIntVec { pub struct PersistentCompactIntVec {
@@ -23,7 +25,10 @@ impl PersistentCompactIntVec {
let mmap = unsafe { Mmap::map(&File::open(path)?)? }; let mmap = unsafe { Mmap::map(&File::open(path)?)? };
if mmap.len() < HEADER_SIZE { if mmap.len() < HEADER_SIZE {
return Err(io::Error::new(io::ErrorKind::InvalidData, "PCIV file too short")); return Err(io::Error::new(
io::ErrorKind::InvalidData,
"PCIV file too short",
));
} }
if &mmap[0..4] != &MAGIC { if &mmap[0..4] != &MAGIC {
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PCIV magic")); return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PCIV magic"));
@@ -43,15 +48,30 @@ impl PersistentCompactIntVec {
index.push(parse_index_entry(&mmap, index_offset, i)); index.push(parse_index_entry(&mmap, index_offset, i));
} }
Ok(Self { mmap, n, n_overflow, step, index, primary_offset, data_offset, path: path.to_path_buf() }) Ok(Self {
mmap,
n,
n_overflow,
step,
index,
primary_offset,
data_offset,
path: path.to_path_buf(),
})
} }
#[inline] #[inline]
pub fn path(&self) -> &Path { &self.path } pub fn path(&self) -> &Path {
&self.path
}
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
#[inline] #[inline]
pub fn get(&self, slot: usize) -> u32 { pub fn get(&self, slot: usize) -> u32 {
@@ -82,9 +102,16 @@ impl PersistentCompactIntVec {
let (pos_start, pos_end) = if self.step == 0 { let (pos_start, pos_end) = if self.step == 0 {
(0, self.n_overflow) (0, self.n_overflow)
} else { } else {
let i = self.index.partition_point(|&(s, _)| s <= slot).saturating_sub(1); let i = self
.index
.partition_point(|&(s, _)| s <= slot)
.saturating_sub(1);
let start = self.index[i].1; let start = self.index[i].1;
let end = if i + 1 < self.index.len() { self.index[i + 1].1 } else { self.n_overflow }; let end = if i + 1 < self.index.len() {
self.index[i + 1].1
} else {
self.n_overflow
};
(start, end) (start, end)
}; };
let mut lo = pos_start; let mut lo = pos_start;
@@ -135,13 +162,18 @@ impl PersistentCompactIntVec {
#[inline] #[inline]
pub fn view(&self) -> IntSliceView<'_> { pub fn view(&self) -> IntSliceView<'_> {
let primary = &self.mmap[self.primary_offset..self.primary_offset + self.n]; let primary = &self.mmap[self.primary_offset..self.primary_offset + self.n];
let overflow_raw = &self.mmap[self.data_offset..self.data_offset + self.n_overflow * OVERFLOW_ENTRY_SIZE]; let overflow_raw =
&self.mmap[self.data_offset..self.data_offset + self.n_overflow * OVERFLOW_ENTRY_SIZE];
IntSliceView::new(primary, overflow_raw, self.n_overflow, self.n) IntSliceView::new(primary, overflow_raw, self.n_overflow, self.n)
} }
#[inline] #[inline]
pub fn iter(&self) -> Iter<'_> { pub fn iter(&self) -> Iter<'_> {
Iter { pciv: self, slot: 0, overflow_pos: 0 } Iter {
pciv: self,
slot: 0,
overflow_pos: 0,
}
} }
// ── Distance methods ────────────────────────────────────────────────────── // ── Distance methods ──────────────────────────────────────────────────────
@@ -163,8 +195,14 @@ impl PersistentCompactIntVec {
self.view().relfreq_bray_dist(other.view()) self.view().relfreq_bray_dist(other.view())
} }
pub fn partial_relfreq_bray_dist(&self, other: &PersistentCompactIntVec, sum_a: f64, sum_b: f64) -> f64 { pub fn partial_relfreq_bray_dist(
self.view().partial_relfreq_bray_dist(other.view(), sum_a, sum_b) &self,
other: &PersistentCompactIntVec,
sum_a: f64,
sum_b: f64,
) -> f64 {
self.view()
.partial_relfreq_bray_dist(other.view(), sum_a, sum_b)
} }
pub fn euclidean_dist(&self, other: &PersistentCompactIntVec) -> f64 { pub fn euclidean_dist(&self, other: &PersistentCompactIntVec) -> f64 {
@@ -179,16 +217,28 @@ impl PersistentCompactIntVec {
self.view().relfreq_euclidean_dist(other.view()) self.view().relfreq_euclidean_dist(other.view())
} }
pub fn partial_relfreq_euclidean_dist(&self, other: &PersistentCompactIntVec, sum_a: f64, sum_b: f64) -> f64 { pub fn partial_relfreq_euclidean_dist(
self.view().partial_relfreq_euclidean_dist(other.view(), sum_a, sum_b) &self,
other: &PersistentCompactIntVec,
sum_a: f64,
sum_b: f64,
) -> f64 {
self.view()
.partial_relfreq_euclidean_dist(other.view(), sum_a, sum_b)
} }
pub fn hellinger_euclidean_dist(&self, other: &PersistentCompactIntVec) -> f64 { pub fn hellinger_euclidean_dist(&self, other: &PersistentCompactIntVec) -> f64 {
self.view().hellinger_euclidean_dist(other.view()) self.view().hellinger_euclidean_dist(other.view())
} }
pub fn partial_hellinger_euclidean_dist(&self, other: &PersistentCompactIntVec, sum_a: f64, sum_b: f64) -> f64 { pub fn partial_hellinger_euclidean_dist(
self.view().partial_hellinger_euclidean_dist(other.view(), sum_a, sum_b) &self,
other: &PersistentCompactIntVec,
sum_a: f64,
sum_b: f64,
) -> f64 {
self.view()
.partial_hellinger_euclidean_dist(other.view(), sum_a, sum_b)
} }
pub fn hellinger_dist(&self, other: &PersistentCompactIntVec) -> f64 { pub fn hellinger_dist(&self, other: &PersistentCompactIntVec) -> f64 {
@@ -199,8 +249,13 @@ impl PersistentCompactIntVec {
self.view().threshold_jaccard_dist(other.view(), threshold) self.view().threshold_jaccard_dist(other.view(), threshold)
} }
pub fn partial_threshold_jaccard_dist(&self, other: &PersistentCompactIntVec, threshold: u32) -> (u64, u64) { pub fn partial_threshold_jaccard_dist(
self.view().partial_threshold_jaccard_dist(other.view(), threshold) &self,
other: &PersistentCompactIntVec,
threshold: u32,
) -> (u64, u64) {
self.view()
.partial_threshold_jaccard_dist(other.view(), threshold)
} }
pub fn jaccard_dist(&self, other: &PersistentCompactIntVec) -> f64 { pub fn jaccard_dist(&self, other: &PersistentCompactIntVec) -> f64 {
@@ -212,7 +267,9 @@ impl<'a> IntoIterator for &'a PersistentCompactIntVec {
type Item = u32; type Item = u32;
type IntoIter = Iter<'a>; type IntoIter = Iter<'a>;
#[inline] #[inline]
fn into_iter(self) -> Iter<'a> { self.iter() } fn into_iter(self) -> Iter<'a> {
self.iter()
}
} }
pub struct Iter<'a> { pub struct Iter<'a> {
@@ -228,7 +285,9 @@ impl Iterator for Iter<'_> {
#[inline] #[inline]
fn next(&mut self) -> Option<u32> { fn next(&mut self) -> Option<u32> {
if self.slot >= self.pciv.n { return None; } if self.slot >= self.pciv.n {
return None;
}
let v = self.pciv.mmap[self.pciv.primary_offset + self.slot]; let v = self.pciv.mmap[self.pciv.primary_offset + self.slot];
self.slot += 1; self.slot += 1;
if v < 255 { if v < 255 {
+1 -1
View File
@@ -12,11 +12,11 @@
use std::io; use std::io;
use crate::PersistentBitMatrix;
use crate::bitmatrix::batch_presence_counts; use crate::bitmatrix::batch_presence_counts;
use crate::colgroup::{ColGroup, chunked_presence_count}; use crate::colgroup::{ColGroup, chunked_presence_count};
use crate::intmatrix::PersistentIntMatrix; use crate::intmatrix::PersistentIntMatrix;
use crate::tempintvec::TempCompactIntVec; use crate::tempintvec::TempCompactIntVec;
use crate::PersistentBitMatrix;
/// Tallies a per-row presence-count vector into `hist[j]` = number of rows /// Tallies a per-row presence-count vector into `hist[j]` = number of rows
/// whose count is `j`. `hist` has `n_cols + 1` entries. /// whose count is `j`. `hist` has `n_cols + 1` entries.
+3 -1
View File
@@ -629,7 +629,9 @@ impl PersistentSparseCompactIntMatrixBuilder {
/// new format is fully written. Idempotent: a no-op if the sparse format is /// new format is fully written. Idempotent: a no-op if the sparse format is
/// already present. /// already present.
pub fn pack_sparse_compact_int_matrix(dir: &Path) -> io::Result<()> { pub fn pack_sparse_compact_int_matrix(dir: &Path) -> io::Result<()> {
use crate::intmatrix::{PackedCompactIntMatrix, pack_compact_int_matrix, packed_int_matrix_n_cols}; use crate::intmatrix::{
PackedCompactIntMatrix, pack_compact_int_matrix, packed_int_matrix_n_cols,
};
if is_present(dir) { if is_present(dir) {
return Ok(()); return Ok(());
@@ -21,7 +21,10 @@ use crate::sparse_intmatrix::PersistentSparseCompactIntMatrixBuilder;
use crate::transpose::{DEFAULT_MAX_HITS, DEFAULT_WINDOW_ROWS, Hit, transpose_windows}; use crate::transpose::{DEFAULT_MAX_HITS, DEFAULT_WINDOW_ROWS, Hit, transpose_windows};
fn invalid(path: &Path, what: &str) -> io::Error { fn invalid(path: &Path, what: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, format!("{}: {what}", path.display())) io::Error::new(
io::ErrorKind::InvalidData,
format!("{}: {what}", path.display()),
)
} }
/// Appends the non-zero cells of column `c` (file `path`) for rows /// Appends the non-zero cells of column `c` (file `path`) for rows
@@ -101,7 +104,10 @@ fn read_int_window(
if h.2 == 255 { if h.2 == 255 {
let (slot, value) = parse_overflow_entry(&raw, 0, k); let (slot, value) = parse_overflow_entry(&raw, 0, k);
if slot != start + h.0 as usize { if slot != start + h.0 as usize {
return Err(invalid(path, "overflow entry does not match its sentinel slot")); return Err(invalid(
path,
"overflow entry does not match its sentinel slot",
));
} }
h.2 = value; h.2 = value;
k += 1; k += 1;
@@ -135,7 +141,9 @@ impl PersistentSparseCompactIntMatrixBuilder {
window_rows, window_rows,
max_hits, max_hits,
0u32, 0u32,
|c, start, end, hits| read_int_window(&col_path(dir, c), meta.n, c, start, end, &mut primary, hits), |c, start, end, hits| {
read_int_window(&col_path(dir, c), meta.n, c, start, end, &mut primary, hits)
},
|_, batch| { |_, batch| {
for i in 0..batch.len() { for i in 0..batch.len() {
builder.push_row(batch.cols(i), batch.vals(i)); builder.push_row(batch.cols(i), batch.vals(i));
+42 -14
View File
@@ -23,17 +23,29 @@ impl TempCompactIntVec {
} }
#[inline] #[inline]
pub fn len(&self) -> usize { self.vec.len() } pub fn len(&self) -> usize {
self.vec.len()
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.vec.is_empty() } pub fn is_empty(&self) -> bool {
self.vec.is_empty()
}
#[inline] #[inline]
pub fn get(&self, slot: usize) -> u32 { self.vec.get(slot) } pub fn get(&self, slot: usize) -> u32 {
self.vec.get(slot)
}
#[inline] #[inline]
pub fn sum(&self) -> u64 { self.vec.sum() } pub fn sum(&self) -> u64 {
self.vec.sum()
}
#[inline] #[inline]
pub fn view(&self) -> IntSliceView<'_> { self.vec.view() } pub fn view(&self) -> IntSliceView<'_> {
self.vec.view()
}
#[inline] #[inline]
pub fn iter(&self) -> crate::reader::Iter<'_> { self.vec.iter() } pub fn iter(&self) -> crate::reader::Iter<'_> {
self.vec.iter()
}
} }
// ── TempCompactIntVecBuilder — mutable, becomes TempCompactIntVec on freeze ── // ── TempCompactIntVecBuilder — mutable, becomes TempCompactIntVec on freeze ──
@@ -58,17 +70,27 @@ impl TempCompactIntVecBuilder {
} }
#[inline] #[inline]
pub fn n(&self) -> usize { self.builder.len() } pub fn n(&self) -> usize {
self.builder.len()
}
#[inline] #[inline]
pub fn set(&mut self, slot: usize, value: u32) { self.builder.set(slot, value); } pub fn set(&mut self, slot: usize, value: u32) {
self.builder.set(slot, value);
}
#[inline] #[inline]
pub fn get(&self, slot: usize) -> u32 { self.builder.get(slot) } pub fn get(&self, slot: usize) -> u32 {
self.builder.get(slot)
}
#[inline] #[inline]
pub fn primary_bytes(&self) -> &[u8] { self.builder.primary_bytes() } pub fn primary_bytes(&self) -> &[u8] {
self.builder.primary_bytes()
}
#[inline] #[inline]
pub fn primary_bytes_mut(&mut self) -> &mut [u8] { self.builder.primary_bytes_mut() } pub fn primary_bytes_mut(&mut self) -> &mut [u8] {
self.builder.primary_bytes_mut()
}
#[inline] #[inline]
pub fn inc_present(&mut self, col: BitSliceView<'_>) { pub fn inc_present(&mut self, col: BitSliceView<'_>) {
@@ -101,9 +123,15 @@ impl TempCompactIntVecBuilder {
} }
#[inline] #[inline]
pub fn min(&mut self, other: IntSliceView<'_>) { self.builder.min(other); } pub fn min(&mut self, other: IntSliceView<'_>) {
self.builder.min(other);
}
#[inline] #[inline]
pub fn max(&mut self, other: IntSliceView<'_>) { self.builder.max(other); } pub fn max(&mut self, other: IntSliceView<'_>) {
self.builder.max(other);
}
#[inline] #[inline]
pub fn diff(&mut self, other: IntSliceView<'_>) { self.builder.diff(other); } pub fn diff(&mut self, other: IntSliceView<'_>) {
self.builder.diff(other);
}
} }
+43 -17
View File
@@ -1,7 +1,7 @@
use tempfile::tempdir; use tempfile::tempdir;
use crate::{pack_bit_matrix, PersistentBitMatrix, PersistentBitMatrixBuilder};
use crate::traits::BitPartials; use crate::traits::BitPartials;
use crate::{PersistentBitMatrix, PersistentBitMatrixBuilder, pack_bit_matrix};
fn make_matrix(cols: &[&[bool]]) -> (tempfile::TempDir, PersistentBitMatrix) { fn make_matrix(cols: &[&[bool]]) -> (tempfile::TempDir, PersistentBitMatrix) {
let n = cols.first().map_or(0, |c| c.len()); let n = cols.first().map_or(0, |c| c.len());
@@ -48,10 +48,14 @@ fn two_cols_roundtrip() {
let presence = dir.path().join("presence"); let presence = dir.path().join("presence");
let mut b = PersistentBitMatrixBuilder::new(3, &presence).unwrap(); let mut b = PersistentBitMatrixBuilder::new(3, &presence).unwrap();
let mut col0 = b.add_col().unwrap(); let mut col0 = b.add_col().unwrap();
col0.set(0, true); col0.set(1, false); col0.set(2, true); col0.set(0, true);
col0.set(1, false);
col0.set(2, true);
col0.close().unwrap(); col0.close().unwrap();
let mut col1 = b.add_col().unwrap(); let mut col1 = b.add_col().unwrap();
col1.set(0, false); col1.set(1, true); col1.set(2, false); col1.set(0, false);
col1.set(1, true);
col1.set(2, false);
col1.close().unwrap(); col1.close().unwrap();
b.close().unwrap(); b.close().unwrap();
@@ -69,7 +73,9 @@ fn resume_continues_n_cols_and_appends_columns() {
let mut b = PersistentBitMatrixBuilder::new(3, &presence).unwrap(); let mut b = PersistentBitMatrixBuilder::new(3, &presence).unwrap();
let mut col0 = b.add_col().unwrap(); let mut col0 = b.add_col().unwrap();
col0.set(0, true); col0.set(1, false); col0.set(2, true); col0.set(0, true);
col0.set(1, false);
col0.set(2, true);
col0.close().unwrap(); col0.close().unwrap();
b.close().unwrap(); b.close().unwrap();
@@ -77,7 +83,9 @@ fn resume_continues_n_cols_and_appends_columns() {
assert_eq!(resumed.n(), 3); assert_eq!(resumed.n(), 3);
assert_eq!(resumed.n_cols(), 1); assert_eq!(resumed.n_cols(), 1);
let mut col1 = resumed.add_col().unwrap(); let mut col1 = resumed.add_col().unwrap();
col1.set(0, false); col1.set(1, true); col1.set(2, false); col1.set(0, false);
col1.set(1, true);
col1.set(2, false);
col1.close().unwrap(); col1.close().unwrap();
resumed.close().unwrap(); resumed.close().unwrap();
@@ -93,12 +101,16 @@ fn resume_twice_keeps_appending() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let presence = dir.path().join("presence"); let presence = dir.path().join("presence");
PersistentBitMatrixBuilder::new(2, &presence).unwrap().close().unwrap(); PersistentBitMatrixBuilder::new(2, &presence)
.unwrap()
.close()
.unwrap();
for v in [true, false, true] { for v in [true, false, true] {
let mut b = PersistentBitMatrixBuilder::resume(&presence).unwrap(); let mut b = PersistentBitMatrixBuilder::resume(&presence).unwrap();
let mut col = b.add_col().unwrap(); let mut col = b.add_col().unwrap();
col.set(0, v); col.set(1, !v); col.set(0, v);
col.set(1, !v);
col.close().unwrap(); col.close().unwrap();
b.close().unwrap(); b.close().unwrap();
} }
@@ -115,7 +127,9 @@ fn col_accessor() {
let presence = dir.path().join("presence"); let presence = dir.path().join("presence");
let mut b = PersistentBitMatrixBuilder::new(3, &presence).unwrap(); let mut b = PersistentBitMatrixBuilder::new(3, &presence).unwrap();
let mut col = b.add_col().unwrap(); let mut col = b.add_col().unwrap();
col.set(0, true); col.set(1, false); col.set(2, true); col.set(0, true);
col.set(1, false);
col.set(2, true);
col.close().unwrap(); col.close().unwrap();
b.close().unwrap(); b.close().unwrap();
@@ -163,10 +177,15 @@ fn jaccard_dist_matrix_symmetry_and_diagonal() {
]); ]);
let dm = m.jaccard_dist_matrix(); let dm = m.jaccard_dist_matrix();
let n = m.n_cols(); let n = m.n_cols();
for i in 0..n { assert_eq!(dm[[i, i]], 0.0, "diagonal"); } for i in 0..n {
assert_eq!(dm[[i, i]], 0.0, "diagonal");
}
for i in 0..n { for i in 0..n {
for j in 0..n { for j in 0..n {
assert!((dm[[i, j]] - dm[[j, i]]).abs() < 1e-12, "symmetry [{i},{j}]"); assert!(
(dm[[i, j]] - dm[[j, i]]).abs() < 1e-12,
"symmetry [{i},{j}]"
);
} }
} }
} }
@@ -196,7 +215,9 @@ fn hamming_dist_matrix_symmetry_and_diagonal() {
]); ]);
let dm = m.hamming_dist_matrix(); let dm = m.hamming_dist_matrix();
let n = m.n_cols(); let n = m.n_cols();
for i in 0..n { assert_eq!(dm[[i, i]], 0, "diagonal"); } for i in 0..n {
assert_eq!(dm[[i, i]], 0, "diagonal");
}
for i in 0..n { for i in 0..n {
for j in 0..n { for j in 0..n {
assert_eq!(dm[[i, j]], dm[[j, i]], "symmetry [{i},{j}]"); assert_eq!(dm[[i, j]], dm[[j, i]], "symmetry [{i},{j}]");
@@ -255,10 +276,7 @@ fn partial_hamming_matches_hamming() {
#[test] #[test]
fn col_view_packed_values() { fn col_view_packed_values() {
let (dir, _) = make_matrix(&[ let (dir, _) = make_matrix(&[&[true, false, true, true], &[false, true, false, true]]);
&[true, false, true, true],
&[false, true, false, true],
]);
pack_bit_matrix(&dir.path().join("presence")).unwrap(); pack_bit_matrix(&dir.path().join("presence")).unwrap();
let m = PersistentBitMatrix::open(dir.path()).unwrap(); let m = PersistentBitMatrix::open(dir.path()).unwrap();
@@ -299,7 +317,11 @@ fn col_view_packed_matches_columnar() {
for s in 0..col_ref.len() { for s in 0..col_ref.len() {
assert_eq!(col_view.get(s), col_ref.get(s), "col={c} slot={s}"); assert_eq!(col_view.get(s), col_ref.get(s), "col={c} slot={s}");
} }
assert_eq!(col_view.count_ones(), col_ref.count_ones(), "col={c} count_ones"); assert_eq!(
col_view.count_ones(),
col_ref.count_ones(),
"col={c} count_ones"
);
assert_eq!(col_view.words(), col_ref.words(), "col={c} words"); assert_eq!(col_view.words(), col_ref.words(), "col={c} words");
} }
drop(dir_col); drop(dir_col);
@@ -318,7 +340,11 @@ fn count_geq_ignores_threshold() {
&[true, true, true, false], &[true, true, true, false],
]); ]);
for t in [0u32, 1, 2, 100] { for t in [0u32, 1, 2, 100] {
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), vec![3, 0, 3], "threshold {t}"); assert_eq!(
ColumnWeights::count_geq(&m, t).to_vec(),
vec![3, 0, 3],
"threshold {t}"
);
} }
} }
+50 -13
View File
@@ -1,6 +1,9 @@
use tempfile::tempdir; use tempfile::tempdir;
use crate::{PersistentBitVec, PersistentBitVecBuilder, PersistentCompactIntVec, PersistentCompactIntVecBuilder}; use crate::{
PersistentBitVec, PersistentBitVecBuilder, PersistentCompactIntVec,
PersistentCompactIntVecBuilder,
};
fn make_bv(bits: &[bool]) -> (tempfile::TempDir, PersistentBitVec) { fn make_bv(bits: &[bool]) -> (tempfile::TempDir, PersistentBitVec) {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -36,7 +39,9 @@ fn set_get_roundtrip() {
#[test] #[test]
fn iter_matches_get() { fn iter_matches_get() {
let bits = vec![true, false, true, false, true, true, false, true, false, true]; let bits = vec![
true, false, true, false, true, true, false, true, false, true,
];
let (_dir, r) = make_bv(&bits); let (_dir, r) = make_bv(&bits);
let via_iter: Vec<bool> = r.iter().collect(); let via_iter: Vec<bool> = r.iter().collect();
let via_get: Vec<bool> = (0..bits.len()).map(|s| r.get(s)).collect(); let via_get: Vec<bool> = (0..bits.len()).map(|s| r.get(s)).collect();
@@ -65,7 +70,10 @@ fn build_from_roundtrip() {
let (_da, ra) = make_bv(&bits); let (_da, ra) = make_bv(&bits);
let dir_b = tempdir().unwrap(); let dir_b = tempdir().unwrap();
let path_b = dir_b.path().join("b.pbiv"); let path_b = dir_b.path().join("b.pbiv");
PersistentBitVecBuilder::build_from(&ra, &path_b).unwrap().close().unwrap(); PersistentBitVecBuilder::build_from(&ra, &path_b)
.unwrap()
.close()
.unwrap();
let rb = PersistentBitVec::open(&path_b).unwrap(); let rb = PersistentBitVec::open(&path_b).unwrap();
assert_eq!(ra.iter().collect::<Vec<_>>(), rb.iter().collect::<Vec<_>>()); assert_eq!(ra.iter().collect::<Vec<_>>(), rb.iter().collect::<Vec<_>>());
} }
@@ -80,7 +88,10 @@ fn op_and() {
b.and(rb.view()); b.and(rb.view());
b.close().unwrap(); b.close().unwrap();
let r = PersistentBitVec::open(&path).unwrap(); let r = PersistentBitVec::open(&path).unwrap();
assert_eq!(r.iter().collect::<Vec<_>>(), vec![true, false, false, false]); assert_eq!(
r.iter().collect::<Vec<_>>(),
vec![true, false, false, false]
);
} }
#[test] #[test]
@@ -134,7 +145,10 @@ fn op_not_non_aligned_no_padding_leak() {
b.not(); b.not();
b.close().unwrap(); b.close().unwrap();
let r = PersistentBitVec::open(&path).unwrap(); let r = PersistentBitVec::open(&path).unwrap();
assert_eq!(r.iter().collect::<Vec<_>>(), vec![false, true, false, true, false]); assert_eq!(
r.iter().collect::<Vec<_>>(),
vec![false, true, false, true, false]
);
// count_ones must reflect exactly the 2 set bits, not 2 + stray padding bits // count_ones must reflect exactly the 2 set bits, not 2 + stray padding bits
assert_eq!(r.count_ones(), 2); assert_eq!(r.count_ones(), 2);
} }
@@ -165,7 +179,9 @@ fn make_pciv(counts: &[u32]) -> (tempfile::TempDir, PersistentCompactIntVec) {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("c.pciv"); let path = dir.path().join("c.pciv");
let mut b = PersistentCompactIntVecBuilder::new(counts.len(), &path).unwrap(); let mut b = PersistentCompactIntVecBuilder::new(counts.len(), &path).unwrap();
for (i, &v) in counts.iter().enumerate() { b.set(i, v); } for (i, &v) in counts.iter().enumerate() {
b.set(i, v);
}
b.close().unwrap(); b.close().unwrap();
let r = PersistentCompactIntVec::open(&path).unwrap(); let r = PersistentCompactIntVec::open(&path).unwrap();
(dir, r) (dir, r)
@@ -177,9 +193,15 @@ fn build_from_presence_basic() {
let (_dc, rc) = make_pciv(&counts); let (_dc, rc) = make_pciv(&counts);
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("bv.pbiv"); let path = dir.path().join("bv.pbiv");
PersistentBitVecBuilder::build_from_presence(&rc, &path).unwrap().close().unwrap(); PersistentBitVecBuilder::build_from_presence(&rc, &path)
.unwrap()
.close()
.unwrap();
let bv = PersistentBitVec::open(&path).unwrap(); let bv = PersistentBitVec::open(&path).unwrap();
assert_eq!(bv.iter().collect::<Vec<_>>(), vec![false, true, false, true, true, false]); assert_eq!(
bv.iter().collect::<Vec<_>>(),
vec![false, true, false, true, true, false]
);
assert_eq!(bv.count_ones(), 3); assert_eq!(bv.count_ones(), 3);
} }
@@ -190,9 +212,15 @@ fn build_from_counts_with_threshold() {
let (_dc, rc) = make_pciv(&counts); let (_dc, rc) = make_pciv(&counts);
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("bv.pbiv"); let path = dir.path().join("bv.pbiv");
PersistentBitVecBuilder::build_from_counts(&rc, 5, &path).unwrap().close().unwrap(); PersistentBitVecBuilder::build_from_counts(&rc, 5, &path)
.unwrap()
.close()
.unwrap();
let bv = PersistentBitVec::open(&path).unwrap(); let bv = PersistentBitVec::open(&path).unwrap();
assert_eq!(bv.iter().collect::<Vec<_>>(), vec![false, false, true, true, false, true]); assert_eq!(
bv.iter().collect::<Vec<_>>(),
vec![false, false, true, true, false, true]
);
} }
#[test] #[test]
@@ -202,9 +230,15 @@ fn build_from_counts_with_overflow_values() {
let (_dc, rc) = make_pciv(&counts); let (_dc, rc) = make_pciv(&counts);
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("bv.pbiv"); let path = dir.path().join("bv.pbiv");
PersistentBitVecBuilder::build_from_counts(&rc, 200, &path).unwrap().close().unwrap(); PersistentBitVecBuilder::build_from_counts(&rc, 200, &path)
.unwrap()
.close()
.unwrap();
let bv = PersistentBitVec::open(&path).unwrap(); let bv = PersistentBitVec::open(&path).unwrap();
assert_eq!(bv.iter().collect::<Vec<_>>(), vec![false, false, true, false]); assert_eq!(
bv.iter().collect::<Vec<_>>(),
vec![false, false, true, false]
);
} }
#[test] #[test]
@@ -264,7 +298,10 @@ fn bitslice_view_collect_slots_values() {
let bits = vec![true, false, true, false, true]; let bits = vec![true, false, true, false, true];
let (_dir, r) = make_bv(&bits); let (_dir, r) = make_bv(&bits);
let view = r.view(); let view = r.view();
assert_eq!(view.collect_slots_values(&[0, 1, 2]), vec![true, false, true]); assert_eq!(
view.collect_slots_values(&[0, 1, 2]),
vec![true, false, true]
);
assert_eq!(view.collect_slots_values(&[4, 3]), vec![true, false]); assert_eq!(view.collect_slots_values(&[4, 3]), vec![true, false]);
} }
+7 -3
View File
@@ -2,8 +2,8 @@ use tempfile::tempdir;
use crate::{ use crate::{
ColGroup, MatrixGroupOps, PersistentBitMatrix, PersistentBitMatrixBuilder, ColGroup, MatrixGroupOps, PersistentBitMatrix, PersistentBitMatrixBuilder,
PersistentIntMatrix, PersistentCompactIntMatrixBuilder, PersistentCompactIntMatrixBuilder, PersistentIntMatrix, PersistentSparseBitMatrixBuilder,
PersistentSparseBitMatrixBuilder, batch_presence_counts, batch_presence_counts,
}; };
use crate::{PersistentBitVecBuilder, PersistentCompactIntVec, PersistentCompactIntVecBuilder}; use crate::{PersistentBitVecBuilder, PersistentCompactIntVec, PersistentCompactIntVecBuilder};
@@ -283,7 +283,11 @@ fn batch_presence_counts_matches_naive_for_columnar_and_sparse() {
for (label, mat) in [("columnar", &columnar), ("sparse", &sparse)] { for (label, mat) in [("columnar", &columnar), ("sparse", &sparse)] {
let counts = batch_presence_counts(mat, &groups).unwrap(); let counts = batch_presence_counts(mat, &groups).unwrap();
assert_eq!(counts.len(), groups.len(), "{label}: wrong number of results"); assert_eq!(
counts.len(),
groups.len(),
"{label}: wrong number of results"
);
for (gi, exp) in expected.iter().enumerate() { for (gi, exp) in expected.iter().enumerate() {
for (row, &e) in exp.iter().enumerate() { for (row, &e) in exp.iter().enumerate() {
assert_eq!(counts[gi].get(row), e, "{label}: group {gi} row {row}"); assert_eq!(counts[gi].get(row), e, "{label}: group {gi} row {row}");
+10 -2
View File
@@ -148,8 +148,16 @@ fn successor_and_predecessor_small() {
let values = [0u64, 3, 3, 7, 42, 42, 42, 100]; let values = [0u64, 3, 3, 7, 42, 42, 42, 100];
let (_dir, ef) = build(&values, 1000); let (_dir, ef) = build(&values, 1000);
for x in 0..=105u64 { for x in 0..=105u64 {
assert_eq!(ef.successor(x), naive_successor(&values, x), "successor({x})"); assert_eq!(
assert_eq!(ef.predecessor(x), naive_predecessor(&values, x), "predecessor({x})"); ef.successor(x),
naive_successor(&values, x),
"successor({x})"
);
assert_eq!(
ef.predecessor(x),
naive_predecessor(&values, x),
"predecessor({x})"
);
} }
} }
+44 -9
View File
@@ -58,7 +58,10 @@ fn batch_int_group_stats_matches_hand_computed_for_columnar_and_sparse() {
let (_dcol, columnar) = make_columnar(&cols); let (_dcol, columnar) = make_columnar(&cols);
let (_dsparse, sparse) = make_sparse(&cols); let (_dsparse, sparse) = make_sparse(&cols);
let groups = [ColGroup::new("g1", vec![0, 1]), ColGroup::new("g2", vec![1, 2])]; let groups = [
ColGroup::new("g1", vec![0, 1]),
ColGroup::new("g2", vec![1, 2]),
];
let threshold = 2; let threshold = 2;
// g1={0,1}: presence_count, sum, min, max per row. // g1={0,1}: presence_count, sum, min, max per row.
@@ -78,15 +81,47 @@ fn batch_int_group_stats_matches_hand_computed_for_columnar_and_sparse() {
assert_eq!(stats.len(), 2, "{label}: wrong number of groups"); assert_eq!(stats.len(), 2, "{label}: wrong number of groups");
for row in 0..4 { for row in 0..4 {
assert_eq!(stats[0].presence_count.get(row), g1_presence[row], "{label}: g1 presence row {row}"); assert_eq!(
assert_eq!(stats[0].sum.get(row) as u64, g1_sum[row], "{label}: g1 sum row {row}"); stats[0].presence_count.get(row),
assert_eq!(stats[0].min.get(row), g1_min[row], "{label}: g1 min row {row}"); g1_presence[row],
assert_eq!(stats[0].max.get(row), g1_max[row], "{label}: g1 max row {row}"); "{label}: g1 presence row {row}"
);
assert_eq!(
stats[0].sum.get(row) as u64,
g1_sum[row],
"{label}: g1 sum row {row}"
);
assert_eq!(
stats[0].min.get(row),
g1_min[row],
"{label}: g1 min row {row}"
);
assert_eq!(
stats[0].max.get(row),
g1_max[row],
"{label}: g1 max row {row}"
);
assert_eq!(stats[1].presence_count.get(row), g2_presence[row], "{label}: g2 presence row {row}"); assert_eq!(
assert_eq!(stats[1].sum.get(row) as u64, g2_sum[row], "{label}: g2 sum row {row}"); stats[1].presence_count.get(row),
assert_eq!(stats[1].min.get(row), g2_min[row], "{label}: g2 min row {row}"); g2_presence[row],
assert_eq!(stats[1].max.get(row), g2_max[row], "{label}: g2 max row {row}"); "{label}: g2 presence row {row}"
);
assert_eq!(
stats[1].sum.get(row) as u64,
g2_sum[row],
"{label}: g2 sum row {row}"
);
assert_eq!(
stats[1].min.get(row),
g2_min[row],
"{label}: g2 min row {row}"
);
assert_eq!(
stats[1].max.get(row),
g2_max[row],
"{label}: g2 max row {row}"
);
} }
} }
} }
+37 -8
View File
@@ -687,7 +687,9 @@ fn intslice_view_collect_slots_values() {
/// Naive per-column `count(v >= threshold)` over column-major `data`. /// Naive per-column `count(v >= threshold)` over column-major `data`.
fn naive_count_geq(data: &[&[u32]], threshold: u32) -> Vec<u64> { fn naive_count_geq(data: &[&[u32]], threshold: u32) -> Vec<u64> {
data.iter().map(|col| col.iter().filter(|&&v| v >= threshold).count() as u64).collect() 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. /// Thresholds straddling 0, 1, the primary-byte limit (255) and the overflow values.
@@ -699,7 +701,11 @@ fn count_geq_columnar_matches_naive() {
let (_d, m) = make_matrix(data); let (_d, m) = make_matrix(data);
assert_eq!(m.storage_kind(), StorageKind::Columnar); assert_eq!(m.storage_kind(), StorageKind::Columnar);
for t in GEQ_THRESHOLDS { for t in GEQ_THRESHOLDS {
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}"); assert_eq!(
ColumnWeights::count_geq(&m, t).to_vec(),
naive_count_geq(data, t),
"threshold {t}"
);
} }
} }
@@ -711,7 +717,11 @@ fn count_geq_packed_matches_naive() {
let m = PersistentIntMatrix::open(dir.path()).unwrap(); let m = PersistentIntMatrix::open(dir.path()).unwrap();
assert_eq!(m.storage_kind(), StorageKind::Packed); assert_eq!(m.storage_kind(), StorageKind::Packed);
for t in GEQ_THRESHOLDS { for t in GEQ_THRESHOLDS {
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}"); assert_eq!(
ColumnWeights::count_geq(&m, t).to_vec(),
naive_count_geq(data, t),
"threshold {t}"
);
} }
} }
@@ -723,7 +733,11 @@ fn count_geq_sparse_enum_matches_naive() {
let m = PersistentIntMatrix::open(dir.path()).unwrap(); let m = PersistentIntMatrix::open(dir.path()).unwrap();
assert_eq!(m.storage_kind(), StorageKind::Sparse); assert_eq!(m.storage_kind(), StorageKind::Sparse);
for t in GEQ_THRESHOLDS { for t in GEQ_THRESHOLDS {
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}"); assert_eq!(
ColumnWeights::count_geq(&m, t).to_vec(),
naive_count_geq(data, t),
"threshold {t}"
);
} }
} }
@@ -732,7 +746,10 @@ fn partial_kmer_counts_is_count_geq_one() {
let data: &[&[u32]] = &[&[0, 1, 2, 300], &[5, 0, 0, 0]]; let data: &[&[u32]] = &[&[0, 1, 2, 300], &[5, 0, 0, 0]];
let (_d, m) = make_matrix(data); 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(), m.count_nonzero().to_vec());
assert_eq!(m.partial_kmer_counts().to_vec(), ColumnWeights::count_geq(&m, 1).to_vec()); assert_eq!(
m.partial_kmer_counts().to_vec(),
ColumnWeights::count_geq(&m, 1).to_vec()
);
} }
#[test] #[test]
@@ -767,7 +784,11 @@ const HIST_DATA: &[&[u32]] = &[
fn row_presence_histogram_columnar_matches_naive() { fn row_presence_histogram_columnar_matches_naive() {
let (_d, m) = make_matrix(HIST_DATA); let (_d, m) = make_matrix(HIST_DATA);
for t in GEQ_THRESHOLDS { for t in GEQ_THRESHOLDS {
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}"); assert_eq!(
m.row_presence_histogram(t).unwrap(),
naive_row_hist(HIST_DATA, t),
"threshold {t}"
);
} }
} }
@@ -778,7 +799,11 @@ fn row_presence_histogram_packed_matches_naive() {
let m = PersistentIntMatrix::open(dir.path()).unwrap(); let m = PersistentIntMatrix::open(dir.path()).unwrap();
assert_eq!(m.storage_kind(), StorageKind::Packed); assert_eq!(m.storage_kind(), StorageKind::Packed);
for t in GEQ_THRESHOLDS { for t in GEQ_THRESHOLDS {
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}"); assert_eq!(
m.row_presence_histogram(t).unwrap(),
naive_row_hist(HIST_DATA, t),
"threshold {t}"
);
} }
} }
@@ -789,7 +814,11 @@ fn row_presence_histogram_sparse_matches_naive() {
let m = PersistentIntMatrix::open(dir.path()).unwrap(); let m = PersistentIntMatrix::open(dir.path()).unwrap();
assert_eq!(m.storage_kind(), StorageKind::Sparse); assert_eq!(m.storage_kind(), StorageKind::Sparse);
for t in GEQ_THRESHOLDS { for t in GEQ_THRESHOLDS {
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}"); assert_eq!(
m.row_presence_histogram(t).unwrap(),
naive_row_hist(HIST_DATA, t),
"threshold {t}"
);
} }
} }
+8 -2
View File
@@ -80,9 +80,15 @@ fn add_mem_col_matrix_reads_back() {
for presence in [true, false] { for presence in [true, false] {
let n = 100; let n = 100;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let data = dir.path().join(if presence { "presence" } else { "counts" }); let data = dir
.path()
.join(if presence { "presence" } else { "counts" });
let value = |c: usize, slot: usize| -> u32 { let value = |c: usize, slot: usize| -> u32 {
if (slot + c).is_multiple_of(3) { (slot * 7 + c) as u32 % 400 + 1 } else { 0 } if (slot + c).is_multiple_of(3) {
(slot * 7 + c) as u32 % 400 + 1
} else {
0
}
}; };
let mut mb = MatrixBuilder::new(presence, n, &data).unwrap(); let mut mb = MatrixBuilder::new(presence, n, &data).unwrap();
+30 -8
View File
@@ -118,7 +118,14 @@ fn sparse_index_built_for_many_overflows() {
#[test] #[test]
fn iter_matches_get() { fn iter_matches_get() {
let values = [(0usize, 255u32), (1, 1000), (2, 50), (3, 1_313_691), (4, 7), (5, 42)]; let values = [
(0usize, 255u32),
(1, 1000),
(2, 50),
(3, 1_313_691),
(4, 7),
(5, 42),
];
let n = 6; let n = 6;
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("test.pciv"); let path = dir.path().join("test.pciv");
@@ -168,7 +175,10 @@ fn build_from_roundtrip() {
let (_dir_a, ra) = make_pciv(&a); let (_dir_a, ra) = make_pciv(&a);
let dir_b = tempdir().unwrap(); let dir_b = tempdir().unwrap();
let path_b = dir_b.path().join("b.pciv"); let path_b = dir_b.path().join("b.pciv");
PersistentCompactIntVecBuilder::build_from(&ra, &path_b).unwrap().close().unwrap(); PersistentCompactIntVecBuilder::build_from(&ra, &path_b)
.unwrap()
.close()
.unwrap();
let rb = PersistentCompactIntVec::open(&path_b).unwrap(); let rb = PersistentCompactIntVec::open(&path_b).unwrap();
assert_eq!(ra.iter().collect::<Vec<_>>(), rb.iter().collect::<Vec<_>>()); assert_eq!(ra.iter().collect::<Vec<_>>(), rb.iter().collect::<Vec<_>>());
} }
@@ -354,14 +364,18 @@ fn partial_dists_bulk_path_matches_naive_reference_with_overflow() {
let naive_bray: u64 = a.iter().zip(&b).map(|(&x, &y)| x.min(y) as u64).sum(); let naive_bray: u64 = a.iter().zip(&b).map(|(&x, &y)| x.min(y) as u64).sum();
assert_eq!(ra.partial_bray_dist(&rb), naive_bray); assert_eq!(ra.partial_bray_dist(&rb), naive_bray);
let naive_euclidean: f64 = a.iter().zip(&b) let naive_euclidean: f64 = a
.map(|(&x, &y)| { let d = x as f64 - y as f64; d * d }) .iter()
.zip(&b)
.map(|(&x, &y)| {
let d = x as f64 - y as f64;
d * d
})
.sum(); .sum();
assert!((ra.partial_euclidean_dist(&rb) - naive_euclidean).abs() < 1e-9); assert!((ra.partial_euclidean_dist(&rb) - naive_euclidean).abs() < 1e-9);
for threshold in [1u32, 6, 255, 600] { for threshold in [1u32, 6, 255, 600] {
let (naive_inter, naive_union) = a.iter().zip(&b) let (naive_inter, naive_union) = a.iter().zip(&b).fold((0u64, 0u64), |(i, u), (&x, &y)| {
.fold((0u64, 0u64), |(i, u), (&x, &y)| {
let xp = x >= threshold; let xp = x >= threshold;
let yp = y >= threshold; let yp = y >= threshold;
(i + (xp & yp) as u64, u + (xp | yp) as u64) (i + (xp & yp) as u64, u + (xp | yp) as u64)
@@ -379,13 +393,21 @@ fn mixed_large_dataset() {
let path = dir.path().join("test.pciv"); let path = dir.path().join("test.pciv");
let mut b = PersistentCompactIntVecBuilder::new(n, &path).unwrap(); let mut b = PersistentCompactIntVecBuilder::new(n, &path).unwrap();
for i in 0..n { for i in 0..n {
let v = if i % 100 == 0 { 100_000 + i as u32 } else { i as u32 % 200 }; let v = if i % 100 == 0 {
100_000 + i as u32
} else {
i as u32 % 200
};
b.set(i, v); b.set(i, v);
} }
b.close().unwrap(); b.close().unwrap();
let r = PersistentCompactIntVec::open(&path).unwrap(); let r = PersistentCompactIntVec::open(&path).unwrap();
for i in 0..n { for i in 0..n {
let expected = if i % 100 == 0 { 100_000 + i as u32 } else { i as u32 % 200 }; let expected = if i % 100 == 0 {
100_000 + i as u32
} else {
i as u32 % 200
};
assert_eq!(r.get(i), expected, "slot {i}"); assert_eq!(r.get(i), expected, "slot {i}");
} }
} }
+27 -7
View File
@@ -19,11 +19,21 @@ fn naive_rank1(bits: &[bool], pos: usize) -> u64 {
} }
fn naive_select1(bits: &[bool], k: u64) -> usize { fn naive_select1(bits: &[bool], k: u64) -> usize {
bits.iter().enumerate().filter(|&(_, &b)| b).nth(k as usize).unwrap().0 bits.iter()
.enumerate()
.filter(|&(_, &b)| b)
.nth(k as usize)
.unwrap()
.0
} }
fn naive_select0(bits: &[bool], k: u64) -> usize { fn naive_select0(bits: &[bool], k: u64) -> usize {
bits.iter().enumerate().filter(|&(_, &b)| !b).nth(k as usize).unwrap().0 bits.iter()
.enumerate()
.filter(|&(_, &b)| !b)
.nth(k as usize)
.unwrap()
.0
} }
#[test] #[test]
@@ -45,7 +55,9 @@ fn count_ones_matches_naive() {
#[test] #[test]
fn rank1_matches_naive_small() { fn rank1_matches_naive_small() {
let bits = [true, false, true, true, false, false, true, true, false, true]; let bits = [
true, false, true, true, false, false, true, true, false, true,
];
let (_dir, r) = build(&bits); let (_dir, r) = build(&bits);
for pos in 0..=bits.len() { for pos in 0..=bits.len() {
assert_eq!(r.rank1(pos), naive_rank1(&bits, pos), "rank1({pos})"); assert_eq!(r.rank1(pos), naive_rank1(&bits, pos), "rank1({pos})");
@@ -76,7 +88,9 @@ fn rank0_is_complement_of_rank1() {
#[test] #[test]
fn select1_matches_naive_small() { fn select1_matches_naive_small() {
let bits = [true, false, true, true, false, false, true, true, false, true]; let bits = [
true, false, true, true, false, false, true, true, false, true,
];
let (_dir, r) = build(&bits); let (_dir, r) = build(&bits);
let n_ones = bits.iter().filter(|&&b| b).count() as u64; let n_ones = bits.iter().filter(|&&b| b).count() as u64;
for k in 0..n_ones { for k in 0..n_ones {
@@ -97,7 +111,9 @@ fn select1_matches_naive_multi_block() {
#[test] #[test]
fn select0_matches_naive_small() { fn select0_matches_naive_small() {
let bits = [true, false, true, true, false, false, true, true, false, true]; let bits = [
true, false, true, true, false, false, true, true, false, true,
];
let (_dir, r) = build(&bits); let (_dir, r) = build(&bits);
let n_zeros = bits.iter().filter(|&&b| !b).count() as u64; let n_zeros = bits.iter().filter(|&&b| !b).count() as u64;
for k in 0..n_zeros { for k in 0..n_zeros {
@@ -191,8 +207,12 @@ fn select1_run_of_ten_then_gap_then_run() {
// Mirrors the exact bit pattern from the failing EliasFano case: // Mirrors the exact bit pattern from the failing EliasFano case:
// positions 0..=9 set, 10 clear, 11..=20 set. // positions 0..=9 set, 10 clear, 11..=20 set.
let mut bits = vec![false; 30]; let mut bits = vec![false; 30];
for p in 0..=9 { bits[p] = true; } for p in 0..=9 {
for p in 11..=20 { bits[p] = true; } bits[p] = true;
}
for p in 11..=20 {
bits[p] = true;
}
let (_dir, r) = build(&bits); let (_dir, r) = build(&bits);
assert_eq!(r.select1(9), 9, "select1(9)"); assert_eq!(r.select1(9), 9, "select1(9)");
assert_eq!(r.select1(10), 11, "select1(10)"); assert_eq!(r.select1(10), 11, "select1(10)");
+82 -24
View File
@@ -1,6 +1,9 @@
use tempfile::tempdir; use tempfile::tempdir;
use crate::{pack_bit_matrix, pack_sparse_bit_matrix, BinaryMatrix, PersistentBitMatrix, PersistentBitMatrixBuilder, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder}; use crate::{
BinaryMatrix, PersistentBitMatrix, PersistentBitMatrixBuilder, PersistentSparseBitMatrix,
PersistentSparseBitMatrixBuilder, pack_bit_matrix, pack_sparse_bit_matrix,
};
/// Builds a dense `PersistentBitMatrix` from column-major `bool` data — /// Builds a dense `PersistentBitMatrix` from column-major `bool` data —
/// mirrors `tests/bitmatrix.rs`'s own `make_matrix` helper. /// mirrors `tests/bitmatrix.rs`'s own `make_matrix` helper.
@@ -98,7 +101,8 @@ fn dense_to_sparse_matches_dense_on_real_shaped_data() {
assert_eq!(sparse.n_cols(), dense.n_cols()); assert_eq!(sparse.n_cols(), dense.n_cols());
for slot in 0..dense.n() { for slot in 0..dense.n() {
assert_eq!( assert_eq!(
row_as_bool(&sparse, slot), &*dense.row(slot), row_as_bool(&sparse, slot),
&*dense.row(slot),
"slot {slot}: dense vs sparse disagree" "slot {slot}: dense vs sparse disagree"
); );
} }
@@ -262,7 +266,11 @@ fn binary_matrix_trait_interchangeable_dense_and_sparse() {
assert_eq!(BinaryMatrix::n(&dense), BinaryMatrix::n(&sparse)); assert_eq!(BinaryMatrix::n(&dense), BinaryMatrix::n(&sparse));
assert_eq!(BinaryMatrix::n_cols(&dense), BinaryMatrix::n_cols(&sparse)); assert_eq!(BinaryMatrix::n_cols(&dense), BinaryMatrix::n_cols(&sparse));
for slot in 0..BinaryMatrix::n(&dense) { for slot in 0..BinaryMatrix::n(&dense) {
assert_eq!(sum_via_trait(&dense, slot), sum_via_trait(&sparse, slot), "slot {slot}"); assert_eq!(
sum_via_trait(&dense, slot),
sum_via_trait(&sparse, slot),
"slot {slot}"
);
} }
let dense_counts = BinaryMatrix::count_ones(&dense); let dense_counts = BinaryMatrix::count_ones(&dense);
let sparse_counts = BinaryMatrix::count_ones(&sparse); let sparse_counts = BinaryMatrix::count_ones(&sparse);
@@ -279,11 +287,26 @@ fn reopen_large_real_shaped_data_with_heavy_dedup() {
.map(|i| { .map(|i| {
let mut row = vec![false; n_cols]; let mut row = vec![false; n_cols];
match i % 5 { match i % 5 {
0 => { row[i % n_cols] = true; } // singleton, varies per row 0 => {
1 => { row[3] = true; row[7] = true; } // repeated multi-set A row[i % n_cols] = true;
2 => { row[3] = true; row[7] = true; } // same set A again } // singleton, varies per row
3 => { row[10] = true; row[20] = true; row[30] = true; } // repeated multi-set B 1 => {
_ => { row[(i * 13) % n_cols] = true; row[(i * 29) % n_cols] = true; } // varying pairs row[3] = true;
row[7] = true;
} // repeated multi-set A
2 => {
row[3] = true;
row[7] = true;
} // same set A again
3 => {
row[10] = true;
row[20] = true;
row[30] = true;
} // repeated multi-set B
_ => {
row[(i * 13) % n_cols] = true;
row[(i * 29) % n_cols] = true;
} // varying pairs
} }
row row
}) })
@@ -321,7 +344,10 @@ fn pack_sparse_bit_matrix_transposes_columnar_directly() {
]; ];
let (dir, dense) = make_dense(cols); let (dir, dense) = make_dense(cols);
let presence_dir = dir.path().join("presence"); let presence_dir = dir.path().join("presence");
assert!(!presence_dir.join("matrix.pbmx").exists(), "still Columnar before packing"); assert!(
!presence_dir.join("matrix.pbmx").exists(),
"still Columnar before packing"
);
let expected_rows: Vec<Box<[bool]>> = (0..dense.n()).map(|s| dense.row(s)).collect(); let expected_rows: Vec<Box<[bool]>> = (0..dense.n()).map(|s| dense.row(s)).collect();
let n_cols = dense.n_cols(); let n_cols = dense.n_cols();
@@ -330,9 +356,18 @@ fn pack_sparse_bit_matrix_transposes_columnar_directly() {
pack_sparse_bit_matrix(&presence_dir).unwrap(); pack_sparse_bit_matrix(&presence_dir).unwrap();
assert!(presence_dir.join("is_multi.prsb").exists()); assert!(presence_dir.join("is_multi.prsb").exists());
assert!(!presence_dir.join("meta.json").exists(), "columnar meta.json cleaned up"); assert!(
assert!(!presence_dir.join("col_000000.pbiv").exists(), "columnar column files cleaned up"); !presence_dir.join("meta.json").exists(),
assert!(!presence_dir.join("matrix.pbmx").exists(), "never materialised"); "columnar meta.json cleaned up"
);
assert!(
!presence_dir.join("col_000000.pbiv").exists(),
"columnar column files cleaned up"
);
assert!(
!presence_dir.join("matrix.pbmx").exists(),
"never materialised"
);
let sparse = PersistentSparseBitMatrix::open(&presence_dir).unwrap(); let sparse = PersistentSparseBitMatrix::open(&presence_dir).unwrap();
assert_eq!(sparse.n(), expected_rows.len()); assert_eq!(sparse.n(), expected_rows.len());
@@ -350,10 +385,7 @@ fn pack_sparse_bit_matrix_transposes_columnar_directly() {
/// still used as the transpose source and cleaned up afterward. /// still used as the transpose source and cleaned up afterward.
#[test] #[test]
fn pack_sparse_bit_matrix_from_already_packed_matrix() { fn pack_sparse_bit_matrix_from_already_packed_matrix() {
let cols: &[&[bool]] = &[ let cols: &[&[bool]] = &[&[true, false, true], &[false, true, true]];
&[true, false, true],
&[false, true, true],
];
let (dir, dense) = make_dense(cols); let (dir, dense) = make_dense(cols);
let presence_dir = dir.path().join("presence"); let presence_dir = dir.path().join("presence");
let expected_rows: Vec<Box<[bool]>> = (0..dense.n()).map(|s| dense.row(s)).collect(); let expected_rows: Vec<Box<[bool]>> = (0..dense.n()).map(|s| dense.row(s)).collect();
@@ -364,7 +396,10 @@ fn pack_sparse_bit_matrix_from_already_packed_matrix() {
assert!(presence_dir.join("matrix.pbmx").exists()); assert!(presence_dir.join("matrix.pbmx").exists());
pack_sparse_bit_matrix(&presence_dir).unwrap(); pack_sparse_bit_matrix(&presence_dir).unwrap();
assert!(!presence_dir.join("matrix.pbmx").exists(), "packed intermediate cleaned up"); assert!(
!presence_dir.join("matrix.pbmx").exists(),
"packed intermediate cleaned up"
);
let sparse = PersistentSparseBitMatrix::open(&presence_dir).unwrap(); let sparse = PersistentSparseBitMatrix::open(&presence_dir).unwrap();
assert_eq!(sparse.n_cols(), n_cols); assert_eq!(sparse.n_cols(), n_cols);
@@ -395,7 +430,9 @@ fn partial_jaccard_and_hamming_match_dense_including_diagonal() {
let (dir_dense, dense) = make_dense(cols); let (dir_dense, dense) = make_dense(cols);
let n = cols.first().unwrap().len(); let n = cols.first().unwrap().len();
let n_cols = cols.len(); let n_cols = cols.len();
let rows: Vec<Vec<bool>> = (0..n).map(|s| cols.iter().map(|c| c[s]).collect()).collect(); let rows: Vec<Vec<bool>> = (0..n)
.map(|s| cols.iter().map(|c| c[s]).collect())
.collect();
let row_refs: Vec<&[bool]> = rows.iter().map(|r| r.as_slice()).collect(); let row_refs: Vec<&[bool]> = rows.iter().map(|r| r.as_slice()).collect();
let (dir_sparse, sparse) = make_sparse(&row_refs, n_cols); let (dir_sparse, sparse) = make_sparse(&row_refs, n_cols);
@@ -409,7 +446,11 @@ fn partial_jaccard_and_hamming_match_dense_including_diagonal() {
assert_eq!(dense_hamming, sparse_hamming, "partial_hamming"); assert_eq!(dense_hamming, sparse_hamming, "partial_hamming");
for i in 0..n_cols { for i in 0..n_cols {
assert_eq!(sparse_hamming[[i, i]], 0, "hamming self-distance must be 0, col {i}"); assert_eq!(
sparse_hamming[[i, i]],
0,
"hamming self-distance must be 0, col {i}"
);
} }
drop(dir_dense); drop(dir_dense);
@@ -440,17 +481,29 @@ fn build_permuted_follows_the_permutation() {
assert_eq!(permuted.n(), src.n()); assert_eq!(permuted.n(), src.n());
assert_eq!(permuted.n_cols(), src.n_cols()); assert_eq!(permuted.n_cols(), src.n_cols());
for (new, &old) in new_to_old.iter().enumerate() { for (new, &old) in new_to_old.iter().enumerate() {
assert_eq!(row_as_bool(&permuted, new), row_as_bool(&src, old as usize), "new row {new}"); assert_eq!(
row_as_bool(&permuted, new),
row_as_bool(&src, old as usize),
"new row {new}"
);
} }
} }
#[test] #[test]
fn sparse_count_geq_ignores_threshold() { fn sparse_count_geq_ignores_threshold() {
use crate::traits::ColumnWeights; use crate::traits::ColumnWeights;
let rows: &[&[bool]] = &[&[true, false, true], &[false, false, true], &[true, false, false]]; let rows: &[&[bool]] = &[
&[true, false, true],
&[false, false, true],
&[true, false, false],
];
let (_d, m) = make_sparse(rows, 3); let (_d, m) = make_sparse(rows, 3);
for t in [0u32, 1, 2, 100] { for t in [0u32, 1, 2, 100] {
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), vec![2, 0, 2], "threshold {t}"); assert_eq!(
ColumnWeights::count_geq(&m, t).to_vec(),
vec![2, 0, 2],
"threshold {t}"
);
} }
} }
@@ -462,11 +515,16 @@ fn sparse_row_presence_histogram_matches_dense() {
&[true, false, true, false, false], &[true, false, true, false, false],
]; ];
let (_dd, dense) = make_dense(cols); let (_dd, dense) = make_dense(cols);
let rows: Vec<Vec<bool>> = (0..5).map(|s| cols.iter().map(|c| c[s]).collect()).collect(); 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 row_refs: Vec<&[bool]> = rows.iter().map(Vec::as_slice).collect();
let (_ds, sparse) = make_sparse(&row_refs, 3); let (_ds, sparse) = make_sparse(&row_refs, 3);
let sparse = PersistentBitMatrix::Sparse(sparse); let sparse = PersistentBitMatrix::Sparse(sparse);
assert_eq!(sparse.row_presence_histogram().unwrap(), dense.row_presence_histogram().unwrap()); assert_eq!(
sparse.row_presence_histogram().unwrap(),
dense.row_presence_histogram().unwrap()
);
// Rows carry 2, 0, 3, 1, 0 genomes. // Rows carry 2, 0, 3, 1, 0 genomes.
assert_eq!(sparse.row_presence_histogram().unwrap(), vec![2, 1, 1, 1]); assert_eq!(sparse.row_presence_histogram().unwrap(), vec![2, 1, 1, 1]);
} }
@@ -1,7 +1,7 @@
use tempfile::tempdir; use tempfile::tempdir;
use crate::{ use crate::{
ColumnWeights, PersistentIntMatrix, PersistentCompactIntMatrixBuilder, ColumnWeights, PersistentCompactIntMatrixBuilder, PersistentIntMatrix,
PersistentSparseCompactIntMatrix, PersistentSparseCompactIntMatrixBuilder, PersistentSparseCompactIntMatrix, PersistentSparseCompactIntMatrixBuilder,
pack_compact_int_matrix, pack_sparse_compact_int_matrix, pack_compact_int_matrix, pack_sparse_compact_int_matrix,
}; };
@@ -167,7 +167,11 @@ fn count_geq_matches_naive_for_every_threshold() {
} }
} }
} }
assert_eq!(m.count_geq(threshold).to_vec(), expected.to_vec(), "threshold {threshold}"); assert_eq!(
m.count_geq(threshold).to_vec(),
expected.to_vec(),
"threshold {threshold}"
);
} }
} }
@@ -81,7 +81,12 @@ fn sparse_files(dir: &Path) -> Vec<(String, Vec<u8>)> {
let n = p.file_name().unwrap().to_string_lossy().into_owned(); let n = p.file_name().unwrap().to_string_lossy().into_owned();
!(n.starts_with("col_") || n == "meta.json" || n.starts_with("matrix.")) !(n.starts_with("col_") || n == "meta.json" || n.starts_with("matrix."))
}) })
.map(|p| (p.file_name().unwrap().to_string_lossy().into_owned(), fs::read(&p).unwrap())) .map(|p| {
(
p.file_name().unwrap().to_string_lossy().into_owned(),
fs::read(&p).unwrap(),
)
})
.collect(); .collect();
v.sort(); v.sort();
v v
@@ -91,7 +96,10 @@ const WINDOWS: &[(usize, usize)] = &[
(64, usize::MAX / 4), // smallest window, never too dense (64, usize::MAX / 4), // smallest window, never too dense
(192, 50), // forces the retry-with-half-window path (192, 50), // forces the retry-with-half-window path
(4096, 10_000), // a few windows (4096, 10_000), // a few windows
(crate::transpose::DEFAULT_WINDOW_ROWS, crate::transpose::DEFAULT_MAX_HITS), (
crate::transpose::DEFAULT_WINDOW_ROWS,
crate::transpose::DEFAULT_MAX_HITS,
),
]; ];
#[test] #[test]
@@ -101,7 +109,10 @@ fn bit_columnar_transpose_is_byte_identical_to_the_dense_route() {
let ref_dir = ref_root.path().join("presence"); let ref_dir = ref_root.path().join("presence");
pack_bit_matrix(&ref_dir).unwrap(); pack_bit_matrix(&ref_dir).unwrap();
let dense = PersistentBitMatrix::open(ref_root.path()).unwrap(); let dense = PersistentBitMatrix::open(ref_root.path()).unwrap();
PersistentSparseBitMatrixBuilder::build_from_dense(&dense, &ref_dir).unwrap().close().unwrap(); PersistentSparseBitMatrixBuilder::build_from_dense(&dense, &ref_dir)
.unwrap()
.close()
.unwrap();
drop(dense); drop(dense);
let expected = sparse_files(&ref_dir); let expected = sparse_files(&ref_dir);
assert!(!expected.is_empty()); assert!(!expected.is_empty());
@@ -115,7 +126,11 @@ fn bit_columnar_transpose_is_byte_identical_to_the_dense_route() {
.unwrap() .unwrap()
.close() .close()
.unwrap(); .unwrap();
assert_eq!(sparse_files(&dir), expected, "window={window} max_hits={max_hits}"); assert_eq!(
sparse_files(&dir),
expected,
"window={window} max_hits={max_hits}"
);
} }
} }
@@ -126,7 +141,10 @@ fn int_columnar_transpose_is_byte_identical_to_the_dense_route() {
let ref_dir = ref_root.path().join("counts"); let ref_dir = ref_root.path().join("counts");
pack_compact_int_matrix(&ref_dir).unwrap(); pack_compact_int_matrix(&ref_dir).unwrap();
let dense = PersistentIntMatrix::open(ref_root.path()).unwrap(); let dense = PersistentIntMatrix::open(ref_root.path()).unwrap();
PersistentSparseCompactIntMatrixBuilder::build_from_dense(&dense, &ref_dir).unwrap().close().unwrap(); PersistentSparseCompactIntMatrixBuilder::build_from_dense(&dense, &ref_dir)
.unwrap()
.close()
.unwrap();
drop(dense); drop(dense);
let expected = sparse_files(&ref_dir); let expected = sparse_files(&ref_dir);
assert!(!expected.is_empty()); assert!(!expected.is_empty());
@@ -136,11 +154,17 @@ fn int_columnar_transpose_is_byte_identical_to_the_dense_route() {
build_ints(root.path()); build_ints(root.path());
let dir = root.path().join("counts"); let dir = root.path().join("counts");
let meta = MatrixMeta::load(&dir).unwrap(); let meta = MatrixMeta::load(&dir).unwrap();
PersistentSparseCompactIntMatrixBuilder::build_from_columnar_with(&dir, &meta, window, max_hits) PersistentSparseCompactIntMatrixBuilder::build_from_columnar_with(
&dir, &meta, window, max_hits,
)
.unwrap() .unwrap()
.close() .close()
.unwrap(); .unwrap();
assert_eq!(sparse_files(&dir), expected, "window={window} max_hits={max_hits}"); assert_eq!(
sparse_files(&dir),
expected,
"window={window} max_hits={max_hits}"
);
} }
} }
@@ -151,6 +175,8 @@ fn columnar_transpose_rejects_a_column_of_another_length() {
let dir = root.path().join("presence"); let dir = root.path().join("presence");
let mut meta = MatrixMeta::load(&dir).unwrap(); let mut meta = MatrixMeta::load(&dir).unwrap();
meta.n += 64; // metadata claims more rows than the column files hold meta.n += 64; // metadata claims more rows than the column files hold
let err = PersistentSparseBitMatrixBuilder::build_from_columnar(&dir, &meta).err().expect("must fail"); let err = PersistentSparseBitMatrixBuilder::build_from_columnar(&dir, &meta)
.err()
.expect("must fail");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
} }
+19 -2
View File
@@ -40,11 +40,28 @@ fn for_each_set_in_matches_get_loop_on_all_boundaries() {
} }
} }
let v = BitSliceView::new(&w, n); let v = BitSliceView::new(&w, n);
let cuts = [0, 1, 63, 64, 65, 100, 127, 128, 129, n / 2, n.saturating_sub(1), n]; let cuts = [
0,
1,
63,
64,
65,
100,
127,
128,
129,
n / 2,
n.saturating_sub(1),
n,
];
for &a in &cuts { for &a in &cuts {
for &b in &cuts { for &b in &cuts {
if a <= n && b <= n { if a <= n && b <= n {
assert_eq!(scanned(&v, a..b), naive(&v, a..b), "n={n} seed={seed} thin={thin} range={a}..{b}"); assert_eq!(
scanned(&v, a..b),
naive(&v, a..b),
"n={n} seed={seed} thin={thin} range={a}..{b}"
);
} }
} }
} }
+23 -9
View File
@@ -44,8 +44,11 @@ pub trait BinaryMatrix {
fn jaccard_to_mash(d_jaccard: &Array2<f64>, k: usize) -> Array2<f64> { fn jaccard_to_mash(d_jaccard: &Array2<f64>, k: usize) -> Array2<f64> {
d_jaccard.mapv(|d| { d_jaccard.mapv(|d| {
let j = 1.0 - d; let j = 1.0 - d;
if j <= 0.0 { 1.0 } if j <= 0.0 {
else { -1.0 / k as f64 * (2.0 * j / (1.0 + j)).ln() } 1.0
} else {
-1.0 / k as f64 * (2.0 * j / (1.0 + j)).ln()
}
}) })
} }
@@ -98,8 +101,11 @@ pub trait CountPartials: ColumnWeights {
for j in 0..n { for j in 0..n {
if i != j { if i != j {
let d = w[i] + w[j]; let d = w[i] + w[j];
m[[i, j]] = if d == 0 { 0.0 } m[[i, j]] = if d == 0 {
else { 1.0 - 2.0 * sum_min[[i, j]] as f64 / d as f64 }; 0.0
} else {
1.0 - 2.0 * sum_min[[i, j]] as f64 / d as f64
};
} }
} }
} }
@@ -122,8 +128,11 @@ pub trait CountPartials: ColumnWeights {
for j in 0..n { for j in 0..n {
if i != j { if i != j {
let u = union[[i, j]]; let u = union[[i, j]];
m[[i, j]] = if u == 0 { 0.0 } m[[i, j]] = if u == 0 {
else { 1.0 - inter[[i, j]] as f64 / u as f64 }; 0.0
} else {
1.0 - inter[[i, j]] as f64 / u as f64
};
} }
} }
} }
@@ -150,7 +159,9 @@ pub trait CountPartials: ColumnWeights {
let global = self.col_weights(); let global = self.col_weights();
let mut m = self.partial_relfreq_bray(&global).mapv(|v| 1.0 - v); let mut m = self.partial_relfreq_bray(&global).mapv(|v| 1.0 - v);
let n = m.shape()[0]; let n = m.shape()[0];
for i in 0..n { m[[i, i]] = 0.0; } for i in 0..n {
m[[i, i]] = 0.0;
}
m m
} }
@@ -190,8 +201,11 @@ pub trait BitPartials: ColumnWeights {
for j in 0..n { for j in 0..n {
if i != j { if i != j {
let u = union[[i, j]]; let u = union[[i, j]];
m[[i, j]] = if u == 0 { 0.0 } m[[i, j]] = if u == 0 {
else { 1.0 - inter[[i, j]] as f64 / u as f64 }; 0.0
} else {
1.0 - inter[[i, j]] as f64 / u as f64
};
} }
} }
} }
+5 -1
View File
@@ -39,7 +39,11 @@ pub(crate) struct RowBatch<V> {
impl<V: Copy> RowBatch<V> { impl<V: Copy> RowBatch<V> {
fn new() -> Self { fn new() -> Self {
Self { offsets: Vec::new(), cols: Vec::new(), vals: Vec::new() } Self {
offsets: Vec::new(),
cols: Vec::new(),
vals: Vec::new(),
}
} }
/// Number of rows in the window. /// Number of rows in the window.
+177 -49
View File
@@ -12,14 +12,22 @@ pub struct BitSliceView<'a> {
impl<'a> BitSliceView<'a> { impl<'a> BitSliceView<'a> {
#[inline] #[inline]
pub fn new(words: &'a [u64], n: usize) -> Self { Self { words, n } } pub fn new(words: &'a [u64], n: usize) -> Self {
Self { words, n }
}
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
#[inline] #[inline]
pub fn words(&self) -> &'a [u64] { self.words } pub fn words(&self) -> &'a [u64] {
self.words
}
#[inline] #[inline]
pub fn get(&self, slot: usize) -> bool { pub fn get(&self, slot: usize) -> bool {
@@ -39,7 +47,9 @@ impl<'a> BitSliceView<'a> {
pub fn fill_slots_values(&self, slots: &[usize], out: &mut [bool]) { pub fn fill_slots_values(&self, slots: &[usize], out: &mut [bool]) {
assert_eq!(slots.len(), out.len()); assert_eq!(slots.len(), out.len());
let n = slots.len(); let n = slots.len();
if n == 0 { return; } if n == 0 {
return;
}
let mut perm: Vec<usize> = (0..n).collect(); let mut perm: Vec<usize> = (0..n).collect();
perm.sort_by_key(|&i| slots[i]); perm.sort_by_key(|&i| slots[i]);
let sorted: Vec<usize> = perm.iter().map(|&i| slots[i]).collect(); let sorted: Vec<usize> = perm.iter().map(|&i| slots[i]).collect();
@@ -53,11 +63,17 @@ impl<'a> BitSliceView<'a> {
/// locality (see `enumerate_nonzero_slots`), so this takes `slots` as /// locality (see `enumerate_nonzero_slots`), so this takes `slots` as
/// given. /// given.
#[inline] #[inline]
pub fn enumerate_slots_values<'b>(self, slots: &'b [usize]) -> impl Iterator<Item = (usize, bool)> + 'b pub fn enumerate_slots_values<'b>(
self,
slots: &'b [usize],
) -> impl Iterator<Item = (usize, bool)> + 'b
where where
Self: 'b, Self: 'b,
{ {
slots.iter().enumerate().map(move |(pos, &slot)| (pos, self.get(slot))) slots
.iter()
.enumerate()
.map(move |(pos, &slot)| (pos, self.get(slot)))
} }
/// `(position in slots, 1)` for every slot whose bit is set — the value /// `(position in slots, 1)` for every slot whose bit is set — the value
@@ -69,39 +85,60 @@ impl<'a> BitSliceView<'a> {
/// several columns over the same slot set sort it once beforehand /// several columns over the same slot set sort it once beforehand
/// purely for cache-friendlier `get` access (see /// purely for cache-friendlier `get` access (see
/// `PersistentBitMatrix::nonzero_iter`). /// `PersistentBitMatrix::nonzero_iter`).
pub fn enumerate_nonzero_slots<'b>(self, slots: &'b [usize]) -> impl Iterator<Item = (usize, u32)> + 'b pub fn enumerate_nonzero_slots<'b>(
self,
slots: &'b [usize],
) -> impl Iterator<Item = (usize, u32)> + 'b
where where
Self: 'b, Self: 'b,
{ {
self.enumerate_slots_values(slots).filter_map(|(pos, v)| v.then_some((pos, 1u32))) self.enumerate_slots_values(slots)
.filter_map(|(pos, v)| v.then_some((pos, 1u32)))
} }
pub fn count_ones(&self) -> u64 { pub fn count_ones(&self) -> u64 {
self.words.iter().map(|w| w.count_ones() as u64).sum() self.words.iter().map(|w| w.count_ones() as u64).sum()
} }
pub fn count_zeros(&self) -> u64 { self.n as u64 - self.count_ones() } pub fn count_zeros(&self) -> u64 {
self.n as u64 - self.count_ones()
}
#[inline] #[inline]
pub fn iter(&self) -> BitSliceIter<'a> { pub fn iter(&self) -> BitSliceIter<'a> {
BitSliceIter { words: self.words, slot: 0, n: self.n } BitSliceIter {
words: self.words,
slot: 0,
n: self.n,
}
} }
pub fn partial_jaccard_dist(self, other: BitSliceView<'_>) -> (u64, u64) { pub fn partial_jaccard_dist(self, other: BitSliceView<'_>) -> (u64, u64) {
assert_eq!(self.n, other.n, "BitSliceView length mismatch"); assert_eq!(self.n, other.n, "BitSliceView length mismatch");
self.words.iter().zip(other.words) self.words
.iter()
.zip(other.words)
.fold((0u64, 0u64), |(i, u), (&a, &b)| { .fold((0u64, 0u64), |(i, u), (&a, &b)| {
(i + (a & b).count_ones() as u64, u + (a | b).count_ones() as u64) (
i + (a & b).count_ones() as u64,
u + (a | b).count_ones() as u64,
)
}) })
} }
pub fn jaccard_dist(self, other: BitSliceView<'_>) -> f64 { pub fn jaccard_dist(self, other: BitSliceView<'_>) -> f64 {
let (inter, union) = self.partial_jaccard_dist(other); let (inter, union) = self.partial_jaccard_dist(other);
if union == 0 { 0.0 } else { 1.0 - inter as f64 / union as f64 } if union == 0 {
0.0
} else {
1.0 - inter as f64 / union as f64
}
} }
pub fn hamming_dist(self, other: BitSliceView<'_>) -> u64 { pub fn hamming_dist(self, other: BitSliceView<'_>) -> u64 {
assert_eq!(self.n, other.n, "BitSliceView length mismatch"); assert_eq!(self.n, other.n, "BitSliceView length mismatch");
self.words.iter().zip(other.words) self.words
.iter()
.zip(other.words)
.map(|(&a, &b)| (a ^ b).count_ones() as u64) .map(|(&a, &b)| (a ^ b).count_ones() as u64)
.sum() .sum()
} }
@@ -119,7 +156,9 @@ impl Iterator for BitSliceIter<'_> {
type Item = bool; type Item = bool;
#[inline] #[inline]
fn next(&mut self) -> Option<bool> { fn next(&mut self) -> Option<bool> {
if self.slot >= self.n { return None; } if self.slot >= self.n {
return None;
}
let v = (self.words[self.slot >> 6] >> (self.slot & 63)) & 1 != 0; let v = (self.words[self.slot >> 6] >> (self.slot & 63)) & 1 != 0;
self.slot += 1; self.slot += 1;
Some(v) Some(v)
@@ -147,17 +186,30 @@ pub struct IntSliceView<'a> {
impl<'a> IntSliceView<'a> { impl<'a> IntSliceView<'a> {
#[inline] #[inline]
pub fn new(primary: &'a [u8], overflow_raw: &'a [u8], n_overflow: usize, n: usize) -> Self { pub fn new(primary: &'a [u8], overflow_raw: &'a [u8], n_overflow: usize, n: usize) -> Self {
Self { primary, overflow_raw, n_overflow, n } Self {
primary,
overflow_raw,
n_overflow,
n,
}
} }
#[inline] #[inline]
pub fn len(&self) -> usize { self.n } pub fn len(&self) -> usize {
self.n
}
#[inline] #[inline]
pub fn is_empty(&self) -> bool { self.n == 0 } pub fn is_empty(&self) -> bool {
self.n == 0
}
#[inline] #[inline]
pub fn primary_bytes(&self) -> &'a [u8] { self.primary } pub fn primary_bytes(&self) -> &'a [u8] {
self.primary
}
#[inline] #[inline]
pub fn n_overflow(&self) -> usize { self.n_overflow } pub fn n_overflow(&self) -> usize {
self.n_overflow
}
#[inline] #[inline]
pub fn overflow_entries(&self) -> impl Iterator<Item = (usize, u32)> + 'a { pub fn overflow_entries(&self) -> impl Iterator<Item = (usize, u32)> + 'a {
@@ -169,7 +221,9 @@ impl<'a> IntSliceView<'a> {
/// O(log n_overflow) via binary search (overflow is always sorted by slot). /// O(log n_overflow) via binary search (overflow is always sorted by slot).
pub fn get(&self, slot: usize) -> u32 { pub fn get(&self, slot: usize) -> u32 {
let b = self.primary[slot]; let b = self.primary[slot];
if b < 255 { return b as u32; } if b < 255 {
return b as u32;
}
let mut lo = 0usize; let mut lo = 0usize;
let mut hi = self.n_overflow; let mut hi = self.n_overflow;
while lo < hi { while lo < hi {
@@ -198,7 +252,9 @@ impl<'a> IntSliceView<'a> {
pub fn fill_slots_values(&self, slots: &[usize], out: &mut [u32]) { pub fn fill_slots_values(&self, slots: &[usize], out: &mut [u32]) {
assert_eq!(slots.len(), out.len()); assert_eq!(slots.len(), out.len());
let n = slots.len(); let n = slots.len();
if n == 0 { return; } if n == 0 {
return;
}
let mut perm: Vec<usize> = (0..n).collect(); let mut perm: Vec<usize> = (0..n).collect();
perm.sort_by_key(|&i| slots[i]); perm.sort_by_key(|&i| slots[i]);
let sorted: Vec<usize> = perm.iter().map(|&i| slots[i]).collect(); let sorted: Vec<usize> = perm.iter().map(|&i| slots[i]).collect();
@@ -211,21 +267,31 @@ impl<'a> IntSliceView<'a> {
/// [`BitSliceView::enumerate_slots_values`]: order never affects /// [`BitSliceView::enumerate_slots_values`]: order never affects
/// correctness here. /// correctness here.
#[inline] #[inline]
pub fn enumerate_slots_values<'b>(self, slots: &'b [usize]) -> impl Iterator<Item = (usize, u32)> + 'b pub fn enumerate_slots_values<'b>(
self,
slots: &'b [usize],
) -> impl Iterator<Item = (usize, u32)> + 'b
where where
Self: 'b, Self: 'b,
{ {
slots.iter().enumerate().map(move |(pos, &slot)| (pos, self.get(slot))) slots
.iter()
.enumerate()
.map(move |(pos, &slot)| (pos, self.get(slot)))
} }
/// Like [`BitSliceView::enumerate_nonzero_slots`]: `(position in slots, /// Like [`BitSliceView::enumerate_nonzero_slots`]: `(position in slots,
/// value)` for every nonzero value — a `filter_map` over `get`, not a /// value)` for every nonzero value — a `filter_map` over `get`, not a
/// new traversal. /// new traversal.
pub fn enumerate_nonzero_slots<'b>(self, slots: &'b [usize]) -> impl Iterator<Item = (usize, u32)> + 'b pub fn enumerate_nonzero_slots<'b>(
self,
slots: &'b [usize],
) -> impl Iterator<Item = (usize, u32)> + 'b
where where
Self: 'b, Self: 'b,
{ {
self.enumerate_slots_values(slots).filter_map(|(pos, v)| (v != 0).then_some((pos, v))) self.enumerate_slots_values(slots)
.filter_map(|(pos, v)| (v != 0).then_some((pos, v)))
} }
/// Sequential merge scan: yields all n values in slot order. /// Sequential merge scan: yields all n values in slot order.
@@ -280,7 +346,10 @@ impl<'a> IntSliceView<'a> {
pub fn partial_bray_dist(self, other: IntSliceView<'_>) -> u64 { pub fn partial_bray_dist(self, other: IntSliceView<'_>) -> u64 {
assert_eq!(self.n, other.n, "length mismatch"); assert_eq!(self.n, other.n, "length mismatch");
let term = |a: u32, b: u32| (a as u64).min(b as u64); let term = |a: u32, b: u32| (a as u64).min(b as u64);
let mut total: u64 = self.primary.iter().zip(other.primary) let mut total: u64 = self
.primary
.iter()
.zip(other.primary)
.map(|(&a, &b)| term(a as u32, b as u32)) .map(|(&a, &b)| term(a as u32, b as u32))
.sum(); .sum();
self.for_each_overflow_pair(other, |slot, a_true, b_true| { self.for_each_overflow_pair(other, |slot, a_true, b_true| {
@@ -294,12 +363,17 @@ impl<'a> IntSliceView<'a> {
pub fn bray_dist(self, other: IntSliceView<'_>) -> f64 { pub fn bray_dist(self, other: IntSliceView<'_>) -> f64 {
let sum_min = self.partial_bray_dist(other); let sum_min = self.partial_bray_dist(other);
let denom = self.sum() + other.sum(); let denom = self.sum() + other.sum();
if denom == 0 { 0.0 } else { 1.0 - 2.0 * sum_min as f64 / denom as f64 } if denom == 0 {
0.0
} else {
1.0 - 2.0 * sum_min as f64 / denom as f64
}
} }
pub fn partial_relfreq_bray_dist(self, other: IntSliceView<'_>, sa: f64, sb: f64) -> f64 { pub fn partial_relfreq_bray_dist(self, other: IntSliceView<'_>, sa: f64, sb: f64) -> f64 {
assert_eq!(self.n, other.n, "length mismatch"); assert_eq!(self.n, other.n, "length mismatch");
self.iter().zip(other.iter()) self.iter()
.zip(other.iter())
.map(|(a, b)| { .map(|(a, b)| {
let pa = if sa > 0.0 { a as f64 / sa } else { 0.0 }; let pa = if sa > 0.0 { a as f64 / sa } else { 0.0 };
let pb = if sb > 0.0 { b as f64 / sb } else { 0.0 }; let pb = if sb > 0.0 { b as f64 / sb } else { 0.0 };
@@ -311,14 +385,22 @@ impl<'a> IntSliceView<'a> {
pub fn relfreq_bray_dist(self, other: IntSliceView<'_>) -> f64 { pub fn relfreq_bray_dist(self, other: IntSliceView<'_>) -> f64 {
let sa = self.sum() as f64; let sa = self.sum() as f64;
let sb = other.sum() as f64; let sb = other.sum() as f64;
if sa == 0.0 && sb == 0.0 { return 0.0; } if sa == 0.0 && sb == 0.0 {
return 0.0;
}
1.0 - self.partial_relfreq_bray_dist(other, sa, sb) 1.0 - self.partial_relfreq_bray_dist(other, sa, sb)
} }
pub fn partial_euclidean_dist(self, other: IntSliceView<'_>) -> f64 { pub fn partial_euclidean_dist(self, other: IntSliceView<'_>) -> f64 {
assert_eq!(self.n, other.n, "length mismatch"); assert_eq!(self.n, other.n, "length mismatch");
let term = |a: u32, b: u32| { let d = a as f64 - b as f64; d * d }; let term = |a: u32, b: u32| {
let mut total: f64 = self.primary.iter().zip(other.primary) let d = a as f64 - b as f64;
d * d
};
let mut total: f64 = self
.primary
.iter()
.zip(other.primary)
.map(|(&a, &b)| term(a as u32, b as u32)) .map(|(&a, &b)| term(a as u32, b as u32))
.sum(); .sum();
self.for_each_overflow_pair(other, |slot, a_true, b_true| { self.for_each_overflow_pair(other, |slot, a_true, b_true| {
@@ -335,7 +417,8 @@ impl<'a> IntSliceView<'a> {
pub fn partial_relfreq_euclidean_dist(self, other: IntSliceView<'_>, sa: f64, sb: f64) -> f64 { pub fn partial_relfreq_euclidean_dist(self, other: IntSliceView<'_>, sa: f64, sb: f64) -> f64 {
assert_eq!(self.n, other.n, "length mismatch"); assert_eq!(self.n, other.n, "length mismatch");
self.iter().zip(other.iter()) self.iter()
.zip(other.iter())
.map(|(a, b)| { .map(|(a, b)| {
let pa = if sa > 0.0 { a as f64 / sa } else { 0.0 }; let pa = if sa > 0.0 { a as f64 / sa } else { 0.0 };
let pb = if sb > 0.0 { b as f64 / sb } else { 0.0 }; let pb = if sb > 0.0 { b as f64 / sb } else { 0.0 };
@@ -348,16 +431,32 @@ impl<'a> IntSliceView<'a> {
pub fn relfreq_euclidean_dist(self, other: IntSliceView<'_>) -> f64 { pub fn relfreq_euclidean_dist(self, other: IntSliceView<'_>) -> f64 {
let sa = self.sum() as f64; let sa = self.sum() as f64;
let sb = other.sum() as f64; let sb = other.sum() as f64;
if sa == 0.0 && sb == 0.0 { return 0.0; } if sa == 0.0 && sb == 0.0 {
return 0.0;
}
self.partial_relfreq_euclidean_dist(other, sa, sb).sqrt() self.partial_relfreq_euclidean_dist(other, sa, sb).sqrt()
} }
pub fn partial_hellinger_euclidean_dist(self, other: IntSliceView<'_>, sa: f64, sb: f64) -> f64 { pub fn partial_hellinger_euclidean_dist(
self,
other: IntSliceView<'_>,
sa: f64,
sb: f64,
) -> f64 {
assert_eq!(self.n, other.n, "length mismatch"); assert_eq!(self.n, other.n, "length mismatch");
self.iter().zip(other.iter()) self.iter()
.zip(other.iter())
.map(|(a, b)| { .map(|(a, b)| {
let pa = if sa > 0.0 { (a as f64 / sa).sqrt() } else { 0.0 }; let pa = if sa > 0.0 {
let pb = if sb > 0.0 { (b as f64 / sb).sqrt() } else { 0.0 }; (a as f64 / sa).sqrt()
} else {
0.0
};
let pb = if sb > 0.0 {
(b as f64 / sb).sqrt()
} else {
0.0
};
let d = pa - pb; let d = pa - pb;
d * d d * d
}) })
@@ -367,7 +466,9 @@ impl<'a> IntSliceView<'a> {
pub fn hellinger_euclidean_dist(self, other: IntSliceView<'_>) -> f64 { pub fn hellinger_euclidean_dist(self, other: IntSliceView<'_>) -> f64 {
let sa = self.sum() as f64; let sa = self.sum() as f64;
let sb = other.sum() as f64; let sb = other.sum() as f64;
if sa == 0.0 && sb == 0.0 { return 0.0; } if sa == 0.0 && sb == 0.0 {
return 0.0;
}
self.partial_hellinger_euclidean_dist(other, sa, sb).sqrt() self.partial_hellinger_euclidean_dist(other, sa, sb).sqrt()
} }
@@ -375,14 +476,21 @@ impl<'a> IntSliceView<'a> {
self.hellinger_euclidean_dist(other) / std::f64::consts::SQRT_2 self.hellinger_euclidean_dist(other) / std::f64::consts::SQRT_2
} }
pub fn partial_threshold_jaccard_dist(self, other: IntSliceView<'_>, threshold: u32) -> (u64, u64) { pub fn partial_threshold_jaccard_dist(
self,
other: IntSliceView<'_>,
threshold: u32,
) -> (u64, u64) {
assert_eq!(self.n, other.n, "length mismatch"); assert_eq!(self.n, other.n, "length mismatch");
let term = |a: u32, b: u32| { let term = |a: u32, b: u32| {
let ap = a >= threshold; let ap = a >= threshold;
let bp = b >= threshold; let bp = b >= threshold;
((ap & bp) as u64, (ap | bp) as u64) ((ap & bp) as u64, (ap | bp) as u64)
}; };
let (mut inter, mut uni) = self.primary.iter().zip(other.primary) let (mut inter, mut uni) =
self.primary
.iter()
.zip(other.primary)
.fold((0u64, 0u64), |(inter, uni), (&a, &b)| { .fold((0u64, 0u64), |(inter, uni), (&a, &b)| {
let (ti, tu) = term(a as u32, b as u32); let (ti, tu) = term(a as u32, b as u32);
(inter + ti, uni + tu) (inter + ti, uni + tu)
@@ -398,7 +506,11 @@ impl<'a> IntSliceView<'a> {
pub fn threshold_jaccard_dist(self, other: IntSliceView<'_>, threshold: u32) -> f64 { pub fn threshold_jaccard_dist(self, other: IntSliceView<'_>, threshold: u32) -> f64 {
let (inter, union) = self.partial_threshold_jaccard_dist(other, threshold); let (inter, union) = self.partial_threshold_jaccard_dist(other, threshold);
if union == 0 { 0.0 } else { 1.0 - inter as f64 / union as f64 } if union == 0 {
0.0
} else {
1.0 - inter as f64 / union as f64
}
} }
pub fn jaccard_dist(self, other: IntSliceView<'_>) -> f64 { pub fn jaccard_dist(self, other: IntSliceView<'_>) -> f64 {
@@ -413,7 +525,11 @@ impl<'a> IntSliceView<'a> {
/// one. Overflow entries are sorted by slot in both views (on-disk /// one. Overflow entries are sorted by slot in both views (on-disk
/// invariant, see `format::finalize_pciv`), so their union is walked in /// invariant, see `format::finalize_pciv`), so their union is walked in
/// one linear merge — no allocation, no full second pass over `n`. /// one linear merge — no allocation, no full second pass over `n`.
fn for_each_overflow_pair(self, other: IntSliceView<'_>, mut correct: impl FnMut(usize, u32, u32)) { fn for_each_overflow_pair(
self,
other: IntSliceView<'_>,
mut correct: impl FnMut(usize, u32, u32),
) {
let mut a_it = self.overflow_entries().peekable(); let mut a_it = self.overflow_entries().peekable();
let mut b_it = other.overflow_entries().peekable(); let mut b_it = other.overflow_entries().peekable();
loop { loop {
@@ -446,14 +562,20 @@ impl<'a> IntSliceView<'a> {
/// can be written once and reused by every matrix type instead of /// can be written once and reused by every matrix type instead of
/// reimplementing the same sort-then-scan-columns loop per format. /// reimplementing the same sort-then-scan-columns loop per format.
pub(crate) trait NonzeroSlotsView: Sized { pub(crate) trait NonzeroSlotsView: Sized {
fn enumerate_nonzero_slots<'b>(self, slots: &'b [usize]) -> impl Iterator<Item = (usize, u32)> + 'b fn enumerate_nonzero_slots<'b>(
self,
slots: &'b [usize],
) -> impl Iterator<Item = (usize, u32)> + 'b
where where
Self: 'b; Self: 'b;
} }
impl<'a> NonzeroSlotsView for BitSliceView<'a> { impl<'a> NonzeroSlotsView for BitSliceView<'a> {
#[inline] #[inline]
fn enumerate_nonzero_slots<'b>(self, slots: &'b [usize]) -> impl Iterator<Item = (usize, u32)> + 'b fn enumerate_nonzero_slots<'b>(
self,
slots: &'b [usize],
) -> impl Iterator<Item = (usize, u32)> + 'b
where where
Self: 'b, Self: 'b,
{ {
@@ -463,7 +585,10 @@ impl<'a> NonzeroSlotsView for BitSliceView<'a> {
impl<'a> NonzeroSlotsView for IntSliceView<'a> { impl<'a> NonzeroSlotsView for IntSliceView<'a> {
#[inline] #[inline]
fn enumerate_nonzero_slots<'b>(self, slots: &'b [usize]) -> impl Iterator<Item = (usize, u32)> + 'b fn enumerate_nonzero_slots<'b>(
self,
slots: &'b [usize],
) -> impl Iterator<Item = (usize, u32)> + 'b
where where
Self: 'b, Self: 'b,
{ {
@@ -491,7 +616,8 @@ pub(crate) fn nonzero_triples<V: NonzeroSlotsView>(
let mut hits: Vec<(usize, usize, u32)> = Vec::new(); let mut hits: Vec<(usize, usize, u32)> = Vec::new();
for c in 0..n_cols { for c in 0..n_cols {
hits.extend( hits.extend(
col_view(c).enumerate_nonzero_slots(&sorted_slots) col_view(c)
.enumerate_nonzero_slots(&sorted_slots)
.map(|(pos, v)| (perm[pos], c, v)), .map(|(pos, v)| (perm[pos], c, v)),
); );
} }
@@ -512,7 +638,9 @@ impl Iterator for IntSliceViewIter<'_> {
type Item = u32; type Item = u32;
#[inline] #[inline]
fn next(&mut self) -> Option<u32> { fn next(&mut self) -> Option<u32> {
if self.slot >= self.n { return None; } if self.slot >= self.n {
return None;
}
let v = self.primary[self.slot]; let v = self.primary[self.slot];
self.slot += 1; self.slot += 1;
if v < 255 { if v < 255 {
+6 -1
View File
@@ -19,7 +19,12 @@ impl BitSliceView<'_> {
/// Panics if `range.end > self.len()`. /// Panics if `range.end > self.len()`.
#[inline] #[inline]
pub fn for_each_set_in(&self, range: Range<usize>, mut f: impl FnMut(usize)) { pub fn for_each_set_in(&self, range: Range<usize>, mut f: impl FnMut(usize)) {
assert!(range.end <= self.n, "range end {} past view length {}", range.end, self.n); assert!(
range.end <= self.n,
"range end {} past view length {}",
range.end,
self.n
);
if range.start >= range.end { if range.start >= range.end {
return; return;
} }
+18 -7
View File
@@ -7,7 +7,7 @@ use std::cell::RefCell;
use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::atomic::{AtomicU8, Ordering};
use super::kmer_hash::KmerHashBuilder; use super::kmer_hash::KmerHashBuilder;
use super::node::{IS_VISITED_MASK, Node}; use super::node::{Node, IS_VISITED_MASK};
use super::unitig_iter::UnitigNucIter; use super::unitig_iter::UnitigNucIter;
use super::walk::WalkState; use super::walk::WalkState;
@@ -79,7 +79,8 @@ impl GraphDeBruijn {
if node.is_visited() { if node.is_visited() {
return; return;
} }
if self.is_start(*kmer, node, atomic, true) || self.is_start(*kmer, node, atomic, false) { if self.is_start(*kmer, node, atomic, true) || self.is_start(*kmer, node, atomic, false)
{
node.set_start(); node.set_start();
atomic.store(node.0, Ordering::Relaxed); atomic.store(node.0, Ordering::Relaxed);
} }
@@ -120,7 +121,12 @@ impl GraphDeBruijn {
Some(WalkState::new(kmer, node, true, atomic)) Some(WalkState::new(kmer, node, true, atomic))
} }
pub(super) fn unitig_nucleotides(&self, kmer: CanonicalKmer, k: usize, direct: bool) -> Option<UnitigNucIter<'_>> { pub(super) fn unitig_nucleotides(
&self,
kmer: CanonicalKmer,
k: usize,
direct: bool,
) -> Option<UnitigNucIter<'_>> {
let atomic = self.nodes.get(&kmer)?; let atomic = self.nodes.get(&kmer)?;
let old = atomic.fetch_or(IS_VISITED_MASK, Ordering::AcqRel); let old = atomic.fetch_or(IS_VISITED_MASK, Ordering::AcqRel);
if old & IS_VISITED_MASK != 0 { if old & IS_VISITED_MASK != 0 {
@@ -128,7 +134,9 @@ impl GraphDeBruijn {
} }
let start = WalkState::new(kmer, Node(old), direct, atomic); let start = WalkState::new(kmer, Node(old), direct, atomic);
let next_step = start.walk(self).and_then(|(next_state, nuc)| { let next_step = start.walk(self).and_then(|(next_state, nuc)| {
let ext_old = next_state.atomic.fetch_or(IS_VISITED_MASK, Ordering::AcqRel); let ext_old = next_state
.atomic
.fetch_or(IS_VISITED_MASK, Ordering::AcqRel);
(ext_old & IS_VISITED_MASK == 0).then_some((next_state, nuc)) (ext_old & IS_VISITED_MASK == 0).then_some((next_state, nuc))
}); });
Some(UnitigNucIter::new(self, kmer, k, direct, next_step)) Some(UnitigNucIter::new(self, kmer, k, direct, next_step))
@@ -152,7 +160,9 @@ impl GraphDeBruijn {
.then_some(kmer) .then_some(kmer)
}) })
.for_each(|kmer| { .for_each(|kmer| {
let Some(direct) = self.start_direction(kmer) else { return }; let Some(direct) = self.start_direction(kmer) else {
return;
};
if let Some(iter) = self.unitig_nucleotides(kmer, k, direct) { if let Some(iter) = self.unitig_nucleotides(kmer, k, direct) {
n_new.fetch_add(1, Ordering::Relaxed); n_new.fetch_add(1, Ordering::Relaxed);
f(iter); f(iter);
@@ -162,7 +172,9 @@ impl GraphDeBruijn {
#[cfg(any(test, feature = "test-utils"))] #[cfg(any(test, feature = "test-utils"))]
self.nodes.iter().for_each(|(&kmer, atomic)| { self.nodes.iter().for_each(|(&kmer, atomic)| {
if Node(atomic.load(Ordering::Acquire)).is_start() { if Node(atomic.load(Ordering::Acquire)).is_start() {
let Some(direct) = self.start_direction(kmer) else { return }; let Some(direct) = self.start_direction(kmer) else {
return;
};
if let Some(iter) = self.unitig_nucleotides(kmer, k, direct) { if let Some(iter) = self.unitig_nucleotides(kmer, k, direct) {
n_new.fetch_add(1, Ordering::Relaxed); n_new.fetch_add(1, Ordering::Relaxed);
f(iter); f(iter);
@@ -199,7 +211,6 @@ impl GraphDeBruijn {
} }
} }
} }
} }
/// Merge `other` into `self`. /// Merge `other` into `self`.
+3 -1
View File
@@ -50,7 +50,9 @@ impl Iterator for UnitigNucIter<'_> {
Some(nuc) Some(nuc)
} else if let Some((state, nuc)) = self.next_step.take() { } else if let Some((state, nuc)) = self.next_step.take() {
self.next_step = state.walk(self.graph).and_then(|(next_state, next_nuc)| { self.next_step = state.walk(self.graph).and_then(|(next_state, next_nuc)| {
let old = next_state.atomic.fetch_or(IS_VISITED_MASK, Ordering::AcqRel); let old = next_state
.atomic
.fetch_or(IS_VISITED_MASK, Ordering::AcqRel);
(old & IS_VISITED_MASK == 0).then_some((next_state, next_nuc)) (old & IS_VISITED_MASK == 0).then_some((next_state, next_nuc))
}); });
Some(nuc) Some(nuc)
+6 -1
View File
@@ -18,7 +18,12 @@ pub struct WalkState<'g> {
impl<'g> WalkState<'g> { impl<'g> WalkState<'g> {
pub fn new(kmer: CanonicalKmer, node: Node, direct: bool, atomic: &'g AtomicU8) -> Self { pub fn new(kmer: CanonicalKmer, node: Node, direct: bool, atomic: &'g AtomicU8) -> Self {
debug_assert!(!node.is_visited(), "Cannot walk over a visited node"); debug_assert!(!node.is_visited(), "Cannot walk over a visited node");
Self { kmer, node, direct, atomic } Self {
kmer,
node,
direct,
atomic,
}
} }
pub fn leavable(&self, graph: &'g GraphDeBruijn) -> bool { pub fn leavable(&self, graph: &'g GraphDeBruijn) -> bool {
+20 -4
View File
@@ -354,9 +354,21 @@ fn linear_chain_is_one_unitig_whatever_the_orientations() {
let g = graph_from_ascii(&seq); let g = graph_from_ascii(&seq);
g.compute_degrees_and_mark_starts(); g.compute_degrees_and_mark_starts();
let unitigs = collect_unitigs(&g); let unitigs = collect_unitigs(&g);
assert_eq!(unitigs.len(), 1, "seed {seed}: repeat-free sequence must give one unitig"); assert_eq!(
assert_eq!(unitigs[0].seql(), seq.len(), "seed {seed}: unitig spans the sequence"); unitigs.len(),
assert_eq!(kmers_from_unitigs(&unitigs), kmers, "seed {seed}: same k-mers"); 1,
"seed {seed}: repeat-free sequence must give one unitig"
);
assert_eq!(
unitigs[0].seql(),
seq.len(),
"seed {seed}: unitig spans the sequence"
);
assert_eq!(
kmers_from_unitigs(&unitigs),
kmers,
"seed {seed}: same k-mers"
);
} }
} }
@@ -398,5 +410,9 @@ fn unitigs_partition_the_kmers_of_branching_reads() {
let unitigs = collect_unitigs(&g); let unitigs = collect_unitigs(&g);
let covered: usize = unitigs.iter().map(|u| u.seql() - k + 1).sum(); let covered: usize = unitigs.iter().map(|u| u.seql() - k + 1).sum();
assert_eq!(covered, g.len(), "every k-mer in exactly one unitig"); assert_eq!(covered, g.len(), "every k-mer in exactly one unitig");
assert_eq!(kmers_from_unitigs(&unitigs).len(), g.len(), "no k-mer missing"); assert_eq!(
kmers_from_unitigs(&unitigs).len(),
g.len(),
"no k-mer missing"
);
} }
+1 -4
View File
@@ -19,10 +19,7 @@ impl fmt::Display for JsonVal<'_> {
} }
/// Write a JSON object `{"k1":v1,"k2":v2,...}` to `writer`. /// Write a JSON object `{"k1":v1,"k2":v2,...}` to `writer`.
pub fn annotation<W: Write>( pub fn annotation<W: Write>(writer: &mut W, fields: &[(&str, JsonVal<'_>)]) -> io::Result<()> {
writer: &mut W,
fields: &[(&str, JsonVal<'_>)],
) -> io::Result<()> {
write!(writer, "{{")?; write!(writer, "{{")?;
for (i, (k, v)) in fields.iter().enumerate() { for (i, (k, v)) in fields.iter().enumerate() {
if i > 0 { if i > 0 {
+16 -6
View File
@@ -53,7 +53,7 @@ pub fn write_scatter<W: Write>(
&[ &[
("seq_length", JsonVal::Num(ascii.len() as u64)), ("seq_length", JsonVal::Num(ascii.len() as u64)),
("kmer_size", JsonVal::Num(k as u64)), ("kmer_size", JsonVal::Num(k as u64)),
("minimizer_size",JsonVal::Num(m as u64)), ("minimizer_size", JsonVal::Num(m as u64)),
("partition", JsonVal::Num(partition as u64)), ("partition", JsonVal::Num(partition as u64)),
("minimizer", JsonVal::Str(min_str)), ("minimizer", JsonVal::Str(min_str)),
], ],
@@ -80,7 +80,7 @@ pub fn write_count<W: Write>(
&[ &[
("seq_length", JsonVal::Num(ascii.len() as u64)), ("seq_length", JsonVal::Num(ascii.len() as u64)),
("kmer_size", JsonVal::Num(k as u64)), ("kmer_size", JsonVal::Num(k as u64)),
("minimizer_size",JsonVal::Num(m as u64)), ("minimizer_size", JsonVal::Num(m as u64)),
("partition", JsonVal::Num(partition as u64)), ("partition", JsonVal::Num(partition as u64)),
("count", JsonVal::Num(sk.count() as u64)), ("count", JsonVal::Num(sk.count() as u64)),
], ],
@@ -255,11 +255,21 @@ mod tests {
let sk2 = make(b"TTTTTTTT"); let sk2 = make(b"TTTTTTTT");
let id1 = capture(|w| write_scatter(&sk1, w, 4, 2, 0, Minimizer::from_raw_unchecked(0))) let id1 = capture(|w| write_scatter(&sk1, w, 4, 2, 0, Minimizer::from_raw_unchecked(0)))
.lines().next().unwrap() .lines()
.split_whitespace().next().unwrap()[1..].to_string(); .next()
.unwrap()
.split_whitespace()
.next()
.unwrap()[1..]
.to_string();
let id2 = capture(|w| write_scatter(&sk2, w, 4, 2, 0, Minimizer::from_raw_unchecked(0))) let id2 = capture(|w| write_scatter(&sk2, w, 4, 2, 0, Minimizer::from_raw_unchecked(0)))
.lines().next().unwrap() .lines()
.split_whitespace().next().unwrap()[1..].to_string(); .next()
.unwrap()
.split_whitespace()
.next()
.unwrap()[1..]
.to_string();
assert_ne!(id1, id2); assert_ne!(id1, id2);
} }
+63 -22
View File
@@ -4,10 +4,10 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use rayon::prelude::*; use rayon::prelude::*;
use obikindex::{OKIError, OKIResult};
use obikindex::KmerIndex;
use obikidxcache::index_cache::IndexCache;
use obikfilter::KmerFilter; use obikfilter::KmerFilter;
use obikidxcache::index_cache::IndexCache;
use obikindex::KmerIndex;
use obikindex::{OKIError, OKIResult};
use obikfilter::FilteredPartitionIter; use obikfilter::FilteredPartitionIter;
@@ -70,60 +70,101 @@ impl IndexDump for Arc<KmerIndex> {
let write_row = |buf: &mut Vec<u8>, row: &[u32], prefix: &str| { let write_row = |buf: &mut Vec<u8>, row: &[u32], prefix: &str| {
let _ = buf.write_all(prefix.as_bytes()); let _ = buf.write_all(prefix.as_bytes());
for &v in row { let _ = write!(buf, ",{v}"); } for &v in row {
let _ = write!(buf, ",{v}");
}
let _ = buf.write_all(b"\n"); let _ = buf.write_all(b"\n");
}; };
let chunks: Vec<OKIResult<Vec<u8>>> = if let Some(limit) = head { let chunks: Vec<OKIResult<Vec<u8>>> = if let Some(limit) = head {
// ── Bounded: atomic counter, early exit when limit reached ──────── // ── Bounded: atomic counter, early exit when limit reached ────────
let remaining = AtomicUsize::new(limit); let remaining = AtomicUsize::new(limit);
(0..n).into_par_iter().map(|i| { (0..n)
if remaining.load(Ordering::Relaxed) == 0 { return Ok(vec![]); } .into_par_iter()
.map(|i| {
if remaining.load(Ordering::Relaxed) == 0 {
return Ok(vec![]);
}
let mut buf = Vec::<u8>::new(); let mut buf = Vec::<u8>::new();
let try_write = |buf: &mut Vec<u8>, row: &[u32], prefix: &str| -> bool { let try_write = |buf: &mut Vec<u8>, row: &[u32], prefix: &str| -> bool {
match remaining.try_update(Ordering::SeqCst, Ordering::SeqCst, |cur| { match remaining.try_update(Ordering::SeqCst, Ordering::SeqCst, |cur| {
if cur > 0 { Some(cur - 1) } else { None } if cur > 0 { Some(cur - 1) } else { None }
}) { }) {
Err(_) => false, Err(_) => false,
Ok(_) => { write_row(buf, row, prefix); true } Ok(_) => {
write_row(buf, row, prefix);
true
}
} }
}; };
let cache = IndexCache::new(Arc::clone(self), Some(vec![i])); let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
if debug { if debug {
cache.iter_partition_kmers_located(i, use_counts, n_genomes, filters, |part, layer, kmer, row| { cache.iter_partition_kmers_located(
let seq = String::from_utf8(kmer.to_ascii()).unwrap_or_else(|_| "?".repeat(kmer_size)); i,
use_counts,
n_genomes,
filters,
|part, layer, kmer, row| {
let seq = String::from_utf8(kmer.to_ascii())
.unwrap_or_else(|_| "?".repeat(kmer_size));
try_write(&mut buf, &row, &format!("{part},{layer},{seq}")) try_write(&mut buf, &row, &format!("{part},{layer},{seq}"))
})?; },
)?;
} else { } else {
cache.iter_partition_kmers(i, use_counts, n_genomes, filters, |kmer, row| { cache.iter_partition_kmers(
let seq = String::from_utf8(kmer.to_ascii()).unwrap_or_else(|_| "?".repeat(kmer_size)); i,
use_counts,
n_genomes,
filters,
|kmer, row| {
let seq = String::from_utf8(kmer.to_ascii())
.unwrap_or_else(|_| "?".repeat(kmer_size));
try_write(&mut buf, &row, &seq) try_write(&mut buf, &row, &seq)
})?; },
)?;
} }
on_partition(); on_partition();
Ok(buf) Ok(buf)
}).collect() })
.collect()
} else { } else {
// ── Unbounded: no atomic, no contention ─────────────────────────── // ── Unbounded: no atomic, no contention ───────────────────────────
(0..n).into_par_iter().map(|i| { (0..n)
.into_par_iter()
.map(|i| {
let mut buf = Vec::<u8>::new(); let mut buf = Vec::<u8>::new();
let cache = IndexCache::new(Arc::clone(self), Some(vec![i])); let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
if debug { if debug {
cache.iter_partition_kmers_located(i, use_counts, n_genomes, filters, |part, layer, kmer, row| { cache.iter_partition_kmers_located(
let seq = String::from_utf8(kmer.to_ascii()).unwrap_or_else(|_| "?".repeat(kmer_size)); i,
use_counts,
n_genomes,
filters,
|part, layer, kmer, row| {
let seq = String::from_utf8(kmer.to_ascii())
.unwrap_or_else(|_| "?".repeat(kmer_size));
write_row(&mut buf, &row, &format!("{part},{layer},{seq}")); write_row(&mut buf, &row, &format!("{part},{layer},{seq}"));
true true
})?; },
)?;
} else { } else {
cache.iter_partition_kmers(i, use_counts, n_genomes, filters, |kmer, row| { cache.iter_partition_kmers(
let seq = String::from_utf8(kmer.to_ascii()).unwrap_or_else(|_| "?".repeat(kmer_size)); i,
use_counts,
n_genomes,
filters,
|kmer, row| {
let seq = String::from_utf8(kmer.to_ascii())
.unwrap_or_else(|_| "?".repeat(kmer_size));
write_row(&mut buf, &row, &seq); write_row(&mut buf, &row, &seq);
true true
})?; },
)?;
} }
on_partition(); on_partition();
Ok(buf) Ok(buf)
}).collect() })
.collect()
}; };
// ── Sequential write ────────────────────────────────────────────────── // ── Sequential write ──────────────────────────────────────────────────
+13 -4
View File
@@ -40,15 +40,24 @@ impl IndexUnitigs for Arc<KmerIndex> {
let g = (0..n) let g = (0..n)
.into_par_iter() .into_par_iter()
.try_fold(GraphDeBruijn::new, |mut local_g, i| -> OKIResult<GraphDeBruijn> { .try_fold(
GraphDeBruijn::new,
|mut local_g, i| -> OKIResult<GraphDeBruijn> {
let cache = IndexCache::new(Arc::clone(self), Some(vec![i])); let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
cache.iter_partition_kmers(i, use_counts, n_genomes, filters, |kmer, _row| { cache.iter_partition_kmers(
i,
use_counts,
n_genomes,
filters,
|kmer, _row| {
local_g.push(kmer); local_g.push(kmer);
true true
})?; },
)?;
on_partition(); on_partition();
Ok(local_g) Ok(local_g)
}) },
)
.try_reduce(GraphDeBruijn::new, |mut a, b| { .try_reduce(GraphDeBruijn::new, |mut a, b| {
a.merge(b); a.merge(b);
Ok(a) Ok(a)
+13 -3
View File
@@ -60,12 +60,22 @@ fn emit_f64_1d(out: &mut String, name: &str, n: usize, values: &[f64]) {
out.push_str("];\n"); out.push_str("];\n");
} }
fn emit_f64_2d(out: &mut String, name: &str, rows: usize, cols: usize, values: &[[f64; WS_MAX + 1]]) { fn emit_f64_2d(
out.push_str(&format!("pub(crate) const {name}: [[f64; {cols}]; {rows}] = [\n")); out: &mut String,
name: &str,
rows: usize,
cols: usize,
values: &[[f64; WS_MAX + 1]],
) {
out.push_str(&format!(
"pub(crate) const {name}: [[f64; {cols}]; {rows}] = [\n"
));
for row in values { for row in values {
out.push_str(" ["); out.push_str(" [");
for (i, v) in row.iter().enumerate() { for (i, v) in row.iter().enumerate() {
if i > 0 { out.push_str(", "); } if i > 0 {
out.push_str(", ");
}
out.push_str(&format!("{v:?}")); out.push_str(&format!("{v:?}"));
} }
out.push_str("],\n"); out.push_str("],\n");
+16 -4
View File
@@ -7,7 +7,9 @@ const LEVEL_MAX: usize = 6;
fn kmer_from_ascii(seq: &[u8]) -> CanonicalKmer { fn kmer_from_ascii(seq: &[u8]) -> CanonicalKmer {
obikseq::set_k(K); obikseq::set_k(K);
Kmer::from_ascii(seq).expect("valid k-mer sequence").canonical() Kmer::from_ascii(seq)
.expect("valid k-mer sequence")
.canonical()
} }
#[test] #[test]
@@ -24,7 +26,10 @@ fn homopolymer_scores_lower_than_diverse_sequence() {
); );
// A pure homopolymer is the most degenerate case representable — its // A pure homopolymer is the most degenerate case representable — its
// score should sit near the bottom of the range, not just "somewhat lower". // score should sit near the bottom of the range, not just "somewhat lower".
assert!(e_homopolymer < 0.3, "homopolymer entropy unexpectedly high: {e_homopolymer}"); assert!(
e_homopolymer < 0.3,
"homopolymer entropy unexpectedly high: {e_homopolymer}"
);
} }
#[test] #[test]
@@ -44,9 +49,16 @@ fn entropy_is_within_zero_one_range() {
repeat, repeat,
"CATTAGCGTACCTGATCAGGT".to_string(), "CATTAGCGTACCTGATCAGGT".to_string(),
] { ] {
assert_eq!(seq.len(), K, "test sequence must be exactly K bases: {seq:?}"); assert_eq!(
seq.len(),
K,
"test sequence must be exactly K bases: {seq:?}"
);
let kmer = kmer_from_ascii(seq.as_bytes()); let kmer = kmer_from_ascii(seq.as_bytes());
let e = kmer.entropy(LEVEL_MAX); let e = kmer.entropy(LEVEL_MAX);
assert!((0.0..=1.0).contains(&e), "entropy {e} out of [0,1] for {seq:?}"); assert!(
(0.0..=1.0).contains(&e),
"entropy {e} out of [0,1] for {seq:?}"
);
} }
} }
+6 -2
View File
@@ -183,8 +183,12 @@ impl EntropyTracker {
fn push_warmup_increments( fn push_warmup_increments(
&mut self, &mut self,
received: usize, received: usize,
raw1: u64, raw2: u64, raw3: u64, raw1: u64,
raw4: u64, raw5: u64, raw6: u64, raw2: u64,
raw3: u64,
raw4: u64,
raw5: u64,
raw6: u64,
) { ) {
let g1 = self.k1c[raw1 as usize] as usize; let g1 = self.k1c[raw1 as usize] as usize;
Self::update_sums_increment::<1>(&mut self.sum_f_log_f, g1); Self::update_sums_increment::<1>(&mut self.sum_f_log_f, g1);
+44 -16
View File
@@ -226,26 +226,48 @@ impl GroupQuorumFilter {
impl KmerFilter for GroupQuorumFilter { impl KmerFilter for GroupQuorumFilter {
fn passes(&self, _kmer: CanonicalKmer, row: &[u32], _n_genomes: usize) -> bool { fn passes(&self, _kmer: CanonicalKmer, row: &[u32], _n_genomes: usize) -> bool {
if !self.selection.ingroup_idx.is_empty() { if !self.selection.ingroup_idx.is_empty() {
let n = self.selection.ingroup_idx.iter() let n = self
.selection
.ingroup_idx
.iter()
.filter(|&&i| row.get(i).copied().unwrap_or(0) > self.threshold) .filter(|&&i| row.get(i).copied().unwrap_or(0) > self.threshold)
.count(); .count();
let denom = self.selection.ingroup_idx.len(); let denom = self.selection.ingroup_idx.len();
if n < self.min_count { return false; } if n < self.min_count {
if n > self.max_count { return false; } return false;
}
if n > self.max_count {
return false;
}
let frac = n as f64 / denom as f64; let frac = n as f64 / denom as f64;
if frac < self.min_frac { return false; } if frac < self.min_frac {
if frac > self.max_frac { return false; } return false;
}
if frac > self.max_frac {
return false;
}
} }
if !self.selection.outgroup_idx.is_empty() { if !self.selection.outgroup_idx.is_empty() {
let n = self.selection.outgroup_idx.iter() let n = self
.selection
.outgroup_idx
.iter()
.filter(|&&i| row.get(i).copied().unwrap_or(0) > self.threshold) .filter(|&&i| row.get(i).copied().unwrap_or(0) > self.threshold)
.count(); .count();
let denom = self.selection.outgroup_idx.len(); let denom = self.selection.outgroup_idx.len();
if n < self.min_outgroup_count { return false; } if n < self.min_outgroup_count {
if n > self.max_outgroup_count { return false; } return false;
}
if n > self.max_outgroup_count {
return false;
}
let frac = n as f64 / denom as f64; let frac = n as f64 / denom as f64;
if frac < self.min_outgroup_frac { return false; } if frac < self.min_outgroup_frac {
if frac > self.max_outgroup_frac { return false; } return false;
}
if frac > self.max_outgroup_frac {
return false;
}
} }
true true
} }
@@ -255,17 +277,23 @@ impl KmerFilter for GroupQuorumFilter {
let mut parts: Vec<FilterMask> = Vec::new(); let mut parts: Vec<FilterMask> = Vec::new();
if !self.selection.ingroup_idx.is_empty() { if !self.selection.ingroup_idx.is_empty() {
Self::group_mask_parts( Self::group_mask_parts(
&self.selection.ingroup_idx, t, &self.selection.ingroup_idx,
self.min_count, self.max_count, t,
self.min_frac, self.max_frac, self.min_count,
self.max_count,
self.min_frac,
self.max_frac,
&mut parts, &mut parts,
); );
} }
if !self.selection.outgroup_idx.is_empty() { if !self.selection.outgroup_idx.is_empty() {
Self::group_mask_parts( Self::group_mask_parts(
&self.selection.outgroup_idx, t, &self.selection.outgroup_idx,
self.min_outgroup_count, self.max_outgroup_count, t,
self.min_outgroup_frac, self.max_outgroup_frac, self.min_outgroup_count,
self.max_outgroup_count,
self.min_outgroup_frac,
self.max_outgroup_frac,
&mut parts, &mut parts,
); );
} }
+17 -2
View File
@@ -31,7 +31,11 @@ pub struct Filter<'a> {
} }
impl<'a> Filter<'a> { impl<'a> Filter<'a> {
pub fn new(src: Arc<KmerIndex>, output: impl Into<PathBuf>, filters: &'a [Box<dyn KmerFilter>]) -> Self { pub fn new(
src: Arc<KmerIndex>,
output: impl Into<PathBuf>,
filters: &'a [Box<dyn KmerFilter>],
) -> Self {
Self { Self {
src, src,
output: output.into(), output: output.into(),
@@ -118,7 +122,18 @@ impl Algorithm for Filter<'_> {
runner runner
.run( .run(
&order, &order,
|i| filter_partition(&dst, src, i, filters, use_counts, !use_counts, block_bits, &mode), |i| {
filter_partition(
&dst,
src,
i,
filters,
use_counts,
!use_counts,
block_bits,
&mode,
)
},
|_, _, _| { |_, _, _| {
done += 1; done += 1;
if let Some(cb) = on_progress.as_mut() { if let Some(cb) = on_progress.as_mut() {
+14 -3
View File
@@ -44,10 +44,16 @@ pub(crate) fn filter_partition(
// the same order of magnitude `IndexCache` already holds open for this // the same order of magnitude `IndexCache` already holds open for this
// partition. // partition.
let mut by_layer: HashMap<usize, HashMap<CanonicalKmer, Box<[u32]>>> = HashMap::new(); let mut by_layer: HashMap<usize, HashMap<CanonicalKmer, Box<[u32]>>> = HashMap::new();
cache.iter_partition_kmers_located(i, use_counts, n_genomes, filters, |_part, layer, kmer, row| { cache.iter_partition_kmers_located(
i,
use_counts,
n_genomes,
filters,
|_part, layer, kmer, row| {
by_layer.entry(layer).or_default().insert(kmer, row); by_layer.entry(layer).or_default().insert(kmer, row);
true true
})?; },
)?;
for l in 0..n_layers { for l in 0..n_layers {
let survivors = by_layer.remove(&l).unwrap_or_default(); let survivors = by_layer.remove(&l).unwrap_or_default();
@@ -70,7 +76,12 @@ pub(crate) fn filter_partition(
mode, mode,
output_presence, output_presence,
n_genomes, n_genomes,
|kmer| survivors.get(&kmer).cloned().expect("kmer pushed into the graph must be a survivor"), |kmer| {
survivors
.get(&kmer)
.cloned()
.expect("kmer pushed into the graph must be a survivor")
},
)?; )?;
} }
+2 -2
View File
@@ -17,8 +17,8 @@ mod partition_iter;
mod predicate; mod predicate;
pub use filter::{ pub use filter::{
GroupQuorumFilter, KmerFilter, MaxGenomeCount, MaxGenomeFraction, MaxTotalCount, GroupQuorumFilter, KmerFilter, MaxGenomeCount, MaxGenomeFraction, MaxTotalCount, MinComplexity,
MinComplexity, MinGenomeCount, MinGenomeFraction, MinTotalCount, passes_all, MinGenomeCount, MinGenomeFraction, MinTotalCount, passes_all,
}; };
pub use filter_algo::Filter; pub use filter_algo::Filter;
pub use partition_iter::FilteredPartitionIter; pub use partition_iter::FilteredPartitionIter;
+11 -4
View File
@@ -8,9 +8,9 @@
//! destination index still being built (see `obikmerge::partition_merge`, //! destination index still being built (see `obikmerge::partition_merge`,
//! which follows the same source-only-cache rule). //! which follows the same source-only-cache rule).
use obikidxcache::index_cache::IndexCache;
use obikindex::OKIResult; use obikindex::OKIResult;
use obikindex::layer::{KmerLayer, LayerContent}; use obikindex::layer::{KmerLayer, LayerContent};
use obikidxcache::index_cache::IndexCache;
use obikseq::CanonicalKmer; use obikseq::CanonicalKmer;
use crate::filter::{KmerFilter, passes_all}; use crate::filter::{KmerFilter, passes_all};
@@ -63,7 +63,9 @@ impl FilteredPartitionIter for IndexCache {
) -> OKIResult<bool> { ) -> OKIResult<bool> {
for l in 0..self.n_layer(part).unwrap_or(0) { for l in 0..self.n_layer(part).unwrap_or(0) {
let layer = self.get_layer(part, l).expect("layer within n_layer(part)"); let layer = self.get_layer(part, l).expect("layer within n_layer(part)");
if !iter_layer_kmers(&layer, use_counts, n_genomes, filters, &mut |kmer, row| cb(kmer, row))? { if !iter_layer_kmers(&layer, use_counts, n_genomes, filters, &mut |kmer, row| {
cb(kmer, row)
})? {
return Ok(false); return Ok(false);
} }
} }
@@ -80,7 +82,9 @@ impl FilteredPartitionIter for IndexCache {
) -> OKIResult<bool> { ) -> OKIResult<bool> {
for l in 0..self.n_layer(part).unwrap_or(0) { for l in 0..self.n_layer(part).unwrap_or(0) {
let layer = self.get_layer(part, l).expect("layer within n_layer(part)"); let layer = self.get_layer(part, l).expect("layer within n_layer(part)");
if !iter_layer_kmers(&layer, use_counts, n_genomes, filters, &mut |kmer, row| cb(part, l, kmer, row))? { if !iter_layer_kmers(&layer, use_counts, n_genomes, filters, &mut |kmer, row| {
cb(part, l, kmer, row)
})? {
return Ok(false); return Ok(false);
} }
} }
@@ -112,7 +116,10 @@ fn iter_layer_kmers(
} else { } else {
let mut bool_cols: Vec<Vec<bool>> = vec![Vec::new(); n_genomes]; let mut bool_cols: Vec<Vec<bool>> = vec![Vec::new(); n_genomes];
layer.fill_sub_matrix_carries(&slots, &mut bool_cols); layer.fill_sub_matrix_carries(&slots, &mut bool_cols);
bool_cols.iter().map(|c| c.iter().map(|&b| b as u32).collect()).collect() bool_cols
.iter()
.map(|c| c.iter().map(|&b| b as u32).collect())
.collect()
}; };
for (i, kmer) in kmers.into_iter().enumerate() { for (i, kmer) in kmers.into_iter().enumerate() {
+123 -40
View File
@@ -7,7 +7,13 @@ use obikindex::{GenomeInfo, IndexMeta};
// ── Operator ────────────────────────────────────────────────────────────────── // ── Operator ──────────────────────────────────────────────────────────────────
enum PredOp { Wildcard, Eq, Ne, Matches, NotMatches } enum PredOp {
Wildcard,
Eq,
Ne,
Matches,
NotMatches,
}
// ── MetaPred ────────────────────────────────────────────────────────────────── // ── MetaPred ──────────────────────────────────────────────────────────────────
@@ -27,24 +33,29 @@ impl MetaPred {
pub fn parse(s: &str) -> Result<Self, String> { pub fn parse(s: &str) -> Result<Self, String> {
let t = s.trim(); let t = s.trim();
if t == "*" || t.eq_ignore_ascii_case("all") { if t == "*" || t.eq_ignore_ascii_case("all") {
return Ok(Self { key: String::new(), op: PredOp::Wildcard, values: vec![] }); return Ok(Self {
key: String::new(),
op: PredOp::Wildcard,
values: vec![],
});
} }
let (op, key, rhs) = let (op, key, rhs) = if let Some(pos) = s.find("!=") {
if let Some(pos) = s.find("!=") { (PredOp::Ne, &s[..pos], &s[pos + 2..])
(PredOp::Ne, &s[..pos], &s[pos+2..])
} else if let Some(pos) = s.find("!~") { } else if let Some(pos) = s.find("!~") {
(PredOp::NotMatches, &s[..pos], &s[pos+2..]) (PredOp::NotMatches, &s[..pos], &s[pos + 2..])
} else if let Some(pos) = s.find('=') { } else if let Some(pos) = s.find('=') {
(PredOp::Eq, &s[..pos], &s[pos+1..]) (PredOp::Eq, &s[..pos], &s[pos + 1..])
} else if let Some(pos) = s.find('~') { } else if let Some(pos) = s.find('~') {
(PredOp::Matches, &s[..pos], &s[pos+1..]) (PredOp::Matches, &s[..pos], &s[pos + 1..])
} else { } else {
return Err(format!("no operator found in predicate: {s}")); return Err(format!("no operator found in predicate: {s}"));
}; };
let key = key.trim().to_string(); let key = key.trim().to_string();
if key.is_empty() { return Err(format!("empty key in predicate: {s}")); } if key.is_empty() {
return Err(format!("empty key in predicate: {s}"));
}
let values: Vec<String> = rhs.split('|').map(|v| v.trim().to_string()).collect(); let values: Vec<String> = rhs.split('|').map(|v| v.trim().to_string()).collect();
if values.iter().any(|v| v.is_empty()) { if values.iter().any(|v| v.is_empty()) {
@@ -56,7 +67,9 @@ impl MetaPred {
/// Evaluate against one genome's metadata. /// Evaluate against one genome's metadata.
/// Returns `None` when the key is absent (NA propagation). /// Returns `None` when the key is absent (NA propagation).
pub(crate) fn eval(&self, meta: &HashMap<String, String>) -> Option<bool> { pub(crate) fn eval(&self, meta: &HashMap<String, String>) -> Option<bool> {
if matches!(self.op, PredOp::Wildcard) { return Some(true); } if matches!(self.op, PredOp::Wildcard) {
return Some(true);
}
let value = meta.get(&self.key)?; let value = meta.get(&self.key)?;
Some(match self.op { Some(match self.op {
PredOp::Wildcard => unreachable!(), PredOp::Wildcard => unreachable!(),
@@ -76,8 +89,12 @@ impl MetaPred {
/// `pattern` is a `TaxPattern` query (see `obitaxonomy::TaxPattern` for syntax). /// `pattern` is a `TaxPattern` query (see `obitaxonomy::TaxPattern` for syntax).
/// Returns `false` if either fails to parse. /// Returns `false` if either fails to parse.
fn path_matches(value: &str, pattern: &str) -> bool { fn path_matches(value: &str, pattern: &str) -> bool {
let Ok(path) = TaxPath::parse(value) else { return false }; let Ok(path) = TaxPath::parse(value) else {
let Ok(pat) = TaxPattern::parse(pattern) else { return false }; return false;
};
let Ok(pat) = TaxPattern::parse(pattern) else {
return false;
};
pat.matches(&path) pat.matches(&path)
} }
@@ -113,22 +130,41 @@ fn eval_or(preds: &[MetaPred], meta: &HashMap<String, String>) -> Option<bool> {
// ── Genome classification ───────────────────────────────────────────────────── // ── Genome classification ─────────────────────────────────────────────────────
enum Membership { Ingroup, Outgroup, Uncategorized } enum Membership {
Ingroup,
Outgroup,
Uncategorized,
}
fn classify( fn classify(
genomes: &[GenomeInfo], genomes: &[GenomeInfo],
ingroup: &[MetaPred], ingroup: &[MetaPred],
outgroup: &[MetaPred], outgroup: &[MetaPred],
) -> Vec<Membership> { ) -> Vec<Membership> {
genomes.iter().map(|g| { genomes
let in_r = if ingroup.is_empty() { None } else { eval_and(ingroup, &g.meta) }; .iter()
let out_r = if outgroup.is_empty() { None } else { eval_or(outgroup, &g.meta) }; .map(|g| {
let in_r = if ingroup.is_empty() {
None
} else {
eval_and(ingroup, &g.meta)
};
let out_r = if outgroup.is_empty() {
None
} else {
eval_or(outgroup, &g.meta)
};
// Ingroup wins over outgroup. // Ingroup wins over outgroup.
if in_r == Some(true) { return Membership::Ingroup; } if in_r == Some(true) {
if out_r == Some(true) { return Membership::Outgroup; } return Membership::Ingroup;
}
if out_r == Some(true) {
return Membership::Outgroup;
}
Membership::Uncategorized Membership::Uncategorized
}).collect() })
.collect()
} }
// ── Group quorum filter construction ────────────────────────────────────────── // ── Group quorum filter construction ──────────────────────────────────────────
@@ -161,8 +197,14 @@ pub struct GenomeSelector {
impl GenomeSelector { impl GenomeSelector {
/// Parse ingroup (AND'd) and outgroup (OR'd) predicate strings. /// Parse ingroup (AND'd) and outgroup (OR'd) predicate strings.
pub fn parse(ingroup: &[String], outgroup: &[String]) -> Result<Self, String> { pub fn parse(ingroup: &[String], outgroup: &[String]) -> Result<Self, String> {
let ingroup = ingroup.iter().map(|s| MetaPred::parse(s)).collect::<Result<Vec<_>, _>>()?; let ingroup = ingroup
let outgroup = outgroup.iter().map(|s| MetaPred::parse(s)).collect::<Result<Vec<_>, _>>()?; .iter()
.map(|s| MetaPred::parse(s))
.collect::<Result<Vec<_>, _>>()?;
let outgroup = outgroup
.iter()
.map(|s| MetaPred::parse(s))
.collect::<Result<Vec<_>, _>>()?;
Ok(Self { ingroup, outgroup }) Ok(Self { ingroup, outgroup })
} }
@@ -174,17 +216,29 @@ impl GenomeSelector {
let genomes = meta.genomes().map_err(|e| e.to_string())?; let genomes = meta.genomes().map_err(|e| e.to_string())?;
if self.ingroup.is_empty() && self.outgroup.is_empty() { if self.ingroup.is_empty() && self.outgroup.is_empty() {
return Ok(Selection { ingroup_idx: (0..genomes.len()).collect(), outgroup_idx: vec![] }); return Ok(Selection {
ingroup_idx: (0..genomes.len()).collect(),
outgroup_idx: vec![],
});
} }
let members = classify(&genomes, &self.ingroup, &self.outgroup); let members = classify(&genomes, &self.ingroup, &self.outgroup);
let ingroup_idx: Vec<usize> = members.iter().enumerate() let ingroup_idx: Vec<usize> = members
.iter()
.enumerate()
.filter(|(_, m)| matches!(m, Membership::Ingroup)) .filter(|(_, m)| matches!(m, Membership::Ingroup))
.map(|(i, _)| i).collect(); .map(|(i, _)| i)
let outgroup_idx: Vec<usize> = members.iter().enumerate() .collect();
let outgroup_idx: Vec<usize> = members
.iter()
.enumerate()
.filter(|(_, m)| matches!(m, Membership::Outgroup)) .filter(|(_, m)| matches!(m, Membership::Outgroup))
.map(|(i, _)| i).collect(); .map(|(i, _)| i)
Ok(Selection { ingroup_idx, outgroup_idx }) .collect();
Ok(Selection {
ingroup_idx,
outgroup_idx,
})
} }
/// Build a `GroupQuorumFilter` from this selector's classification of `meta`. /// Build a `GroupQuorumFilter` from this selector's classification of `meta`.
@@ -202,34 +256,60 @@ impl GenomeSelector {
let in_size = selection.ingroup_idx.len(); let in_size = selection.ingroup_idx.len();
let out_size = selection.outgroup_idx.len(); let out_size = selection.outgroup_idx.len();
let ingroup_quorum_explicit = p.min_count.is_some() || p.max_count.is_some() let ingroup_quorum_explicit = p.min_count.is_some()
|| p.min_frac.is_some() || p.max_frac.is_some(); || p.max_count.is_some()
let outgroup_quorum_explicit = p.min_outgroup_count.is_some() || p.max_outgroup_count.is_some() || p.min_frac.is_some()
|| p.min_outgroup_frac.is_some() || p.max_outgroup_frac.is_some(); || p.max_frac.is_some();
let outgroup_quorum_explicit = p.min_outgroup_count.is_some()
|| p.max_outgroup_count.is_some()
|| p.min_outgroup_frac.is_some()
|| p.max_outgroup_frac.is_some();
let default_min_frac = if !self.ingroup.is_empty() && !ingroup_quorum_explicit { 1.0 } else { 0.0 }; let default_min_frac = if !self.ingroup.is_empty() && !ingroup_quorum_explicit {
let default_max_outgroup_count = if !self.outgroup.is_empty() && !outgroup_quorum_explicit { 0 } else { out_size }; 1.0
} else {
0.0
};
let default_max_outgroup_count = if !self.outgroup.is_empty() && !outgroup_quorum_explicit {
0
} else {
out_size
};
// Resolve a signed count: negative means an offset from the group size // Resolve a signed count: negative means an offset from the group size
// (e.g. -1 = all but one), floored at 1 so the negative form always keeps // (e.g. -1 = all but one), floored at 1 so the negative form always keeps
// constraining the group — even a singleton group, where n-1 would be 0 // constraining the group — even a singleton group, where n-1 would be 0
// and would otherwise drop the constraint entirely. // and would otherwise drop the constraint entirely.
let resolve = |v: isize, size: usize| -> usize { let resolve = |v: isize, size: usize| -> usize {
if v < 0 { (size as isize + v).max(1) as usize } else { v as usize } if v < 0 {
(size as isize + v).max(1) as usize
} else {
v as usize
}
}; };
let min_count = p.min_count.map(|v| resolve(v, in_size)).unwrap_or(0); let min_count = p.min_count.map(|v| resolve(v, in_size)).unwrap_or(0);
let max_count = p.max_count.map(|v| resolve(v, in_size)).unwrap_or(in_size); let max_count = p.max_count.map(|v| resolve(v, in_size)).unwrap_or(in_size);
let min_frac = p.min_frac.unwrap_or(default_min_frac); let min_frac = p.min_frac.unwrap_or(default_min_frac);
let max_frac = p.max_frac.unwrap_or(1.0); let max_frac = p.max_frac.unwrap_or(1.0);
let min_outgroup_count = p.min_outgroup_count.map(|v| resolve(v, out_size)).unwrap_or(0); let min_outgroup_count = p
let max_outgroup_count = p.max_outgroup_count.map(|v| resolve(v, out_size)).unwrap_or(default_max_outgroup_count); .min_outgroup_count
.map(|v| resolve(v, out_size))
.unwrap_or(0);
let max_outgroup_count = p
.max_outgroup_count
.map(|v| resolve(v, out_size))
.unwrap_or(default_max_outgroup_count);
let min_outgroup_frac = p.min_outgroup_frac.unwrap_or(0.0); let min_outgroup_frac = p.min_outgroup_frac.unwrap_or(0.0);
let max_outgroup_frac = p.max_outgroup_frac.unwrap_or(1.0); let max_outgroup_frac = p.max_outgroup_frac.unwrap_or(1.0);
for (v, lo, hi) in [ for (v, lo, hi) in [
("--min-frac/--max-frac", min_frac, max_frac), ("--min-frac/--max-frac", min_frac, max_frac),
("--min-outgroup-frac/--max-outgroup-frac", min_outgroup_frac, max_outgroup_frac), (
"--min-outgroup-frac/--max-outgroup-frac",
min_outgroup_frac,
max_outgroup_frac,
),
] { ] {
if !(0.0..=1.0).contains(&lo) || !(0.0..=1.0).contains(&hi) { if !(0.0..=1.0).contains(&lo) || !(0.0..=1.0).contains(&hi) {
return Err(format!("{v}: fraction values must be in [0.0, 1.0]")); return Err(format!("{v}: fraction values must be in [0.0, 1.0]"));
@@ -239,10 +319,14 @@ impl GenomeSelector {
} }
} }
if min_count > max_count { if min_count > max_count {
return Err(format!("--min-count/--max-count: min ({min_count}) is greater than max ({max_count})")); return Err(format!(
"--min-count/--max-count: min ({min_count}) is greater than max ({max_count})"
));
} }
if min_outgroup_count > max_outgroup_count { if min_outgroup_count > max_outgroup_count {
return Err(format!("--min-outgroup-count/--max-outgroup-count: min ({min_outgroup_count}) is greater than max ({max_outgroup_count})")); return Err(format!(
"--min-outgroup-count/--max-outgroup-count: min ({min_outgroup_count}) is greater than max ({max_outgroup_count})"
));
} }
Ok(GroupQuorumFilter { Ok(GroupQuorumFilter {
@@ -259,4 +343,3 @@ impl GenomeSelector {
}) })
} }
} }
+10 -2
View File
@@ -156,7 +156,10 @@ impl IndexCache {
/// (not an error) if `partition` isn't cached — same convention as /// (not an error) if `partition` isn't cached — same convention as
/// [`get_layer`](Self::get_layer). `'static` for the same reason /// [`get_layer`](Self::get_layer). `'static` for the same reason
/// [`iter_indexed`](Self::iter_indexed) is. /// [`iter_indexed`](Self::iter_indexed) is.
pub fn iter_partition(&self, partition: usize) -> impl Iterator<Item = Arc<KmerLayer>> + 'static { pub fn iter_partition(
&self,
partition: usize,
) -> impl Iterator<Item = Arc<KmerLayer>> + 'static {
LayerIter { LayerIter {
cache: Arc::clone(&self.layer_cache), cache: Arc::clone(&self.layer_cache),
partitions: vec![partition].into_iter(), partitions: vec![partition].into_iter(),
@@ -173,7 +176,12 @@ impl IndexCache {
pub fn iter_indexed(&self) -> impl Iterator<Item = (usize, usize, Arc<KmerLayer>)> + 'static { pub fn iter_indexed(&self) -> impl Iterator<Item = (usize, usize, Arc<KmerLayer>)> + 'static {
LayerIter { LayerIter {
cache: Arc::clone(&self.layer_cache), cache: Arc::clone(&self.layer_cache),
partitions: self.layer_cache.keys().copied().collect::<Vec<_>>().into_iter(), partitions: self
.layer_cache
.keys()
.copied()
.collect::<Vec<_>>()
.into_iter(),
current: None, current: None,
} }
} }
+29 -8
View File
@@ -7,8 +7,12 @@ use obicompactvec::{PersistentBitMatrix, PersistentSparseBitMatrix};
use obikindex::KmerIndex; use obikindex::KmerIndex;
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
let sparse_root = std::env::args().nth(1).expect("usage: compare_sparse <sparse_root> <dense_root>"); let sparse_root = std::env::args()
let dense_root = std::env::args().nth(2).expect("usage: compare_sparse <sparse_root> <dense_root>"); .nth(1)
.expect("usage: compare_sparse <sparse_root> <dense_root>");
let dense_root = std::env::args()
.nth(2)
.expect("usage: compare_sparse <sparse_root> <dense_root>");
let sparse = KmerIndex::open(&sparse_root)?; let sparse = KmerIndex::open(&sparse_root)?;
let dense = KmerIndex::open(&dense_root)?; let dense = KmerIndex::open(&dense_root)?;
@@ -16,8 +20,16 @@ fn main() -> anyhow::Result<()> {
let n_parts = sparse.n_partitions(); let n_parts = sparse.n_partitions();
let n_layers = sparse.n_layers_per_partition()?; let n_layers = sparse.n_layers_per_partition()?;
println!("index sparse: {} partitions, {} layers", sparse.n_partitions(), n_layers); println!(
println!("index dense: {} partitions, {} layers", dense.n_partitions(), dense.n_layers_per_partition()?); "index sparse: {} partitions, {} layers",
sparse.n_partitions(),
n_layers
);
println!(
"index dense: {} partitions, {} layers",
dense.n_partitions(),
dense.n_layers_per_partition()?
);
let mut total_layers = 0usize; let mut total_layers = 0usize;
let mut total_cells = 0usize; let mut total_cells = 0usize;
@@ -83,7 +95,8 @@ fn main() -> anyhow::Result<()> {
if dense_row[c] != sparse_row[c] { if dense_row[c] != sparse_row[c] {
mismatched_cells += 1; mismatched_cells += 1;
if first_mismatch.is_none() { if first_mismatch.is_none() {
first_mismatch = Some((part, layer, slot, c, dense_row[c], sparse_row[c])); first_mismatch =
Some((part, layer, slot, c, dense_row[c], sparse_row[c]));
} }
} }
} }
@@ -93,12 +106,20 @@ fn main() -> anyhow::Result<()> {
} }
} }
println!("Vérifié {} layers, {} cellules totales", total_layers, total_cells); println!(
"Vérifié {} layers, {} cellules totales",
total_layers, total_cells
);
if let Some((part, layer, slot, col, d, s)) = first_mismatch { if let Some((part, layer, slot, col, d, s)) = first_mismatch {
eprintln!("PREMIER MISMATCH : part={part} layer={layer} slot={slot} col={col} dense={d} sparse={s}"); eprintln!(
"PREMIER MISMATCH : part={part} layer={layer} slot={slot} col={col} dense={d} sparse={s}"
);
println!("MISMATCHES : {} cellules différentes", mismatched_cells); println!("MISMATCHES : {} cellules différentes", mismatched_cells);
} else { } else {
println!("OK : toutes les {} cellules sont identiques entre dense et sparse.", total_cells); println!(
"OK : toutes les {} cellules sont identiques entre dense et sparse.",
total_cells
);
} }
Ok(()) Ok(())
+10 -2
View File
@@ -55,7 +55,11 @@ pub trait IndexBuilder: Sized {
/// Shared tail of the `select`/`rebuild`/`merge` construction paths, /// Shared tail of the `select`/`rebuild`/`merge` construction paths,
/// once their partitions have been written. `sparse` selects the /// once their partitions have been written. `sparse` selects the
/// on-disk presence-matrix format (see `pack_matrices`). /// on-disk presence-matrix format (see `pack_matrices`).
fn finalize_indexed<P: AsRef<Path>>(output: P, rep: &mut Reporter, sparse: bool) -> OKIResult<Self>; fn finalize_indexed<P: AsRef<Path>>(
output: P,
rep: &mut Reporter,
sparse: bool,
) -> OKIResult<Self>;
/// Current construction state, read fresh from `index.meta` (see /// Current construction state, read fresh from `index.meta` (see
/// `DevDocMD/implementation/partition_layer_cache.md`, "(11)" — no /// `DevDocMD/implementation/partition_layer_cache.md`, "(11)" — no
@@ -100,7 +104,11 @@ impl IndexBuilder for KmerIndex {
Ok(idx) Ok(idx)
} }
fn finalize_indexed<P: AsRef<Path>>(output: P, rep: &mut Reporter, sparse: bool) -> OKIResult<Self> { fn finalize_indexed<P: AsRef<Path>>(
output: P,
rep: &mut Reporter,
sparse: bool,
) -> OKIResult<Self> {
let output = output.as_ref(); let output = output.as_ref();
// `output` is held exclusively by the builder that wrote it: reopen // `output` is held exclusively by the builder that wrote it: reopen
// without a lock, a locking `open` would wait for that builder for ever. // without a lock, a locking `open` would wait for that builder for ever.
+4 -1
View File
@@ -23,7 +23,10 @@ pub enum OKIError {
IncompatibleEvidence(String), IncompatibleEvidence(String),
/// Malformed data encountered while reading/writing a layer file, tagged /// Malformed data encountered while reading/writing a layer file, tagged
/// with the operation that hit it. /// with the operation that hit it.
InvalidData { context: &'static str, detail: String }, InvalidData {
context: &'static str,
detail: String,
},
} }
pub type OKIResult<T> = Result<T, OKIError>; pub type OKIResult<T> = Result<T, OKIError>;
+10 -2
View File
@@ -38,7 +38,11 @@ impl KmerIndex {
let genomes = genome_info.into_iter().collect(); let genomes = genome_info.into_iter().collect();
let meta = IndexMeta::create_at(&root_path, config, genomes).map_err(OKIError::Io)?; let meta = IndexMeta::create_at(&root_path, config, genomes).map_err(OKIError::Io)?;
let lock = obisys::LockSlot::empty(&root_path); let lock = obisys::LockSlot::empty(&root_path);
let idx = Self { root_path, meta: Arc::new(meta), lock }; let idx = Self {
root_path,
meta: Arc::new(meta),
lock,
};
if !idx.acquire_lock() { if !idx.acquire_lock() {
return Err(OKIError::Io(std::io::Error::other( return Err(OKIError::Io(std::io::Error::other(
"failed to acquire index lock right after create", "failed to acquire index lock right after create",
@@ -102,7 +106,11 @@ impl KmerIndex {
set_k(meta.config.kmer_size); set_k(meta.config.kmer_size);
set_m(meta.config.minimizer_size); set_m(meta.config.minimizer_size);
let lock = obisys::LockSlot::empty(&root_path); let lock = obisys::LockSlot::empty(&root_path);
Ok(Self { root_path, meta: Arc::new(meta), lock }) Ok(Self {
root_path,
meta: Arc::new(meta),
lock,
})
} }
/// Take the exclusive directory lock and hold it until `self` is dropped /// Take the exclusive directory lock and hold it until `self` is dropped
+3 -3
View File
@@ -1,11 +1,11 @@
mod builder;
pub mod error; pub mod error;
mod kmer_index;
pub mod meta; pub mod meta;
pub mod state; pub mod state;
mod builder;
mod kmer_index;
pub use error::{OKIError, OKIResult};
pub use builder::IndexBuilder; pub use builder::IndexBuilder;
pub use error::{OKIError, OKIResult};
pub use kmer_index::KmerIndex; pub use kmer_index::KmerIndex;
pub use meta::{GenomeInfo, IndexConfig, IndexMeta, META_FILENAME}; pub use meta::{GenomeInfo, IndexConfig, IndexMeta, META_FILENAME};
pub use state::IndexState; pub use state::IndexState;
+54 -18
View File
@@ -27,7 +27,9 @@ use std::path::{Path, PathBuf};
use crate::layer::utils::LAYERNAME_SUFFIX; use crate::layer::utils::LAYERNAME_SUFFIX;
use ndarray::{Array1, Array2}; use ndarray::{Array1, Array2};
use obicompactvec::{BitPartials, ColumnWeights, CountPartials, PersistentBitMatrix, PersistentIntMatrix}; use obicompactvec::{
BitPartials, ColumnWeights, CountPartials, PersistentBitMatrix, PersistentIntMatrix,
};
use obikseq::CanonicalKmer; use obikseq::CanonicalKmer;
use crate::index::error::OKIResult; use crate::index::error::OKIResult;
@@ -274,7 +276,9 @@ impl KmerLayer {
match self { match self {
KmerLayer::Count { layer, .. } => layer.row_presence_histogram(threshold), KmerLayer::Count { layer, .. } => layer.row_presence_histogram(threshold),
KmerLayer::Presence { layer, .. } => layer.row_presence_histogram(), KmerLayer::Presence { layer, .. } => layer.row_presence_histogram(),
KmerLayer::Empty { .. } => panic!("Layer::row_presence_histogram() called on an Empty layer"), KmerLayer::Empty { .. } => {
panic!("Layer::row_presence_histogram() called on an Empty layer")
}
} }
} }
@@ -398,43 +402,67 @@ impl CountPartials for KmerLayer {
fn partial_bray(&self) -> Array2<u64> { fn partial_bray(&self) -> Array2<u64> {
match self { match self {
KmerLayer::Count { layer, .. } => layer.partial_bray(), KmerLayer::Count { layer, .. } => layer.partial_bray(),
KmerLayer::Presence { .. } => panic!("CountPartials::partial_bray() called on a Presence layer"), KmerLayer::Presence { .. } => {
KmerLayer::Empty { .. } => panic!("CountPartials::partial_bray() called on an Empty layer"), panic!("CountPartials::partial_bray() called on a Presence layer")
}
KmerLayer::Empty { .. } => {
panic!("CountPartials::partial_bray() called on an Empty layer")
}
} }
} }
fn partial_euclidean(&self) -> Array2<f64> { fn partial_euclidean(&self) -> Array2<f64> {
match self { match self {
KmerLayer::Count { layer, .. } => layer.partial_euclidean(), KmerLayer::Count { layer, .. } => layer.partial_euclidean(),
KmerLayer::Presence { .. } => panic!("CountPartials::partial_euclidean() called on a Presence layer"), KmerLayer::Presence { .. } => {
KmerLayer::Empty { .. } => panic!("CountPartials::partial_euclidean() called on an Empty layer"), panic!("CountPartials::partial_euclidean() called on a Presence layer")
}
KmerLayer::Empty { .. } => {
panic!("CountPartials::partial_euclidean() called on an Empty layer")
}
} }
} }
fn partial_threshold_jaccard(&self, threshold: u32) -> (Array2<u64>, Array2<u64>) { fn partial_threshold_jaccard(&self, threshold: u32) -> (Array2<u64>, Array2<u64>) {
match self { match self {
KmerLayer::Count { layer, .. } => layer.partial_threshold_jaccard(threshold), KmerLayer::Count { layer, .. } => layer.partial_threshold_jaccard(threshold),
KmerLayer::Presence { .. } => panic!("CountPartials::partial_threshold_jaccard() called on a Presence layer"), KmerLayer::Presence { .. } => {
KmerLayer::Empty { .. } => panic!("CountPartials::partial_threshold_jaccard() called on an Empty layer"), panic!("CountPartials::partial_threshold_jaccard() called on a Presence layer")
}
KmerLayer::Empty { .. } => {
panic!("CountPartials::partial_threshold_jaccard() called on an Empty layer")
}
} }
} }
fn partial_relfreq_bray(&self, global: &Array1<u64>) -> Array2<f64> { fn partial_relfreq_bray(&self, global: &Array1<u64>) -> Array2<f64> {
match self { match self {
KmerLayer::Count { layer, .. } => layer.partial_relfreq_bray(global), KmerLayer::Count { layer, .. } => layer.partial_relfreq_bray(global),
KmerLayer::Presence { .. } => panic!("CountPartials::partial_relfreq_bray() called on a Presence layer"), KmerLayer::Presence { .. } => {
KmerLayer::Empty { .. } => panic!("CountPartials::partial_relfreq_bray() called on an Empty layer"), panic!("CountPartials::partial_relfreq_bray() called on a Presence layer")
}
KmerLayer::Empty { .. } => {
panic!("CountPartials::partial_relfreq_bray() called on an Empty layer")
}
} }
} }
fn partial_relfreq_euclidean(&self, global: &Array1<u64>) -> Array2<f64> { fn partial_relfreq_euclidean(&self, global: &Array1<u64>) -> Array2<f64> {
match self { match self {
KmerLayer::Count { layer, .. } => layer.partial_relfreq_euclidean(global), KmerLayer::Count { layer, .. } => layer.partial_relfreq_euclidean(global),
KmerLayer::Presence { .. } => panic!("CountPartials::partial_relfreq_euclidean() called on a Presence layer"), KmerLayer::Presence { .. } => {
KmerLayer::Empty { .. } => panic!("CountPartials::partial_relfreq_euclidean() called on an Empty layer"), panic!("CountPartials::partial_relfreq_euclidean() called on a Presence layer")
}
KmerLayer::Empty { .. } => {
panic!("CountPartials::partial_relfreq_euclidean() called on an Empty layer")
}
} }
} }
fn partial_hellinger(&self, global: &Array1<u64>) -> Array2<f64> { fn partial_hellinger(&self, global: &Array1<u64>) -> Array2<f64> {
match self { match self {
KmerLayer::Count { layer, .. } => layer.partial_hellinger(global), KmerLayer::Count { layer, .. } => layer.partial_hellinger(global),
KmerLayer::Presence { .. } => panic!("CountPartials::partial_hellinger() called on a Presence layer"), KmerLayer::Presence { .. } => {
KmerLayer::Empty { .. } => panic!("CountPartials::partial_hellinger() called on an Empty layer"), panic!("CountPartials::partial_hellinger() called on a Presence layer")
}
KmerLayer::Empty { .. } => {
panic!("CountPartials::partial_hellinger() called on an Empty layer")
}
} }
} }
} }
@@ -443,15 +471,23 @@ impl BitPartials for KmerLayer {
fn partial_jaccard(&self) -> (Array2<u64>, Array2<u64>) { fn partial_jaccard(&self) -> (Array2<u64>, Array2<u64>) {
match self { match self {
KmerLayer::Presence { layer, .. } => layer.partial_jaccard(), KmerLayer::Presence { layer, .. } => layer.partial_jaccard(),
KmerLayer::Count { .. } => panic!("BitPartials::partial_jaccard() called on a Count layer"), KmerLayer::Count { .. } => {
KmerLayer::Empty { .. } => panic!("BitPartials::partial_jaccard() called on an Empty layer"), panic!("BitPartials::partial_jaccard() called on a Count layer")
}
KmerLayer::Empty { .. } => {
panic!("BitPartials::partial_jaccard() called on an Empty layer")
}
} }
} }
fn partial_hamming(&self) -> Array2<u64> { fn partial_hamming(&self) -> Array2<u64> {
match self { match self {
KmerLayer::Presence { layer, .. } => layer.partial_hamming(), KmerLayer::Presence { layer, .. } => layer.partial_hamming(),
KmerLayer::Count { .. } => panic!("BitPartials::partial_hamming() called on a Count layer"), KmerLayer::Count { .. } => {
KmerLayer::Empty { .. } => panic!("BitPartials::partial_hamming() called on an Empty layer"), panic!("BitPartials::partial_hamming() called on a Count layer")
}
KmerLayer::Empty { .. } => {
panic!("BitPartials::partial_hamming() called on an Empty layer")
}
} }
} }
} }
+3 -1
View File
@@ -42,7 +42,9 @@ pub struct EvidenceWriter {
impl EvidenceWriter { impl EvidenceWriter {
pub fn new(n_slots: usize) -> Self { pub fn new(n_slots: usize) -> Self {
Self { buf: vec![0u32; n_slots] } Self {
buf: vec![0u32; n_slots],
}
} }
#[inline] #[inline]
+48 -16
View File
@@ -34,11 +34,17 @@ impl FingerprintVec {
let f = File::open(path)?; let f = File::open(path)?;
let mmap = unsafe { Mmap::map(&f)? }; let mmap = unsafe { Mmap::map(&f)? };
if mmap.len() < HEADER || &mmap[..4] != MAGIC { if mmap.len() < HEADER || &mmap[..4] != MAGIC {
return Err(OKIError::InvalidData { context: "layer", detail: "bad fingerprint magic".into() }); return Err(OKIError::InvalidData {
context: "layer",
detail: "bad fingerprint magic".into(),
});
} }
let b = mmap[4]; let b = mmap[4];
if b == 0 || b > 64 { if b == 0 || b > 64 {
return Err(OKIError::InvalidData { context: "layer", detail: "invalid fingerprint width".into() }); return Err(OKIError::InvalidData {
context: "layer",
detail: "invalid fingerprint width".into(),
});
} }
let n = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize; let n = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize;
let mask: u64 = if b == 64 { u64::MAX } else { (1u64 << b) - 1 }; let mask: u64 = if b == 64 { u64::MAX } else { (1u64 << b) - 1 };
@@ -47,14 +53,20 @@ impl FingerprintVec {
std::slice::from_raw_parts(mmap[HEADER..].as_ptr(), (n * b as usize + 7) / 8) std::slice::from_raw_parts(mmap[HEADER..].as_ptr(), (n * b as usize + 7) / 8)
}; };
let bits = BitSlice::<u8, Lsb0>::from_slice(data); let bits = BitSlice::<u8, Lsb0>::from_slice(data);
Ok(Self { _mmap: mmap, bits, n, b, mask }) Ok(Self {
_mmap: mmap,
bits,
n,
b,
mask,
})
} }
#[inline] #[inline]
pub fn get(&self, slot: usize) -> u64 { pub fn get(&self, slot: usize) -> u64 {
debug_assert!(slot < self.n); debug_assert!(slot < self.n);
let lo = slot * self.b as usize; let lo = slot * self.b as usize;
self.bits[lo .. lo + self.b as usize].load_le::<u64>() self.bits[lo..lo + self.b as usize].load_le::<u64>()
} }
#[inline] #[inline]
@@ -62,8 +74,12 @@ impl FingerprintVec {
self.get(slot) == (fingerprint & self.mask) self.get(slot) == (fingerprint & self.mask)
} }
pub fn n(&self) -> usize { self.n } pub fn n(&self) -> usize {
pub fn b(&self) -> u8 { self.b } self.n
}
pub fn b(&self) -> u8 {
self.b
}
} }
// ── Writer ──────────────────────────────────────────────────────────────────── // ── Writer ────────────────────────────────────────────────────────────────────
@@ -78,7 +94,11 @@ impl FingerprintVecWriter {
pub fn new(n: usize, b: u8) -> Self { pub fn new(n: usize, b: u8) -> Self {
assert!(b > 0 && b <= 64, "fingerprint width must be 1..=64"); assert!(b > 0 && b <= 64, "fingerprint width must be 1..=64");
let data_bytes = (n * b as usize + 7) / 8; let data_bytes = (n * b as usize + 7) / 8;
Self { buf: vec![0u8; data_bytes], n, b } Self {
buf: vec![0u8; data_bytes],
n,
b,
}
} }
#[inline] #[inline]
@@ -86,14 +106,15 @@ impl FingerprintVecWriter {
debug_assert!(slot < self.n); debug_assert!(slot < self.n);
let lo = slot * self.b as usize; let lo = slot * self.b as usize;
let bits = BitSlice::<u8, Lsb0>::from_slice_mut(&mut self.buf); let bits = BitSlice::<u8, Lsb0>::from_slice_mut(&mut self.buf);
bits[lo .. lo + self.b as usize].store_le(fingerprint); bits[lo..lo + self.b as usize].store_le(fingerprint);
} }
pub fn write(self, path: &Path) -> OKIResult<()> { pub fn write(self, path: &Path) -> OKIResult<()> {
let mut f = BufWriter::new(File::create(path).map_err(OKIError::Io)?); let mut f = BufWriter::new(File::create(path).map_err(OKIError::Io)?);
f.write_all(MAGIC).map_err(OKIError::Io)?; f.write_all(MAGIC).map_err(OKIError::Io)?;
f.write_all(&[self.b, 0, 0, 0]).map_err(OKIError::Io)?; f.write_all(&[self.b, 0, 0, 0]).map_err(OKIError::Io)?;
f.write_all(&(self.n as u64).to_le_bytes()).map_err(OKIError::Io)?; f.write_all(&(self.n as u64).to_le_bytes())
.map_err(OKIError::Io)?;
f.write_all(&self.buf).map_err(OKIError::Io)?; f.write_all(&self.buf).map_err(OKIError::Io)?;
Ok(()) Ok(())
} }
@@ -124,13 +145,21 @@ mod tests {
} }
#[test] #[test]
fn roundtrip_b1() { roundtrip(8, 1, &[1, 0, 1, 1, 0, 0, 1, 0]); } fn roundtrip_b1() {
roundtrip(8, 1, &[1, 0, 1, 1, 0, 0, 1, 0]);
}
#[test] #[test]
fn roundtrip_b8() { roundtrip(4, 8, &[0, 127, 200, 255]); } fn roundtrip_b8() {
roundtrip(4, 8, &[0, 127, 200, 255]);
}
#[test] #[test]
fn roundtrip_b16() { roundtrip(3, 16, &[0, 0xABCD, 0xFFFF]); } fn roundtrip_b16() {
roundtrip(3, 16, &[0, 0xABCD, 0xFFFF]);
}
#[test] #[test]
fn roundtrip_b7() { roundtrip(5, 7, &[0, 63, 127, 1, 42]); } fn roundtrip_b7() {
roundtrip(5, 7, &[0, 63, 127, 1, 42]);
}
#[test] #[test]
fn roundtrip_b13_unaligned() { fn roundtrip_b13_unaligned() {
let vals: Vec<u64> = (0..20).map(|i| (i * 317) % (1 << 13)).collect(); let vals: Vec<u64> = (0..20).map(|i| (i * 317) % (1 << 13)).collect();
@@ -141,11 +170,14 @@ mod tests {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let path = dir.path().join("fp.bin"); let path = dir.path().join("fp.bin");
let mut w = FingerprintVecWriter::new(4, 8); let mut w = FingerprintVecWriter::new(4, 8);
w.set(0, 42); w.set(1, 0); w.set(2, 255); w.set(3, 17); w.set(0, 42);
w.set(1, 0);
w.set(2, 255);
w.set(3, 17);
w.write(&path).unwrap(); w.write(&path).unwrap();
let r = FingerprintVec::open(&path).unwrap(); let r = FingerprintVec::open(&path).unwrap();
assert!( r.matches(0, 42)); assert!(r.matches(0, 42));
assert!(!r.matches(0, 43)); assert!(!r.matches(0, 43));
assert!( r.matches(2, 255)); assert!(r.matches(2, 255));
} }
} }
+3 -1
View File
@@ -32,7 +32,9 @@ pub enum IndexMode {
} }
impl Default for IndexMode { impl Default for IndexMode {
fn default() -> Self { Self::Exact } fn default() -> Self {
Self::Exact
}
} }
impl IndexMode { impl IndexMode {
+112 -39
View File
@@ -24,7 +24,8 @@ pub(crate) const FINGERPRINT_FILE: &str = "fingerprint.bin";
/// The layer MPHF: `Xxh3Int` hasher, `CubicEps` buckets, multi-part (`SINGLE_PART = false`), /// The layer MPHF: `Xxh3Int` hasher, `CubicEps` buckets, multi-part (`SINGLE_PART = false`),
/// minimal (`REMAP = true`). Built owned (construction + store); queried through /// minimal (`REMAP = true`). Built owned (construction + store); queried through
/// `MemCase<Mphf>::uncase()`, the ε-copy view into the memory-mapped file. /// `MemCase<Mphf>::uncase()`, the ε-copy view into the memory-mapped file.
pub type Mphf = PtrHash<u64, CubicEps, CachelineEfVec<Vec<CachelineEf>>, Xxh3Int, Vec<u8>, false, true>; pub type Mphf =
PtrHash<u64, CubicEps, CachelineEfVec<Vec<CachelineEf>>, Xxh3Int, Vec<u8>, false, true>;
/// Construction parameters of [`Mphf`] — the one place they are chosen /// Construction parameters of [`Mphf`] — the one place they are chosen
/// (`lambda = 3.5`, `alpha = 0.99`, `CubicEps`, ~2.4 bits/key). /// (`lambda = 3.5`, `alpha = 0.99`, `CubicEps`, ~2.4 bits/key).
@@ -99,14 +100,20 @@ impl LayerEvidence {
/// mmap the evidence file(s) this identity points to. /// mmap the evidence file(s) this identity points to.
fn open(self) -> OKIResult<OpenLayerEvidence> { fn open(self) -> OKIResult<OpenLayerEvidence> {
Ok(match self { Ok(match self {
LayerEvidence::Exact { evidence_path, unitig_path } => OpenLayerEvidence::Exact { LayerEvidence::Exact {
evidence_path,
unitig_path,
} => OpenLayerEvidence::Exact {
evidence: Evidence::open(&evidence_path)?, evidence: Evidence::open(&evidence_path)?,
unitigs: Arc::new(UnitigFileReader::open(&unitig_path)?), unitigs: Arc::new(UnitigFileReader::open(&unitig_path)?),
}, },
LayerEvidence::Approx { fingerprint_path } => OpenLayerEvidence::Approx { LayerEvidence::Approx { fingerprint_path } => OpenLayerEvidence::Approx {
fingerprint: FingerprintVec::open(&fingerprint_path)?, fingerprint: FingerprintVec::open(&fingerprint_path)?,
}, },
LayerEvidence::Hybrid { evidence_path, fingerprint_path } => OpenLayerEvidence::Hybrid { LayerEvidence::Hybrid {
evidence_path,
fingerprint_path,
} => OpenLayerEvidence::Hybrid {
evidence: Evidence::open(&evidence_path)?, evidence: Evidence::open(&evidence_path)?,
fingerprint: FingerprintVec::open(&fingerprint_path)?, fingerprint: FingerprintVec::open(&fingerprint_path)?,
}, },
@@ -136,10 +143,13 @@ impl EvidenceKind {
(true, false) => Ok(EvidenceKind::Exact), (true, false) => Ok(EvidenceKind::Exact),
(false, true) => Ok(EvidenceKind::Approx), (false, true) => Ok(EvidenceKind::Approx),
(true, true) => Ok(EvidenceKind::Hybrid), (true, true) => Ok(EvidenceKind::Hybrid),
(false, false) => Err(OKIError::InvalidData { context: "layer", detail: format!( (false, false) => Err(OKIError::InvalidData {
context: "layer",
detail: format!(
"no evidence.bin or fingerprint.bin in {}", "no evidence.bin or fingerprint.bin in {}",
layer_dir.display() layer_dir.display()
) }), ),
}),
} }
} }
} }
@@ -177,7 +187,12 @@ impl MphfLayer {
OpenLayerEvidence::Hybrid { evidence, .. } => evidence.len(), OpenLayerEvidence::Hybrid { evidence, .. } => evidence.len(),
OpenLayerEvidence::Approx { fingerprint } => fingerprint.n(), OpenLayerEvidence::Approx { fingerprint } => fingerprint.n(),
}; };
Ok(Self { unitigs, mphf, ev, n }) Ok(Self {
unitigs,
mphf,
ev,
n,
})
} }
// ── Query API ───────────────────────────────────────────────────────────── // ── Query API ─────────────────────────────────────────────────────────────
@@ -404,7 +419,10 @@ pub struct MphfOnly(MemCase<Mphf>);
impl MphfOnly { impl MphfOnly {
pub fn open(dir: &Path) -> OKIResult<Self> { pub fn open(dir: &Path) -> OKIResult<Self> {
let mphf: MemCase<Mphf> = unsafe { Mphf::mmap(&dir.join(MPHF_FILE), Flags::empty()) } let mphf: MemCase<Mphf> = unsafe { Mphf::mmap(&dir.join(MPHF_FILE), Flags::empty()) }
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?; .map_err(|e| OKIError::InvalidData {
context: "layer",
detail: e.to_string(),
})?;
Ok(Self(mphf)) Ok(Self(mphf))
} }
@@ -458,20 +476,32 @@ impl MphfLayer {
return Ok(0); return Ok(0);
} }
let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) } let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }.map_err(|e| {
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?; OKIError::InvalidData {
context: "layer",
detail: e.to_string(),
}
})?;
let mut ev = EvidenceWriter::new(n); let mut ev = EvidenceWriter::new(n);
let mut seen = vec![0u8; (n + 7) / 8]; let mut seen = vec![0u8; (n + 7) / 8];
for (slot, _, chunk_id, rank) in SlottedKmers::new(&mphf, unitigs.iter_indexed_canonical_kmers()) { for (slot, _, chunk_id, rank) in
SlottedKmers::new(&mphf, unitigs.iter_indexed_canonical_kmers())
{
if slot >= n { if slot >= n {
return Err(OKIError::InvalidData { context: "mphf", detail: "slot out of bounds".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "slot out of bounds".into(),
});
} }
let byte = slot / 8; let byte = slot / 8;
let bit = 1u8 << (slot % 8); let bit = 1u8 << (slot % 8);
if seen[byte] & bit != 0 { if seen[byte] & bit != 0 {
return Err(OKIError::InvalidData { context: "mphf", detail: "duplicate slot".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "duplicate slot".into(),
});
} }
seen[byte] |= bit; seen[byte] |= bit;
ev.set(slot, chunk_id as u32, rank as u8); ev.set(slot, chunk_id as u32, rank as u8);
@@ -485,12 +515,16 @@ impl MphfLayer {
/// Build `fingerprint.bin` from `unitigs.bin` + `mphf.bin`. /// Build `fingerprint.bin` from `unitigs.bin` + `mphf.bin`.
pub fn build_approx_evidence(dir: &Path, b: u8, z: u8) -> OKIResult<usize> { pub fn build_approx_evidence(dir: &Path, b: u8, z: u8) -> OKIResult<usize> {
if b == 0 || b > 64 { if b == 0 || b > 64 {
return Err(OKIError::InvalidData { context: "layer", detail: return Err(OKIError::InvalidData {
"fingerprint width must be 1..=64".into(), context: "layer",
detail: "fingerprint width must be 1..=64".into(),
}); });
} }
if z == 0 { if z == 0 {
return Err(OKIError::InvalidData { context: "layer", detail: "z must be ≥ 1".into() }); return Err(OKIError::InvalidData {
context: "layer",
detail: "z must be ≥ 1".into(),
});
} }
let unitig_path = dir.join(UNITIGS_FILE); let unitig_path = dir.join(UNITIGS_FILE);
let unitigs = UnitigFileReader::open_sequential(&unitig_path)?; let unitigs = UnitigFileReader::open_sequential(&unitig_path)?;
@@ -501,14 +535,21 @@ impl MphfLayer {
return Ok(0); return Ok(0);
} }
let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) } let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }.map_err(|e| {
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?; OKIError::InvalidData {
context: "layer",
detail: e.to_string(),
}
})?;
let mut fw = FingerprintVecWriter::new(n, b); let mut fw = FingerprintVecWriter::new(n, b);
for (slot, kmer, _, _) in SlottedKmers::new(&mphf, unitigs.iter_indexed_canonical_kmers()) { for (slot, kmer, _, _) in SlottedKmers::new(&mphf, unitigs.iter_indexed_canonical_kmers()) {
if slot >= n { if slot >= n {
return Err(OKIError::InvalidData { context: "mphf", detail: "slot out of bounds".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "slot out of bounds".into(),
});
} }
fw.set(slot, kmer.seq_hash()); fw.set(slot, kmer.seq_hash());
} }
@@ -535,15 +576,24 @@ impl MphfLayer {
let sk_to_olm = |e: obiskio::SKError| match e { let sk_to_olm = |e: obiskio::SKError| match e {
obiskio::SKError::Io(io) => OKIError::Io(io), obiskio::SKError::Io(io) => OKIError::Io(io),
e => OKIError::InvalidData { context: "layer", detail: e.to_string() }, e => OKIError::InvalidData {
context: "layer",
detail: e.to_string(),
},
}; };
// ── Empty layer ─────────────────────────────────────────────────────── // ── Empty layer ───────────────────────────────────────────────────────
if n == 0 { if n == 0 {
let mphf: Mphf = Mphf::try_new(&[] as &[u64], mphf_params()) let mphf: Mphf = Mphf::try_new(&[] as &[u64], mphf_params()).ok_or_else(|| {
.ok_or_else(|| OKIError::InvalidData { context: "mphf", detail: "construction failed".into() })?; OKIError::InvalidData {
unsafe { mphf.store(&dir.join(MPHF_FILE)) } context: "mphf",
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?; detail: "construction failed".into(),
}
})?;
unsafe { mphf.store(&dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData {
context: "layer",
detail: e.to_string(),
})?;
match mode { match mode {
IndexMode::Exact | IndexMode::Hybrid { .. } => { IndexMode::Exact | IndexMode::Hybrid { .. } => {
fs::File::create(dir.join(EVIDENCE_FILE))?; fs::File::create(dir.join(EVIDENCE_FILE))?;
@@ -561,13 +611,12 @@ impl MphfLayer {
// ── Pass 1: MPHF via clonable mmap iterator ─────────────────────────── // ── Pass 1: MPHF via clonable mmap iterator ───────────────────────────
let keys = CanonicalKmerIter::new(&unitig_path).map_err(sk_to_olm)?; let keys = CanonicalKmerIter::new(&unitig_path).map_err(sk_to_olm)?;
let mphf: Mphf = Mphf::new_from_par_iter( let mphf: Mphf =
n, Mphf::new_from_par_iter(n, keys.map(|k| k.raw()).par_bridge(), mphf_params());
keys.map(|k| k.raw()).par_bridge(), unsafe { mphf.store(&dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData {
mphf_params(), context: "layer",
); detail: e.to_string(),
unsafe { mphf.store(&dir.join(MPHF_FILE)) } })?;
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?;
// ── Pass 2: fill evidence files + callback ──────────────────────────── // ── Pass 2: fill evidence files + callback ────────────────────────────
let unitigs2 = UnitigFileReader::open_sequential(&unitig_path)?; let unitigs2 = UnitigFileReader::open_sequential(&unitig_path)?;
@@ -576,14 +625,22 @@ impl MphfLayer {
match mode { match mode {
IndexMode::Exact => { IndexMode::Exact => {
let mut ev = EvidenceWriter::new(n); let mut ev = EvidenceWriter::new(n);
for (slot, kmer, chunk_id, rank) in SlottedKmers::new(&mphf, unitigs2.iter_indexed_canonical_kmers()) { for (slot, kmer, chunk_id, rank) in
SlottedKmers::new(&mphf, unitigs2.iter_indexed_canonical_kmers())
{
if slot >= n { if slot >= n {
return Err(OKIError::InvalidData { context: "mphf", detail: "slot out of bounds".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "slot out of bounds".into(),
});
} }
let byte = slot / 8; let byte = slot / 8;
let bit = 1u8 << (slot % 8); let bit = 1u8 << (slot % 8);
if seen[byte] & bit != 0 { if seen[byte] & bit != 0 {
return Err(OKIError::InvalidData { context: "mphf", detail: "duplicate slot".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "duplicate slot".into(),
});
} }
seen[byte] |= bit; seen[byte] |= bit;
ev.set(slot, chunk_id as u32, rank as u8); ev.set(slot, chunk_id as u32, rank as u8);
@@ -595,14 +652,22 @@ impl MphfLayer {
IndexMode::Approx { b, .. } => { IndexMode::Approx { b, .. } => {
let mut fw = FingerprintVecWriter::new(n, *b); let mut fw = FingerprintVecWriter::new(n, *b);
for (slot, kmer, _, _) in SlottedKmers::new(&mphf, unitigs2.iter_indexed_canonical_kmers()) { for (slot, kmer, _, _) in
SlottedKmers::new(&mphf, unitigs2.iter_indexed_canonical_kmers())
{
if slot >= n { if slot >= n {
return Err(OKIError::InvalidData { context: "mphf", detail: "slot out of bounds".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "slot out of bounds".into(),
});
} }
let byte = slot / 8; let byte = slot / 8;
let bit = 1u8 << (slot % 8); let bit = 1u8 << (slot % 8);
if seen[byte] & bit != 0 { if seen[byte] & bit != 0 {
return Err(OKIError::InvalidData { context: "mphf", detail: "duplicate slot".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "duplicate slot".into(),
});
} }
seen[byte] |= bit; seen[byte] |= bit;
fw.set(slot, kmer.seq_hash()); fw.set(slot, kmer.seq_hash());
@@ -614,14 +679,22 @@ impl MphfLayer {
IndexMode::Hybrid { b, .. } => { IndexMode::Hybrid { b, .. } => {
let mut ev = EvidenceWriter::new(n); let mut ev = EvidenceWriter::new(n);
let mut fw = FingerprintVecWriter::new(n, *b); let mut fw = FingerprintVecWriter::new(n, *b);
for (slot, kmer, chunk_id, rank) in SlottedKmers::new(&mphf, unitigs2.iter_indexed_canonical_kmers()) { for (slot, kmer, chunk_id, rank) in
SlottedKmers::new(&mphf, unitigs2.iter_indexed_canonical_kmers())
{
if slot >= n { if slot >= n {
return Err(OKIError::InvalidData { context: "mphf", detail: "slot out of bounds".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "slot out of bounds".into(),
});
} }
let byte = slot / 8; let byte = slot / 8;
let bit = 1u8 << (slot % 8); let bit = 1u8 << (slot % 8);
if seen[byte] & bit != 0 { if seen[byte] & bit != 0 {
return Err(OKIError::InvalidData { context: "mphf", detail: "duplicate slot".into() }); return Err(OKIError::InvalidData {
context: "mphf",
detail: "duplicate slot".into(),
});
} }
seen[byte] |= bit; seen[byte] |= bit;
ev.set(slot, chunk_id as u32, rank as u8); ev.set(slot, chunk_id as u32, rank as u8);
+14 -4
View File
@@ -201,7 +201,8 @@ fn count_layer_reports_count_content_and_columnar_storage() {
DEFAULT_BLOCK_BITS, DEFAULT_BLOCK_BITS,
&IndexMode::Exact, &IndexMode::Exact,
|_| 1, |_| 1,
).unwrap(); )
.unwrap();
let layer = TypedLayer::<PersistentIntMatrix>::open(dir.path()).unwrap(); let layer = TypedLayer::<PersistentIntMatrix>::open(dir.path()).unwrap();
assert_eq!(layer.content(), LayerContent::Count); assert_eq!(layer.content(), LayerContent::Count);
@@ -238,8 +239,17 @@ fn enumerate_kmers_is_stable_across_calls() {
write_unitigs(dir.path(), &[b"AAAACGT", b"TTTTGCA"]); write_unitigs(dir.path(), &[b"AAAACGT", b"TTTTGCA"]);
let reader = UnitigFileReader::open_sequential(&dir.path().join(UNITIGS_FILE)).unwrap(); let reader = UnitigFileReader::open_sequential(&dir.path().join(UNITIGS_FILE)).unwrap();
let first: Vec<CanonicalKmer> = reader.iter_indexed_canonical_kmers().map(|(k, _, _)| k).collect(); let first: Vec<CanonicalKmer> = reader
.iter_indexed_canonical_kmers()
.map(|(k, _, _)| k)
.collect();
let reader2 = UnitigFileReader::open_sequential(&dir.path().join(UNITIGS_FILE)).unwrap(); let reader2 = UnitigFileReader::open_sequential(&dir.path().join(UNITIGS_FILE)).unwrap();
let second: Vec<CanonicalKmer> = reader2.iter_indexed_canonical_kmers().map(|(k, _, _)| k).collect(); let second: Vec<CanonicalKmer> = reader2
assert_eq!(first, second, "iter_indexed_canonical_kmers must be deterministic across calls"); .iter_indexed_canonical_kmers()
.map(|(k, _, _)| k)
.collect();
assert_eq!(
first, second,
"iter_indexed_canonical_kmers must be deterministic across calls"
);
} }
+4 -2
View File
@@ -1,10 +1,10 @@
// use crate::layer::utils::layer_dir; // use crate::layer::utils::layer_dir;
use ndarray::{Array1, Array2};
use obicompactvec::{ use obicompactvec::{
BinaryMatrix, BitPartials, ColBuilder, CountPartials, MatrixBuilder, PersistentBitMatrix, BinaryMatrix, BitPartials, ColBuilder, CountPartials, MatrixBuilder, PersistentBitMatrix,
PersistentBitMatrixBuilder, PersistentCompactIntMatrixBuilder, PersistentIntMatrix, PersistentBitMatrixBuilder, PersistentCompactIntMatrixBuilder, PersistentIntMatrix,
PersistentSparseBitMatrix, PersistentSparseBitMatrix,
}; };
use ndarray::{Array1, Array2};
use obikseq::CanonicalKmer; use obikseq::CanonicalKmer;
use obiskio::{UnitigFileReader, UnitigFileWriter}; use obiskio::{UnitigFileReader, UnitigFileWriter};
use std::collections::HashMap; use std::collections::HashMap;
@@ -399,7 +399,9 @@ impl TypedLayer<PersistentIntMatrix> {
/// genomes, a k-mer being present in a genome when its count reaches /// genomes, a k-mer being present in a genome when its count reaches
/// `threshold` (see `PersistentIntMatrix::row_presence_histogram`). /// `threshold` (see `PersistentIntMatrix::row_presence_histogram`).
pub fn row_presence_histogram(&self, threshold: u32) -> OKIResult<Vec<u64>> { pub fn row_presence_histogram(&self, threshold: u32) -> OKIResult<Vec<u64>> {
self.data.row_presence_histogram(threshold).map_err(OKIError::Io) self.data
.row_presence_histogram(threshold)
.map_err(OKIError::Io)
} }
/// Extract a sub-matrix of counts for the rows at `slots`. /// Extract a sub-matrix of counts for the rows at `slots`.
+4 -6
View File
@@ -12,10 +12,8 @@ pub mod index;
pub mod layer; pub mod layer;
pub mod partition; pub mod partition;
pub use index::{
GenomeInfo,
IndexBuilder, IndexConfig, IndexMeta, IndexState,
KmerIndex, OKIError, OKIResult,
META_FILENAME,
};
pub use index::meta; pub use index::meta;
pub use index::{
GenomeInfo, IndexBuilder, IndexConfig, IndexMeta, IndexState, KmerIndex, META_FILENAME,
OKIError, OKIResult,
};
+42 -10
View File
@@ -81,38 +81,68 @@ fn main() {
n n
}) })
.sum(); .sum();
eprintln!("IDEAL: nodes={} links={} -> maximal unitigs ≈ {}", kmers.len(), links, kmers.len() - links); eprintln!(
"IDEAL: nodes={} links={} -> maximal unitigs ≈ {}",
kmers.len(),
links,
kmers.len() - links
);
} }
if std::env::var("IDEALDUMP").is_ok() { if std::env::var("IDEALDUMP").is_ok() {
let set: HashSet<u64> = kmers.iter().map(|c| c.raw()).collect(); let set: HashSet<u64> = kmers.iter().map(|c| c.raw()).collect();
let outs = |a: obikseq::Kmer| -> Vec<obikseq::Kmer> { let outs = |a: obikseq::Kmer| -> Vec<obikseq::Kmer> {
(0..4u8).map(|x| a.push_right(x)).filter(|b| set.contains(&b.canonical().raw())).collect() (0..4u8)
.map(|x| a.push_right(x))
.filter(|b| set.contains(&b.canonical().raw()))
.collect()
}; };
// oriented kmer a has a mutual predecessor p iff ins(a)=={p} and outs(p)=={a} // oriented kmer a has a mutual predecessor p iff ins(a)=={p} and outs(p)=={a}
let pred = |a: obikseq::Kmer| -> Option<obikseq::Kmer> { let pred = |a: obikseq::Kmer| -> Option<obikseq::Kmer> {
let ins: Vec<obikseq::Kmer> = outs(a.revcomp()).into_iter().map(|b| b.revcomp()).collect(); let ins: Vec<obikseq::Kmer> =
if ins.len() == 1 && outs(ins[0]).len() == 1 { Some(ins[0]) } else { None } outs(a.revcomp()).into_iter().map(|b| b.revcomp()).collect();
if ins.len() == 1 && outs(ins[0]).len() == 1 {
Some(ins[0])
} else {
None
}
}; };
let mut seen_chains = std::collections::BTreeSet::new(); let mut seen_chains = std::collections::BTreeSet::new();
for c in &kmers { for c in &kmers {
for o in [c.into_kmer(), c.into_kmer().revcomp()] { for o in [c.into_kmer(), c.into_kmer().revcomp()] {
if pred(o).is_some() { continue; } if pred(o).is_some() {
continue;
}
let mut text: Vec<u8> = (0..k).map(|i| b"ACGT"[o.nucleotide(i) as usize]).collect(); let mut text: Vec<u8> = (0..k).map(|i| b"ACGT"[o.nucleotide(i) as usize]).collect();
let mut cur = o; let mut cur = o;
loop { loop {
let ob = outs(cur); let ob = outs(cur);
if ob.len() != 1 { break; } if ob.len() != 1 {
break;
}
let b = ob[0]; let b = ob[0];
if pred(b).is_none() { break; } if pred(b).is_none() {
break;
}
text.push(b"ACGT"[b.nucleotide(k - 1) as usize]); text.push(b"ACGT"[b.nucleotide(k - 1) as usize]);
cur = b; cur = b;
} }
let s = String::from_utf8(text).unwrap(); let s = String::from_utf8(text).unwrap();
let rc: String = s.bytes().rev().map(|c| match c { b'A' => 'T', b'C' => 'G', b'G' => 'C', _ => 'A' }).collect(); let rc: String = s
.bytes()
.rev()
.map(|c| match c {
b'A' => 'T',
b'C' => 'G',
b'G' => 'C',
_ => 'A',
})
.collect();
seen_chains.insert(if s <= rc { s } else { rc }); seen_chains.insert(if s <= rc { s } else { rc });
} }
} }
for u in &seen_chains { println!("IDEALUNITIG {} {}", u.len(), u); } for u in &seen_chains {
println!("IDEALUNITIG {} {}", u.len(), u);
}
} }
for r in 0..repeat { for r in 0..repeat {
let t = Instant::now(); let t = Instant::now();
@@ -150,7 +180,9 @@ fn main() {
if dump { if dump {
let mut v = seqs.lock().unwrap().clone(); let mut v = seqs.lock().unwrap().clone();
v.sort(); v.sort();
for u in v { println!("UNITIG {} {}", u.len(), u); } for u in v {
println!("UNITIG {} {}", u.len(), u);
}
} }
println!( println!(
"run {r}: nodes={} push={:.2?} degrees={:.2?} unitigs={:.2?} -> {} unitigs, {} nucleotides", "run {r}: nodes={} push={:.2?} degrees={:.2?} unitigs={:.2?} -> {} unitigs, {} nucleotides",
@@ -15,9 +15,7 @@ use super::kmer_sort::sort_unique_kmers;
fn build_mphf(unique_path: &Path, f0: usize) -> io::Result<Mphf> { fn build_mphf(unique_path: &Path, f0: usize) -> io::Result<Mphf> {
let file = fs::File::open(unique_path)?; let file = fs::File::open(unique_path)?;
let mmap = unsafe { Mmap::map(&file)? }; let mmap = unsafe { Mmap::map(&file)? };
let kmers: &[u64] = unsafe { let kmers: &[u64] = unsafe { std::slice::from_raw_parts(mmap.as_ptr() as *const u64, f0) };
std::slice::from_raw_parts(mmap.as_ptr() as *const u64, f0)
};
// Sequential constructor: the outer par_iter over partitions already saturates // Sequential constructor: the outer par_iter over partitions already saturates
// the Rayon pool. new_from_par_iter would get no additional threads and adds // the Rayon pool. new_from_par_iter would get no additional threads and adds
// coordination overhead. try_new accesses the same mmap'd pages at zero extra cost. // coordination overhead. try_new accesses the same mmap'd pages at zero extra cost.
@@ -82,20 +82,28 @@ fn merge_and_dedup(chunk_paths: &[PathBuf], unique_path: &Path) -> io::Result<us
impl ChunkReader { impl ChunkReader {
fn open(path: &Path) -> io::Result<Self> { fn open(path: &Path) -> io::Result<Self> {
let f = fs::File::open(path)?; let f = fs::File::open(path)?;
Ok(Self { mmap: unsafe { Mmap::map(&f)? }, pos: 0 }) Ok(Self {
mmap: unsafe { Mmap::map(&f)? },
pos: 0,
})
} }
fn peek(&self) -> Option<u64> { fn peek(&self) -> Option<u64> {
let off = self.pos * 8; let off = self.pos * 8;
if off + 8 <= self.mmap.len() { if off + 8 <= self.mmap.len() {
Some(u64::from_le_bytes(self.mmap[off..off + 8].try_into().unwrap())) Some(u64::from_le_bytes(
self.mmap[off..off + 8].try_into().unwrap(),
))
} else { } else {
None None
} }
} }
fn advance(&mut self) { self.pos += 1; } fn advance(&mut self) {
self.pos += 1;
}
} }
let mut readers: Vec<ChunkReader> = chunk_paths.iter() let mut readers: Vec<ChunkReader> = chunk_paths
.iter()
.map(|p| ChunkReader::open(p)) .map(|p| ChunkReader::open(p))
.collect::<io::Result<_>>()?; .collect::<io::Result<_>>()?;
@@ -10,11 +10,11 @@ use std::path::{Path, PathBuf};
use tracing::debug; use tracing::debug;
use niffler::send::compression::Format;
use niffler::Level; use niffler::Level;
use obikseq::superkmer::SuperKmer; use niffler::send::compression::Format;
use obikseq::Sequence;
use obikindex::layer::KmerLayer; use obikindex::layer::KmerLayer;
use obikseq::Sequence;
use obikseq::superkmer::SuperKmer;
use obiskio::{SKFileMeta, SKFileReader, SKFileWriter, SKResult}; use obiskio::{SKFileMeta, SKFileReader, SKFileWriter, SKResult};
/// Scratch-file extension for this algorithm's own intermediate split /// Scratch-file extension for this algorithm's own intermediate split
@@ -74,7 +74,11 @@ const MAX_SK_COUNT: u64 = (1 << 24) - 1;
/// Deduplicate one partition's layer-0 in place (two-phase split /// Deduplicate one partition's layer-0 in place (two-phase split
/// + merge): `layer.raw_superkmers_path()` -> `layer.dereplicated_superkmers_path()`. /// + merge): `layer.raw_superkmers_path()` -> `layer.dereplicated_superkmers_path()`.
pub(crate) fn dereplicate_partition(layer: &KmerLayer, level: Level, n_temp: usize) -> SKResult<()> { pub(crate) fn dereplicate_partition(
layer: &KmerLayer,
level: Level,
n_temp: usize,
) -> SKResult<()> {
let raw_path = layer.raw_superkmers_path(); let raw_path = layer.raw_superkmers_path();
if !raw_path.exists() { if !raw_path.exists() {
return Ok(()); return Ok(());
@@ -104,9 +104,7 @@ impl Algorithm for LayerBuilder<'_> {
let runner = PartitionRunner::new(); let runner = PartitionRunner::new();
runner.run( runner.run(
&order, &order,
|i| { |i| index.build_index_layer(i, min_ab, max_ab, with_counts, &evidence, block_bits),
index.build_index_layer(i, min_ab, max_ab, with_counts, &evidence, block_bits)
},
|_i, n_kmers, _elapsed| { |_i, n_kmers, _elapsed| {
total_kmers += n_kmers; total_kmers += n_kmers;
done += 1; done += 1;
-2
View File
@@ -13,7 +13,6 @@ pub mod dereplicator;
pub mod layer_builder; pub mod layer_builder;
pub mod partitionner; pub mod partitionner;
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use obikindex::KmerIndex; use obikindex::KmerIndex;
@@ -64,7 +63,6 @@ where
Ok(()) Ok(())
} }
/// Sequential counterpart to [`par_over_layer0`]: every partition's layer 0 /// Sequential counterpart to [`par_over_layer0`]: every partition's layer 0
/// that exists, in order, skipping those that don't — for callers that /// that exists, in order, skipping those that don't — for callers that
/// aggregate into shared state (e.g. [`counter::Counter::run`]'s spectrum /// aggregate into shared state (e.g. [`counter::Counter::run`]'s spectrum
@@ -256,7 +256,10 @@ impl Algorithm for PartitionRouter<'_> {
/// Errors if `.files(...)` was never called. /// Errors if `.files(...)` was never called.
fn run(&mut self) -> obikalgorithm::Result<()> { fn run(&mut self) -> obikalgorithm::Result<()> {
let path_source = self.files.take().ok_or_else(|| { let path_source = self.files.take().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "PartitionRouter::run: .files(...) was never called") io::Error::new(
io::ErrorKind::InvalidInput,
"PartitionRouter::run: .files(...) was never called",
)
})?; })?;
let k = self.index.kmer_size(); let k = self.index.kmer_size();
@@ -3,8 +3,8 @@ use std::collections::HashMap;
use crate::algorithms::counter::Counter; use crate::algorithms::counter::Counter;
use crate::algorithms::dereplicator::Dereplicator; use crate::algorithms::dereplicator::Dereplicator;
use obikalgorithm::Algorithm; use obikalgorithm::Algorithm;
use obikindex::{IndexConfig, KmerIndex};
use obikindex::layer::IndexMode; use obikindex::layer::IndexMode;
use obikindex::{IndexConfig, KmerIndex};
use obikrope::Rope; use obikrope::Rope;
use obikseq::SuperKmer; use obikseq::SuperKmer;
use obiskbuilder::build_superkmers; use obiskbuilder::build_superkmers;
@@ -26,7 +26,7 @@ use std::path::Path;
use crate::graph_pipeline::{materialize_layer, write_graph_as_unitigs}; use crate::graph_pipeline::{materialize_layer, write_graph_as_unitigs};
use epserde::prelude::*; use epserde::prelude::*;
use obicompactvec::{PersistentIntMatrix, PersistentCompactIntVec}; use obicompactvec::{PersistentCompactIntVec, PersistentIntMatrix};
use obidebruinj::GraphDeBruijn; use obidebruinj::GraphDeBruijn;
use obikindex::layer::IndexMode; use obikindex::layer::IndexMode;
use obikindex::layer::{KmerLayer, Mphf, TypedLayer}; use obikindex::layer::{KmerLayer, Mphf, TypedLayer};
@@ -138,7 +138,12 @@ impl PrivateBuilder for KmerIndex {
// A partition that received no k-mer has no layer 0 on disk at all // A partition that received no k-mer has no layer 0 on disk at all
// (small inputs against many partitions): nothing to build, not an // (small inputs against many partitions): nothing to build, not an
// error. // error.
if self.partition(i).map_err(|e| io::Error::other(e.to_string()))?.n_layers() == 0 { if self
.partition(i)
.map_err(|e| io::Error::other(e.to_string()))?
.n_layers()
== 0
{
return Ok(0); return Ok(0);
} }
let layer0 = self let layer0 = self
@@ -159,7 +164,9 @@ impl PrivateBuilder for KmerIndex {
let mphf1_opt: Option<Mphf> = if need_counts { let mphf1_opt: Option<Mphf> = if need_counts {
let p = layer0_dir.join("mphf1.bin"); let p = layer0_dir.join("mphf1.bin");
p.exists().then(|| unsafe { Mphf::load_full(&p) }.ok()).flatten() p.exists()
.then(|| unsafe { Mphf::load_full(&p) }.ok())
.flatten()
} else { } else {
None None
}; };
+18 -12
View File
@@ -1,18 +1,16 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use tracing::debug;
use obipipeline::{ use obipipeline::{
Pipeline, PipelineError, PipelineSender, SharedFlatFn, Stage, WorkerPool, Pipeline, PipelineError, PipelineSender, SharedFlatFn, Stage, WorkerPool, make_sink,
make_sink, make_source, make_transform, make_source, make_transform, throttle,
throttle,
}; };
use tracing::debug;
use obidebruinj::GraphDeBruijn; use obidebruinj::GraphDeBruijn;
use obikseq::CanonicalKmer;
use obikindex::layer::{IndexMode, TypedLayer}; use obikindex::layer::{IndexMode, TypedLayer};
use obikindex::{OKIError, OKIResult}; use obikindex::{OKIError, OKIResult};
use obikseq::CanonicalKmer;
// ── KmerGraphData ───────────────────────────────────────────────────────────── // ── KmerGraphData ─────────────────────────────────────────────────────────────
@@ -57,8 +55,7 @@ where
Stage::Flat(Arc::new( Stage::Flat(Arc::new(
move |data: KmerGraphData, move |data: KmerGraphData,
push: &PipelineSender<Result<KmerGraphData, PipelineError>>, push: &PipelineSender<Result<KmerGraphData, PipelineError>>,
delta: &PipelineSender<isize>| delta: &PipelineSender<isize>| {
{
if let KmerGraphData::File(t) = data { if let KmerGraphData::File(t) = data {
let path = t.item; let path = t.item;
let _guard = t.guard; // released at end of block let _guard = t.guard; // released at end of block
@@ -80,21 +77,30 @@ where
} }
}, },
) as SharedFlatFn<KmerGraphData>), ) as SharedFlatFn<KmerGraphData>),
make_transform!(KmerGraphData, { make_transform!(
KmerGraphData,
{
let filter = Arc::clone(&filter); let filter = Arc::clone(&filter);
move |batch: Vec<CanonicalKmer>| -> Vec<CanonicalKmer> { move |batch: Vec<CanonicalKmer>| -> Vec<CanonicalKmer> {
batch.into_iter().filter(|k| filter(*k)).collect() batch.into_iter().filter(|k| filter(*k)).collect()
} }
}, RawBatch, FilteredBatch), },
RawBatch,
FilteredBatch
),
], ],
make_sink!(KmerGraphData, { make_sink!(
KmerGraphData,
{
move |batch: Vec<CanonicalKmer>| { move |batch: Vec<CanonicalKmer>| {
let mut g = g_sink.lock().unwrap(); let mut g = g_sink.lock().unwrap();
for kmer in batch { for kmer in batch {
g.push(kmer); g.push(kmer);
} }
} }
}, FilteredBatch), },
FilteredBatch
),
); );
WorkerPool::new(pipeline, n_workers, capacity).run(); WorkerPool::new(pipeline, n_workers, capacity).run();
+3 -1
View File
@@ -19,4 +19,6 @@ mod extensions;
pub mod graph_pipeline; pub mod graph_pipeline;
pub use extensions::IndexBuilder; pub use extensions::IndexBuilder;
pub use graph_pipeline::{build_graph, build_layer_from_kmers, materialize_layer, write_graph_as_unitigs}; pub use graph_pipeline::{
build_graph, build_layer_from_kmers, materialize_layer, write_graph_as_unitigs,
};
+5 -3
View File
@@ -1,9 +1,9 @@
use std::path::PathBuf; use std::path::PathBuf;
use clap::Args; use clap::Args;
use obiread::NucPage;
use obikseq::RoutableSuperKmer; use obikseq::RoutableSuperKmer;
use obipipeline::Throttled; use obipipeline::Throttled;
use obiread::NucPage;
// ── Shared arguments ────────────────────────────────────────────────────────── // ── Shared arguments ──────────────────────────────────────────────────────────
@@ -78,7 +78,10 @@ impl CommonArgs {
std::process::exit(1); std::process::exit(1);
} }
if m < 3 || m >= k { if m < 3 || m >= k {
eprintln!("error: --minimizer-size must be in [3, k−1] = [3, {}] (got {m})", k - 1); eprintln!(
"error: --minimizer-size must be in [3, k−1] = [3, {}] (got {m})",
k - 1
);
std::process::exit(1); std::process::exit(1);
} }
if m % 2 == 0 { if m % 2 == 0 {
@@ -120,4 +123,3 @@ pub enum PipelineData {
unsafe impl Send for PipelineData {} unsafe impl Send for PipelineData {}
unsafe impl Sync for PipelineData {} unsafe impl Sync for PipelineData {}
+4 -1
View File
@@ -128,7 +128,10 @@ fn run_annotate(args: &AnnotateArgs) {
}) })
.clone(); .clone();
let id_col_idx = headers.iter().position(|h| h == args.id_col).unwrap_or_else(|| { let id_col_idx = headers
.iter()
.position(|h| h == args.id_col)
.unwrap_or_else(|| {
eprintln!("error: id column '{}' not found in CSV", args.id_col); eprintln!("error: id column '{}' not found in CSV", args.id_col);
std::process::exit(1); std::process::exit(1);
}); });
+3 -2
View File
@@ -7,8 +7,8 @@ use obikrebuild::IndexReindex;
use obisys::Reporter; use obisys::Reporter;
use tracing::info; use tracing::info;
use crate::cli::block_size_to_bits;
use super::index::resolve_approx_params; use super::index::resolve_approx_params;
use crate::cli::block_size_to_bits;
#[derive(Args)] #[derive(Args)]
pub struct ConvertArgs { pub struct ConvertArgs {
@@ -117,7 +117,8 @@ pub fn run(args: ConvertArgs) {
let block_bits = block_size_to_bits(args.block_size); let block_bits = block_size_to_bits(args.block_size);
let mut rep = Reporter::new(); let mut rep = Reporter::new();
idx.reindex(target, block_bits, &mut rep).unwrap_or_else(|e| { idx.reindex(target, block_bits, &mut rep)
.unwrap_or_else(|e| {
eprintln!("convert error: {e}"); eprintln!("convert error: {e}");
std::process::exit(1); std::process::exit(1);
}); });
+16 -4
View File
@@ -38,23 +38,35 @@ pub fn run(args: DumpArgs) {
std::process::exit(1); std::process::exit(1);
})); }));
let n_genomes = idx.meta().genomes().unwrap_or_else(|e| { let n_genomes = idx
.meta()
.genomes()
.unwrap_or_else(|e| {
eprintln!("error reading index metadata: {e}"); eprintln!("error reading index metadata: {e}");
std::process::exit(1); std::process::exit(1);
}).len(); })
.len();
info!( info!(
"dumping {} partition(s), {} genome(s)", "dumping {} partition(s), {} genome(s)",
idx.n_partitions(), idx.n_partitions(),
n_genomes n_genomes
); );
let filters: Vec<Box<dyn KmerFilter>> = vec![Box::new(args.group_filter.build_filter(&idx.meta()))]; let filters: Vec<Box<dyn KmerFilter>> =
vec![Box::new(args.group_filter.build_filter(&idx.meta()))];
let pb = progress_bar("dump", idx.n_partitions() as u64, "partitions"); let pb = progress_bar("dump", idx.n_partitions() as u64, "partitions");
let stdout = io::stdout(); let stdout = io::stdout();
let mut out = BufWriter::new(stdout.lock()); let mut out = BufWriter::new(stdout.lock());
idx.dump(&mut out, args.force_presence, args.debug, args.head, &filters, || pb.inc(1)) idx.dump(
&mut out,
args.force_presence,
args.debug,
args.head,
&filters,
|| pb.inc(1),
)
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
eprintln!("dump error: {e}"); eprintln!("dump error: {e}");
std::process::exit(1); std::process::exit(1);
+6 -1
View File
@@ -67,5 +67,10 @@ pub fn run(args: EstimateArgs) {
println!("{:<22} {}", "z:", z); println!("{:<22} {}", "z:", z);
println!("{:<22} {}", "evidence bits (b):", b); println!("{:<22} {}", "evidence bits (b):", b);
println!("{:<22} {:.3e} (1/2^{})", "FP per k-mer:", fp_kmer, b); println!("{:<22} {:.3e} (1/2^{})", "FP per k-mer:", fp_kmer, b);
println!("{:<22} {:.3e} (1/2^{})", "FP per z-window:", fp_window, b as u32 * z as u32); println!(
"{:<22} {:.3e} (1/2^{})",
"FP per z-window:",
fp_window,
b as u32 * z as u32
);
} }
+22 -3
View File
@@ -60,8 +60,24 @@ mod tests {
#[test] #[test]
fn csv_has_header_and_one_row_per_r() { fn csv_has_header_and_one_row_per_r() {
let rows = vec![ 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 {
SharingRow { r: 2, k_r: 5, observed: 0.25, expected: 0.01, deviation: 0.24, expected_false_positives: 0.5, fdr: 0.1 }, 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(); let mut buf = Vec::new();
write_csv(&rows, &mut buf).unwrap(); write_csv(&rows, &mut buf).unwrap();
@@ -69,6 +85,9 @@ mod tests {
let lines: Vec<&str> = text.lines().collect(); 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[0], "r,k_r,O_r,q_r,D_r,FP_r,FDR_r");
assert_eq!(lines.len(), 3); 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"); assert_eq!(
lines[2],
"2,5,2.500000e-1,1.000000e-2,2.400000e-1,5.000000e-1,1.000000e-1"
);
} }
} }
+12 -4
View File
@@ -66,16 +66,24 @@ pub fn run(args: FilterArgs) {
filters.push(Box::new(MaxTotalCount { total: v })); filters.push(Box::new(MaxTotalCount { total: v }));
} }
if let Some(theta) = args.min_complexity { if let Some(theta) = args.min_complexity {
filters.push(Box::new(MinComplexity { level_max: args.complexity_level_max, theta })); filters.push(Box::new(MinComplexity {
level_max: args.complexity_level_max,
theta,
}));
} }
let n_genomes = src.meta().genomes().unwrap_or_else(|e| { let n_genomes = src
.meta()
.genomes()
.unwrap_or_else(|e| {
eprintln!("error reading index metadata: {e}"); eprintln!("error reading index metadata: {e}");
std::process::exit(1); std::process::exit(1);
}).len(); })
.len();
info!( info!(
"filter: {} genome(s), source={}", "filter: {} genome(s), source={}",
n_genomes, args.source.display() n_genomes,
args.source.display()
); );
let mut rep = Reporter::new(); let mut rep = Reporter::new();
+1 -1
View File
@@ -6,8 +6,8 @@ pub mod filter;
pub mod index; pub mod index;
pub mod merge; pub mod merge;
pub mod pack; pub mod pack;
mod predicate;
pub mod phylo; pub mod phylo;
mod predicate;
pub mod query; pub mod query;
pub mod select; pub mod select;
pub mod superkmer; pub mod superkmer;
+6 -2
View File
@@ -32,10 +32,14 @@ pub fn run(args: PackArgs) {
std::process::exit(1); std::process::exit(1);
})); }));
let n_genomes = idx.meta().genomes().unwrap_or_else(|e| { let n_genomes = idx
.meta()
.genomes()
.unwrap_or_else(|e| {
eprintln!("error reading index metadata: {e}"); eprintln!("error reading index metadata: {e}");
std::process::exit(1); std::process::exit(1);
}).len(); })
.len();
info!( info!(
"pack: {} partition(s), {} genome(s)", "pack: {} partition(s), {} genome(s)",
idx.n_partitions(), idx.n_partitions(),
+8 -2
View File
@@ -32,7 +32,11 @@ pub(super) fn write_alignment_outputs(
if args.align.fasta || !args.align.vcf { if args.align.fasta || !args.align.vcf {
let path = path_for("fasta"); let path = path_for("fasta");
let mut f = create(&path); let mut f = create(&path);
for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) { for (&g, seq) in alignment
.genome_indices
.iter()
.zip(alignment.sequences.iter())
{
obifastwrite::write_plain_record(seq, &labels[g], &mut f).unwrap(); obifastwrite::write_plain_record(seq, &labels[g], &mut f).unwrap();
} }
info!("pseudo-alignment ({n_sites} site(s), {n_genomes} genome(s)) → {path}"); info!("pseudo-alignment ({n_sites} site(s), {n_genomes} genome(s)) → {path}");
@@ -41,7 +45,9 @@ pub(super) fn write_alignment_outputs(
if args.align.vcf { if args.align.vcf {
let path = path_for("vcf"); let path = path_for("vcf");
let mut f = create(&path); let mut f = create(&path);
let written = alignment.write_vcf(labels, !args.sample.no_ambiguity, &mut f).unwrap_or_else(|e| { let written = alignment
.write_vcf(labels, !args.sample.no_ambiguity, &mut f)
.unwrap_or_else(|e| {
eprintln!("error writing {path}: {e}"); eprintln!("error writing {path}: {e}");
std::process::exit(1); std::process::exit(1);
}); });
+24 -7
View File
@@ -107,7 +107,11 @@ fn drop_ascertainment_noninformative(alignment: &SnpAlignment) -> SnpAlignment {
.filter(|&(_, &k)| k) .filter(|&(_, &k)| k)
.map(|(&site, _)| site) .map(|(&site, _)| site)
.collect(); .collect();
SnpAlignment { sequences, genome_indices: alignment.genome_indices.clone(), sites } SnpAlignment {
sequences,
genome_indices: alignment.genome_indices.clone(),
sites,
}
} }
/// Recode every occurrence of a byte in `symbols` to `-` — the same /// Recode every occurrence of a byte in `symbols` to `-` — the same
@@ -126,7 +130,11 @@ fn recode_symbols_as_absent(alignment: &SnpAlignment, symbols: &[u8]) -> SnpAlig
.collect() .collect()
}) })
.collect(); .collect();
SnpAlignment { sequences, genome_indices: alignment.genome_indices.clone(), sites: alignment.sites.clone() } SnpAlignment {
sequences,
genome_indices: alignment.genome_indices.clone(),
sites: alignment.sites.clone(),
}
} }
fn compact_alphabet(alignment: &SnpAlignment, free_loss: bool) -> CompactAlphabet { fn compact_alphabet(alignment: &SnpAlignment, free_loss: bool) -> CompactAlphabet {
@@ -276,7 +284,11 @@ fn write_iqtree_alignment(
std::process::exit(1); std::process::exit(1);
})); }));
let n_sites = alignment.sequences.first().map(|s| s.len()).unwrap_or(0); let n_sites = alignment.sequences.first().map(|s| s.len()).unwrap_or(0);
for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) { for (&g, seq) in alignment
.genome_indices
.iter()
.zip(alignment.sequences.iter())
{
let recoded: Vec<u8> = seq let recoded: Vec<u8> = seq
.iter() .iter()
.map(|&b| { .map(|&b| {
@@ -391,7 +403,11 @@ mod tests {
fn alignment(sequences: Vec<Vec<u8>>) -> SnpAlignment { fn alignment(sequences: Vec<Vec<u8>>) -> SnpAlignment {
let genome_indices = (0..sequences.len()).collect(); let genome_indices = (0..sequences.len()).collect();
SnpAlignment { sequences, genome_indices, sites: Vec::new() } SnpAlignment {
sequences,
genome_indices,
sites: Vec::new(),
}
} }
#[test] #[test]
@@ -442,9 +458,10 @@ mod tests {
// --free-loss — compact index 0 -> 'A', compact index 1 -> 'G'. // --free-loss — compact index 0 -> 'A', compact index 1 -> 'G'.
let alignment = alignment(vec![vec![b'A', b'-'], vec![b'-', b'G']]); let alignment = alignment(vec![vec![b'A', b'-'], vec![b'-', b'G']]);
let alphabet = compact_alphabet(&alignment, true); let alphabet = compact_alphabet(&alignment, true);
let output = Some( let output = Some(std::env::temp_dir().join(format!(
std::env::temp_dir().join(format!("obikmer2_test_iqtree_states_{}", std::process::id())), "obikmer2_test_iqtree_states_{}",
); std::process::id()
)));
let path = write_iqtree_states_csv(&alphabet, &output); let path = write_iqtree_states_csv(&alphabet, &output);
let csv = std::fs::read_to_string(&path).unwrap(); let csv = std::fs::read_to_string(&path).unwrap();
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff. Show more