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:
1 parent
8159137f8b
commit
ed0d563995
212 files changed
+4782
-1835
No files matched your search
@@ -10,26 +10,39 @@ use std::error::Error;
|
||||
use std::path::Path;
|
||||
use std::time::Instant;
|
||||
|
||||
use obicompactvec::{PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder};
|
||||
use obicompactvec::{
|
||||
PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder,
|
||||
};
|
||||
|
||||
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 t0 = Instant::now();
|
||||
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 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());
|
||||
|
||||
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_cols = dense.n_cols();
|
||||
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 {
|
||||
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::time::Instant;
|
||||
|
||||
use obicompactvec::{PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder};
|
||||
use obicompactvec::{
|
||||
PersistentBitMatrix, PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder,
|
||||
};
|
||||
|
||||
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 t0 = Instant::now();
|
||||
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 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());
|
||||
|
||||
compare(&dense, &sparse)?;
|
||||
@@ -36,7 +46,10 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
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_cols = dense.n_cols();
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
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 sparse_size = dir_size(sparse_dir)?;
|
||||
|
||||
|
||||
@@ -13,15 +13,19 @@ use super::col_path;
|
||||
// ── Builder (unchanged — always builds Columnar) ──────────────────────────────
|
||||
|
||||
pub struct PersistentBitMatrixBuilder {
|
||||
dir: PathBuf,
|
||||
n: usize,
|
||||
dir: PathBuf,
|
||||
n: usize,
|
||||
n_cols: usize,
|
||||
}
|
||||
|
||||
impl PersistentBitMatrixBuilder {
|
||||
pub fn new(n: usize, dir: &Path) -> io::Result<Self> {
|
||||
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
|
||||
@@ -32,11 +36,19 @@ impl PersistentBitMatrixBuilder {
|
||||
/// on-disk column naming or `MatrixMeta` themselves.
|
||||
pub fn resume(dir: &Path) -> io::Result<Self> {
|
||||
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_cols(&self) -> usize { self.n_cols }
|
||||
pub fn n(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
pub fn n_cols(&self) -> usize {
|
||||
self.n_cols
|
||||
}
|
||||
|
||||
pub fn add_col(&mut self) -> io::Result<PersistentBitVecBuilder> {
|
||||
let path = col_path(&self.dir, self.n_cols);
|
||||
@@ -73,6 +85,10 @@ impl PersistentBitMatrixBuilder {
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,16 @@ use crate::bitvec::{PersistentBitVec, PersistentBitVecBuilder};
|
||||
use crate::meta::MatrixMeta;
|
||||
|
||||
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 ─────────────────────────────────────────────────────────
|
||||
|
||||
/// Per-column file layout (original format).
|
||||
pub struct ColumnarBitMatrix {
|
||||
cols: Vec<PersistentBitVec>,
|
||||
n: usize,
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl ColumnarBitMatrix {
|
||||
@@ -27,11 +29,17 @@ impl ColumnarBitMatrix {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn n(&self) -> usize { self.n }
|
||||
pub(crate) fn n(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn n_cols(&self) -> usize { self.cols.len() }
|
||||
pub(crate) fn n_cols(&self) -> usize {
|
||||
self.cols.len()
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn col(&self, c: usize) -> &PersistentBitVec { &self.cols[c] }
|
||||
pub(crate) fn col(&self, c: usize) -> &PersistentBitVec {
|
||||
&self.cols[c]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
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>) {
|
||||
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> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
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::tempintvec::{TempCompactIntVec, TempCompactIntVecBuilder};
|
||||
|
||||
@@ -114,9 +114,15 @@ pub fn batch_presence_counts(
|
||||
// ── MatrixGroupOps ────────────────────────────────────────────────────────────
|
||||
|
||||
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.
|
||||
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> {
|
||||
@@ -139,7 +145,9 @@ impl MatrixGroupOps for PersistentBitMatrix {
|
||||
let mut result = TempCompactIntVecBuilder::new(n)?;
|
||||
if let Some((&first, rest)) = g.indices.split_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()
|
||||
}
|
||||
|
||||
@@ -24,10 +24,14 @@ pub use builder::PersistentBitMatrixBuilder;
|
||||
pub use group_ops::batch_presence_counts;
|
||||
pub use packed::pack_bit_matrix;
|
||||
pub use persistent::PersistentBitMatrix;
|
||||
pub use sparse::{PersistentSparseBitMatrix, PersistentSparseBitMatrixBuilder, pack_sparse_bit_matrix};
|
||||
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 {
|
||||
dir.join(format!("col_{col:06}.pbiv"))
|
||||
|
||||
@@ -10,17 +10,19 @@ use crate::meta::MatrixMeta;
|
||||
use crate::views::BitSliceView;
|
||||
|
||||
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 ───────────────────────────────────────────────────────────
|
||||
|
||||
const PBMX_MAGIC: [u8; 4] = *b"PBMX";
|
||||
const PBMX_HEADER: usize = 24; // magic(4) + pad(4) + n_rows(8) + n_cols(8)
|
||||
const PBIV_HEADER: usize = 16; // magic(4) + pad(4) + n(8)
|
||||
const PBMX_MAGIC: [u8; 4] = *b"PBMX";
|
||||
const PBMX_HEADER: usize = 24; // magic(4) + pad(4) + n_rows(8) + n_cols(8)
|
||||
const PBIV_HEADER: usize = 16; // magic(4) + pad(4) + n(8)
|
||||
|
||||
/// Single-file packed layout: all columns concatenated behind a header.
|
||||
pub struct PackedBitMatrix {
|
||||
mmap: Mmap,
|
||||
mmap: Mmap,
|
||||
pub(super) n_rows: usize,
|
||||
pub(super) n_cols: usize,
|
||||
/// Absolute byte offset to the start of each column's bit data
|
||||
@@ -32,22 +34,31 @@ impl PackedBitMatrix {
|
||||
pub(crate) fn open(path: &Path) -> io::Result<Self> {
|
||||
let mmap = unsafe { Mmap::map(&File::open(path)?)? };
|
||||
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 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PBMX magic"));
|
||||
}
|
||||
let n_rows = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize;
|
||||
let n_rows = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize;
|
||||
let n_cols = u64::from_le_bytes(mmap[16..24].try_into().unwrap()) as usize;
|
||||
|
||||
let mut data_offsets = Vec::with_capacity(n_cols);
|
||||
for c in 0..n_cols {
|
||||
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);
|
||||
}
|
||||
|
||||
Ok(Self { mmap, n_rows, n_cols, data_offsets })
|
||||
Ok(Self {
|
||||
mmap,
|
||||
n_rows,
|
||||
n_cols,
|
||||
data_offsets,
|
||||
})
|
||||
}
|
||||
|
||||
#[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
|
||||
// stale one — never silently discarded as "leftover cleanup".
|
||||
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"));
|
||||
return Ok(());
|
||||
}
|
||||
@@ -162,7 +175,9 @@ pub fn pack_bit_matrix(dir: &Path) -> io::Result<()> {
|
||||
out.write_all(&[0u8; 4])?;
|
||||
out.write_all(&(meta.n 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 {
|
||||
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);
|
||||
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"))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -8,31 +8,51 @@ use rayon::prelude::*;
|
||||
/// 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
|
||||
/// `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()
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
for (c, out) in buf.iter_mut().enumerate() { *out = get(c, slot); }
|
||||
pub(crate) fn fill_row_generic<T: Copy>(
|
||||
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`
|
||||
/// all have this exact shape (`(0..n_cols).into_par_iter().map(f).collect()`)
|
||||
/// across every `Columnar`/`Packed` backend — written once here instead of
|
||||
/// 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())
|
||||
}
|
||||
|
||||
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>
|
||||
where T: Clone + Default {
|
||||
where
|
||||
T: Clone + 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
|
||||
}
|
||||
|
||||
@@ -45,11 +65,17 @@ where T: Clone + Default {
|
||||
/// see `pairwise2_matrix`), not zero. Distance finalisations that need a
|
||||
/// 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>
|
||||
where T: Copy + Default + Send {
|
||||
where
|
||||
T: Copy + Default + Send,
|
||||
{
|
||||
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)));
|
||||
for i in 0..n { m[[i, i]] = f(i, i); }
|
||||
for i in 0..n {
|
||||
m[[i, i]] = f(i, i);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
@@ -57,17 +83,27 @@ where T: Copy + Default + Send {
|
||||
/// symmetric matrices simultaneously (e.g. intersection + union for Jaccard).
|
||||
/// 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.
|
||||
pub(crate) fn pairwise2_matrix<T>(n: usize, f: impl Fn(usize, usize) -> (T, T) + Sync) -> (Array2<T>, Array2<T>)
|
||||
where T: Copy + Default + Send {
|
||||
pub(crate) fn pairwise2_matrix<T>(
|
||||
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)
|
||||
.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();
|
||||
let mut m0 = Array2::from_elem((n, n), T::default());
|
||||
let mut m1 = Array2::from_elem((n, n), T::default());
|
||||
for (i, j, a, b) in results {
|
||||
m0[[i, j]] = a; m0[[j, i]] = a;
|
||||
m1[[i, j]] = b; m1[[j, i]] = b;
|
||||
m0[[i, j]] = a;
|
||||
m0[[j, i]] = a;
|
||||
m1[[i, j]] = b;
|
||||
m1[[j, i]] = b;
|
||||
}
|
||||
for i in 0..n {
|
||||
let (a, b) = f(i, i);
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::layer_meta::LayerMeta;
|
||||
use crate::meta::MatrixMeta;
|
||||
use crate::storage_kind::StorageKind;
|
||||
use crate::traits::{BitPartials, ColumnWeights};
|
||||
use crate::views::{nonzero_triples, BitSliceView};
|
||||
use crate::views::{BitSliceView, nonzero_triples};
|
||||
|
||||
use super::columnar::ColumnarBitMatrix;
|
||||
use super::packed::PackedBitMatrix;
|
||||
@@ -42,7 +42,9 @@ impl PersistentBitMatrix {
|
||||
let presence_dir = layer_dir.join("presence");
|
||||
|
||||
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() {
|
||||
@@ -50,18 +52,25 @@ impl PersistentBitMatrix {
|
||||
}
|
||||
|
||||
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
|
||||
let meta = LayerMeta::load(layer_dir).map_err(|_| io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!(
|
||||
"no presence matrix and no layer_meta.json in {} — run 'obikmer upgrade'",
|
||||
layer_dir.display()
|
||||
),
|
||||
))?;
|
||||
Ok(Self::Implicit { n_rows: meta.n, n_cols: 1 })
|
||||
let meta = LayerMeta::load(layer_dir).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!(
|
||||
"no presence matrix and no layer_meta.json in {} — run 'obikmer upgrade'",
|
||||
layer_dir.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
Ok(Self::Implicit {
|
||||
n_rows: meta.n,
|
||||
n_cols: 1,
|
||||
})
|
||||
}
|
||||
|
||||
/// This already-open matrix's storage format — reads the discriminant
|
||||
@@ -69,9 +78,9 @@ impl PersistentBitMatrix {
|
||||
#[inline]
|
||||
pub fn storage_kind(&self) -> StorageKind {
|
||||
match self {
|
||||
Self::Columnar(_) => StorageKind::Columnar,
|
||||
Self::Packed(_) => StorageKind::Packed,
|
||||
Self::Sparse(_) => StorageKind::Sparse,
|
||||
Self::Columnar(_) => StorageKind::Columnar,
|
||||
Self::Packed(_) => StorageKind::Packed,
|
||||
Self::Sparse(_) => StorageKind::Sparse,
|
||||
Self::Implicit { .. } => StorageKind::Implicit,
|
||||
}
|
||||
}
|
||||
@@ -96,16 +105,19 @@ impl PersistentBitMatrix {
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("cannot detect presence storage format in {}", layer_dir.display()),
|
||||
format!(
|
||||
"cannot detect presence storage format in {}",
|
||||
layer_dir.display()
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn n(&self) -> usize {
|
||||
match self {
|
||||
Self::Columnar(m) => m.n(),
|
||||
Self::Packed(m) => m.n_rows,
|
||||
Self::Sparse(m) => m.n(),
|
||||
Self::Columnar(m) => m.n(),
|
||||
Self::Packed(m) => m.n_rows,
|
||||
Self::Sparse(m) => m.n(),
|
||||
Self::Implicit { n_rows, .. } => *n_rows,
|
||||
}
|
||||
}
|
||||
@@ -113,9 +125,9 @@ impl PersistentBitMatrix {
|
||||
#[inline]
|
||||
pub fn n_cols(&self) -> usize {
|
||||
match self {
|
||||
Self::Columnar(m) => m.n_cols(),
|
||||
Self::Packed(m) => m.n_cols,
|
||||
Self::Sparse(m) => m.n_cols(),
|
||||
Self::Columnar(m) => m.n_cols(),
|
||||
Self::Packed(m) => m.n_cols,
|
||||
Self::Sparse(m) => m.n_cols(),
|
||||
Self::Implicit { n_cols, .. } => *n_cols,
|
||||
}
|
||||
}
|
||||
@@ -132,9 +144,11 @@ impl PersistentBitMatrix {
|
||||
pub fn col_view(&self, c: usize) -> BitSliceView<'_> {
|
||||
match self {
|
||||
Self::Columnar(m) => m.col(c).view(),
|
||||
Self::Packed(m) => m.col_slice(c),
|
||||
Self::Sparse(_) => panic!("col_view() not available on Sparse PersistentBitMatrix"),
|
||||
Self::Implicit { .. } => panic!("col_view() not available on Implicit PersistentBitMatrix"),
|
||||
Self::Packed(m) => m.col_slice(c),
|
||||
Self::Sparse(_) => panic!("col_view() not available on Sparse PersistentBitMatrix"),
|
||||
Self::Implicit { .. } => {
|
||||
panic!("col_view() not available on Implicit PersistentBitMatrix")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,8 +161,8 @@ impl PersistentBitMatrix {
|
||||
pub fn get(&self, c: usize, slot: usize) -> u32 {
|
||||
match self {
|
||||
Self::Columnar(m) => m.col(c).get(slot) as u32,
|
||||
Self::Packed(m) => m.col_slice(c).get(slot) as u32,
|
||||
Self::Sparse(m) => m.get(c, slot),
|
||||
Self::Packed(m) => m.col_slice(c).get(slot) as u32,
|
||||
Self::Sparse(m) => m.get(c, slot),
|
||||
Self::Implicit { .. } => 1,
|
||||
}
|
||||
}
|
||||
@@ -156,21 +170,21 @@ impl PersistentBitMatrix {
|
||||
pub fn col_persist(&self, c: usize, path: &Path) -> io::Result<PersistentBitVecBuilder> {
|
||||
match self {
|
||||
Self::Columnar(m) => PersistentBitVecBuilder::build_from(m.col(c), path),
|
||||
Self::Packed(m) => m.col_persist(c, path),
|
||||
Self::Sparse(_) => Err(io::Error::new(io::ErrorKind::Unsupported,
|
||||
"col_persist not available on Sparse PersistentBitMatrix")),
|
||||
Self::Implicit { n_rows, .. } => {
|
||||
PersistentBitVecBuilder::new_ones(*n_rows, path)
|
||||
}
|
||||
Self::Packed(m) => m.col_persist(c, path),
|
||||
Self::Sparse(_) => Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"col_persist not available on Sparse PersistentBitMatrix",
|
||||
)),
|
||||
Self::Implicit { n_rows, .. } => PersistentBitVecBuilder::new_ones(*n_rows, path),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn row(&self, slot: usize) -> Box<[bool]> {
|
||||
match self {
|
||||
Self::Columnar(m) => m.row(slot),
|
||||
Self::Packed(m) => m.row(slot),
|
||||
Self::Sparse(m) => m.row(slot),
|
||||
Self::Columnar(m) => m.row(slot),
|
||||
Self::Packed(m) => m.row(slot),
|
||||
Self::Sparse(m) => m.row(slot),
|
||||
Self::Implicit { n_cols, .. } => vec![true; *n_cols].into_boxed_slice(),
|
||||
}
|
||||
}
|
||||
@@ -179,9 +193,9 @@ impl PersistentBitMatrix {
|
||||
#[inline]
|
||||
pub fn fill_row(&self, slot: usize, buf: &mut [u32]) {
|
||||
match self {
|
||||
Self::Columnar(m) => m.fill_row(slot, buf),
|
||||
Self::Packed(m) => m.fill_row(slot, buf),
|
||||
Self::Sparse(m) => m.fill_row(slot, buf),
|
||||
Self::Columnar(m) => m.fill_row(slot, buf),
|
||||
Self::Packed(m) => m.fill_row(slot, buf),
|
||||
Self::Sparse(m) => m.fill_row(slot, buf),
|
||||
Self::Implicit { n_cols, .. } => buf[..*n_cols].fill(1),
|
||||
}
|
||||
}
|
||||
@@ -244,41 +258,50 @@ impl PersistentBitMatrix {
|
||||
/// constraint against it; the allocation is one `Box` per call, not
|
||||
/// per cell — negligible next to what it replaces (a fresh `Vec`
|
||||
/// 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 {
|
||||
Self::Sparse(m) => Box::new(m.nonzero_iter(slots)),
|
||||
Self::Implicit { .. } => {
|
||||
Box::new(slots.iter().enumerate().map(|(i, _)| (i, 0usize, 1u32)))
|
||||
}
|
||||
Self::Columnar(_) | Self::Packed(_) => {
|
||||
Box::new(nonzero_triples(slots, self.n_cols(), |c| self.col_view(c), false))
|
||||
}
|
||||
Self::Columnar(_) | Self::Packed(_) => Box::new(nonzero_triples(
|
||||
slots,
|
||||
self.n_cols(),
|
||||
|c| self.col_view(c),
|
||||
false,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn count_ones(&self) -> Array1<u64> {
|
||||
match self {
|
||||
Self::Columnar(m) => m.count_ones(),
|
||||
Self::Packed(m) => m.count_ones(),
|
||||
Self::Sparse(m) => m.count_ones(),
|
||||
Self::Columnar(m) => m.count_ones(),
|
||||
Self::Packed(m) => m.count_ones(),
|
||||
Self::Sparse(m) => m.count_ones(),
|
||||
Self::Implicit { n_rows, n_cols } => Array1::from_elem(*n_cols, *n_rows as u64),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn partial_jaccard_dist_matrix(&self) -> (Array2<u64>, Array2<u64>) {
|
||||
match self {
|
||||
Self::Columnar(m) => m.partial_jaccard_dist_matrix(),
|
||||
Self::Packed(m) => m.partial_jaccard_dist_matrix(),
|
||||
Self::Sparse(m) => BitPartials::partial_jaccard(m),
|
||||
Self::Columnar(m) => m.partial_jaccard_dist_matrix(),
|
||||
Self::Packed(m) => m.partial_jaccard_dist_matrix(),
|
||||
Self::Sparse(m) => BitPartials::partial_jaccard(m),
|
||||
Self::Implicit { n_rows, n_cols } => {
|
||||
let v = *n_rows as u64;
|
||||
let n = *n_cols;
|
||||
let mut inter = Array2::zeros((n, n));
|
||||
let mut union = Array2::zeros((n, n));
|
||||
for i in 0..n { for j in 0..n {
|
||||
inter[[i, j]] = v; union[[i, j]] = v;
|
||||
}}
|
||||
for i in 0..n {
|
||||
for j in 0..n {
|
||||
inter[[i, j]] = v;
|
||||
union[[i, j]] = v;
|
||||
}
|
||||
}
|
||||
(inter, union)
|
||||
}
|
||||
}
|
||||
@@ -286,10 +309,10 @@ impl PersistentBitMatrix {
|
||||
|
||||
pub fn partial_hamming_dist_matrix(&self) -> Array2<u64> {
|
||||
match self {
|
||||
Self::Columnar(m) => m.partial_hamming_dist_matrix(),
|
||||
Self::Packed(m) => m.partial_hamming_dist_matrix(),
|
||||
Self::Sparse(m) => BitPartials::partial_hamming(m),
|
||||
Self::Implicit { n_cols, .. } => Array2::zeros((*n_cols, *n_cols)),
|
||||
Self::Columnar(m) => m.partial_hamming_dist_matrix(),
|
||||
Self::Packed(m) => m.partial_hamming_dist_matrix(),
|
||||
Self::Sparse(m) => BitPartials::partial_hamming(m),
|
||||
Self::Implicit { n_cols, .. } => Array2::zeros((*n_cols, *n_cols)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,11 +326,15 @@ impl PersistentBitMatrix {
|
||||
|
||||
impl ColumnWeights for PersistentBitMatrix {
|
||||
#[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
|
||||
/// `threshold` is.
|
||||
#[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 {
|
||||
@@ -323,15 +350,27 @@ impl BitPartials for PersistentBitMatrix {
|
||||
|
||||
impl crate::traits::BinaryMatrix for PersistentBitMatrix {
|
||||
#[inline]
|
||||
fn n(&self) -> usize { self.n() }
|
||||
fn n(&self) -> usize {
|
||||
self.n()
|
||||
}
|
||||
#[inline]
|
||||
fn n_cols(&self) -> usize { self.n_cols() }
|
||||
fn n_cols(&self) -> usize {
|
||||
self.n_cols()
|
||||
}
|
||||
#[inline]
|
||||
fn row(&self, slot: usize) -> Box<[bool]> { self.row(slot) }
|
||||
fn row(&self, slot: usize) -> Box<[bool]> {
|
||||
self.row(slot)
|
||||
}
|
||||
#[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]
|
||||
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]
|
||||
fn count_ones(&self) -> Array1<u64> { self.count_ones() }
|
||||
fn count_ones(&self) -> Array1<u64> {
|
||||
self.count_ones()
|
||||
}
|
||||
}
|
||||
@@ -28,22 +28,36 @@ use std::path::{Path, PathBuf};
|
||||
use memmap2::Mmap;
|
||||
use ndarray::{Array1, Array2};
|
||||
|
||||
use crate::traits::{BitPartials, ColumnWeights};
|
||||
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::rankselect::{PersistentRankSelectBitVec, PersistentRankSelectBitVecBuilder};
|
||||
use crate::traits::{BitPartials, ColumnWeights};
|
||||
|
||||
use super::PersistentBitMatrix;
|
||||
use super::col_path;
|
||||
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 singleton_path(dir: &Path) -> PathBuf { dir.join("singleton.pfiv") }
|
||||
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") }
|
||||
fn is_multi_path(dir: &Path) -> PathBuf {
|
||||
dir.join("is_multi.prsb")
|
||||
}
|
||||
fn singleton_path(dir: &Path) -> PathBuf {
|
||||
dir.join("singleton.pfiv")
|
||||
}
|
||||
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 {
|
||||
n: usize,
|
||||
@@ -57,7 +71,12 @@ impl SparseMeta {
|
||||
fn load(dir: &Path) -> io::Result<Self> {
|
||||
let s = fs::read_to_string(meta_path(dir))?;
|
||||
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 {
|
||||
n: get("n")?,
|
||||
@@ -175,15 +194,25 @@ impl PersistentSparseBitMatrix {
|
||||
Some(unsafe { Mmap::map(&dict_file)? })
|
||||
};
|
||||
Ok(Self {
|
||||
is_multi, singleton, multi, dict_offsets, dict_values,
|
||||
n: meta.n, n_cols: meta.n_cols, n_distinct_multi: meta.n_distinct_multi,
|
||||
is_multi,
|
||||
singleton,
|
||||
multi,
|
||||
dict_offsets,
|
||||
dict_values,
|
||||
n: meta.n,
|
||||
n_cols: meta.n_cols,
|
||||
n_distinct_multi: meta.n_distinct_multi,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn n(&self) -> usize { self.n }
|
||||
pub fn n(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn n_cols(&self) -> usize { self.n_cols }
|
||||
pub fn n_cols(&self) -> usize {
|
||||
self.n_cols
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn dict_bytes(&self) -> &[u8] {
|
||||
@@ -342,44 +371,61 @@ impl PersistentSparseBitMatrix {
|
||||
/// `n_cols`-wide buffer, ever. See
|
||||
/// `DevDocMD/architecture/siblings.md`, "`query` never benefits from
|
||||
/// 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 cur_idx = 0usize;
|
||||
let mut buf: Vec<usize> = Vec::new();
|
||||
let mut buf_pos = 0usize;
|
||||
|
||||
std::iter::from_fn(move || loop {
|
||||
if buf_pos < buf.len() {
|
||||
let g = buf[buf_pos];
|
||||
buf_pos += 1;
|
||||
return Some((cur_idx, g, 1u32));
|
||||
std::iter::from_fn(move || {
|
||||
loop {
|
||||
if buf_pos < buf.len() {
|
||||
let g = buf[buf_pos];
|
||||
buf_pos += 1;
|
||||
return Some((cur_idx, g, 1u32));
|
||||
}
|
||||
if next_slot >= slots.len() {
|
||||
return None;
|
||||
}
|
||||
cur_idx = next_slot;
|
||||
let slot = slots[next_slot];
|
||||
next_slot += 1;
|
||||
buf.clear();
|
||||
self.for_each_genome_in_row(slot, |g| buf.push(g));
|
||||
buf_pos = 0;
|
||||
}
|
||||
if next_slot >= slots.len() {
|
||||
return None;
|
||||
}
|
||||
cur_idx = next_slot;
|
||||
let slot = slots[next_slot];
|
||||
next_slot += 1;
|
||||
buf.clear();
|
||||
self.for_each_genome_in_row(slot, |g| buf.push(g));
|
||||
buf_pos = 0;
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::traits::BinaryMatrix for PersistentSparseBitMatrix {
|
||||
#[inline]
|
||||
fn n(&self) -> usize { self.n() }
|
||||
fn n(&self) -> usize {
|
||||
self.n()
|
||||
}
|
||||
#[inline]
|
||||
fn n_cols(&self) -> usize { self.n_cols() }
|
||||
fn n_cols(&self) -> usize {
|
||||
self.n_cols()
|
||||
}
|
||||
#[inline]
|
||||
fn row(&self, slot: usize) -> Box<[bool]> { self.row(slot) }
|
||||
fn row(&self, slot: usize) -> Box<[bool]> {
|
||||
self.row(slot)
|
||||
}
|
||||
#[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]
|
||||
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]
|
||||
fn count_ones(&self) -> Array1<u64> { self.count_ones() }
|
||||
fn count_ones(&self) -> Array1<u64> {
|
||||
self.count_ones()
|
||||
}
|
||||
}
|
||||
|
||||
// ── PersistentSparseBitMatrixBuilder ────────────────────────────────────────
|
||||
@@ -455,14 +501,19 @@ impl PersistentSparseBitMatrixBuilder {
|
||||
is_multi_b.close()?;
|
||||
|
||||
let singleton_width = bit_width_for_range(self.n_cols as u64);
|
||||
let mut singleton_b = PersistentFixedIntVecBuilder::new(n_singleton, singleton_width, &singleton_path(&self.dir))?;
|
||||
let mut singleton_b = PersistentFixedIntVecBuilder::new(
|
||||
n_singleton,
|
||||
singleton_width,
|
||||
&singleton_path(&self.dir),
|
||||
)?;
|
||||
for (i, &v) in self.singleton_values.iter().enumerate() {
|
||||
singleton_b.set(i, v as u64);
|
||||
}
|
||||
singleton_b.close()?;
|
||||
|
||||
let multi_width = bit_width_for_range(n_distinct_multi as u64);
|
||||
let mut multi_b = PersistentFixedIntVecBuilder::new(n_multi, multi_width, &multi_path(&self.dir))?;
|
||||
let mut multi_b =
|
||||
PersistentFixedIntVecBuilder::new(n_multi, multi_width, &multi_path(&self.dir))?;
|
||||
for (i, &v) in self.multi_dict_ids.iter().enumerate() {
|
||||
multi_b.set(i, v as u64);
|
||||
}
|
||||
@@ -477,14 +528,22 @@ impl PersistentSparseBitMatrixBuilder {
|
||||
}
|
||||
}
|
||||
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 {
|
||||
offsets_b.push(o);
|
||||
}
|
||||
offsets_b.close()?;
|
||||
fs::write(dict_values_path(&self.dir), &dict_values)?;
|
||||
|
||||
SparseMeta { n, n_cols: self.n_cols, n_singleton, n_multi, n_distinct_multi }.save(&self.dir)?;
|
||||
SparseMeta {
|
||||
n,
|
||||
n_cols: self.n_cols,
|
||||
n_singleton,
|
||||
n_multi,
|
||||
n_distinct_multi,
|
||||
}
|
||||
.save(&self.dir)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,11 @@ fn read_bit_window(
|
||||
bytes.resize(nw * 8, 0);
|
||||
file.read_exact_at(bytes, (PBIV_HEADER + start / 8) as u64)?;
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -77,7 +81,14 @@ impl PersistentSparseBitMatrixBuilder {
|
||||
max_hits,
|
||||
(),
|
||||
|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| {
|
||||
hits.push((r as u32, c as u32, ()));
|
||||
});
|
||||
|
||||
@@ -230,7 +230,10 @@ impl PersistentBitVecBuilder {
|
||||
|
||||
pub fn build_from(source: &PersistentBitVec, path: &Path) -> io::Result<Self> {
|
||||
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 n = source.len();
|
||||
Ok(Self {
|
||||
|
||||
@@ -5,43 +5,65 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
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::views::{BitSliceView, IntSliceView};
|
||||
|
||||
pub struct PersistentCompactIntVecBuilder {
|
||||
path: PathBuf,
|
||||
mmap: MmapMut,
|
||||
n: usize,
|
||||
path: PathBuf,
|
||||
mmap: MmapMut,
|
||||
n: usize,
|
||||
overflow: HashMap<usize, u32>,
|
||||
}
|
||||
|
||||
impl PersistentCompactIntVecBuilder {
|
||||
pub fn new(n: usize, path: &Path) -> io::Result<Self> {
|
||||
let file = OpenOptions::new()
|
||||
.read(true).write(true).create(true).truncate(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(path)?;
|
||||
file.set_len((HEADER_SIZE + n) as u64)?;
|
||||
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 file = OpenOptions::new()
|
||||
.read(true).write(true).create(true).truncate(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(path)?;
|
||||
file.set_len((HEADER_SIZE + n) as u64)?;
|
||||
let mut mmap = unsafe { MmapMut::map_mut(&file)? };
|
||||
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> {
|
||||
fs::copy(source.path(), path)?;
|
||||
let file = OpenOptions::new().read(true).write(true).open(path)?;
|
||||
let mmap = unsafe { MmapMut::map_mut(&file)? };
|
||||
let n = source.len();
|
||||
let n = source.len();
|
||||
let n_overflow = u64::from_le_bytes(mmap[16..24].try_into().unwrap()) as usize;
|
||||
let data_offset = HEADER_SIZE + n;
|
||||
let mut overflow = HashMap::with_capacity(n_overflow);
|
||||
@@ -49,14 +71,22 @@ impl PersistentCompactIntVecBuilder {
|
||||
let (slot, value) = parse_overflow_entry(&mmap, data_offset, i);
|
||||
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]
|
||||
pub fn get(&self, slot: usize) -> u32 {
|
||||
match self.mmap[HEADER_SIZE + slot] {
|
||||
255 => *self.overflow.get(&slot).expect("sentinel without overflow entry"),
|
||||
v => v as u32,
|
||||
255 => *self
|
||||
.overflow
|
||||
.get(&slot)
|
||||
.expect("sentinel without overflow entry"),
|
||||
v => v as u32,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,20 +102,33 @@ impl PersistentCompactIntVecBuilder {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.n == 0 }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
|
||||
#[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]
|
||||
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]
|
||||
pub fn clear_overflow(&mut self) { self.overflow.clear(); }
|
||||
pub fn clear_overflow(&mut self) {
|
||||
self.overflow.clear();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
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]
|
||||
pub fn count_nonzero(&self) -> u64 {
|
||||
@@ -121,12 +164,16 @@ impl PersistentCompactIntVecBuilder {
|
||||
pub fn inc_present(&mut self, col: BitSliceView<'_>) {
|
||||
let n = self.n;
|
||||
for (wi, &word) in col.words().iter().enumerate() {
|
||||
if word == 0 { continue; }
|
||||
if word == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut w = word;
|
||||
while w != 0 {
|
||||
let bit = w.trailing_zeros() as usize;
|
||||
let bit = w.trailing_zeros() as usize;
|
||||
let slot = wi * 64 + bit;
|
||||
if slot < n { self.inc(slot); }
|
||||
if slot < n {
|
||||
self.inc(slot);
|
||||
}
|
||||
w &= w - 1;
|
||||
}
|
||||
}
|
||||
@@ -137,14 +184,18 @@ impl PersistentCompactIntVecBuilder {
|
||||
pub fn inc_present_fast(&mut self, col: BitSliceView<'_>) {
|
||||
{
|
||||
let primary = self.primary_bytes_mut();
|
||||
let n = primary.len();
|
||||
let n = primary.len();
|
||||
for (wi, &word) in col.words().iter().enumerate() {
|
||||
if word == 0 { continue; }
|
||||
if word == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut w = word;
|
||||
while w != 0 {
|
||||
let bit = w.trailing_zeros() as usize;
|
||||
let s = wi * 64 + bit;
|
||||
if s < n { primary[s] += 1; }
|
||||
let bit = w.trailing_zeros() as usize;
|
||||
let s = wi * 64 + bit;
|
||||
if s < n {
|
||||
primary[s] += 1;
|
||||
}
|
||||
w &= w - 1;
|
||||
}
|
||||
}
|
||||
@@ -166,7 +217,9 @@ impl PersistentCompactIntVecBuilder {
|
||||
}
|
||||
}
|
||||
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() {
|
||||
if pred(val) { self.primary_bytes_mut()[slot] += 1; }
|
||||
if pred(val) {
|
||||
self.primary_bytes_mut()[slot] += 1;
|
||||
}
|
||||
}
|
||||
debug_assert!(
|
||||
!self.primary_bytes().contains(&255),
|
||||
@@ -200,7 +255,12 @@ impl PersistentCompactIntVecBuilder {
|
||||
// through this loop).
|
||||
let mut newly_overflow: Vec<(usize, u32)> = 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 {
|
||||
let sum = *a as u32 + b as u32;
|
||||
if sum < 255 {
|
||||
@@ -213,7 +273,9 @@ impl PersistentCompactIntVecBuilder {
|
||||
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 {
|
||||
let sv = self.get(s);
|
||||
let ov = other.get(s);
|
||||
@@ -225,8 +287,14 @@ impl PersistentCompactIntVecBuilder {
|
||||
let self_ov: Vec<(usize, u32)> = self.overflow_entries().collect();
|
||||
let other_ov: HashMap<usize, u32> = other.overflow_entries().collect();
|
||||
self.clear_overflow();
|
||||
for (a, &b) in self.primary_bytes_mut().iter_mut().zip(other.primary_bytes()) {
|
||||
if b < *a { *a = b; }
|
||||
for (a, &b) in self
|
||||
.primary_bytes_mut()
|
||||
.iter_mut()
|
||||
.zip(other.primary_bytes())
|
||||
{
|
||||
if b < *a {
|
||||
*a = b;
|
||||
}
|
||||
}
|
||||
for (slot, self_val) in self_ov {
|
||||
if let Some(&other_val) = other_ov.get(&slot) {
|
||||
@@ -240,8 +308,14 @@ impl PersistentCompactIntVecBuilder {
|
||||
let sv = self.get(slot);
|
||||
self.set(slot, sv.max(other_val));
|
||||
}
|
||||
for (a, &b) in self.primary_bytes_mut().iter_mut().zip(other.primary_bytes()) {
|
||||
if b > *a { *a = b; }
|
||||
for (a, &b) in self
|
||||
.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
|
||||
// slots need the overflow map, settled after the loop.
|
||||
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 {
|
||||
*a = if b < 255 { a.saturating_sub(b) } else { 0 };
|
||||
} else {
|
||||
@@ -271,14 +350,18 @@ impl PersistentCompactIntVecBuilder {
|
||||
pub fn mask_with(&mut self, mask: BitSliceView<'_>) {
|
||||
let n = self.n;
|
||||
for (wi, &word) in mask.words().iter().enumerate() {
|
||||
if word == u64::MAX { continue; }
|
||||
if word == u64::MAX {
|
||||
continue;
|
||||
}
|
||||
let mut zeros = !word;
|
||||
while zeros != 0 {
|
||||
let bit = zeros.trailing_zeros() as usize;
|
||||
let s = wi * 64 + bit;
|
||||
let s = wi * 64 + bit;
|
||||
if s < n {
|
||||
let b = self.primary_bytes()[s];
|
||||
if b != 0 { self.set(s, 0); }
|
||||
if b != 0 {
|
||||
self.set(s, 0);
|
||||
}
|
||||
}
|
||||
zeros &= zeros - 1;
|
||||
}
|
||||
@@ -287,7 +370,12 @@ impl PersistentCompactIntVecBuilder {
|
||||
|
||||
pub fn close(self) -> io::Result<()> {
|
||||
self.mmap.flush()?;
|
||||
let Self { path, mmap, n, overflow } = self;
|
||||
let Self {
|
||||
path,
|
||||
mmap,
|
||||
n,
|
||||
overflow,
|
||||
} = self;
|
||||
drop(mmap);
|
||||
let mut entries: Vec<(usize, u32)> = overflow.into_iter().collect();
|
||||
entries.sort_unstable_by_key(|&(slot, _)| slot);
|
||||
|
||||
@@ -11,13 +11,16 @@ use crate::tempintvec::{TempCompactIntVec, TempCompactIntVecBuilder};
|
||||
/// partitions and layers because the column structure (samples / genomes) is
|
||||
/// identical everywhere — only the row space (kmer slots) is partitioned.
|
||||
pub struct ColGroup {
|
||||
pub name: String,
|
||||
pub name: String,
|
||||
pub indices: Vec<usize>,
|
||||
}
|
||||
|
||||
impl ColGroup {
|
||||
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> {
|
||||
if indices.len() < 255 {
|
||||
let mut builder = TempCompactIntVecBuilder::new(n)?;
|
||||
for &c in indices { inc(&mut builder, c); }
|
||||
for &c in indices {
|
||||
inc(&mut builder, c);
|
||||
}
|
||||
builder.freeze()
|
||||
} else {
|
||||
let mut result = TempCompactIntVecBuilder::new(n)?;
|
||||
for chunk in indices.chunks(254) {
|
||||
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()?;
|
||||
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.
|
||||
pub trait MatrixGroupOps {
|
||||
/// 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.
|
||||
fn partial_group_sum(&self, g: &ColGroup) -> io::Result<TempCompactIntVec>;
|
||||
@@ -105,9 +116,17 @@ pub trait MatrixGroupOps {
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum FilterMask {
|
||||
/// 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`.
|
||||
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`.
|
||||
SumGeq { indices: Vec<usize>, min_sum: u32 },
|
||||
/// 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`
|
||||
/// 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 {
|
||||
FilterMask::PresenceGeq { indices, threshold, min_count } => {
|
||||
FilterMask::PresenceGeq {
|
||||
indices,
|
||||
threshold,
|
||||
min_count,
|
||||
} => {
|
||||
let g = ColGroup::new("", indices.clone());
|
||||
let counts = mat.partial_group_presence_count(&g, *threshold)?;
|
||||
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.freeze()
|
||||
}
|
||||
FilterMask::PresenceLeq { indices, threshold, max_count } => {
|
||||
FilterMask::PresenceLeq {
|
||||
indices,
|
||||
threshold,
|
||||
max_count,
|
||||
} => {
|
||||
let g = ColGroup::new("", indices.clone());
|
||||
let counts = mat.partial_group_presence_count(&g, *threshold)?;
|
||||
let mut b = TempBitVecBuilder::new(n)?;
|
||||
|
||||
@@ -61,13 +61,22 @@ impl EliasFano {
|
||||
let high = PersistentRankSelectBitVec::open(&high_path(base))?;
|
||||
let n = low.len();
|
||||
let low_width = low.width();
|
||||
Ok(Self { low, high, n, low_width })
|
||||
Ok(Self {
|
||||
low,
|
||||
high,
|
||||
n,
|
||||
low_width,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[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.
|
||||
pub fn get(&self, i: usize) -> u64 {
|
||||
@@ -167,19 +176,35 @@ impl EliasFanoBuilder {
|
||||
// truth on reopen, no separate bookkeeping of `low_width` needed.
|
||||
let low = PersistentFixedIntVecBuilder::new(n, low_width, &low_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
|
||||
/// value (monotone non-decreasing), and `< universe` as given to
|
||||
/// [`new`](Self::new).
|
||||
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!(
|
||||
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);
|
||||
let high_part = value >> self.low_width;
|
||||
self.high.set(high_part as usize + self.next, true);
|
||||
@@ -188,7 +213,11 @@ impl EliasFanoBuilder {
|
||||
}
|
||||
|
||||
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.high.close()
|
||||
}
|
||||
|
||||
@@ -45,7 +45,11 @@ fn n_words_for(n: usize, width: u32) -> usize {
|
||||
|
||||
#[inline]
|
||||
fn mask(width: u32) -> u64 {
|
||||
if width >= 64 { u64::MAX } else { (1u64 << width) - 1 }
|
||||
if width >= 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
(1u64 << width) - 1
|
||||
}
|
||||
}
|
||||
|
||||
// ── PersistentFixedIntVec ───────────────────────────────────────────────────
|
||||
@@ -61,17 +65,30 @@ impl PersistentFixedIntVec {
|
||||
pub fn open(path: &Path) -> io::Result<Self> {
|
||||
let (mmap, n) = open_mmap_file(path, MAGIC, HEADER_SIZE)?;
|
||||
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]
|
||||
pub fn path(&self) -> &Path { &self.path }
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.n == 0 }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
#[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.
|
||||
#[inline]
|
||||
@@ -106,7 +123,10 @@ fn get_packed(words: &[u64], slot: usize, width: u32) -> u64 {
|
||||
#[inline]
|
||||
fn set_packed(words: &mut [u64], slot: usize, width: u32, value: u64) {
|
||||
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 word_idx = (bit_offset / 64) as usize;
|
||||
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 pad = [width as u8, 0, 0, 0];
|
||||
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]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.n == 0 }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
#[inline]
|
||||
pub fn width(&self) -> u32 { self.width }
|
||||
pub fn width(&self) -> u32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn data_words_mut(&mut self) -> &mut [u64] {
|
||||
|
||||
@@ -37,8 +37,8 @@ pub(crate) fn byte_count_nonzero(primary: &[u8]) -> u64 {
|
||||
#[inline]
|
||||
pub fn parse_overflow_entry(data: &[u8], base: usize, i: usize) -> (usize, u32) {
|
||||
let off = base + i * OVERFLOW_ENTRY_SIZE;
|
||||
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 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());
|
||||
(slot, value)
|
||||
}
|
||||
|
||||
@@ -46,8 +46,8 @@ pub fn parse_overflow_entry(data: &[u8], base: usize, i: usize) -> (usize, u32)
|
||||
#[inline]
|
||||
pub fn parse_index_entry(data: &[u8], base: usize, i: usize) -> (usize, usize) {
|
||||
let off = base + i * INDEX_ENTRY_SIZE;
|
||||
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 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;
|
||||
(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
|
||||
/// `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);
|
||||
w.write_all(&MAGIC)?;
|
||||
w.write_all(&[0u8; 4])?;
|
||||
|
||||
@@ -73,7 +73,8 @@ impl GroupAccum {
|
||||
let seen_before = self.present_count.get(slot);
|
||||
self.present_count.set(slot, seen_before + 1);
|
||||
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);
|
||||
if seen_before == 0 || value < self.min.get(slot) {
|
||||
|
||||
@@ -23,6 +23,8 @@ impl LayerMeta {
|
||||
}
|
||||
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
Some(Self { n: crate::meta::field(s, "n")? })
|
||||
Some(Self {
|
||||
n: crate::meta::field(s, "n")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -20,29 +20,30 @@ mod sparse_intmatrix_columnar;
|
||||
mod storage_kind;
|
||||
mod tempbitvec;
|
||||
mod tempintvec;
|
||||
mod transpose;
|
||||
pub mod traits;
|
||||
mod transpose;
|
||||
mod views;
|
||||
mod views_scan;
|
||||
|
||||
pub use bitmatrix::{
|
||||
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 builder::PersistentCompactIntVecBuilder;
|
||||
pub use colgroup::{ColGroup, FilterMask, MatrixGroupOps, eval_filter_mask};
|
||||
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 int_group_ops::{IntGroupStats, batch_int_group_stats};
|
||||
pub use intmatrix::{
|
||||
PersistentCompactIntMatrixBuilder, PersistentIntMatrix, pack_compact_int_matrix,
|
||||
};
|
||||
|
||||
pub use layer_meta::LayerMeta;
|
||||
pub use matrix_builder::{ColBuilder, MatrixBuilder};
|
||||
pub use mem_builder::{MemBitVecBuilder, MemCompactIntVecBuilder};
|
||||
pub use mmap_file::{building_path, publish_built};
|
||||
pub use matrix_builder::{ColBuilder, MatrixBuilder};
|
||||
pub use rankselect::{PersistentRankSelectBitVec, PersistentRankSelectBitVecBuilder};
|
||||
pub use reader::{Iter as CompactIntVecIter, PersistentCompactIntVec};
|
||||
pub use sparse_intmatrix::{
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::{MemBitVecBuilder, MemCompactIntVecBuilder, TempBitVec, TempCompactIntVec};
|
||||
use crate::{PersistentBitMatrixBuilder as BitMB, PersistentBitVecBuilder};
|
||||
use crate::{PersistentCompactIntMatrixBuilder as IntMB, PersistentCompactIntVecBuilder};
|
||||
use crate::{MemBitVecBuilder, MemCompactIntVecBuilder, TempBitVec, TempCompactIntVec};
|
||||
|
||||
// ── ColBuilder ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::collections::HashMap;
|
||||
use std::io::{self, Write};
|
||||
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::mmap_file::{write_built, write_std_header};
|
||||
|
||||
@@ -30,7 +30,11 @@ pub struct MemBitVecBuilder {
|
||||
impl MemBitVecBuilder {
|
||||
/// All-false vector of `n` bits, to be written at `path` by `close`.
|
||||
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]
|
||||
@@ -83,7 +87,12 @@ pub struct MemCompactIntVecBuilder {
|
||||
impl MemCompactIntVecBuilder {
|
||||
/// All-zero vector of `n` slots, to be written at `path` by `close`.
|
||||
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]
|
||||
@@ -110,7 +119,12 @@ impl MemCompactIntVecBuilder {
|
||||
/// Writes the PCIV file — header, primary bytes, overflow entries sorted
|
||||
/// by slot, sparse index — and publishes it.
|
||||
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();
|
||||
entries.sort_unstable_by_key(|&(slot, _)| slot);
|
||||
write_built(&path, |w| {
|
||||
|
||||
@@ -20,13 +20,18 @@ impl 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> {
|
||||
let key = format!("\"{}\":", name);
|
||||
let pos = s.find(&key)? + key.len();
|
||||
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()
|
||||
}
|
||||
@@ -38,7 +38,12 @@ pub fn publish_built(path: &Path) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// 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(&pad)?;
|
||||
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
|
||||
/// and starts with `magic`, and returns the mapping plus `n` (read from
|
||||
/// 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 tag = String::from_utf8_lossy(&magic).into_owned();
|
||||
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 {
|
||||
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;
|
||||
Ok((mmap, n))
|
||||
|
||||
@@ -65,19 +65,34 @@ impl PersistentRankSelectBitVec {
|
||||
pub fn open(path: &Path) -> io::Result<Self> {
|
||||
let (mmap, n) = open_mmap_file(path, MAGIC, HEADER_SIZE)?;
|
||||
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]
|
||||
pub fn path(&self) -> &Path { &self.path }
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.n == 0 }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
#[inline]
|
||||
pub fn count_ones(&self) -> u64 { self.total_ones }
|
||||
pub fn count_ones(&self) -> u64 {
|
||||
self.total_ones
|
||||
}
|
||||
#[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.
|
||||
#[inline]
|
||||
@@ -118,7 +133,11 @@ impl PersistentRankSelectBitVec {
|
||||
}
|
||||
let bit_in_word = pos - word_idx * 64;
|
||||
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
|
||||
}
|
||||
@@ -132,7 +151,11 @@ impl PersistentRankSelectBitVec {
|
||||
/// Position of the `k`-th (0-indexed) 1 bit. Panics if fewer than
|
||||
/// `k + 1` ones exist.
|
||||
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 words = self.bit_words();
|
||||
|
||||
@@ -141,7 +164,11 @@ impl PersistentRankSelectBitVec {
|
||||
let mut hi = block_ranks.len();
|
||||
while lo + 1 < hi {
|
||||
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 mut remaining = k - block_ranks[block_idx];
|
||||
@@ -154,7 +181,9 @@ impl PersistentRankSelectBitVec {
|
||||
}
|
||||
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
|
||||
@@ -166,7 +195,10 @@ impl PersistentRankSelectBitVec {
|
||||
/// exact bit within the winning word via `SelectInWord` on `!w`.
|
||||
pub fn select0(&self, k: u64) -> usize {
|
||||
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 words = self.bit_words();
|
||||
|
||||
@@ -176,7 +208,11 @@ impl PersistentRankSelectBitVec {
|
||||
while lo + 1 < hi {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
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 zeros_before_block = (block_idx * BLOCK_WORDS * 64) as u64 - block_ranks[block_idx];
|
||||
@@ -191,7 +227,9 @@ impl PersistentRankSelectBitVec {
|
||||
}
|
||||
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);
|
||||
// 8 extra header zero bytes: `total_ones`, patched in close().
|
||||
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]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.n == 0 }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bit_words_mut(&mut self) -> &mut [u64] {
|
||||
|
||||
@@ -4,7 +4,9 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
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;
|
||||
|
||||
pub struct PersistentCompactIntVec {
|
||||
@@ -23,41 +25,59 @@ impl PersistentCompactIntVec {
|
||||
let mmap = unsafe { Mmap::map(&File::open(path)?)? };
|
||||
|
||||
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 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PCIV 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;
|
||||
let n_overflow = u64::from_le_bytes(mmap[16..24].try_into().unwrap()) as usize;
|
||||
let n_index = u64::from_le_bytes(mmap[24..32].try_into().unwrap()) as usize;
|
||||
let step = u64::from_le_bytes(mmap[32..40].try_into().unwrap()) as usize;
|
||||
let n_index = u64::from_le_bytes(mmap[24..32].try_into().unwrap()) as usize;
|
||||
let step = u64::from_le_bytes(mmap[32..40].try_into().unwrap()) as usize;
|
||||
|
||||
let primary_offset = HEADER_SIZE;
|
||||
let data_offset = primary_offset + n;
|
||||
let index_offset = data_offset + n_overflow * OVERFLOW_ENTRY_SIZE;
|
||||
let data_offset = primary_offset + n;
|
||||
let index_offset = data_offset + n_overflow * OVERFLOW_ENTRY_SIZE;
|
||||
|
||||
let mut index = Vec::with_capacity(n_index);
|
||||
for i in 0..n_index {
|
||||
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]
|
||||
pub fn path(&self) -> &Path { &self.path }
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.n == 0 }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get(&self, slot: usize) -> u32 {
|
||||
match self.mmap[self.primary_offset + slot] {
|
||||
255 => self.overflow_get(slot),
|
||||
v => v as u32,
|
||||
v => v as u32,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,9 +102,16 @@ impl PersistentCompactIntVec {
|
||||
let (pos_start, pos_end) = if self.step == 0 {
|
||||
(0, self.n_overflow)
|
||||
} 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 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)
|
||||
};
|
||||
let mut lo = pos_start;
|
||||
@@ -92,8 +119,8 @@ impl PersistentCompactIntVec {
|
||||
while lo < hi {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
match self.data_slot(mid).cmp(&slot) {
|
||||
std::cmp::Ordering::Equal => return self.data_value(mid),
|
||||
std::cmp::Ordering::Less => lo = mid + 1,
|
||||
std::cmp::Ordering::Equal => return self.data_value(mid),
|
||||
std::cmp::Ordering::Less => lo = mid + 1,
|
||||
std::cmp::Ordering::Greater => hi = mid,
|
||||
}
|
||||
}
|
||||
@@ -135,13 +162,18 @@ impl PersistentCompactIntVec {
|
||||
#[inline]
|
||||
pub fn view(&self) -> IntSliceView<'_> {
|
||||
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)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn iter(&self) -> Iter<'_> {
|
||||
Iter { pciv: self, slot: 0, overflow_pos: 0 }
|
||||
Iter {
|
||||
pciv: self,
|
||||
slot: 0,
|
||||
overflow_pos: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Distance methods ──────────────────────────────────────────────────────
|
||||
@@ -163,8 +195,14 @@ impl PersistentCompactIntVec {
|
||||
self.view().relfreq_bray_dist(other.view())
|
||||
}
|
||||
|
||||
pub fn partial_relfreq_bray_dist(&self, other: &PersistentCompactIntVec, sum_a: f64, sum_b: f64) -> f64 {
|
||||
self.view().partial_relfreq_bray_dist(other.view(), sum_a, sum_b)
|
||||
pub fn partial_relfreq_bray_dist(
|
||||
&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 {
|
||||
@@ -179,16 +217,28 @@ impl PersistentCompactIntVec {
|
||||
self.view().relfreq_euclidean_dist(other.view())
|
||||
}
|
||||
|
||||
pub fn partial_relfreq_euclidean_dist(&self, other: &PersistentCompactIntVec, sum_a: f64, sum_b: f64) -> f64 {
|
||||
self.view().partial_relfreq_euclidean_dist(other.view(), sum_a, sum_b)
|
||||
pub fn partial_relfreq_euclidean_dist(
|
||||
&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 {
|
||||
self.view().hellinger_euclidean_dist(other.view())
|
||||
}
|
||||
|
||||
pub fn partial_hellinger_euclidean_dist(&self, other: &PersistentCompactIntVec, sum_a: f64, sum_b: f64) -> f64 {
|
||||
self.view().partial_hellinger_euclidean_dist(other.view(), sum_a, sum_b)
|
||||
pub fn partial_hellinger_euclidean_dist(
|
||||
&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 {
|
||||
@@ -199,8 +249,13 @@ impl PersistentCompactIntVec {
|
||||
self.view().threshold_jaccard_dist(other.view(), threshold)
|
||||
}
|
||||
|
||||
pub fn partial_threshold_jaccard_dist(&self, other: &PersistentCompactIntVec, threshold: u32) -> (u64, u64) {
|
||||
self.view().partial_threshold_jaccard_dist(other.view(), threshold)
|
||||
pub fn partial_threshold_jaccard_dist(
|
||||
&self,
|
||||
other: &PersistentCompactIntVec,
|
||||
threshold: u32,
|
||||
) -> (u64, u64) {
|
||||
self.view()
|
||||
.partial_threshold_jaccard_dist(other.view(), threshold)
|
||||
}
|
||||
|
||||
pub fn jaccard_dist(&self, other: &PersistentCompactIntVec) -> f64 {
|
||||
@@ -212,7 +267,9 @@ impl<'a> IntoIterator for &'a PersistentCompactIntVec {
|
||||
type Item = u32;
|
||||
type IntoIter = Iter<'a>;
|
||||
#[inline]
|
||||
fn into_iter(self) -> Iter<'a> { self.iter() }
|
||||
fn into_iter(self) -> Iter<'a> {
|
||||
self.iter()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Iter<'a> {
|
||||
@@ -228,7 +285,9 @@ impl Iterator for Iter<'_> {
|
||||
|
||||
#[inline]
|
||||
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];
|
||||
self.slot += 1;
|
||||
if v < 255 {
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
|
||||
use std::io;
|
||||
|
||||
use crate::PersistentBitMatrix;
|
||||
use crate::bitmatrix::batch_presence_counts;
|
||||
use crate::colgroup::{ColGroup, chunked_presence_count};
|
||||
use crate::intmatrix::PersistentIntMatrix;
|
||||
use crate::tempintvec::TempCompactIntVec;
|
||||
use crate::PersistentBitMatrix;
|
||||
|
||||
/// Tallies a per-row presence-count vector into `hist[j]` = number of rows
|
||||
/// whose count is `j`. `hist` has `n_cols + 1` entries.
|
||||
|
||||
@@ -629,7 +629,9 @@ impl PersistentSparseCompactIntMatrixBuilder {
|
||||
/// new format is fully written. Idempotent: a no-op if the sparse format is
|
||||
/// already present.
|
||||
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) {
|
||||
return Ok(());
|
||||
|
||||
@@ -21,7 +21,10 @@ use crate::sparse_intmatrix::PersistentSparseCompactIntMatrixBuilder;
|
||||
use crate::transpose::{DEFAULT_MAX_HITS, DEFAULT_WINDOW_ROWS, Hit, transpose_windows};
|
||||
|
||||
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
|
||||
@@ -101,7 +104,10 @@ fn read_int_window(
|
||||
if h.2 == 255 {
|
||||
let (slot, value) = parse_overflow_entry(&raw, 0, k);
|
||||
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;
|
||||
k += 1;
|
||||
@@ -135,7 +141,9 @@ impl PersistentSparseCompactIntMatrixBuilder {
|
||||
window_rows,
|
||||
max_hits,
|
||||
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| {
|
||||
for i in 0..batch.len() {
|
||||
builder.push_row(batch.cols(i), batch.vals(i));
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::views::{BitSliceView, IntSliceView};
|
||||
// ── TempCompactIntVec — frozen read-only, auto-deleted on drop ────────────────
|
||||
|
||||
pub struct TempCompactIntVec {
|
||||
vec: PersistentCompactIntVec,
|
||||
vec: PersistentCompactIntVec,
|
||||
// Dropped after `vec` (field order), so the mmap is released before the
|
||||
// temp directory is deleted.
|
||||
_temp: TempDir,
|
||||
@@ -23,24 +23,36 @@ impl TempCompactIntVec {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize { self.vec.len() }
|
||||
pub fn len(&self) -> usize {
|
||||
self.vec.len()
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.vec.is_empty() }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.vec.is_empty()
|
||||
}
|
||||
#[inline]
|
||||
pub fn get(&self, slot: usize) -> u32 { self.vec.get(slot) }
|
||||
pub fn get(&self, slot: usize) -> u32 {
|
||||
self.vec.get(slot)
|
||||
}
|
||||
#[inline]
|
||||
pub fn sum(&self) -> u64 { self.vec.sum() }
|
||||
pub fn sum(&self) -> u64 {
|
||||
self.vec.sum()
|
||||
}
|
||||
#[inline]
|
||||
pub fn view(&self) -> IntSliceView<'_> { self.vec.view() }
|
||||
pub fn view(&self) -> IntSliceView<'_> {
|
||||
self.vec.view()
|
||||
}
|
||||
#[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 ──
|
||||
|
||||
pub struct TempCompactIntVecBuilder {
|
||||
builder: PersistentCompactIntVecBuilder,
|
||||
temp: TempDir,
|
||||
temp: TempDir,
|
||||
}
|
||||
|
||||
impl TempCompactIntVecBuilder {
|
||||
@@ -58,17 +70,27 @@ impl TempCompactIntVecBuilder {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn n(&self) -> usize { self.builder.len() }
|
||||
pub fn n(&self) -> usize {
|
||||
self.builder.len()
|
||||
}
|
||||
|
||||
#[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]
|
||||
pub fn get(&self, slot: usize) -> u32 { self.builder.get(slot) }
|
||||
pub fn get(&self, slot: usize) -> u32 {
|
||||
self.builder.get(slot)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_bytes(&self) -> &[u8] { self.builder.primary_bytes() }
|
||||
pub fn primary_bytes(&self) -> &[u8] {
|
||||
self.builder.primary_bytes()
|
||||
}
|
||||
#[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]
|
||||
pub fn inc_present(&mut self, col: BitSliceView<'_>) {
|
||||
@@ -101,9 +123,15 @@ impl TempCompactIntVecBuilder {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn min(&mut self, other: IntSliceView<'_>) { self.builder.min(other); }
|
||||
pub fn min(&mut self, other: IntSliceView<'_>) {
|
||||
self.builder.min(other);
|
||||
}
|
||||
#[inline]
|
||||
pub fn max(&mut self, other: IntSliceView<'_>) { self.builder.max(other); }
|
||||
pub fn max(&mut self, other: IntSliceView<'_>) {
|
||||
self.builder.max(other);
|
||||
}
|
||||
#[inline]
|
||||
pub fn diff(&mut self, other: IntSliceView<'_>) { self.builder.diff(other); }
|
||||
pub fn diff(&mut self, other: IntSliceView<'_>) {
|
||||
self.builder.diff(other);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use tempfile::tempdir;
|
||||
|
||||
use crate::{pack_bit_matrix, PersistentBitMatrix, PersistentBitMatrixBuilder};
|
||||
use crate::traits::BitPartials;
|
||||
use crate::{PersistentBitMatrix, PersistentBitMatrixBuilder, pack_bit_matrix};
|
||||
|
||||
fn make_matrix(cols: &[&[bool]]) -> (tempfile::TempDir, PersistentBitMatrix) {
|
||||
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 mut b = PersistentBitMatrixBuilder::new(3, &presence).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();
|
||||
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();
|
||||
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 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();
|
||||
b.close().unwrap();
|
||||
|
||||
@@ -77,7 +83,9 @@ fn resume_continues_n_cols_and_appends_columns() {
|
||||
assert_eq!(resumed.n(), 3);
|
||||
assert_eq!(resumed.n_cols(), 1);
|
||||
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();
|
||||
resumed.close().unwrap();
|
||||
|
||||
@@ -93,12 +101,16 @@ fn resume_twice_keeps_appending() {
|
||||
let dir = tempdir().unwrap();
|
||||
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] {
|
||||
let mut b = PersistentBitMatrixBuilder::resume(&presence).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();
|
||||
b.close().unwrap();
|
||||
}
|
||||
@@ -115,7 +127,9 @@ fn col_accessor() {
|
||||
let presence = dir.path().join("presence");
|
||||
let mut b = PersistentBitMatrixBuilder::new(3, &presence).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();
|
||||
b.close().unwrap();
|
||||
|
||||
@@ -142,9 +156,9 @@ fn zero_cols_roundtrip() {
|
||||
#[test]
|
||||
fn count_ones_per_column() {
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true, true],
|
||||
&[true, false, true, true],
|
||||
&[false, false, false, false],
|
||||
&[true, true, true, false],
|
||||
&[true, true, true, false],
|
||||
]);
|
||||
let c = m.count_ones();
|
||||
assert_eq!(c[0], 3);
|
||||
@@ -158,15 +172,20 @@ fn count_ones_per_column() {
|
||||
fn jaccard_dist_matrix_symmetry_and_diagonal() {
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true],
|
||||
&[true, true, false],
|
||||
&[true, true, false],
|
||||
&[false, true, true],
|
||||
]);
|
||||
let dm = m.jaccard_dist_matrix();
|
||||
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 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}]"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -175,7 +194,7 @@ fn jaccard_dist_matrix_symmetry_and_diagonal() {
|
||||
fn jaccard_dist_matrix_values_match_pairwise() {
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true],
|
||||
&[true, true, false],
|
||||
&[true, true, false],
|
||||
&[false, true, true],
|
||||
]);
|
||||
let dm = m.jaccard_dist_matrix();
|
||||
@@ -191,12 +210,14 @@ fn jaccard_dist_matrix_values_match_pairwise() {
|
||||
fn hamming_dist_matrix_symmetry_and_diagonal() {
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true],
|
||||
&[true, true, false],
|
||||
&[true, true, false],
|
||||
&[false, true, true],
|
||||
]);
|
||||
let dm = m.hamming_dist_matrix();
|
||||
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 j in 0..n {
|
||||
assert_eq!(dm[[i, j]], dm[[j, i]], "symmetry [{i},{j}]");
|
||||
@@ -208,7 +229,7 @@ fn hamming_dist_matrix_symmetry_and_diagonal() {
|
||||
fn hamming_dist_matrix_values_match_pairwise() {
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true],
|
||||
&[true, true, false],
|
||||
&[true, true, false],
|
||||
&[false, true, true],
|
||||
]);
|
||||
let dm = m.hamming_dist_matrix();
|
||||
@@ -223,7 +244,7 @@ fn hamming_dist_matrix_values_match_pairwise() {
|
||||
fn partial_jaccard_consistent() {
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true, true],
|
||||
&[true, true, false, true],
|
||||
&[true, true, false, true],
|
||||
&[false, true, true, false],
|
||||
]);
|
||||
let (inter, union) = m.partial_jaccard_dist_matrix();
|
||||
@@ -247,7 +268,7 @@ fn partial_hamming_matches_hamming() {
|
||||
&[true, true, false],
|
||||
]);
|
||||
let partial = m.partial_hamming_dist_matrix();
|
||||
let full = m.hamming_dist_matrix();
|
||||
let full = m.hamming_dist_matrix();
|
||||
assert_eq!(partial, full);
|
||||
}
|
||||
|
||||
@@ -255,10 +276,7 @@ fn partial_hamming_matches_hamming() {
|
||||
|
||||
#[test]
|
||||
fn col_view_packed_values() {
|
||||
let (dir, _) = make_matrix(&[
|
||||
&[true, false, true, true],
|
||||
&[false, true, false, true],
|
||||
]);
|
||||
let (dir, _) = make_matrix(&[&[true, false, true, true], &[false, true, false, true]]);
|
||||
pack_bit_matrix(&dir.path().join("presence")).unwrap();
|
||||
let m = PersistentBitMatrix::open(dir.path()).unwrap();
|
||||
|
||||
@@ -288,18 +306,22 @@ fn col_view_packed_matches_columnar() {
|
||||
&[true, true, true, false, false, false, true, true],
|
||||
];
|
||||
let (dir_col, m_col) = make_matrix(data);
|
||||
let (dir_pack, _) = make_matrix(data);
|
||||
let (dir_pack, _) = make_matrix(data);
|
||||
pack_bit_matrix(&dir_pack.path().join("presence")).unwrap();
|
||||
let m_pack = PersistentBitMatrix::open(dir_pack.path()).unwrap();
|
||||
|
||||
for c in 0..data.len() {
|
||||
let col_ref = m_col.col(c);
|
||||
let col_ref = m_col.col(c);
|
||||
let col_view = m_pack.col_view(c);
|
||||
assert_eq!(col_view.len(), col_ref.len(), "col={c} 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.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");
|
||||
}
|
||||
drop(dir_col);
|
||||
@@ -313,21 +335,25 @@ fn col_view_packed_matches_columnar() {
|
||||
fn count_geq_ignores_threshold() {
|
||||
use crate::traits::ColumnWeights;
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true, true],
|
||||
&[true, false, true, true],
|
||||
&[false, false, false, false],
|
||||
&[true, true, true, false],
|
||||
&[true, true, true, false],
|
||||
]);
|
||||
for t in [0u32, 1, 2, 100] {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), vec![3, 0, 3], "threshold {t}");
|
||||
assert_eq!(
|
||||
ColumnWeights::count_geq(&m, t).to_vec(),
|
||||
vec![3, 0, 3],
|
||||
"threshold {t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_presence_histogram_dense() {
|
||||
let (_d, m) = make_matrix(&[
|
||||
&[true, false, true, true],
|
||||
&[false, false, true, false],
|
||||
&[true, false, true, false],
|
||||
&[true, false, true, true],
|
||||
&[false, false, true, false],
|
||||
&[true, false, true, false],
|
||||
]);
|
||||
// Rows carry 2, 0, 3, 1 genomes.
|
||||
assert_eq!(m.row_presence_histogram().unwrap(), vec![1, 1, 1, 1]);
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
use tempfile::tempdir;
|
||||
|
||||
use crate::{PersistentBitVec, PersistentBitVecBuilder, PersistentCompactIntVec, PersistentCompactIntVecBuilder};
|
||||
use crate::{
|
||||
PersistentBitVec, PersistentBitVecBuilder, PersistentCompactIntVec,
|
||||
PersistentCompactIntVecBuilder,
|
||||
};
|
||||
|
||||
fn make_bv(bits: &[bool]) -> (tempfile::TempDir, PersistentBitVec) {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("v.pbiv");
|
||||
let mut b = PersistentBitVecBuilder::new(bits.len(), &path).unwrap();
|
||||
for (i, &v) in bits.iter().enumerate() {
|
||||
@@ -16,7 +19,7 @@ fn make_bv(bits: &[bool]) -> (tempfile::TempDir, PersistentBitVec) {
|
||||
|
||||
#[test]
|
||||
fn all_false_by_default() {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("v.pbiv");
|
||||
let b = PersistentBitVecBuilder::new(16, &path).unwrap();
|
||||
b.close().unwrap();
|
||||
@@ -36,10 +39,12 @@ fn set_get_roundtrip() {
|
||||
|
||||
#[test]
|
||||
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 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();
|
||||
assert_eq!(via_iter, via_get);
|
||||
}
|
||||
|
||||
@@ -47,7 +52,7 @@ fn iter_matches_get() {
|
||||
fn count_ones_and_zeros() {
|
||||
let bits = vec![true, false, true, true, false];
|
||||
let (_dir, r) = make_bv(&bits);
|
||||
assert_eq!(r.count_ones(), 3);
|
||||
assert_eq!(r.count_ones(), 3);
|
||||
assert_eq!(r.count_zeros(), 2);
|
||||
}
|
||||
|
||||
@@ -65,28 +70,34 @@ fn build_from_roundtrip() {
|
||||
let (_da, ra) = make_bv(&bits);
|
||||
let dir_b = tempdir().unwrap();
|
||||
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();
|
||||
assert_eq!(ra.iter().collect::<Vec<_>>(), rb.iter().collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn op_and() {
|
||||
let (_da, ra) = make_bv(&[true, true, false, false]);
|
||||
let (_db, rb) = make_bv(&[true, false, true, false]);
|
||||
let (_da, ra) = make_bv(&[true, true, false, false]);
|
||||
let (_db, rb) = make_bv(&[true, false, true, false]);
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("out.pbiv");
|
||||
let mut b = PersistentBitVecBuilder::build_from(&ra, &path).unwrap();
|
||||
b.and(rb.view());
|
||||
b.close().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]
|
||||
fn op_or() {
|
||||
let (_da, ra) = make_bv(&[true, true, false, false]);
|
||||
let (_db, rb) = make_bv(&[true, false, true, false]);
|
||||
let (_da, ra) = make_bv(&[true, true, false, false]);
|
||||
let (_db, rb) = make_bv(&[true, false, true, false]);
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("out.pbiv");
|
||||
let mut b = PersistentBitVecBuilder::build_from(&ra, &path).unwrap();
|
||||
@@ -98,8 +109,8 @@ fn op_or() {
|
||||
|
||||
#[test]
|
||||
fn op_xor() {
|
||||
let (_da, ra) = make_bv(&[true, true, false, false]);
|
||||
let (_db, rb) = make_bv(&[true, false, true, false]);
|
||||
let (_da, ra) = make_bv(&[true, true, false, false]);
|
||||
let (_db, rb) = make_bv(&[true, false, true, false]);
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("out.pbiv");
|
||||
let mut b = PersistentBitVecBuilder::build_from(&ra, &path).unwrap();
|
||||
@@ -134,7 +145,10 @@ fn op_not_non_aligned_no_padding_leak() {
|
||||
b.not();
|
||||
b.close().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
|
||||
assert_eq!(r.count_ones(), 2);
|
||||
}
|
||||
@@ -142,8 +156,8 @@ fn op_not_non_aligned_no_padding_leak() {
|
||||
#[test]
|
||||
fn jaccard_dist_basic() {
|
||||
// A={0,2} B={0,1} → inter=1 union=3 → dist=2/3
|
||||
let (_da, ra) = make_bv(&[true, false, true, false]);
|
||||
let (_db, rb) = make_bv(&[true, true, false, false]);
|
||||
let (_da, ra) = make_bv(&[true, false, true, false]);
|
||||
let (_db, rb) = make_bv(&[true, true, false, false]);
|
||||
let d = ra.jaccard_dist(&rb);
|
||||
assert!((d - 2.0 / 3.0).abs() < 1e-12, "got {d}");
|
||||
}
|
||||
@@ -156,16 +170,18 @@ fn jaccard_dist_identical() {
|
||||
|
||||
#[test]
|
||||
fn jaccard_dist_disjoint() {
|
||||
let (_da, ra) = make_bv(&[true, false]);
|
||||
let (_da, ra) = make_bv(&[true, false]);
|
||||
let (_db, rb) = make_bv(&[false, true]);
|
||||
assert_eq!(ra.jaccard_dist(&rb), 1.0);
|
||||
}
|
||||
|
||||
fn make_pciv(counts: &[u32]) -> (tempfile::TempDir, PersistentCompactIntVec) {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("c.pciv");
|
||||
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();
|
||||
let r = PersistentCompactIntVec::open(&path).unwrap();
|
||||
(dir, r)
|
||||
@@ -175,11 +191,17 @@ fn make_pciv(counts: &[u32]) -> (tempfile::TempDir, PersistentCompactIntVec) {
|
||||
fn build_from_presence_basic() {
|
||||
let counts = vec![0u32, 3, 0, 7, 1, 0];
|
||||
let (_dc, rc) = make_pciv(&counts);
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
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();
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -188,11 +210,17 @@ fn build_from_counts_with_threshold() {
|
||||
// threshold=5: present if count >= 5
|
||||
let counts = vec![0u32, 3, 5, 10, 4, 6];
|
||||
let (_dc, rc) = make_pciv(&counts);
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
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();
|
||||
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]
|
||||
@@ -200,18 +228,24 @@ fn build_from_counts_with_overflow_values() {
|
||||
// overflow value (>= 255) must pass threshold
|
||||
let counts = vec![0u32, 100, 1_000_000, 50];
|
||||
let (_dc, rc) = make_pciv(&counts);
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
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();
|
||||
assert_eq!(bv.iter().collect::<Vec<_>>(), vec![false, false, true, false]);
|
||||
assert_eq!(
|
||||
bv.iter().collect::<Vec<_>>(),
|
||||
vec![false, false, true, false]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hamming_dist_basic() {
|
||||
// differ at positions 1 and 2
|
||||
let (_da, ra) = make_bv(&[true, true, false, true]);
|
||||
let (_db, rb) = make_bv(&[true, false, true, true]);
|
||||
let (_da, ra) = make_bv(&[true, true, false, true]);
|
||||
let (_db, rb) = make_bv(&[true, false, true, true]);
|
||||
assert_eq!(ra.hamming_dist(&rb), 2);
|
||||
}
|
||||
|
||||
@@ -264,7 +298,10 @@ fn bitslice_view_collect_slots_values() {
|
||||
let bits = vec![true, false, true, false, true];
|
||||
let (_dir, r) = make_bv(&bits);
|
||||
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]);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ use tempfile::tempdir;
|
||||
|
||||
use crate::{
|
||||
ColGroup, MatrixGroupOps, PersistentBitMatrix, PersistentBitMatrixBuilder,
|
||||
PersistentIntMatrix, PersistentCompactIntMatrixBuilder,
|
||||
PersistentSparseBitMatrixBuilder, batch_presence_counts,
|
||||
PersistentCompactIntMatrixBuilder, PersistentIntMatrix, PersistentSparseBitMatrixBuilder,
|
||||
batch_presence_counts,
|
||||
};
|
||||
use crate::{PersistentBitVecBuilder, PersistentCompactIntVec, PersistentCompactIntVecBuilder};
|
||||
|
||||
@@ -248,10 +248,10 @@ fn int_presence_count_additive_across_split() {
|
||||
fn batch_presence_counts_matches_naive_for_columnar_and_sparse() {
|
||||
// Column-major: cols[c][row]
|
||||
let cols: [&[bool]; 4] = [
|
||||
&[true, false, true, false, true], // col0
|
||||
&[true, true, false, false, true], // col1
|
||||
&[false, true, true, true, false], // col2
|
||||
&[false, false, false, true, true], // col3
|
||||
&[true, false, true, false, true], // col0
|
||||
&[true, true, false, false, true], // col1
|
||||
&[false, true, true, true, false], // col2
|
||||
&[false, false, false, true, true], // col3
|
||||
];
|
||||
let (_dcol, columnar) = make_bit_matrix(&cols);
|
||||
|
||||
@@ -283,7 +283,11 @@ fn batch_presence_counts_matches_naive_for_columnar_and_sparse() {
|
||||
|
||||
for (label, mat) in [("columnar", &columnar), ("sparse", &sparse)] {
|
||||
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 (row, &e) in exp.iter().enumerate() {
|
||||
assert_eq!(counts[gi].get(row), e, "{label}: group {gi} row {row}");
|
||||
|
||||
@@ -148,8 +148,16 @@ fn successor_and_predecessor_small() {
|
||||
let values = [0u64, 3, 3, 7, 42, 42, 42, 100];
|
||||
let (_dir, ef) = build(&values, 1000);
|
||||
for x in 0..=105u64 {
|
||||
assert_eq!(ef.successor(x), naive_successor(&values, x), "successor({x})");
|
||||
assert_eq!(ef.predecessor(x), naive_predecessor(&values, x), "predecessor({x})");
|
||||
assert_eq!(
|
||||
ef.successor(x),
|
||||
naive_successor(&values, x),
|
||||
"successor({x})"
|
||||
);
|
||||
assert_eq!(
|
||||
ef.predecessor(x),
|
||||
naive_predecessor(&values, x),
|
||||
"predecessor({x})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,7 +58,10 @@ fn batch_int_group_stats_matches_hand_computed_for_columnar_and_sparse() {
|
||||
let (_dcol, columnar) = make_columnar(&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;
|
||||
|
||||
// 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");
|
||||
|
||||
for row in 0..4 {
|
||||
assert_eq!(stats[0].presence_count.get(row), g1_presence[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[0].presence_count.get(row),
|
||||
g1_presence[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!(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}");
|
||||
assert_eq!(
|
||||
stats[1].presence_count.get(row),
|
||||
g2_presence[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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -687,7 +687,9 @@ fn intslice_view_collect_slots_values() {
|
||||
|
||||
/// Naive per-column `count(v >= threshold)` over column-major `data`.
|
||||
fn naive_count_geq(data: &[&[u32]], threshold: u32) -> Vec<u64> {
|
||||
data.iter().map(|col| col.iter().filter(|&&v| v >= threshold).count() as u64).collect()
|
||||
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.
|
||||
@@ -699,7 +701,11 @@ fn count_geq_columnar_matches_naive() {
|
||||
let (_d, m) = make_matrix(data);
|
||||
assert_eq!(m.storage_kind(), StorageKind::Columnar);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}");
|
||||
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();
|
||||
assert_eq!(m.storage_kind(), StorageKind::Packed);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}");
|
||||
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();
|
||||
assert_eq!(m.storage_kind(), StorageKind::Sparse);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(ColumnWeights::count_geq(&m, t).to_vec(), naive_count_geq(data, t), "threshold {t}");
|
||||
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 (_d, m) = make_matrix(data);
|
||||
assert_eq!(m.partial_kmer_counts().to_vec(), m.count_nonzero().to_vec());
|
||||
assert_eq!(m.partial_kmer_counts().to_vec(), ColumnWeights::count_geq(&m, 1).to_vec());
|
||||
assert_eq!(
|
||||
m.partial_kmer_counts().to_vec(),
|
||||
ColumnWeights::count_geq(&m, 1).to_vec()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -767,7 +784,11 @@ const HIST_DATA: &[&[u32]] = &[
|
||||
fn row_presence_histogram_columnar_matches_naive() {
|
||||
let (_d, m) = make_matrix(HIST_DATA);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}");
|
||||
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();
|
||||
assert_eq!(m.storage_kind(), StorageKind::Packed);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}");
|
||||
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();
|
||||
assert_eq!(m.storage_kind(), StorageKind::Sparse);
|
||||
for t in GEQ_THRESHOLDS {
|
||||
assert_eq!(m.row_presence_histogram(t).unwrap(), naive_row_hist(HIST_DATA, t), "threshold {t}");
|
||||
assert_eq!(
|
||||
m.row_presence_histogram(t).unwrap(),
|
||||
naive_row_hist(HIST_DATA, t),
|
||||
"threshold {t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -80,9 +80,15 @@ fn add_mem_col_matrix_reads_back() {
|
||||
for presence in [true, false] {
|
||||
let n = 100;
|
||||
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 {
|
||||
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();
|
||||
|
||||
@@ -18,7 +18,7 @@ use tempfile::tempdir;
|
||||
use crate::{PersistentCompactIntVec, PersistentCompactIntVecBuilder};
|
||||
|
||||
fn roundtrip(values: &[(usize, u32)], n: usize) -> Vec<u32> {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(n, &path).unwrap();
|
||||
for &(slot, v) in values {
|
||||
@@ -30,7 +30,7 @@ fn roundtrip(values: &[(usize, u32)], n: usize) -> Vec<u32> {
|
||||
}
|
||||
|
||||
fn make_pciv(values: &[u32]) -> (tempfile::TempDir, PersistentCompactIntVec) {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("v.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(values.len(), &path).unwrap();
|
||||
for (i, &v) in values.iter().enumerate() {
|
||||
@@ -49,7 +49,7 @@ fn all_zero_by_default() {
|
||||
|
||||
#[test]
|
||||
fn small_values_no_overflow() {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(4, &path).unwrap();
|
||||
b.set(0, 1);
|
||||
@@ -76,7 +76,7 @@ fn overflow_values_roundtrip() {
|
||||
|
||||
#[test]
|
||||
fn mutation_downward_removes_from_overflow() {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(2, &path).unwrap();
|
||||
b.set(0, 1000);
|
||||
@@ -89,7 +89,7 @@ fn mutation_downward_removes_from_overflow() {
|
||||
|
||||
#[test]
|
||||
fn mutation_upward_updates_overflow() {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(1, &path).unwrap();
|
||||
b.set(0, 300);
|
||||
@@ -101,8 +101,8 @@ fn mutation_upward_updates_overflow() {
|
||||
|
||||
#[test]
|
||||
fn sparse_index_built_for_many_overflows() {
|
||||
let n = 5000usize;
|
||||
let dir = tempdir().unwrap();
|
||||
let n = 5000usize;
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(n, &path).unwrap();
|
||||
for i in 0..n {
|
||||
@@ -118,9 +118,16 @@ fn sparse_index_built_for_many_overflows() {
|
||||
|
||||
#[test]
|
||||
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 dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(n, &path).unwrap();
|
||||
for &(slot, v) in &values {
|
||||
@@ -130,13 +137,13 @@ fn iter_matches_get() {
|
||||
let r = PersistentCompactIntVec::open(&path).unwrap();
|
||||
|
||||
let via_iter: Vec<u32> = r.iter().collect();
|
||||
let via_get: Vec<u32> = (0..n).map(|s| r.get(s)).collect();
|
||||
let via_get: Vec<u32> = (0..n).map(|s| r.get(s)).collect();
|
||||
assert_eq!(via_iter, via_get);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iter_size_hint_exact() {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(5, &path).unwrap();
|
||||
b.set(2, 1000);
|
||||
@@ -150,7 +157,7 @@ fn iter_size_hint_exact() {
|
||||
|
||||
#[test]
|
||||
fn into_iter_for_ref() {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(3, &path).unwrap();
|
||||
b.set(0, 10);
|
||||
@@ -168,14 +175,17 @@ fn build_from_roundtrip() {
|
||||
let (_dir_a, ra) = make_pciv(&a);
|
||||
let dir_b = tempdir().unwrap();
|
||||
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();
|
||||
assert_eq!(ra.iter().collect::<Vec<_>>(), rb.iter().collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combine_min() {
|
||||
let (_da, ra) = make_pciv(&[10, 300, 0, 1000]);
|
||||
let (_da, ra) = make_pciv(&[10, 300, 0, 1000]);
|
||||
let (_db, rb) = make_pciv(&[20, 100, 500, 800]);
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("out.pciv");
|
||||
@@ -188,7 +198,7 @@ fn combine_min() {
|
||||
|
||||
#[test]
|
||||
fn combine_max() {
|
||||
let (_da, ra) = make_pciv(&[10, 300, 0, 1000]);
|
||||
let (_da, ra) = make_pciv(&[10, 300, 0, 1000]);
|
||||
let (_db, rb) = make_pciv(&[20, 100, 500, 800]);
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("out.pciv");
|
||||
@@ -226,8 +236,8 @@ fn sum_aggregation_with_overflow_values() {
|
||||
|
||||
#[test]
|
||||
fn combine_diff() {
|
||||
let (_da, ra) = make_pciv(&[20, 1000, 5, 0]);
|
||||
let (_db, rb) = make_pciv(&[10, 300, 10, 1]);
|
||||
let (_da, ra) = make_pciv(&[20, 1000, 5, 0]);
|
||||
let (_db, rb) = make_pciv(&[10, 300, 10, 1]);
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("out.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::build_from(&ra, &path).unwrap();
|
||||
@@ -354,18 +364,22 @@ 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();
|
||||
assert_eq!(ra.partial_bray_dist(&rb), naive_bray);
|
||||
|
||||
let naive_euclidean: f64 = a.iter().zip(&b)
|
||||
.map(|(&x, &y)| { let d = x as f64 - y as f64; d * d })
|
||||
let naive_euclidean: f64 = a
|
||||
.iter()
|
||||
.zip(&b)
|
||||
.map(|(&x, &y)| {
|
||||
let d = x as f64 - y as f64;
|
||||
d * d
|
||||
})
|
||||
.sum();
|
||||
assert!((ra.partial_euclidean_dist(&rb) - naive_euclidean).abs() < 1e-9);
|
||||
|
||||
for threshold in [1u32, 6, 255, 600] {
|
||||
let (naive_inter, naive_union) = a.iter().zip(&b)
|
||||
.fold((0u64, 0u64), |(i, u), (&x, &y)| {
|
||||
let xp = x >= threshold;
|
||||
let yp = y >= threshold;
|
||||
(i + (xp & yp) as u64, u + (xp | yp) as u64)
|
||||
});
|
||||
let (naive_inter, naive_union) = a.iter().zip(&b).fold((0u64, 0u64), |(i, u), (&x, &y)| {
|
||||
let xp = x >= threshold;
|
||||
let yp = y >= threshold;
|
||||
(i + (xp & yp) as u64, u + (xp | yp) as u64)
|
||||
});
|
||||
let (inter, union) = ra.partial_threshold_jaccard_dist(&rb, threshold);
|
||||
assert_eq!(inter, naive_inter, "threshold {threshold}");
|
||||
assert_eq!(union, naive_union, "threshold {threshold}");
|
||||
@@ -374,18 +388,26 @@ fn partial_dists_bulk_path_matches_naive_reference_with_overflow() {
|
||||
|
||||
#[test]
|
||||
fn mixed_large_dataset() {
|
||||
let n = 1000usize;
|
||||
let dir = tempdir().unwrap();
|
||||
let n = 1000usize;
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("test.pciv");
|
||||
let mut b = PersistentCompactIntVecBuilder::new(n, &path).unwrap();
|
||||
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.close().unwrap();
|
||||
let r = PersistentCompactIntVec::open(&path).unwrap();
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,21 @@ fn naive_rank1(bits: &[bool], pos: usize) -> u64 {
|
||||
}
|
||||
|
||||
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 {
|
||||
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]
|
||||
@@ -45,7 +55,9 @@ fn count_ones_matches_naive() {
|
||||
|
||||
#[test]
|
||||
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);
|
||||
for pos in 0..=bits.len() {
|
||||
assert_eq!(r.rank1(pos), naive_rank1(&bits, pos), "rank1({pos})");
|
||||
@@ -76,7 +88,9 @@ fn rank0_is_complement_of_rank1() {
|
||||
|
||||
#[test]
|
||||
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 n_ones = bits.iter().filter(|&&b| b).count() as u64;
|
||||
for k in 0..n_ones {
|
||||
@@ -97,7 +111,9 @@ fn select1_matches_naive_multi_block() {
|
||||
|
||||
#[test]
|
||||
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 n_zeros = bits.iter().filter(|&&b| !b).count() as u64;
|
||||
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:
|
||||
// positions 0..=9 set, 10 clear, 11..=20 set.
|
||||
let mut bits = vec![false; 30];
|
||||
for p in 0..=9 { bits[p] = true; }
|
||||
for p in 11..=20 { bits[p] = true; }
|
||||
for p in 0..=9 {
|
||||
bits[p] = true;
|
||||
}
|
||||
for p in 11..=20 {
|
||||
bits[p] = true;
|
||||
}
|
||||
let (_dir, r) = build(&bits);
|
||||
assert_eq!(r.select1(9), 9, "select1(9)");
|
||||
assert_eq!(r.select1(10), 11, "select1(10)");
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
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 —
|
||||
/// mirrors `tests/bitmatrix.rs`'s own `make_matrix` helper.
|
||||
@@ -46,11 +49,11 @@ fn basic_roundtrip_singletons_and_multi() {
|
||||
// 5 rows, 4 genomes: mix of singleton, multi-genome, and one repeated
|
||||
// multi-genome set (dedup should collapse it to one dictionary entry).
|
||||
let rows: Vec<&[bool]> = vec![
|
||||
&[true, false, false, false], // singleton: genome 0
|
||||
&[false, false, true, false], // singleton: genome 2
|
||||
&[true, true, false, false], // multi: {0,1}
|
||||
&[false, false, true, true], // multi: {2,3}
|
||||
&[true, true, false, false], // multi: {0,1} again — should dedup
|
||||
&[true, false, false, false], // singleton: genome 0
|
||||
&[false, false, true, false], // singleton: genome 2
|
||||
&[true, true, false, false], // multi: {0,1}
|
||||
&[false, false, true, true], // multi: {2,3}
|
||||
&[true, true, false, false], // multi: {0,1} again — should dedup
|
||||
];
|
||||
let (_dir, m) = make_sparse(&rows, 4);
|
||||
assert_eq!(m.n(), 5);
|
||||
@@ -98,7 +101,8 @@ fn dense_to_sparse_matches_dense_on_real_shaped_data() {
|
||||
assert_eq!(sparse.n_cols(), dense.n_cols());
|
||||
for slot in 0..dense.n() {
|
||||
assert_eq!(
|
||||
row_as_bool(&sparse, slot), &*dense.row(slot),
|
||||
row_as_bool(&sparse, slot),
|
||||
&*dense.row(slot),
|
||||
"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_cols(&dense), BinaryMatrix::n_cols(&sparse));
|
||||
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 sparse_counts = BinaryMatrix::count_ones(&sparse);
|
||||
@@ -279,11 +287,26 @@ fn reopen_large_real_shaped_data_with_heavy_dedup() {
|
||||
.map(|i| {
|
||||
let mut row = vec![false; n_cols];
|
||||
match i % 5 {
|
||||
0 => { row[i % n_cols] = true; } // singleton, varies per row
|
||||
1 => { 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
|
||||
0 => {
|
||||
row[i % n_cols] = true;
|
||||
} // singleton, varies per row
|
||||
1 => {
|
||||
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
|
||||
})
|
||||
@@ -321,7 +344,10 @@ fn pack_sparse_bit_matrix_transposes_columnar_directly() {
|
||||
];
|
||||
let (dir, dense) = make_dense(cols);
|
||||
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 n_cols = dense.n_cols();
|
||||
@@ -330,9 +356,18 @@ fn pack_sparse_bit_matrix_transposes_columnar_directly() {
|
||||
pack_sparse_bit_matrix(&presence_dir).unwrap();
|
||||
|
||||
assert!(presence_dir.join("is_multi.prsb").exists());
|
||||
assert!(!presence_dir.join("meta.json").exists(), "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");
|
||||
assert!(
|
||||
!presence_dir.join("meta.json").exists(),
|
||||
"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();
|
||||
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.
|
||||
#[test]
|
||||
fn pack_sparse_bit_matrix_from_already_packed_matrix() {
|
||||
let cols: &[&[bool]] = &[
|
||||
&[true, false, true],
|
||||
&[false, true, true],
|
||||
];
|
||||
let cols: &[&[bool]] = &[&[true, false, true], &[false, true, true]];
|
||||
let (dir, dense) = make_dense(cols);
|
||||
let presence_dir = dir.path().join("presence");
|
||||
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());
|
||||
|
||||
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();
|
||||
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 n = cols.first().unwrap().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 (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");
|
||||
|
||||
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);
|
||||
@@ -440,33 +481,50 @@ fn build_permuted_follows_the_permutation() {
|
||||
assert_eq!(permuted.n(), src.n());
|
||||
assert_eq!(permuted.n_cols(), src.n_cols());
|
||||
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]
|
||||
fn sparse_count_geq_ignores_threshold() {
|
||||
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);
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_row_presence_histogram_matches_dense() {
|
||||
let cols: &[&[bool]] = &[
|
||||
&[true, false, true, true, false],
|
||||
&[false, false, true, false, false],
|
||||
&[true, false, true, false, false],
|
||||
&[true, false, true, true, false],
|
||||
&[false, false, true, false, false],
|
||||
&[true, false, true, false, false],
|
||||
];
|
||||
let (_dd, dense) = make_dense(cols);
|
||||
let rows: Vec<Vec<bool>> = (0..5).map(|s| cols.iter().map(|c| c[s]).collect()).collect();
|
||||
let rows: Vec<Vec<bool>> = (0..5)
|
||||
.map(|s| cols.iter().map(|c| c[s]).collect())
|
||||
.collect();
|
||||
let row_refs: Vec<&[bool]> = rows.iter().map(Vec::as_slice).collect();
|
||||
let (_ds, sparse) = make_sparse(&row_refs, 3);
|
||||
let sparse = PersistentBitMatrix::Sparse(sparse);
|
||||
assert_eq!(sparse.row_presence_histogram().unwrap(), dense.row_presence_histogram().unwrap());
|
||||
assert_eq!(
|
||||
sparse.row_presence_histogram().unwrap(),
|
||||
dense.row_presence_histogram().unwrap()
|
||||
);
|
||||
// Rows carry 2, 0, 3, 1, 0 genomes.
|
||||
assert_eq!(sparse.row_presence_histogram().unwrap(), vec![2, 1, 1, 1]);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use tempfile::tempdir;
|
||||
|
||||
use crate::{
|
||||
ColumnWeights, PersistentIntMatrix, PersistentCompactIntMatrixBuilder,
|
||||
ColumnWeights, PersistentCompactIntMatrixBuilder, PersistentIntMatrix,
|
||||
PersistentSparseCompactIntMatrix, PersistentSparseCompactIntMatrixBuilder,
|
||||
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,17 +81,25 @@ fn sparse_files(dir: &Path) -> Vec<(String, Vec<u8>)> {
|
||||
let n = p.file_name().unwrap().to_string_lossy().into_owned();
|
||||
!(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();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
const WINDOWS: &[(usize, usize)] = &[
|
||||
(64, usize::MAX / 4), // smallest window, never too dense
|
||||
(192, 50), // forces the retry-with-half-window path
|
||||
(4096, 10_000), // a few windows
|
||||
(crate::transpose::DEFAULT_WINDOW_ROWS, crate::transpose::DEFAULT_MAX_HITS),
|
||||
(64, usize::MAX / 4), // smallest window, never too dense
|
||||
(192, 50), // forces the retry-with-half-window path
|
||||
(4096, 10_000), // a few windows
|
||||
(
|
||||
crate::transpose::DEFAULT_WINDOW_ROWS,
|
||||
crate::transpose::DEFAULT_MAX_HITS,
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
@@ -101,7 +109,10 @@ fn bit_columnar_transpose_is_byte_identical_to_the_dense_route() {
|
||||
let ref_dir = ref_root.path().join("presence");
|
||||
pack_bit_matrix(&ref_dir).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);
|
||||
let expected = sparse_files(&ref_dir);
|
||||
assert!(!expected.is_empty());
|
||||
@@ -115,7 +126,11 @@ fn bit_columnar_transpose_is_byte_identical_to_the_dense_route() {
|
||||
.unwrap()
|
||||
.close()
|
||||
.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");
|
||||
pack_compact_int_matrix(&ref_dir).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);
|
||||
let expected = sparse_files(&ref_dir);
|
||||
assert!(!expected.is_empty());
|
||||
@@ -136,11 +154,17 @@ fn int_columnar_transpose_is_byte_identical_to_the_dense_route() {
|
||||
build_ints(root.path());
|
||||
let dir = root.path().join("counts");
|
||||
let meta = MatrixMeta::load(&dir).unwrap();
|
||||
PersistentSparseCompactIntMatrixBuilder::build_from_columnar_with(&dir, &meta, window, max_hits)
|
||||
.unwrap()
|
||||
.close()
|
||||
.unwrap();
|
||||
assert_eq!(sparse_files(&dir), expected, "window={window} max_hits={max_hits}");
|
||||
PersistentSparseCompactIntMatrixBuilder::build_from_columnar_with(
|
||||
&dir, &meta, window, max_hits,
|
||||
)
|
||||
.unwrap()
|
||||
.close()
|
||||
.unwrap();
|
||||
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 mut meta = MatrixMeta::load(&dir).unwrap();
|
||||
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);
|
||||
}
|
||||
@@ -40,11 +40,28 @@ fn for_each_set_in_matches_get_loop_on_all_boundaries() {
|
||||
}
|
||||
}
|
||||
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 &b in &cuts {
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,8 +44,11 @@ pub trait BinaryMatrix {
|
||||
fn jaccard_to_mash(d_jaccard: &Array2<f64>, k: usize) -> Array2<f64> {
|
||||
d_jaccard.mapv(|d| {
|
||||
let j = 1.0 - d;
|
||||
if j <= 0.0 { 1.0 }
|
||||
else { -1.0 / k as f64 * (2.0 * j / (1.0 + j)).ln() }
|
||||
if j <= 0.0 {
|
||||
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 {
|
||||
if i != j {
|
||||
let d = w[i] + w[j];
|
||||
m[[i, j]] = if d == 0 { 0.0 }
|
||||
else { 1.0 - 2.0 * sum_min[[i, j]] as f64 / d as f64 };
|
||||
m[[i, j]] = if d == 0 {
|
||||
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 {
|
||||
if i != j {
|
||||
let u = union[[i, j]];
|
||||
m[[i, j]] = if u == 0 { 0.0 }
|
||||
else { 1.0 - inter[[i, j]] as f64 / u as f64 };
|
||||
m[[i, j]] = if u == 0 {
|
||||
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 mut m = self.partial_relfreq_bray(&global).mapv(|v| 1.0 - v);
|
||||
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
|
||||
}
|
||||
|
||||
@@ -190,8 +201,11 @@ pub trait BitPartials: ColumnWeights {
|
||||
for j in 0..n {
|
||||
if i != j {
|
||||
let u = union[[i, j]];
|
||||
m[[i, j]] = if u == 0 { 0.0 }
|
||||
else { 1.0 - inter[[i, j]] as f64 / u as f64 };
|
||||
m[[i, j]] = if u == 0 {
|
||||
0.0
|
||||
} else {
|
||||
1.0 - inter[[i, j]] as f64 / u as f64
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,11 @@ pub(crate) struct RowBatch<V> {
|
||||
|
||||
impl<V: Copy> RowBatch<V> {
|
||||
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.
|
||||
|
||||
+197
-69
@@ -7,19 +7,27 @@ use crate::format::{byte_count_nonzero, byte_sum, parse_overflow_entry};
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct BitSliceView<'a> {
|
||||
pub(crate) words: &'a [u64],
|
||||
pub(crate) n: usize,
|
||||
pub(crate) n: usize,
|
||||
}
|
||||
|
||||
impl<'a> BitSliceView<'a> {
|
||||
#[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]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.n == 0 }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
#[inline]
|
||||
pub fn words(&self) -> &'a [u64] { self.words }
|
||||
pub fn words(&self) -> &'a [u64] {
|
||||
self.words
|
||||
}
|
||||
|
||||
#[inline]
|
||||
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]) {
|
||||
assert_eq!(slots.len(), out.len());
|
||||
let n = slots.len();
|
||||
if n == 0 { return; }
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let mut perm: Vec<usize> = (0..n).collect();
|
||||
perm.sort_by_key(|&i| slots[i]);
|
||||
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
|
||||
/// given.
|
||||
#[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
|
||||
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
|
||||
@@ -69,39 +85,60 @@ impl<'a> BitSliceView<'a> {
|
||||
/// several columns over the same slot set sort it once beforehand
|
||||
/// purely for cache-friendlier `get` access (see
|
||||
/// `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
|
||||
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 {
|
||||
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]
|
||||
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) {
|
||||
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)| {
|
||||
(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 {
|
||||
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 {
|
||||
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)
|
||||
.sum()
|
||||
}
|
||||
@@ -111,15 +148,17 @@ impl<'a> BitSliceView<'a> {
|
||||
|
||||
pub struct BitSliceIter<'a> {
|
||||
words: &'a [u64],
|
||||
slot: usize,
|
||||
n: usize,
|
||||
slot: usize,
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl Iterator for BitSliceIter<'_> {
|
||||
type Item = bool;
|
||||
#[inline]
|
||||
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;
|
||||
self.slot += 1;
|
||||
Some(v)
|
||||
@@ -138,30 +177,43 @@ impl ExactSizeIterator for BitSliceIter<'_> {}
|
||||
/// its sorted raw overflow bytes. Zero-copy: all data lives in the caller's mmap.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct IntSliceView<'a> {
|
||||
pub(crate) primary: &'a [u8],
|
||||
pub(crate) overflow_raw: &'a [u8], // n_overflow × OVERFLOW_ENTRY_SIZE bytes, sorted by slot
|
||||
pub(crate) n_overflow: usize,
|
||||
pub(crate) n: usize,
|
||||
pub(crate) primary: &'a [u8],
|
||||
pub(crate) overflow_raw: &'a [u8], // n_overflow × OVERFLOW_ENTRY_SIZE bytes, sorted by slot
|
||||
pub(crate) n_overflow: usize,
|
||||
pub(crate) n: usize,
|
||||
}
|
||||
|
||||
impl<'a> IntSliceView<'a> {
|
||||
#[inline]
|
||||
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]
|
||||
pub fn len(&self) -> usize { self.n }
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool { self.n == 0 }
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
#[inline]
|
||||
pub fn primary_bytes(&self) -> &'a [u8] { self.primary }
|
||||
pub fn primary_bytes(&self) -> &'a [u8] {
|
||||
self.primary
|
||||
}
|
||||
#[inline]
|
||||
pub fn n_overflow(&self) -> usize { self.n_overflow }
|
||||
pub fn n_overflow(&self) -> usize {
|
||||
self.n_overflow
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn overflow_entries(&self) -> impl Iterator<Item = (usize, u32)> + 'a {
|
||||
let raw = self.overflow_raw;
|
||||
let raw = self.overflow_raw;
|
||||
let n_ov = self.n_overflow;
|
||||
(0..n_ov).map(move |i| parse_overflow_entry(raw, 0, i))
|
||||
}
|
||||
@@ -169,15 +221,17 @@ impl<'a> IntSliceView<'a> {
|
||||
/// O(log n_overflow) via binary search (overflow is always sorted by slot).
|
||||
pub fn get(&self, slot: usize) -> u32 {
|
||||
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 hi = self.n_overflow;
|
||||
while lo < hi {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
let (s, v) = parse_overflow_entry(self.overflow_raw, 0, mid);
|
||||
match s.cmp(&slot) {
|
||||
std::cmp::Ordering::Equal => return v,
|
||||
std::cmp::Ordering::Less => lo = mid + 1,
|
||||
std::cmp::Ordering::Equal => return v,
|
||||
std::cmp::Ordering::Less => lo = mid + 1,
|
||||
std::cmp::Ordering::Greater => hi = mid,
|
||||
}
|
||||
}
|
||||
@@ -198,7 +252,9 @@ impl<'a> IntSliceView<'a> {
|
||||
pub fn fill_slots_values(&self, slots: &[usize], out: &mut [u32]) {
|
||||
assert_eq!(slots.len(), out.len());
|
||||
let n = slots.len();
|
||||
if n == 0 { return; }
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let mut perm: Vec<usize> = (0..n).collect();
|
||||
perm.sort_by_key(|&i| slots[i]);
|
||||
let sorted: Vec<usize> = perm.iter().map(|&i| slots[i]).collect();
|
||||
@@ -211,32 +267,42 @@ impl<'a> IntSliceView<'a> {
|
||||
/// [`BitSliceView::enumerate_slots_values`]: order never affects
|
||||
/// correctness here.
|
||||
#[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
|
||||
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,
|
||||
/// value)` for every nonzero value — a `filter_map` over `get`, not a
|
||||
/// 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
|
||||
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.
|
||||
#[inline]
|
||||
pub fn iter(&self) -> IntSliceViewIter<'a> {
|
||||
IntSliceViewIter {
|
||||
primary: self.primary,
|
||||
primary: self.primary,
|
||||
overflow_raw: self.overflow_raw,
|
||||
slot: 0,
|
||||
slot: 0,
|
||||
overflow_pos: 0,
|
||||
n: self.n,
|
||||
n: self.n,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,7 +346,10 @@ impl<'a> IntSliceView<'a> {
|
||||
pub fn partial_bray_dist(self, other: IntSliceView<'_>) -> u64 {
|
||||
assert_eq!(self.n, other.n, "length mismatch");
|
||||
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))
|
||||
.sum();
|
||||
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 {
|
||||
let sum_min = self.partial_bray_dist(other);
|
||||
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 {
|
||||
assert_eq!(self.n, other.n, "length mismatch");
|
||||
self.iter().zip(other.iter())
|
||||
self.iter()
|
||||
.zip(other.iter())
|
||||
.map(|(a, b)| {
|
||||
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 };
|
||||
@@ -311,14 +385,22 @@ impl<'a> IntSliceView<'a> {
|
||||
pub fn relfreq_bray_dist(self, other: IntSliceView<'_>) -> f64 {
|
||||
let sa = self.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)
|
||||
}
|
||||
|
||||
pub fn partial_euclidean_dist(self, other: IntSliceView<'_>) -> f64 {
|
||||
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 mut total: f64 = self.primary.iter().zip(other.primary)
|
||||
let term = |a: u32, b: u32| {
|
||||
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))
|
||||
.sum();
|
||||
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 {
|
||||
assert_eq!(self.n, other.n, "length mismatch");
|
||||
self.iter().zip(other.iter())
|
||||
self.iter()
|
||||
.zip(other.iter())
|
||||
.map(|(a, b)| {
|
||||
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 };
|
||||
@@ -348,16 +431,32 @@ impl<'a> IntSliceView<'a> {
|
||||
pub fn relfreq_euclidean_dist(self, other: IntSliceView<'_>) -> f64 {
|
||||
let sa = self.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()
|
||||
}
|
||||
|
||||
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");
|
||||
self.iter().zip(other.iter())
|
||||
self.iter()
|
||||
.zip(other.iter())
|
||||
.map(|(a, b)| {
|
||||
let pa = if sa > 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 pa = if sa > 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;
|
||||
d * d
|
||||
})
|
||||
@@ -367,7 +466,9 @@ impl<'a> IntSliceView<'a> {
|
||||
pub fn hellinger_euclidean_dist(self, other: IntSliceView<'_>) -> f64 {
|
||||
let sa = self.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()
|
||||
}
|
||||
|
||||
@@ -375,18 +476,25 @@ impl<'a> IntSliceView<'a> {
|
||||
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");
|
||||
let term = |a: u32, b: u32| {
|
||||
let ap = a >= threshold;
|
||||
let bp = b >= threshold;
|
||||
((ap & bp) as u64, (ap | bp) as u64)
|
||||
};
|
||||
let (mut inter, mut uni) = self.primary.iter().zip(other.primary)
|
||||
.fold((0u64, 0u64), |(inter, uni), (&a, &b)| {
|
||||
let (ti, tu) = term(a as u32, b as u32);
|
||||
(inter + ti, uni + tu)
|
||||
});
|
||||
let (mut inter, mut uni) =
|
||||
self.primary
|
||||
.iter()
|
||||
.zip(other.primary)
|
||||
.fold((0u64, 0u64), |(inter, uni), (&a, &b)| {
|
||||
let (ti, tu) = term(a as u32, b as u32);
|
||||
(inter + ti, uni + tu)
|
||||
});
|
||||
self.for_each_overflow_pair(other, |slot, a_true, b_true| {
|
||||
let (wi, wu) = term(self.primary[slot] as u32, other.primary[slot] as u32);
|
||||
let (ri, ru) = term(a_true, b_true);
|
||||
@@ -398,7 +506,11 @@ impl<'a> IntSliceView<'a> {
|
||||
|
||||
pub fn threshold_jaccard_dist(self, other: IntSliceView<'_>, threshold: u32) -> f64 {
|
||||
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 {
|
||||
@@ -413,7 +525,11 @@ impl<'a> IntSliceView<'a> {
|
||||
/// one. Overflow entries are sorted by slot in both views (on-disk
|
||||
/// invariant, see `format::finalize_pciv`), so their union is walked in
|
||||
/// 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 b_it = other.overflow_entries().peekable();
|
||||
loop {
|
||||
@@ -446,14 +562,20 @@ impl<'a> IntSliceView<'a> {
|
||||
/// can be written once and reused by every matrix type instead of
|
||||
/// reimplementing the same sort-then-scan-columns loop per format.
|
||||
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
|
||||
Self: 'b;
|
||||
}
|
||||
|
||||
impl<'a> NonzeroSlotsView for BitSliceView<'a> {
|
||||
#[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
|
||||
Self: 'b,
|
||||
{
|
||||
@@ -463,7 +585,10 @@ impl<'a> NonzeroSlotsView for BitSliceView<'a> {
|
||||
|
||||
impl<'a> NonzeroSlotsView for IntSliceView<'a> {
|
||||
#[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
|
||||
Self: 'b,
|
||||
{
|
||||
@@ -491,7 +616,8 @@ pub(crate) fn nonzero_triples<V: NonzeroSlotsView>(
|
||||
let mut hits: Vec<(usize, usize, u32)> = Vec::new();
|
||||
for c in 0..n_cols {
|
||||
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)),
|
||||
);
|
||||
}
|
||||
@@ -501,18 +627,20 @@ pub(crate) fn nonzero_triples<V: NonzeroSlotsView>(
|
||||
// ── IntSliceViewIter ──────────────────────────────────────────────────────────
|
||||
|
||||
pub struct IntSliceViewIter<'a> {
|
||||
primary: &'a [u8],
|
||||
primary: &'a [u8],
|
||||
overflow_raw: &'a [u8],
|
||||
slot: usize,
|
||||
slot: usize,
|
||||
overflow_pos: usize,
|
||||
n: usize,
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl Iterator for IntSliceViewIter<'_> {
|
||||
type Item = u32;
|
||||
#[inline]
|
||||
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];
|
||||
self.slot += 1;
|
||||
if v < 255 {
|
||||
|
||||
@@ -19,7 +19,12 @@ impl BitSliceView<'_> {
|
||||
/// Panics if `range.end > self.len()`.
|
||||
#[inline]
|
||||
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 {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
|
||||
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::walk::WalkState;
|
||||
|
||||
@@ -79,7 +79,8 @@ impl GraphDeBruijn {
|
||||
if node.is_visited() {
|
||||
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();
|
||||
atomic.store(node.0, Ordering::Relaxed);
|
||||
}
|
||||
@@ -120,7 +121,12 @@ impl GraphDeBruijn {
|
||||
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 old = atomic.fetch_or(IS_VISITED_MASK, Ordering::AcqRel);
|
||||
if old & IS_VISITED_MASK != 0 {
|
||||
@@ -128,7 +134,9 @@ impl GraphDeBruijn {
|
||||
}
|
||||
let start = WalkState::new(kmer, Node(old), direct, atomic);
|
||||
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))
|
||||
});
|
||||
Some(UnitigNucIter::new(self, kmer, k, direct, next_step))
|
||||
@@ -152,7 +160,9 @@ impl GraphDeBruijn {
|
||||
.then_some(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) {
|
||||
n_new.fetch_add(1, Ordering::Relaxed);
|
||||
f(iter);
|
||||
@@ -162,7 +172,9 @@ impl GraphDeBruijn {
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
self.nodes.iter().for_each(|(&kmer, atomic)| {
|
||||
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) {
|
||||
n_new.fetch_add(1, Ordering::Relaxed);
|
||||
f(iter);
|
||||
@@ -199,7 +211,6 @@ impl GraphDeBruijn {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// Merge `other` into `self`.
|
||||
|
||||
@@ -50,7 +50,9 @@ impl Iterator for UnitigNucIter<'_> {
|
||||
Some(nuc)
|
||||
} else if let Some((state, nuc)) = self.next_step.take() {
|
||||
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))
|
||||
});
|
||||
Some(nuc)
|
||||
|
||||
@@ -18,7 +18,12 @@ pub struct WalkState<'g> {
|
||||
impl<'g> WalkState<'g> {
|
||||
pub fn new(kmer: CanonicalKmer, node: Node, direct: bool, atomic: &'g AtomicU8) -> Self {
|
||||
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 {
|
||||
|
||||
@@ -354,9 +354,21 @@ fn linear_chain_is_one_unitig_whatever_the_orientations() {
|
||||
let g = graph_from_ascii(&seq);
|
||||
g.compute_degrees_and_mark_starts();
|
||||
let unitigs = collect_unitigs(&g);
|
||||
assert_eq!(unitigs.len(), 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");
|
||||
assert_eq!(
|
||||
unitigs.len(),
|
||||
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 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!(kmers_from_unitigs(&unitigs).len(), g.len(), "no k-mer missing");
|
||||
assert_eq!(
|
||||
kmers_from_unitigs(&unitigs).len(),
|
||||
g.len(),
|
||||
"no k-mer missing"
|
||||
);
|
||||
}
|
||||
@@ -19,10 +19,7 @@ impl fmt::Display for JsonVal<'_> {
|
||||
}
|
||||
|
||||
/// Write a JSON object `{"k1":v1,"k2":v2,...}` to `writer`.
|
||||
pub fn annotation<W: Write>(
|
||||
writer: &mut W,
|
||||
fields: &[(&str, JsonVal<'_>)],
|
||||
) -> io::Result<()> {
|
||||
pub fn annotation<W: Write>(writer: &mut W, fields: &[(&str, JsonVal<'_>)]) -> io::Result<()> {
|
||||
write!(writer, "{{")?;
|
||||
for (i, (k, v)) in fields.iter().enumerate() {
|
||||
if i > 0 {
|
||||
|
||||
+28
-18
@@ -51,11 +51,11 @@ pub fn write_scatter<W: Write>(
|
||||
&ascii,
|
||||
&id,
|
||||
&[
|
||||
("seq_length", JsonVal::Num(ascii.len() as u64)),
|
||||
("kmer_size", JsonVal::Num(k as u64)),
|
||||
("minimizer_size",JsonVal::Num(m as u64)),
|
||||
("partition", JsonVal::Num(partition as u64)),
|
||||
("minimizer", JsonVal::Str(min_str)),
|
||||
("seq_length", JsonVal::Num(ascii.len() as u64)),
|
||||
("kmer_size", JsonVal::Num(k as u64)),
|
||||
("minimizer_size", JsonVal::Num(m as u64)),
|
||||
("partition", JsonVal::Num(partition as u64)),
|
||||
("minimizer", JsonVal::Str(min_str)),
|
||||
],
|
||||
out,
|
||||
)
|
||||
@@ -78,11 +78,11 @@ pub fn write_count<W: Write>(
|
||||
&ascii,
|
||||
&id,
|
||||
&[
|
||||
("seq_length", JsonVal::Num(ascii.len() as u64)),
|
||||
("kmer_size", JsonVal::Num(k as u64)),
|
||||
("minimizer_size",JsonVal::Num(m as u64)),
|
||||
("partition", JsonVal::Num(partition as u64)),
|
||||
("count", JsonVal::Num(sk.count() as u64)),
|
||||
("seq_length", JsonVal::Num(ascii.len() as u64)),
|
||||
("kmer_size", JsonVal::Num(k as u64)),
|
||||
("minimizer_size", JsonVal::Num(m as u64)),
|
||||
("partition", JsonVal::Num(partition as u64)),
|
||||
("count", JsonVal::Num(sk.count() as u64)),
|
||||
],
|
||||
out,
|
||||
)
|
||||
@@ -107,10 +107,10 @@ pub fn write_unitig<W: Write>(
|
||||
&ascii,
|
||||
&id,
|
||||
&[
|
||||
("seq_length", JsonVal::Num(seql as u64)),
|
||||
("kmer_size", JsonVal::Num(k as u64)),
|
||||
("n_kmers", JsonVal::Num((seql - k + 1) as u64)),
|
||||
("partition", JsonVal::Num(partition as u64)),
|
||||
("seq_length", JsonVal::Num(seql as u64)),
|
||||
("kmer_size", JsonVal::Num(k as u64)),
|
||||
("n_kmers", JsonVal::Num((seql - k + 1) as u64)),
|
||||
("partition", JsonVal::Num(partition as u64)),
|
||||
("unitig_index", JsonVal::Num(index as u64)),
|
||||
],
|
||||
out,
|
||||
@@ -255,11 +255,21 @@ mod tests {
|
||||
let sk2 = make(b"TTTTTTTT");
|
||||
|
||||
let id1 = capture(|w| write_scatter(&sk1, w, 4, 2, 0, Minimizer::from_raw_unchecked(0)))
|
||||
.lines().next().unwrap()
|
||||
.split_whitespace().next().unwrap()[1..].to_string();
|
||||
.lines()
|
||||
.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)))
|
||||
.lines().next().unwrap()
|
||||
.split_whitespace().next().unwrap()[1..].to_string();
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap()[1..]
|
||||
.to_string();
|
||||
assert_ne!(id1, id2);
|
||||
}
|
||||
|
||||
|
||||
+92
-51
@@ -4,10 +4,10 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
use obikindex::{OKIError, OKIResult};
|
||||
use obikindex::KmerIndex;
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikfilter::KmerFilter;
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikindex::KmerIndex;
|
||||
use obikindex::{OKIError, OKIResult};
|
||||
|
||||
use obikfilter::FilteredPartitionIter;
|
||||
|
||||
@@ -50,10 +50,10 @@ impl IndexDump for Arc<KmerIndex> {
|
||||
filters: &[Box<dyn KmerFilter>],
|
||||
on_partition: F,
|
||||
) -> OKIResult<()> {
|
||||
let genomes = self.meta().genomes().map_err(OKIError::Io)?;
|
||||
let genomes = self.meta().genomes().map_err(OKIError::Io)?;
|
||||
let use_counts = self.meta().config.with_counts && !force_presence;
|
||||
let n_genomes = genomes.len().max(1);
|
||||
let kmer_size = self.kmer_size();
|
||||
let n_genomes = genomes.len().max(1);
|
||||
let kmer_size = self.kmer_size();
|
||||
|
||||
// ── Header ────────────────────────────────────────────────────────────
|
||||
if debug {
|
||||
@@ -70,60 +70,101 @@ impl IndexDump for Arc<KmerIndex> {
|
||||
|
||||
let write_row = |buf: &mut Vec<u8>, row: &[u32], prefix: &str| {
|
||||
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 chunks: Vec<OKIResult<Vec<u8>>> = if let Some(limit) = head {
|
||||
// ── Bounded: atomic counter, early exit when limit reached ────────
|
||||
let remaining = AtomicUsize::new(limit);
|
||||
(0..n).into_par_iter().map(|i| {
|
||||
if remaining.load(Ordering::Relaxed) == 0 { return Ok(vec![]); }
|
||||
let mut buf = Vec::<u8>::new();
|
||||
let try_write = |buf: &mut Vec<u8>, row: &[u32], prefix: &str| -> bool {
|
||||
match remaining.try_update(Ordering::SeqCst, Ordering::SeqCst, |cur| {
|
||||
if cur > 0 { Some(cur - 1) } else { None }
|
||||
}) {
|
||||
Err(_) => false,
|
||||
Ok(_) => { write_row(buf, row, prefix); true }
|
||||
(0..n)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
if remaining.load(Ordering::Relaxed) == 0 {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
};
|
||||
let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
|
||||
if debug {
|
||||
cache.iter_partition_kmers_located(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}"))
|
||||
})?;
|
||||
} else {
|
||||
cache.iter_partition_kmers(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)
|
||||
})?;
|
||||
}
|
||||
on_partition();
|
||||
Ok(buf)
|
||||
}).collect()
|
||||
let mut buf = Vec::<u8>::new();
|
||||
let try_write = |buf: &mut Vec<u8>, row: &[u32], prefix: &str| -> bool {
|
||||
match remaining.try_update(Ordering::SeqCst, Ordering::SeqCst, |cur| {
|
||||
if cur > 0 { Some(cur - 1) } else { None }
|
||||
}) {
|
||||
Err(_) => false,
|
||||
Ok(_) => {
|
||||
write_row(buf, row, prefix);
|
||||
true
|
||||
}
|
||||
}
|
||||
};
|
||||
let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
|
||||
if debug {
|
||||
cache.iter_partition_kmers_located(
|
||||
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}"))
|
||||
},
|
||||
)?;
|
||||
} else {
|
||||
cache.iter_partition_kmers(
|
||||
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)
|
||||
},
|
||||
)?;
|
||||
}
|
||||
on_partition();
|
||||
Ok(buf)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
// ── Unbounded: no atomic, no contention ───────────────────────────
|
||||
(0..n).into_par_iter().map(|i| {
|
||||
let mut buf = Vec::<u8>::new();
|
||||
let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
|
||||
if debug {
|
||||
cache.iter_partition_kmers_located(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}"));
|
||||
true
|
||||
})?;
|
||||
} else {
|
||||
cache.iter_partition_kmers(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);
|
||||
true
|
||||
})?;
|
||||
}
|
||||
on_partition();
|
||||
Ok(buf)
|
||||
}).collect()
|
||||
(0..n)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let mut buf = Vec::<u8>::new();
|
||||
let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
|
||||
if debug {
|
||||
cache.iter_partition_kmers_located(
|
||||
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}"));
|
||||
true
|
||||
},
|
||||
)?;
|
||||
} else {
|
||||
cache.iter_partition_kmers(
|
||||
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);
|
||||
true
|
||||
},
|
||||
)?;
|
||||
}
|
||||
on_partition();
|
||||
Ok(buf)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
// ── Sequential write ──────────────────────────────────────────────────
|
||||
|
||||
@@ -40,15 +40,24 @@ impl IndexUnitigs for Arc<KmerIndex> {
|
||||
|
||||
let g = (0..n)
|
||||
.into_par_iter()
|
||||
.try_fold(GraphDeBruijn::new, |mut local_g, i| -> OKIResult<GraphDeBruijn> {
|
||||
let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
|
||||
cache.iter_partition_kmers(i, use_counts, n_genomes, filters, |kmer, _row| {
|
||||
local_g.push(kmer);
|
||||
true
|
||||
})?;
|
||||
on_partition();
|
||||
Ok(local_g)
|
||||
})
|
||||
.try_fold(
|
||||
GraphDeBruijn::new,
|
||||
|mut local_g, i| -> OKIResult<GraphDeBruijn> {
|
||||
let cache = IndexCache::new(Arc::clone(self), Some(vec![i]));
|
||||
cache.iter_partition_kmers(
|
||||
i,
|
||||
use_counts,
|
||||
n_genomes,
|
||||
filters,
|
||||
|kmer, _row| {
|
||||
local_g.push(kmer);
|
||||
true
|
||||
},
|
||||
)?;
|
||||
on_partition();
|
||||
Ok(local_g)
|
||||
},
|
||||
)
|
||||
.try_reduce(GraphDeBruijn::new, |mut a, b| {
|
||||
a.merge(b);
|
||||
Ok(a)
|
||||
|
||||
@@ -60,12 +60,22 @@ fn emit_f64_1d(out: &mut String, name: &str, n: usize, values: &[f64]) {
|
||||
out.push_str("];\n");
|
||||
}
|
||||
|
||||
fn emit_f64_2d(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"));
|
||||
fn emit_f64_2d(
|
||||
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 {
|
||||
out.push_str(" [");
|
||||
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("],\n");
|
||||
|
||||
@@ -7,7 +7,9 @@ const LEVEL_MAX: usize = 6;
|
||||
|
||||
fn kmer_from_ascii(seq: &[u8]) -> CanonicalKmer {
|
||||
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]
|
||||
@@ -24,7 +26,10 @@ fn homopolymer_scores_lower_than_diverse_sequence() {
|
||||
);
|
||||
// A pure homopolymer is the most degenerate case representable — its
|
||||
// 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]
|
||||
@@ -44,9 +49,16 @@ fn entropy_is_within_zero_one_range() {
|
||||
repeat,
|
||||
"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 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:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -183,8 +183,12 @@ impl EntropyTracker {
|
||||
fn push_warmup_increments(
|
||||
&mut self,
|
||||
received: usize,
|
||||
raw1: u64, raw2: u64, raw3: u64,
|
||||
raw4: u64, raw5: u64, raw6: u64,
|
||||
raw1: u64,
|
||||
raw2: u64,
|
||||
raw3: u64,
|
||||
raw4: u64,
|
||||
raw5: u64,
|
||||
raw6: u64,
|
||||
) {
|
||||
let g1 = self.k1c[raw1 as usize] as usize;
|
||||
Self::update_sums_increment::<1>(&mut self.sum_f_log_f, g1);
|
||||
|
||||
@@ -180,16 +180,16 @@ impl KmerFilter for MaxTotalCount {
|
||||
/// `selection.ingroup_idx` / `selection.outgroup_idx` are column indices into
|
||||
/// the per-genome row. When empty, the corresponding quorum is not checked.
|
||||
pub struct GroupQuorumFilter {
|
||||
pub selection: Selection,
|
||||
pub threshold: u32,
|
||||
pub min_count: usize,
|
||||
pub max_count: usize,
|
||||
pub min_frac: f64,
|
||||
pub max_frac: f64,
|
||||
pub selection: Selection,
|
||||
pub threshold: u32,
|
||||
pub min_count: usize,
|
||||
pub max_count: usize,
|
||||
pub min_frac: f64,
|
||||
pub max_frac: f64,
|
||||
pub min_outgroup_count: usize,
|
||||
pub max_outgroup_count: usize,
|
||||
pub min_outgroup_frac: f64,
|
||||
pub max_outgroup_frac: f64,
|
||||
pub min_outgroup_frac: f64,
|
||||
pub max_outgroup_frac: f64,
|
||||
}
|
||||
|
||||
impl GroupQuorumFilter {
|
||||
@@ -226,26 +226,48 @@ impl GroupQuorumFilter {
|
||||
impl KmerFilter for GroupQuorumFilter {
|
||||
fn passes(&self, _kmer: CanonicalKmer, row: &[u32], _n_genomes: usize) -> bool {
|
||||
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)
|
||||
.count();
|
||||
let denom = self.selection.ingroup_idx.len();
|
||||
if n < self.min_count { return false; }
|
||||
if n > self.max_count { return false; }
|
||||
if n < self.min_count {
|
||||
return false;
|
||||
}
|
||||
if n > self.max_count {
|
||||
return false;
|
||||
}
|
||||
let frac = n as f64 / denom as f64;
|
||||
if frac < self.min_frac { return false; }
|
||||
if frac > self.max_frac { return false; }
|
||||
if frac < self.min_frac {
|
||||
return false;
|
||||
}
|
||||
if frac > self.max_frac {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
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)
|
||||
.count();
|
||||
let denom = self.selection.outgroup_idx.len();
|
||||
if n < self.min_outgroup_count { return false; }
|
||||
if n > self.max_outgroup_count { return false; }
|
||||
if n < self.min_outgroup_count {
|
||||
return false;
|
||||
}
|
||||
if n > self.max_outgroup_count {
|
||||
return false;
|
||||
}
|
||||
let frac = n as f64 / denom as f64;
|
||||
if frac < self.min_outgroup_frac { return false; }
|
||||
if frac > self.max_outgroup_frac { return false; }
|
||||
if frac < self.min_outgroup_frac {
|
||||
return false;
|
||||
}
|
||||
if frac > self.max_outgroup_frac {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -255,17 +277,23 @@ impl KmerFilter for GroupQuorumFilter {
|
||||
let mut parts: Vec<FilterMask> = Vec::new();
|
||||
if !self.selection.ingroup_idx.is_empty() {
|
||||
Self::group_mask_parts(
|
||||
&self.selection.ingroup_idx, t,
|
||||
self.min_count, self.max_count,
|
||||
self.min_frac, self.max_frac,
|
||||
&self.selection.ingroup_idx,
|
||||
t,
|
||||
self.min_count,
|
||||
self.max_count,
|
||||
self.min_frac,
|
||||
self.max_frac,
|
||||
&mut parts,
|
||||
);
|
||||
}
|
||||
if !self.selection.outgroup_idx.is_empty() {
|
||||
Self::group_mask_parts(
|
||||
&self.selection.outgroup_idx, t,
|
||||
self.min_outgroup_count, self.max_outgroup_count,
|
||||
self.min_outgroup_frac, self.max_outgroup_frac,
|
||||
&self.selection.outgroup_idx,
|
||||
t,
|
||||
self.min_outgroup_count,
|
||||
self.max_outgroup_count,
|
||||
self.min_outgroup_frac,
|
||||
self.max_outgroup_frac,
|
||||
&mut parts,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,11 @@ pub struct 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 {
|
||||
src,
|
||||
output: output.into(),
|
||||
@@ -118,7 +122,18 @@ impl Algorithm for Filter<'_> {
|
||||
runner
|
||||
.run(
|
||||
&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;
|
||||
if let Some(cb) = on_progress.as_mut() {
|
||||
|
||||
@@ -44,10 +44,16 @@ pub(crate) fn filter_partition(
|
||||
// the same order of magnitude `IndexCache` already holds open for this
|
||||
// partition.
|
||||
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| {
|
||||
by_layer.entry(layer).or_default().insert(kmer, row);
|
||||
true
|
||||
})?;
|
||||
cache.iter_partition_kmers_located(
|
||||
i,
|
||||
use_counts,
|
||||
n_genomes,
|
||||
filters,
|
||||
|_part, layer, kmer, row| {
|
||||
by_layer.entry(layer).or_default().insert(kmer, row);
|
||||
true
|
||||
},
|
||||
)?;
|
||||
|
||||
for l in 0..n_layers {
|
||||
let survivors = by_layer.remove(&l).unwrap_or_default();
|
||||
@@ -70,7 +76,12 @@ pub(crate) fn filter_partition(
|
||||
mode,
|
||||
output_presence,
|
||||
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")
|
||||
},
|
||||
)?;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,8 +17,8 @@ mod partition_iter;
|
||||
mod predicate;
|
||||
|
||||
pub use filter::{
|
||||
GroupQuorumFilter, KmerFilter, MaxGenomeCount, MaxGenomeFraction, MaxTotalCount,
|
||||
MinComplexity, MinGenomeCount, MinGenomeFraction, MinTotalCount, passes_all,
|
||||
GroupQuorumFilter, KmerFilter, MaxGenomeCount, MaxGenomeFraction, MaxTotalCount, MinComplexity,
|
||||
MinGenomeCount, MinGenomeFraction, MinTotalCount, passes_all,
|
||||
};
|
||||
pub use filter_algo::Filter;
|
||||
pub use partition_iter::FilteredPartitionIter;
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
//! destination index still being built (see `obikmerge::partition_merge`,
|
||||
//! which follows the same source-only-cache rule).
|
||||
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikindex::OKIResult;
|
||||
use obikindex::layer::{KmerLayer, LayerContent};
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikseq::CanonicalKmer;
|
||||
|
||||
use crate::filter::{KmerFilter, passes_all};
|
||||
@@ -63,7 +63,9 @@ impl FilteredPartitionIter for IndexCache {
|
||||
) -> OKIResult<bool> {
|
||||
for l in 0..self.n_layer(part).unwrap_or(0) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -80,7 +82,9 @@ impl FilteredPartitionIter for IndexCache {
|
||||
) -> OKIResult<bool> {
|
||||
for l in 0..self.n_layer(part).unwrap_or(0) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -112,7 +116,10 @@ fn iter_layer_kmers(
|
||||
} else {
|
||||
let mut bool_cols: Vec<Vec<bool>> = vec![Vec::new(); n_genomes];
|
||||
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() {
|
||||
|
||||
+160
-77
@@ -7,7 +7,13 @@ use obikindex::{GenomeInfo, IndexMeta};
|
||||
|
||||
// ── Operator ──────────────────────────────────────────────────────────────────
|
||||
|
||||
enum PredOp { Wildcard, Eq, Ne, Matches, NotMatches }
|
||||
enum PredOp {
|
||||
Wildcard,
|
||||
Eq,
|
||||
Ne,
|
||||
Matches,
|
||||
NotMatches,
|
||||
}
|
||||
|
||||
// ── MetaPred ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -16,8 +22,8 @@ enum PredOp { Wildcard, Eq, Ne, Matches, NotMatches }
|
||||
/// Operators: `=` (exact), `!=` (not equal), `~` (path ancestor), `!~` (not ancestor).
|
||||
/// Multiple values separated by `|` are OR'd.
|
||||
pub struct MetaPred {
|
||||
key: String,
|
||||
op: PredOp,
|
||||
key: String,
|
||||
op: PredOp,
|
||||
values: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -27,24 +33,29 @@ impl MetaPred {
|
||||
pub fn parse(s: &str) -> Result<Self, String> {
|
||||
let t = s.trim();
|
||||
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) =
|
||||
if let Some(pos) = s.find("!=") {
|
||||
(PredOp::Ne, &s[..pos], &s[pos+2..])
|
||||
} else if let Some(pos) = s.find("!~") {
|
||||
(PredOp::NotMatches, &s[..pos], &s[pos+2..])
|
||||
} else if let Some(pos) = s.find('=') {
|
||||
(PredOp::Eq, &s[..pos], &s[pos+1..])
|
||||
} else if let Some(pos) = s.find('~') {
|
||||
(PredOp::Matches, &s[..pos], &s[pos+1..])
|
||||
} else {
|
||||
return Err(format!("no operator found in predicate: {s}"));
|
||||
};
|
||||
let (op, key, rhs) = if let Some(pos) = s.find("!=") {
|
||||
(PredOp::Ne, &s[..pos], &s[pos + 2..])
|
||||
} else if let Some(pos) = s.find("!~") {
|
||||
(PredOp::NotMatches, &s[..pos], &s[pos + 2..])
|
||||
} else if let Some(pos) = s.find('=') {
|
||||
(PredOp::Eq, &s[..pos], &s[pos + 1..])
|
||||
} else if let Some(pos) = s.find('~') {
|
||||
(PredOp::Matches, &s[..pos], &s[pos + 1..])
|
||||
} else {
|
||||
return Err(format!("no operator found in predicate: {s}"));
|
||||
};
|
||||
|
||||
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();
|
||||
if values.iter().any(|v| v.is_empty()) {
|
||||
@@ -56,13 +67,15 @@ impl MetaPred {
|
||||
/// Evaluate against one genome's metadata.
|
||||
/// Returns `None` when the key is absent (NA propagation).
|
||||
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)?;
|
||||
Some(match self.op {
|
||||
PredOp::Wildcard => unreachable!(),
|
||||
PredOp::Eq => self.values.iter().any(|v| v == value),
|
||||
PredOp::Ne => self.values.iter().all(|v| v != value),
|
||||
PredOp::Matches => self.values.iter().any(|v| path_matches(value, v)),
|
||||
PredOp::Wildcard => unreachable!(),
|
||||
PredOp::Eq => self.values.iter().any(|v| v == value),
|
||||
PredOp::Ne => self.values.iter().all(|v| v != value),
|
||||
PredOp::Matches => self.values.iter().any(|v| path_matches(value, v)),
|
||||
PredOp::NotMatches => self.values.iter().all(|v| !path_matches(value, v)),
|
||||
})
|
||||
}
|
||||
@@ -76,8 +89,12 @@ impl MetaPred {
|
||||
/// `pattern` is a `TaxPattern` query (see `obitaxonomy::TaxPattern` for syntax).
|
||||
/// Returns `false` if either fails to parse.
|
||||
fn path_matches(value: &str, pattern: &str) -> bool {
|
||||
let Ok(path) = TaxPath::parse(value) else { return false };
|
||||
let Ok(pat) = TaxPattern::parse(pattern) else { return false };
|
||||
let Ok(path) = TaxPath::parse(value) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(pat) = TaxPattern::parse(pattern) else {
|
||||
return false;
|
||||
};
|
||||
pat.matches(&path)
|
||||
}
|
||||
|
||||
@@ -90,8 +107,8 @@ fn eval_and(preds: &[MetaPred], meta: &HashMap<String, String>) -> Option<bool>
|
||||
for pred in preds {
|
||||
match pred.eval(meta) {
|
||||
Some(false) => return Some(false),
|
||||
Some(true) => {}
|
||||
None => has_na = true,
|
||||
Some(true) => {}
|
||||
None => has_na = true,
|
||||
}
|
||||
}
|
||||
if has_na { None } else { Some(true) }
|
||||
@@ -103,9 +120,9 @@ fn eval_or(preds: &[MetaPred], meta: &HashMap<String, String>) -> Option<bool> {
|
||||
let mut has_na = false;
|
||||
for pred in preds {
|
||||
match pred.eval(meta) {
|
||||
Some(true) => return Some(true),
|
||||
Some(true) => return Some(true),
|
||||
Some(false) => {}
|
||||
None => has_na = true,
|
||||
None => has_na = true,
|
||||
}
|
||||
}
|
||||
if has_na { None } else { Some(false) }
|
||||
@@ -113,56 +130,81 @@ fn eval_or(preds: &[MetaPred], meta: &HashMap<String, String>) -> Option<bool> {
|
||||
|
||||
// ── Genome classification ─────────────────────────────────────────────────────
|
||||
|
||||
enum Membership { Ingroup, Outgroup, Uncategorized }
|
||||
enum Membership {
|
||||
Ingroup,
|
||||
Outgroup,
|
||||
Uncategorized,
|
||||
}
|
||||
|
||||
fn classify(
|
||||
genomes: &[GenomeInfo],
|
||||
ingroup: &[MetaPred],
|
||||
ingroup: &[MetaPred],
|
||||
outgroup: &[MetaPred],
|
||||
) -> Vec<Membership> {
|
||||
genomes.iter().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) };
|
||||
genomes
|
||||
.iter()
|
||||
.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.
|
||||
if in_r == Some(true) { return Membership::Ingroup; }
|
||||
if out_r == Some(true) { return Membership::Outgroup; }
|
||||
Membership::Uncategorized
|
||||
}).collect()
|
||||
// Ingroup wins over outgroup.
|
||||
if in_r == Some(true) {
|
||||
return Membership::Ingroup;
|
||||
}
|
||||
if out_r == Some(true) {
|
||||
return Membership::Outgroup;
|
||||
}
|
||||
Membership::Uncategorized
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ── Group quorum filter construction ──────────────────────────────────────────
|
||||
|
||||
pub struct GroupFilterParams {
|
||||
pub threshold: u32,
|
||||
pub min_count: Option<isize>,
|
||||
pub max_count: Option<isize>,
|
||||
pub min_frac: Option<f64>,
|
||||
pub max_frac: Option<f64>,
|
||||
pub threshold: u32,
|
||||
pub min_count: Option<isize>,
|
||||
pub max_count: Option<isize>,
|
||||
pub min_frac: Option<f64>,
|
||||
pub max_frac: Option<f64>,
|
||||
pub min_outgroup_count: Option<isize>,
|
||||
pub max_outgroup_count: Option<isize>,
|
||||
pub min_outgroup_frac: Option<f64>,
|
||||
pub max_outgroup_frac: Option<f64>,
|
||||
pub min_outgroup_frac: Option<f64>,
|
||||
pub max_outgroup_frac: Option<f64>,
|
||||
}
|
||||
|
||||
// ── Genome selector ──────────────────────────────────────────────────────────
|
||||
|
||||
/// Result of running a [`GenomeSelector`] against an index's metadata.
|
||||
pub struct Selection {
|
||||
pub ingroup_idx: Vec<usize>,
|
||||
pub ingroup_idx: Vec<usize>,
|
||||
pub outgroup_idx: Vec<usize>,
|
||||
}
|
||||
|
||||
pub struct GenomeSelector {
|
||||
pub(crate) ingroup: Vec<MetaPred>,
|
||||
pub(crate) ingroup: Vec<MetaPred>,
|
||||
pub(crate) outgroup: Vec<MetaPred>,
|
||||
}
|
||||
|
||||
impl GenomeSelector {
|
||||
/// Parse ingroup (AND'd) and outgroup (OR'd) predicate strings.
|
||||
pub fn parse(ingroup: &[String], outgroup: &[String]) -> Result<Self, String> {
|
||||
let ingroup = ingroup.iter().map(|s| MetaPred::parse(s)).collect::<Result<Vec<_>, _>>()?;
|
||||
let outgroup = outgroup.iter().map(|s| MetaPred::parse(s)).collect::<Result<Vec<_>, _>>()?;
|
||||
let ingroup = ingroup
|
||||
.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 })
|
||||
}
|
||||
|
||||
@@ -174,17 +216,29 @@ impl GenomeSelector {
|
||||
let genomes = meta.genomes().map_err(|e| e.to_string())?;
|
||||
|
||||
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 ingroup_idx: Vec<usize> = members.iter().enumerate()
|
||||
let ingroup_idx: Vec<usize> = members
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, m)| matches!(m, Membership::Ingroup))
|
||||
.map(|(i, _)| i).collect();
|
||||
let outgroup_idx: Vec<usize> = members.iter().enumerate()
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
let outgroup_idx: Vec<usize> = members
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, m)| matches!(m, Membership::Outgroup))
|
||||
.map(|(i, _)| i).collect();
|
||||
Ok(Selection { ingroup_idx, outgroup_idx })
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
Ok(Selection {
|
||||
ingroup_idx,
|
||||
outgroup_idx,
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a `GroupQuorumFilter` from this selector's classification of `meta`.
|
||||
@@ -196,40 +250,66 @@ impl GenomeSelector {
|
||||
pub fn build_group_filter(
|
||||
&self,
|
||||
meta: &IndexMeta,
|
||||
p: GroupFilterParams,
|
||||
p: GroupFilterParams,
|
||||
) -> Result<GroupQuorumFilter, String> {
|
||||
let selection = self.run(meta)?;
|
||||
let in_size = selection.ingroup_idx.len();
|
||||
let in_size = selection.ingroup_idx.len();
|
||||
let out_size = selection.outgroup_idx.len();
|
||||
|
||||
let ingroup_quorum_explicit = p.min_count.is_some() || p.max_count.is_some()
|
||||
|| p.min_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 ingroup_quorum_explicit = p.min_count.is_some()
|
||||
|| p.max_count.is_some()
|
||||
|| p.min_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_max_outgroup_count = if !self.outgroup.is_empty() && !outgroup_quorum_explicit { 0 } else { out_size };
|
||||
let default_min_frac = if !self.ingroup.is_empty() && !ingroup_quorum_explicit {
|
||||
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
|
||||
// (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
|
||||
// and would otherwise drop the constraint entirely.
|
||||
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 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 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 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 max_outgroup_frac = p.max_outgroup_frac.unwrap_or(1.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 min_frac = p.min_frac.unwrap_or(default_min_frac);
|
||||
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 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 max_outgroup_frac = p.max_outgroup_frac.unwrap_or(1.0);
|
||||
|
||||
for (v, lo, hi) in [
|
||||
("--min-frac/--max-frac", min_frac, max_frac),
|
||||
("--min-outgroup-frac/--max-outgroup-frac", min_outgroup_frac, max_outgroup_frac),
|
||||
("--min-frac/--max-frac", min_frac, max_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) {
|
||||
return Err(format!("{v}: fraction values must be in [0.0, 1.0]"));
|
||||
@@ -239,10 +319,14 @@ impl GenomeSelector {
|
||||
}
|
||||
}
|
||||
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 {
|
||||
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 {
|
||||
@@ -259,4 +343,3 @@ impl GenomeSelector {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +156,10 @@ impl IndexCache {
|
||||
/// (not an error) if `partition` isn't cached — same convention as
|
||||
/// [`get_layer`](Self::get_layer). `'static` for the same reason
|
||||
/// [`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 {
|
||||
cache: Arc::clone(&self.layer_cache),
|
||||
partitions: vec![partition].into_iter(),
|
||||
@@ -173,7 +176,12 @@ impl IndexCache {
|
||||
pub fn iter_indexed(&self) -> impl Iterator<Item = (usize, usize, Arc<KmerLayer>)> + 'static {
|
||||
LayerIter {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,12 @@ use obicompactvec::{PersistentBitMatrix, PersistentSparseBitMatrix};
|
||||
use obikindex::KmerIndex;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let sparse_root = std::env::args().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_root = std::env::args()
|
||||
.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 dense = KmerIndex::open(&dense_root)?;
|
||||
@@ -16,8 +20,16 @@ fn main() -> anyhow::Result<()> {
|
||||
let n_parts = sparse.n_partitions();
|
||||
let n_layers = sparse.n_layers_per_partition()?;
|
||||
|
||||
println!("index sparse: {} partitions, {} layers", sparse.n_partitions(), n_layers);
|
||||
println!("index dense: {} partitions, {} layers", dense.n_partitions(), dense.n_layers_per_partition()?);
|
||||
println!(
|
||||
"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_cells = 0usize;
|
||||
@@ -83,7 +95,8 @@ fn main() -> anyhow::Result<()> {
|
||||
if dense_row[c] != sparse_row[c] {
|
||||
mismatched_cells += 1;
|
||||
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 {
|
||||
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);
|
||||
} 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(())
|
||||
|
||||
@@ -55,7 +55,11 @@ pub trait IndexBuilder: Sized {
|
||||
/// Shared tail of the `select`/`rebuild`/`merge` construction paths,
|
||||
/// once their partitions have been written. `sparse` selects the
|
||||
/// 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
|
||||
/// `DevDocMD/implementation/partition_layer_cache.md`, "(11)" — no
|
||||
@@ -100,7 +104,11 @@ impl IndexBuilder for KmerIndex {
|
||||
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();
|
||||
// `output` is held exclusively by the builder that wrote it: reopen
|
||||
// without a lock, a locking `open` would wait for that builder for ever.
|
||||
|
||||
@@ -23,7 +23,10 @@ pub enum OKIError {
|
||||
IncompatibleEvidence(String),
|
||||
/// Malformed data encountered while reading/writing a layer file, tagged
|
||||
/// 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>;
|
||||
|
||||
@@ -38,7 +38,11 @@ impl KmerIndex {
|
||||
let genomes = genome_info.into_iter().collect();
|
||||
let meta = IndexMeta::create_at(&root_path, config, genomes).map_err(OKIError::Io)?;
|
||||
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() {
|
||||
return Err(OKIError::Io(std::io::Error::other(
|
||||
"failed to acquire index lock right after create",
|
||||
@@ -102,7 +106,11 @@ impl KmerIndex {
|
||||
set_k(meta.config.kmer_size);
|
||||
set_m(meta.config.minimizer_size);
|
||||
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
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
mod builder;
|
||||
pub mod error;
|
||||
mod kmer_index;
|
||||
pub mod meta;
|
||||
pub mod state;
|
||||
mod builder;
|
||||
mod kmer_index;
|
||||
|
||||
pub use error::{OKIError, OKIResult};
|
||||
pub use builder::IndexBuilder;
|
||||
pub use error::{OKIError, OKIResult};
|
||||
pub use kmer_index::KmerIndex;
|
||||
pub use meta::{GenomeInfo, IndexConfig, IndexMeta, META_FILENAME};
|
||||
pub use state::IndexState;
|
||||
@@ -27,7 +27,9 @@ use std::path::{Path, PathBuf};
|
||||
use crate::layer::utils::LAYERNAME_SUFFIX;
|
||||
|
||||
use ndarray::{Array1, Array2};
|
||||
use obicompactvec::{BitPartials, ColumnWeights, CountPartials, PersistentBitMatrix, PersistentIntMatrix};
|
||||
use obicompactvec::{
|
||||
BitPartials, ColumnWeights, CountPartials, PersistentBitMatrix, PersistentIntMatrix,
|
||||
};
|
||||
use obikseq::CanonicalKmer;
|
||||
|
||||
use crate::index::error::OKIResult;
|
||||
@@ -274,7 +276,9 @@ impl KmerLayer {
|
||||
match self {
|
||||
KmerLayer::Count { layer, .. } => layer.row_presence_histogram(threshold),
|
||||
KmerLayer::Presence { layer, .. } => layer.row_presence_histogram(),
|
||||
KmerLayer::Empty { .. } => panic!("Layer::row_presence_histogram() called on an Empty layer"),
|
||||
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> {
|
||||
match self {
|
||||
KmerLayer::Count { layer, .. } => layer.partial_bray(),
|
||||
KmerLayer::Presence { .. } => panic!("CountPartials::partial_bray() called on a Presence layer"),
|
||||
KmerLayer::Empty { .. } => panic!("CountPartials::partial_bray() called on an Empty layer"),
|
||||
KmerLayer::Presence { .. } => {
|
||||
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> {
|
||||
match self {
|
||||
KmerLayer::Count { layer, .. } => layer.partial_euclidean(),
|
||||
KmerLayer::Presence { .. } => panic!("CountPartials::partial_euclidean() called on a Presence layer"),
|
||||
KmerLayer::Empty { .. } => panic!("CountPartials::partial_euclidean() called on an Empty layer"),
|
||||
KmerLayer::Presence { .. } => {
|
||||
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>) {
|
||||
match self {
|
||||
KmerLayer::Count { layer, .. } => layer.partial_threshold_jaccard(threshold),
|
||||
KmerLayer::Presence { .. } => panic!("CountPartials::partial_threshold_jaccard() called on a Presence layer"),
|
||||
KmerLayer::Empty { .. } => panic!("CountPartials::partial_threshold_jaccard() called on an Empty layer"),
|
||||
KmerLayer::Presence { .. } => {
|
||||
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> {
|
||||
match self {
|
||||
KmerLayer::Count { layer, .. } => layer.partial_relfreq_bray(global),
|
||||
KmerLayer::Presence { .. } => panic!("CountPartials::partial_relfreq_bray() called on a Presence layer"),
|
||||
KmerLayer::Empty { .. } => panic!("CountPartials::partial_relfreq_bray() called on an Empty layer"),
|
||||
KmerLayer::Presence { .. } => {
|
||||
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> {
|
||||
match self {
|
||||
KmerLayer::Count { layer, .. } => layer.partial_relfreq_euclidean(global),
|
||||
KmerLayer::Presence { .. } => panic!("CountPartials::partial_relfreq_euclidean() called on a Presence layer"),
|
||||
KmerLayer::Empty { .. } => panic!("CountPartials::partial_relfreq_euclidean() called on an Empty layer"),
|
||||
KmerLayer::Presence { .. } => {
|
||||
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> {
|
||||
match self {
|
||||
KmerLayer::Count { layer, .. } => layer.partial_hellinger(global),
|
||||
KmerLayer::Presence { .. } => panic!("CountPartials::partial_hellinger() called on a Presence layer"),
|
||||
KmerLayer::Empty { .. } => panic!("CountPartials::partial_hellinger() called on an Empty layer"),
|
||||
KmerLayer::Presence { .. } => {
|
||||
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>) {
|
||||
match self {
|
||||
KmerLayer::Presence { layer, .. } => layer.partial_jaccard(),
|
||||
KmerLayer::Count { .. } => panic!("BitPartials::partial_jaccard() called on a Count layer"),
|
||||
KmerLayer::Empty { .. } => panic!("BitPartials::partial_jaccard() called on an Empty layer"),
|
||||
KmerLayer::Count { .. } => {
|
||||
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> {
|
||||
match self {
|
||||
KmerLayer::Presence { layer, .. } => layer.partial_hamming(),
|
||||
KmerLayer::Count { .. } => panic!("BitPartials::partial_hamming() called on a Count layer"),
|
||||
KmerLayer::Empty { .. } => panic!("BitPartials::partial_hamming() called on an Empty layer"),
|
||||
KmerLayer::Count { .. } => {
|
||||
panic!("BitPartials::partial_hamming() called on a Count layer")
|
||||
}
|
||||
KmerLayer::Empty { .. } => {
|
||||
panic!("BitPartials::partial_hamming() called on an Empty layer")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,9 @@ pub struct EvidenceWriter {
|
||||
|
||||
impl EvidenceWriter {
|
||||
pub fn new(n_slots: usize) -> Self {
|
||||
Self { buf: vec![0u32; n_slots] }
|
||||
Self {
|
||||
buf: vec![0u32; n_slots],
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -23,10 +23,10 @@ const HEADER: usize = 16;
|
||||
|
||||
pub struct FingerprintVec {
|
||||
_mmap: Mmap,
|
||||
bits: &'static BitSlice<u8, Lsb0>,
|
||||
n: usize,
|
||||
b: u8,
|
||||
mask: u64,
|
||||
bits: &'static BitSlice<u8, Lsb0>,
|
||||
n: usize,
|
||||
b: u8,
|
||||
mask: u64,
|
||||
}
|
||||
|
||||
impl FingerprintVec {
|
||||
@@ -34,11 +34,17 @@ impl FingerprintVec {
|
||||
let f = File::open(path)?;
|
||||
let mmap = unsafe { Mmap::map(&f)? };
|
||||
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];
|
||||
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 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)
|
||||
};
|
||||
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]
|
||||
pub fn get(&self, slot: usize) -> u64 {
|
||||
debug_assert!(slot < self.n);
|
||||
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]
|
||||
@@ -62,23 +74,31 @@ impl FingerprintVec {
|
||||
self.get(slot) == (fingerprint & self.mask)
|
||||
}
|
||||
|
||||
pub fn n(&self) -> usize { self.n }
|
||||
pub fn b(&self) -> u8 { self.b }
|
||||
pub fn n(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
pub fn b(&self) -> u8 {
|
||||
self.b
|
||||
}
|
||||
}
|
||||
|
||||
// ── Writer ────────────────────────────────────────────────────────────────────
|
||||
|
||||
pub struct FingerprintVecWriter {
|
||||
buf: Vec<u8>,
|
||||
n: usize,
|
||||
b: u8,
|
||||
n: usize,
|
||||
b: u8,
|
||||
}
|
||||
|
||||
impl FingerprintVecWriter {
|
||||
pub fn new(n: usize, b: u8) -> Self {
|
||||
assert!(b > 0 && b <= 64, "fingerprint width must be 1..=64");
|
||||
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]
|
||||
@@ -86,14 +106,15 @@ impl FingerprintVecWriter {
|
||||
debug_assert!(slot < self.n);
|
||||
let lo = slot * self.b as usize;
|
||||
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<()> {
|
||||
let mut f = BufWriter::new(File::create(path).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.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)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -107,7 +128,7 @@ mod tests {
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn roundtrip(n: usize, b: u8, values: &[u64]) {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("fp.bin");
|
||||
let mask: u64 = if b == 64 { u64::MAX } else { (1u64 << b) - 1 };
|
||||
let mut w = FingerprintVecWriter::new(n, b);
|
||||
@@ -124,13 +145,21 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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]
|
||||
fn roundtrip_b8() { roundtrip(4, 8, &[0, 127, 200, 255]); }
|
||||
fn roundtrip_b8() {
|
||||
roundtrip(4, 8, &[0, 127, 200, 255]);
|
||||
}
|
||||
#[test]
|
||||
fn roundtrip_b16() { roundtrip(3, 16, &[0, 0xABCD, 0xFFFF]); }
|
||||
fn roundtrip_b16() {
|
||||
roundtrip(3, 16, &[0, 0xABCD, 0xFFFF]);
|
||||
}
|
||||
#[test]
|
||||
fn roundtrip_b7() { roundtrip(5, 7, &[0, 63, 127, 1, 42]); }
|
||||
fn roundtrip_b7() {
|
||||
roundtrip(5, 7, &[0, 63, 127, 1, 42]);
|
||||
}
|
||||
#[test]
|
||||
fn roundtrip_b13_unaligned() {
|
||||
let vals: Vec<u64> = (0..20).map(|i| (i * 317) % (1 << 13)).collect();
|
||||
@@ -138,14 +167,17 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn matches_returns_true_for_exact() {
|
||||
let dir = tempdir().unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("fp.bin");
|
||||
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();
|
||||
let r = FingerprintVec::open(&path).unwrap();
|
||||
assert!( r.matches(0, 42));
|
||||
assert!(r.matches(0, 42));
|
||||
assert!(!r.matches(0, 43));
|
||||
assert!( r.matches(2, 255));
|
||||
assert!(r.matches(2, 255));
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,9 @@ pub enum IndexMode {
|
||||
}
|
||||
|
||||
impl Default for IndexMode {
|
||||
fn default() -> Self { Self::Exact }
|
||||
fn default() -> Self {
|
||||
Self::Exact
|
||||
}
|
||||
}
|
||||
|
||||
impl IndexMode {
|
||||
|
||||
@@ -24,7 +24,8 @@ pub(crate) const FINGERPRINT_FILE: &str = "fingerprint.bin";
|
||||
/// The layer MPHF: `Xxh3Int` hasher, `CubicEps` buckets, multi-part (`SINGLE_PART = false`),
|
||||
/// minimal (`REMAP = true`). Built owned (construction + store); queried through
|
||||
/// `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
|
||||
/// (`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.
|
||||
fn open(self) -> OKIResult<OpenLayerEvidence> {
|
||||
Ok(match self {
|
||||
LayerEvidence::Exact { evidence_path, unitig_path } => OpenLayerEvidence::Exact {
|
||||
LayerEvidence::Exact {
|
||||
evidence_path,
|
||||
unitig_path,
|
||||
} => OpenLayerEvidence::Exact {
|
||||
evidence: Evidence::open(&evidence_path)?,
|
||||
unitigs: Arc::new(UnitigFileReader::open(&unitig_path)?),
|
||||
},
|
||||
LayerEvidence::Approx { fingerprint_path } => OpenLayerEvidence::Approx {
|
||||
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)?,
|
||||
fingerprint: FingerprintVec::open(&fingerprint_path)?,
|
||||
},
|
||||
@@ -136,10 +143,13 @@ impl EvidenceKind {
|
||||
(true, false) => Ok(EvidenceKind::Exact),
|
||||
(false, true) => Ok(EvidenceKind::Approx),
|
||||
(true, true) => Ok(EvidenceKind::Hybrid),
|
||||
(false, false) => Err(OKIError::InvalidData { context: "layer", detail: format!(
|
||||
"no evidence.bin or fingerprint.bin in {}",
|
||||
layer_dir.display()
|
||||
) }),
|
||||
(false, false) => Err(OKIError::InvalidData {
|
||||
context: "layer",
|
||||
detail: format!(
|
||||
"no evidence.bin or fingerprint.bin in {}",
|
||||
layer_dir.display()
|
||||
),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,7 +187,12 @@ impl MphfLayer {
|
||||
OpenLayerEvidence::Hybrid { evidence, .. } => evidence.len(),
|
||||
OpenLayerEvidence::Approx { fingerprint } => fingerprint.n(),
|
||||
};
|
||||
Ok(Self { unitigs, mphf, ev, n })
|
||||
Ok(Self {
|
||||
unitigs,
|
||||
mphf,
|
||||
ev,
|
||||
n,
|
||||
})
|
||||
}
|
||||
|
||||
// ── Query API ─────────────────────────────────────────────────────────────
|
||||
@@ -404,7 +419,10 @@ pub struct MphfOnly(MemCase<Mphf>);
|
||||
impl MphfOnly {
|
||||
pub fn open(dir: &Path) -> OKIResult<Self> {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -458,20 +476,32 @@ impl MphfLayer {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }
|
||||
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?;
|
||||
let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }.map_err(|e| {
|
||||
OKIError::InvalidData {
|
||||
context: "layer",
|
||||
detail: e.to_string(),
|
||||
}
|
||||
})?;
|
||||
|
||||
let mut ev = EvidenceWriter::new(n);
|
||||
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 {
|
||||
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 bit = 1u8 << (slot % 8);
|
||||
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;
|
||||
ev.set(slot, chunk_id as u32, rank as u8);
|
||||
@@ -485,12 +515,16 @@ impl MphfLayer {
|
||||
/// Build `fingerprint.bin` from `unitigs.bin` + `mphf.bin`.
|
||||
pub fn build_approx_evidence(dir: &Path, b: u8, z: u8) -> OKIResult<usize> {
|
||||
if b == 0 || b > 64 {
|
||||
return Err(OKIError::InvalidData { context: "layer", detail:
|
||||
"fingerprint width must be 1..=64".into(),
|
||||
});
|
||||
return Err(OKIError::InvalidData {
|
||||
context: "layer",
|
||||
detail: "fingerprint width must be 1..=64".into(),
|
||||
});
|
||||
}
|
||||
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 unitigs = UnitigFileReader::open_sequential(&unitig_path)?;
|
||||
@@ -501,14 +535,21 @@ impl MphfLayer {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }
|
||||
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?;
|
||||
let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }.map_err(|e| {
|
||||
OKIError::InvalidData {
|
||||
context: "layer",
|
||||
detail: e.to_string(),
|
||||
}
|
||||
})?;
|
||||
|
||||
let mut fw = FingerprintVecWriter::new(n, b);
|
||||
|
||||
for (slot, kmer, _, _) in SlottedKmers::new(&mphf, unitigs.iter_indexed_canonical_kmers()) {
|
||||
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());
|
||||
}
|
||||
@@ -535,15 +576,24 @@ impl MphfLayer {
|
||||
|
||||
let sk_to_olm = |e: obiskio::SKError| match e {
|
||||
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 ───────────────────────────────────────────────────────
|
||||
if n == 0 {
|
||||
let mphf: Mphf = Mphf::try_new(&[] as &[u64], mphf_params())
|
||||
.ok_or_else(|| OKIError::InvalidData { context: "mphf", detail: "construction failed".into() })?;
|
||||
unsafe { mphf.store(&dir.join(MPHF_FILE)) }
|
||||
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?;
|
||||
let mphf: Mphf = Mphf::try_new(&[] as &[u64], mphf_params()).ok_or_else(|| {
|
||||
OKIError::InvalidData {
|
||||
context: "mphf",
|
||||
detail: "construction failed".into(),
|
||||
}
|
||||
})?;
|
||||
unsafe { mphf.store(&dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData {
|
||||
context: "layer",
|
||||
detail: e.to_string(),
|
||||
})?;
|
||||
match mode {
|
||||
IndexMode::Exact | IndexMode::Hybrid { .. } => {
|
||||
fs::File::create(dir.join(EVIDENCE_FILE))?;
|
||||
@@ -561,13 +611,12 @@ impl MphfLayer {
|
||||
|
||||
// ── Pass 1: MPHF via clonable mmap iterator ───────────────────────────
|
||||
let keys = CanonicalKmerIter::new(&unitig_path).map_err(sk_to_olm)?;
|
||||
let mphf: Mphf = Mphf::new_from_par_iter(
|
||||
n,
|
||||
keys.map(|k| k.raw()).par_bridge(),
|
||||
mphf_params(),
|
||||
);
|
||||
unsafe { mphf.store(&dir.join(MPHF_FILE)) }
|
||||
.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string() })?;
|
||||
let mphf: Mphf =
|
||||
Mphf::new_from_par_iter(n, keys.map(|k| k.raw()).par_bridge(), mphf_params());
|
||||
unsafe { mphf.store(&dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData {
|
||||
context: "layer",
|
||||
detail: e.to_string(),
|
||||
})?;
|
||||
|
||||
// ── Pass 2: fill evidence files + callback ────────────────────────────
|
||||
let unitigs2 = UnitigFileReader::open_sequential(&unitig_path)?;
|
||||
@@ -576,14 +625,22 @@ impl MphfLayer {
|
||||
match mode {
|
||||
IndexMode::Exact => {
|
||||
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 {
|
||||
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 bit = 1u8 << (slot % 8);
|
||||
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;
|
||||
ev.set(slot, chunk_id as u32, rank as u8);
|
||||
@@ -595,14 +652,22 @@ impl MphfLayer {
|
||||
|
||||
IndexMode::Approx { 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 {
|
||||
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 bit = 1u8 << (slot % 8);
|
||||
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;
|
||||
fw.set(slot, kmer.seq_hash());
|
||||
@@ -614,14 +679,22 @@ impl MphfLayer {
|
||||
IndexMode::Hybrid { b, .. } => {
|
||||
let mut ev = EvidenceWriter::new(n);
|
||||
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 {
|
||||
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 bit = 1u8 << (slot % 8);
|
||||
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;
|
||||
ev.set(slot, chunk_id as u32, rank as u8);
|
||||
|
||||
@@ -201,7 +201,8 @@ fn count_layer_reports_count_content_and_columnar_storage() {
|
||||
DEFAULT_BLOCK_BITS,
|
||||
&IndexMode::Exact,
|
||||
|_| 1,
|
||||
).unwrap();
|
||||
)
|
||||
.unwrap();
|
||||
let layer = TypedLayer::<PersistentIntMatrix>::open(dir.path()).unwrap();
|
||||
|
||||
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"]);
|
||||
|
||||
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 second: Vec<CanonicalKmer> = reader2.iter_indexed_canonical_kmers().map(|(k, _, _)| k).collect();
|
||||
assert_eq!(first, second, "iter_indexed_canonical_kmers must be deterministic across calls");
|
||||
let second: Vec<CanonicalKmer> = reader2
|
||||
.iter_indexed_canonical_kmers()
|
||||
.map(|(k, _, _)| k)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
first, second,
|
||||
"iter_indexed_canonical_kmers must be deterministic across calls"
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
// use crate::layer::utils::layer_dir;
|
||||
use ndarray::{Array1, Array2};
|
||||
use obicompactvec::{
|
||||
BinaryMatrix, BitPartials, ColBuilder, CountPartials, MatrixBuilder, PersistentBitMatrix,
|
||||
PersistentBitMatrixBuilder, PersistentCompactIntMatrixBuilder, PersistentIntMatrix,
|
||||
PersistentSparseBitMatrix,
|
||||
};
|
||||
use ndarray::{Array1, Array2};
|
||||
use obikseq::CanonicalKmer;
|
||||
use obiskio::{UnitigFileReader, UnitigFileWriter};
|
||||
use std::collections::HashMap;
|
||||
@@ -399,7 +399,9 @@ impl TypedLayer<PersistentIntMatrix> {
|
||||
/// genomes, a k-mer being present in a genome when its count reaches
|
||||
/// `threshold` (see `PersistentIntMatrix::row_presence_histogram`).
|
||||
pub fn row_presence_histogram(&self, threshold: u32) -> OKIResult<Vec<u64>> {
|
||||
self.data.row_presence_histogram(threshold).map_err(OKIError::Io)
|
||||
self.data
|
||||
.row_presence_histogram(threshold)
|
||||
.map_err(OKIError::Io)
|
||||
}
|
||||
|
||||
/// Extract a sub-matrix of counts for the rows at `slots`.
|
||||
|
||||
@@ -12,10 +12,8 @@ pub mod index;
|
||||
pub mod layer;
|
||||
pub mod partition;
|
||||
|
||||
pub use index::{
|
||||
GenomeInfo,
|
||||
IndexBuilder, IndexConfig, IndexMeta, IndexState,
|
||||
KmerIndex, OKIError, OKIResult,
|
||||
META_FILENAME,
|
||||
};
|
||||
pub use index::meta;
|
||||
pub use index::{
|
||||
GenomeInfo, IndexBuilder, IndexConfig, IndexMeta, IndexState, KmerIndex, META_FILENAME,
|
||||
OKIError, OKIResult,
|
||||
};
|
||||
@@ -81,38 +81,68 @@ fn main() {
|
||||
n
|
||||
})
|
||||
.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() {
|
||||
let set: HashSet<u64> = kmers.iter().map(|c| c.raw()).collect();
|
||||
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}
|
||||
let pred = |a: obikseq::Kmer| -> Option<obikseq::Kmer> {
|
||||
let ins: Vec<obikseq::Kmer> = 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 ins: Vec<obikseq::Kmer> =
|
||||
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();
|
||||
for c in &kmers {
|
||||
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 cur = o;
|
||||
loop {
|
||||
let ob = outs(cur);
|
||||
if ob.len() != 1 { break; }
|
||||
if ob.len() != 1 {
|
||||
break;
|
||||
}
|
||||
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]);
|
||||
cur = b;
|
||||
}
|
||||
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 });
|
||||
}
|
||||
}
|
||||
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 {
|
||||
let t = Instant::now();
|
||||
@@ -150,7 +180,9 @@ fn main() {
|
||||
if dump {
|
||||
let mut v = seqs.lock().unwrap().clone();
|
||||
v.sort();
|
||||
for u in v { println!("UNITIG {} {}", u.len(), u); }
|
||||
for u in v {
|
||||
println!("UNITIG {} {}", u.len(), u);
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"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> {
|
||||
let file = fs::File::open(unique_path)?;
|
||||
let mmap = unsafe { Mmap::map(&file)? };
|
||||
let kmers: &[u64] = unsafe {
|
||||
std::slice::from_raw_parts(mmap.as_ptr() as *const u64, f0)
|
||||
};
|
||||
let kmers: &[u64] = unsafe { std::slice::from_raw_parts(mmap.as_ptr() as *const u64, f0) };
|
||||
// Sequential constructor: the outer par_iter over partitions already saturates
|
||||
// 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.
|
||||
|
||||
@@ -77,25 +77,33 @@ fn flush_sorted_chunk(buf: &mut Vec<u64>, work_dir: &Path, idx: usize) -> io::Re
|
||||
fn merge_and_dedup(chunk_paths: &[PathBuf], unique_path: &Path) -> io::Result<usize> {
|
||||
struct ChunkReader {
|
||||
mmap: Mmap,
|
||||
pos: usize,
|
||||
pos: usize,
|
||||
}
|
||||
impl ChunkReader {
|
||||
fn open(path: &Path) -> io::Result<Self> {
|
||||
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> {
|
||||
let off = self.pos * 8;
|
||||
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 {
|
||||
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))
|
||||
.collect::<io::Result<_>>()?;
|
||||
|
||||
@@ -106,8 +114,8 @@ fn merge_and_dedup(chunk_paths: &[PathBuf], unique_path: &Path) -> io::Result<us
|
||||
}
|
||||
}
|
||||
|
||||
let mut w = BufWriter::new(fs::File::create(unique_path)?);
|
||||
let mut f0 = 0usize;
|
||||
let mut w = BufWriter::new(fs::File::create(unique_path)?);
|
||||
let mut f0 = 0usize;
|
||||
let mut prev: Option<u64> = None;
|
||||
|
||||
while let Some(Reverse((val, idx))) = heap.pop() {
|
||||
|
||||
@@ -10,11 +10,11 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use tracing::debug;
|
||||
|
||||
use niffler::send::compression::Format;
|
||||
use niffler::Level;
|
||||
use obikseq::superkmer::SuperKmer;
|
||||
use obikseq::Sequence;
|
||||
use niffler::send::compression::Format;
|
||||
use obikindex::layer::KmerLayer;
|
||||
use obikseq::Sequence;
|
||||
use obikseq::superkmer::SuperKmer;
|
||||
use obiskio::{SKFileMeta, SKFileReader, SKFileWriter, SKResult};
|
||||
|
||||
/// 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
|
||||
/// + 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();
|
||||
if !raw_path.exists() {
|
||||
return Ok(());
|
||||
|
||||
@@ -104,9 +104,7 @@ impl Algorithm for LayerBuilder<'_> {
|
||||
let runner = PartitionRunner::new();
|
||||
runner.run(
|
||||
&order,
|
||||
|i| {
|
||||
index.build_index_layer(i, min_ab, max_ab, with_counts, &evidence, block_bits)
|
||||
},
|
||||
|i| index.build_index_layer(i, min_ab, max_ab, with_counts, &evidence, block_bits),
|
||||
|_i, n_kmers, _elapsed| {
|
||||
total_kmers += n_kmers;
|
||||
done += 1;
|
||||
|
||||
@@ -13,7 +13,6 @@ pub mod dereplicator;
|
||||
pub mod layer_builder;
|
||||
pub mod partitionner;
|
||||
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use obikindex::KmerIndex;
|
||||
@@ -64,7 +63,6 @@ where
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
/// Sequential counterpart to [`par_over_layer0`]: every partition's layer 0
|
||||
/// that exists, in order, skipping those that don't — for callers that
|
||||
/// 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.
|
||||
fn run(&mut self) -> obikalgorithm::Result<()> {
|
||||
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();
|
||||
|
||||
@@ -3,8 +3,8 @@ use std::collections::HashMap;
|
||||
use crate::algorithms::counter::Counter;
|
||||
use crate::algorithms::dereplicator::Dereplicator;
|
||||
use obikalgorithm::Algorithm;
|
||||
use obikindex::{IndexConfig, KmerIndex};
|
||||
use obikindex::layer::IndexMode;
|
||||
use obikindex::{IndexConfig, KmerIndex};
|
||||
use obikrope::Rope;
|
||||
use obikseq::SuperKmer;
|
||||
use obiskbuilder::build_superkmers;
|
||||
|
||||
@@ -26,7 +26,7 @@ use std::path::Path;
|
||||
|
||||
use crate::graph_pipeline::{materialize_layer, write_graph_as_unitigs};
|
||||
use epserde::prelude::*;
|
||||
use obicompactvec::{PersistentIntMatrix, PersistentCompactIntVec};
|
||||
use obicompactvec::{PersistentCompactIntVec, PersistentIntMatrix};
|
||||
use obidebruinj::GraphDeBruijn;
|
||||
use obikindex::layer::IndexMode;
|
||||
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
|
||||
// (small inputs against many partitions): nothing to build, not an
|
||||
// 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);
|
||||
}
|
||||
let layer0 = self
|
||||
@@ -159,7 +164,9 @@ impl PrivateBuilder for KmerIndex {
|
||||
|
||||
let mphf1_opt: Option<Mphf> = if need_counts {
|
||||
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 {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use tracing::debug;
|
||||
use obipipeline::{
|
||||
Pipeline, PipelineError, PipelineSender, SharedFlatFn, Stage, WorkerPool,
|
||||
make_sink, make_source, make_transform,
|
||||
throttle,
|
||||
Pipeline, PipelineError, PipelineSender, SharedFlatFn, Stage, WorkerPool, make_sink,
|
||||
make_source, make_transform, throttle,
|
||||
};
|
||||
use tracing::debug;
|
||||
|
||||
use obidebruinj::GraphDeBruijn;
|
||||
use obikseq::CanonicalKmer;
|
||||
use obikindex::layer::{IndexMode, TypedLayer};
|
||||
use obikindex::{OKIError, OKIResult};
|
||||
|
||||
use obikseq::CanonicalKmer;
|
||||
|
||||
// ── KmerGraphData ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -57,8 +55,7 @@ where
|
||||
Stage::Flat(Arc::new(
|
||||
move |data: KmerGraphData,
|
||||
push: &PipelineSender<Result<KmerGraphData, PipelineError>>,
|
||||
delta: &PipelineSender<isize>|
|
||||
{
|
||||
delta: &PipelineSender<isize>| {
|
||||
if let KmerGraphData::File(t) = data {
|
||||
let path = t.item;
|
||||
let _guard = t.guard; // released at end of block
|
||||
@@ -80,21 +77,30 @@ where
|
||||
}
|
||||
},
|
||||
) as SharedFlatFn<KmerGraphData>),
|
||||
make_transform!(KmerGraphData, {
|
||||
let filter = Arc::clone(&filter);
|
||||
move |batch: Vec<CanonicalKmer>| -> Vec<CanonicalKmer> {
|
||||
batch.into_iter().filter(|k| filter(*k)).collect()
|
||||
}
|
||||
}, RawBatch, FilteredBatch),
|
||||
make_transform!(
|
||||
KmerGraphData,
|
||||
{
|
||||
let filter = Arc::clone(&filter);
|
||||
move |batch: Vec<CanonicalKmer>| -> Vec<CanonicalKmer> {
|
||||
batch.into_iter().filter(|k| filter(*k)).collect()
|
||||
}
|
||||
},
|
||||
RawBatch,
|
||||
FilteredBatch
|
||||
),
|
||||
],
|
||||
make_sink!(KmerGraphData, {
|
||||
move |batch: Vec<CanonicalKmer>| {
|
||||
let mut g = g_sink.lock().unwrap();
|
||||
for kmer in batch {
|
||||
g.push(kmer);
|
||||
make_sink!(
|
||||
KmerGraphData,
|
||||
{
|
||||
move |batch: Vec<CanonicalKmer>| {
|
||||
let mut g = g_sink.lock().unwrap();
|
||||
for kmer in batch {
|
||||
g.push(kmer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, FilteredBatch),
|
||||
},
|
||||
FilteredBatch
|
||||
),
|
||||
);
|
||||
|
||||
WorkerPool::new(pipeline, n_workers, capacity).run();
|
||||
|
||||
@@ -19,4 +19,6 @@ mod extensions;
|
||||
pub mod graph_pipeline;
|
||||
|
||||
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,
|
||||
};
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
use obiread::NucPage;
|
||||
use obikseq::RoutableSuperKmer;
|
||||
use obipipeline::Throttled;
|
||||
use obiread::NucPage;
|
||||
|
||||
// ── Shared arguments ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -78,7 +78,10 @@ impl CommonArgs {
|
||||
std::process::exit(1);
|
||||
}
|
||||
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);
|
||||
}
|
||||
if m % 2 == 0 {
|
||||
@@ -120,4 +123,3 @@ pub enum PipelineData {
|
||||
|
||||
unsafe impl Send for PipelineData {}
|
||||
unsafe impl Sync for PipelineData {}
|
||||
|
||||
@@ -128,10 +128,13 @@ fn run_annotate(args: &AnnotateArgs) {
|
||||
})
|
||||
.clone();
|
||||
|
||||
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);
|
||||
std::process::exit(1);
|
||||
});
|
||||
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);
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let meta_cols: Vec<(usize, String)> = headers
|
||||
.iter()
|
||||
|
||||
@@ -7,8 +7,8 @@ use obikrebuild::IndexReindex;
|
||||
use obisys::Reporter;
|
||||
use tracing::info;
|
||||
|
||||
use crate::cli::block_size_to_bits;
|
||||
use super::index::resolve_approx_params;
|
||||
use crate::cli::block_size_to_bits;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ConvertArgs {
|
||||
@@ -117,10 +117,11 @@ pub fn run(args: ConvertArgs) {
|
||||
|
||||
let block_bits = block_size_to_bits(args.block_size);
|
||||
let mut rep = Reporter::new();
|
||||
idx.reindex(target, block_bits, &mut rep).unwrap_or_else(|e| {
|
||||
eprintln!("convert error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
idx.reindex(target, block_bits, &mut rep)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("convert error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
rep.print();
|
||||
}
|
||||
|
||||
@@ -38,26 +38,38 @@ pub fn run(args: DumpArgs) {
|
||||
std::process::exit(1);
|
||||
}));
|
||||
|
||||
let n_genomes = idx.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
}).len();
|
||||
let n_genomes = idx
|
||||
.meta()
|
||||
.genomes()
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
.len();
|
||||
info!(
|
||||
"dumping {} partition(s), {} genome(s)",
|
||||
idx.n_partitions(),
|
||||
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 stdout = io::stdout();
|
||||
let mut out = BufWriter::new(stdout.lock());
|
||||
|
||||
idx.dump(&mut out, args.force_presence, args.debug, args.head, &filters, || pb.inc(1))
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("dump error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
idx.dump(
|
||||
&mut out,
|
||||
args.force_presence,
|
||||
args.debug,
|
||||
args.head,
|
||||
&filters,
|
||||
|| pb.inc(1),
|
||||
)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("dump error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
pb.finish_and_clear();
|
||||
}
|
||||
@@ -62,10 +62,15 @@ pub fn run(args: EstimateArgs) {
|
||||
let k_index = k_query.saturating_sub(z as usize - 1);
|
||||
let fp_kmer = 1.0_f64 / 2_f64.powi(b as i32);
|
||||
|
||||
println!("{:<22} {}", "k (query):", k_query);
|
||||
println!("{:<22} {}", "k (indexed):", k_index);
|
||||
println!("{:<22} {}", "z:", z);
|
||||
println!("{:<22} {}", "k (query):", k_query);
|
||||
println!("{:<22} {}", "k (indexed):", k_index);
|
||||
println!("{:<22} {}", "z:", z);
|
||||
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 z-window:", fp_window, b as u32 * z as u32);
|
||||
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
|
||||
);
|
||||
}
|
||||
@@ -60,8 +60,24 @@ mod tests {
|
||||
#[test]
|
||||
fn csv_has_header_and_one_row_per_r() {
|
||||
let rows = vec![
|
||||
SharingRow { r: 1, k_r: 20, observed: 1.0, expected: 1.0, deviation: 0.0, expected_false_positives: 30.0, fdr: 1.0 },
|
||||
SharingRow { r: 2, k_r: 5, observed: 0.25, expected: 0.01, deviation: 0.24, expected_false_positives: 0.5, fdr: 0.1 },
|
||||
SharingRow {
|
||||
r: 1,
|
||||
k_r: 20,
|
||||
observed: 1.0,
|
||||
expected: 1.0,
|
||||
deviation: 0.0,
|
||||
expected_false_positives: 30.0,
|
||||
fdr: 1.0,
|
||||
},
|
||||
SharingRow {
|
||||
r: 2,
|
||||
k_r: 5,
|
||||
observed: 0.25,
|
||||
expected: 0.01,
|
||||
deviation: 0.24,
|
||||
expected_false_positives: 0.5,
|
||||
fdr: 0.1,
|
||||
},
|
||||
];
|
||||
let mut buf = Vec::new();
|
||||
write_csv(&rows, &mut buf).unwrap();
|
||||
@@ -69,6 +85,9 @@ mod tests {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines[0], "r,k_r,O_r,q_r,D_r,FP_r,FDR_r");
|
||||
assert_eq!(lines.len(), 3);
|
||||
assert_eq!(lines[2], "2,5,2.500000e-1,1.000000e-2,2.400000e-1,5.000000e-1,1.000000e-1");
|
||||
assert_eq!(
|
||||
lines[2],
|
||||
"2,5,2.500000e-1,1.000000e-2,2.400000e-1,5.000000e-1,1.000000e-1"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -66,16 +66,24 @@ pub fn run(args: FilterArgs) {
|
||||
filters.push(Box::new(MaxTotalCount { total: v }));
|
||||
}
|
||||
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| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
}).len();
|
||||
let n_genomes = src
|
||||
.meta()
|
||||
.genomes()
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
.len();
|
||||
info!(
|
||||
"filter: {} genome(s), source={}",
|
||||
n_genomes, args.source.display()
|
||||
n_genomes,
|
||||
args.source.display()
|
||||
);
|
||||
|
||||
let mut rep = Reporter::new();
|
||||
|
||||
@@ -6,8 +6,8 @@ pub mod filter;
|
||||
pub mod index;
|
||||
pub mod merge;
|
||||
pub mod pack;
|
||||
mod predicate;
|
||||
pub mod phylo;
|
||||
mod predicate;
|
||||
pub mod query;
|
||||
pub mod select;
|
||||
pub mod superkmer;
|
||||
|
||||
@@ -32,10 +32,14 @@ pub fn run(args: PackArgs) {
|
||||
std::process::exit(1);
|
||||
}));
|
||||
|
||||
let n_genomes = idx.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
}).len();
|
||||
let n_genomes = idx
|
||||
.meta()
|
||||
.genomes()
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
.len();
|
||||
info!(
|
||||
"pack: {} partition(s), {} genome(s)",
|
||||
idx.n_partitions(),
|
||||
|
||||
@@ -32,7 +32,11 @@ pub(super) fn write_alignment_outputs(
|
||||
if args.align.fasta || !args.align.vcf {
|
||||
let path = path_for("fasta");
|
||||
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();
|
||||
}
|
||||
info!("pseudo-alignment ({n_sites} site(s), {n_genomes} genome(s)) → {path}");
|
||||
@@ -41,10 +45,12 @@ pub(super) fn write_alignment_outputs(
|
||||
if args.align.vcf {
|
||||
let path = path_for("vcf");
|
||||
let mut f = create(&path);
|
||||
let written = alignment.write_vcf(labels, !args.sample.no_ambiguity, &mut f).unwrap_or_else(|e| {
|
||||
eprintln!("error writing {path}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let written = alignment
|
||||
.write_vcf(labels, !args.sample.no_ambiguity, &mut f)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error writing {path}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
f.flush().unwrap();
|
||||
info!("pseudo-alignment VCF ({written}/{n_sites} site(s), {n_genomes} genome(s)) → {path}");
|
||||
}
|
||||
|
||||
@@ -107,7 +107,11 @@ fn drop_ascertainment_noninformative(alignment: &SnpAlignment) -> SnpAlignment {
|
||||
.filter(|&(_, &k)| k)
|
||||
.map(|(&site, _)| site)
|
||||
.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
|
||||
@@ -126,7 +130,11 @@ fn recode_symbols_as_absent(alignment: &SnpAlignment, symbols: &[u8]) -> SnpAlig
|
||||
.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 {
|
||||
@@ -276,7 +284,11 @@ fn write_iqtree_alignment(
|
||||
std::process::exit(1);
|
||||
}));
|
||||
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
|
||||
.iter()
|
||||
.map(|&b| {
|
||||
@@ -391,7 +403,11 @@ mod tests {
|
||||
|
||||
fn alignment(sequences: Vec<Vec<u8>>) -> SnpAlignment {
|
||||
let genome_indices = (0..sequences.len()).collect();
|
||||
SnpAlignment { sequences, genome_indices, sites: Vec::new() }
|
||||
SnpAlignment {
|
||||
sequences,
|
||||
genome_indices,
|
||||
sites: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -442,9 +458,10 @@ mod tests {
|
||||
// --free-loss — compact index 0 -> 'A', compact index 1 -> 'G'.
|
||||
let alignment = alignment(vec![vec![b'A', b'-'], vec![b'-', b'G']]);
|
||||
let alphabet = compact_alphabet(&alignment, true);
|
||||
let output = Some(
|
||||
std::env::temp_dir().join(format!("obikmer2_test_iqtree_states_{}", std::process::id())),
|
||||
);
|
||||
let output = Some(std::env::temp_dir().join(format!(
|
||||
"obikmer2_test_iqtree_states_{}",
|
||||
std::process::id()
|
||||
)));
|
||||
|
||||
let path = write_iqtree_states_csv(&alphabet, &output);
|
||||
let csv = std::fs::read_to_string(&path).unwrap();
|
||||
|
||||
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user