diff --git a/src/obicompactvec/examples/compare_sparse_dense.rs b/src/obicompactvec/examples/compare_sparse_dense.rs index 0e5e0d08..db81af2b 100644 --- a/src/obicompactvec/examples/compare_sparse_dense.rs +++ b/src/obicompactvec/examples/compare_sparse_dense.rs @@ -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> { - let layer_dir = std::env::args().nth(1).expect("usage: compare_sparse_dense "); + let layer_dir = std::env::args() + .nth(1) + .expect("usage: compare_sparse_dense "); 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> { +fn compare( + dense: &PersistentBitMatrix, + sparse: &PersistentSparseBitMatrix, +) -> Result<(), Box> { 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}"); diff --git a/src/obicompactvec/examples/compare_sparse_dense_presence.rs b/src/obicompactvec/examples/compare_sparse_dense_presence.rs index 04e41c00..6fc50133 100644 --- a/src/obicompactvec/examples/compare_sparse_dense_presence.rs +++ b/src/obicompactvec/examples/compare_sparse_dense_presence.rs @@ -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> { - let layer_dir = std::env::args().nth(1).expect("usage: compare_sparse_dense_presence "); + let layer_dir = std::env::args() + .nth(1) + .expect("usage: compare_sparse_dense_presence "); 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> { Ok(()) } -fn compare(dense: &PersistentBitMatrix, sparse: &PersistentSparseBitMatrix) -> Result<(), Box> { +fn compare( + dense: &PersistentBitMatrix, + sparse: &PersistentSparseBitMatrix, +) -> Result<(), Box> { 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 { Ok(total) } -fn compaction_stats(dense_layer_dir: &Path, sparse_dir: &Path, dense: &PersistentBitMatrix) -> Result<(), Box> { +fn compaction_stats( + dense_layer_dir: &Path, + sparse_dir: &Path, + dense: &PersistentBitMatrix, +) -> Result<(), Box> { let dense_size = dir_size(&dense_layer_dir.join("presence"))?; let sparse_size = dir_size(sparse_dir)?; diff --git a/src/obicompactvec/src/bitmatrix/builder.rs b/src/obicompactvec/src/bitmatrix/builder.rs index 00ee3655..6926076e 100644 --- a/src/obicompactvec/src/bitmatrix/builder.rs +++ b/src/obicompactvec/src/bitmatrix/builder.rs @@ -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 { 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 { 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 { 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) } } diff --git a/src/obicompactvec/src/bitmatrix/columnar.rs b/src/obicompactvec/src/bitmatrix/columnar.rs index 0b05fc1a..69c0b533 100644 --- a/src/obicompactvec/src/bitmatrix/columnar.rs +++ b/src/obicompactvec/src/bitmatrix/columnar.rs @@ -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, - 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, Array2) { - 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 { diff --git a/src/obicompactvec/src/bitmatrix/group_ops.rs b/src/obicompactvec/src/bitmatrix/group_ops.rs index 75805855..7cab35c8 100644 --- a/src/obicompactvec/src/bitmatrix/group_ops.rs +++ b/src/obicompactvec/src/bitmatrix/group_ops.rs @@ -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 { + fn partial_group_presence_count( + &self, + g: &ColGroup, + _threshold: u32, + ) -> io::Result { // 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 { @@ -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() } diff --git a/src/obicompactvec/src/bitmatrix/mod.rs b/src/obicompactvec/src/bitmatrix/mod.rs index 610b88f1..1e0185a3 100644 --- a/src/obicompactvec/src/bitmatrix/mod.rs +++ b/src/obicompactvec/src/bitmatrix/mod.rs @@ -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")) diff --git a/src/obicompactvec/src/bitmatrix/packed.rs b/src/obicompactvec/src/bitmatrix/packed.rs index ca51dfec..7c9aef72 100644 --- a/src/obicompactvec/src/bitmatrix/packed.rs +++ b/src/obicompactvec/src/bitmatrix/packed.rs @@ -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 { 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(()) } diff --git a/src/obicompactvec/src/bitmatrix/pairwise.rs b/src/obicompactvec/src/bitmatrix/pairwise.rs index 4873cd30..3c88e102 100644 --- a/src/obicompactvec/src/bitmatrix/pairwise.rs +++ b/src/obicompactvec/src/bitmatrix/pairwise.rs @@ -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(slot: usize, n_cols: usize, get: impl Fn(usize, usize) -> T) -> Box<[T]> { +pub(crate) fn row_generic( + 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(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( + 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(n_cols: usize, f: impl Fn(usize) -> T + Sync + Send) -> Array1 { +pub(crate) fn par_col_reduce( + n_cols: usize, + f: impl Fn(usize) -> T + Sync + Send, +) -> Array1 { 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(n: usize, vals: impl Iterator) -> Array2 -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(n: usize, f: impl Fn(usize, usize) -> T + Sync) -> Array2 -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(n: usize, f: impl Fn(usize, usize) -> (T, T) + Sync) -> (Array2, Array2) -where T: Copy + Default + Send { +pub(crate) fn pairwise2_matrix( + n: usize, + f: impl Fn(usize, usize) -> (T, T) + Sync, +) -> (Array2, Array2) +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); diff --git a/src/obicompactvec/src/bitmatrix/persistent.rs b/src/obicompactvec/src/bitmatrix/persistent.rs index 59d5025d..0a1c3d85 100644 --- a/src/obicompactvec/src/bitmatrix/persistent.rs +++ b/src/obicompactvec/src/bitmatrix/persistent.rs @@ -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 { 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 + 'a> { + pub fn nonzero_iter<'a>( + &'a self, + slots: &'a [usize], + ) -> Box + '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 { 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, Array2) { 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 { 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 { self.count_ones() } + fn col_weights(&self) -> Array1 { + 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 { self.count_ones() } + fn count_geq(&self, _threshold: u32) -> Array1 { + 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]) { self.fill_sub_matrix(slots, out) } + fn fill_sub_matrix(&self, slots: &[usize], out: &mut [Vec]) { + self.fill_sub_matrix(slots, out) + } #[inline] - fn count_ones(&self) -> Array1 { self.count_ones() } + fn count_ones(&self) -> Array1 { + self.count_ones() + } } diff --git a/src/obicompactvec/src/bitmatrix/sparse.rs b/src/obicompactvec/src/bitmatrix/sparse.rs index f6ff3034..62ac0c38 100644 --- a/src/obicompactvec/src/bitmatrix/sparse.rs +++ b/src/obicompactvec/src/bitmatrix/sparse.rs @@ -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 { 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 + 'a { + pub fn nonzero_iter<'a>( + &'a self, + slots: &'a [usize], + ) -> impl Iterator + 'a { let mut next_slot = 0usize; let mut cur_idx = 0usize; let mut buf: Vec = 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]) { self.fill_sub_matrix(slots, out) } + fn fill_sub_matrix(&self, slots: &[usize], out: &mut [Vec]) { + self.fill_sub_matrix(slots, out) + } #[inline] - fn count_ones(&self) -> Array1 { self.count_ones() } + fn count_ones(&self) -> Array1 { + 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(()) } diff --git a/src/obicompactvec/src/bitmatrix/sparse_columnar.rs b/src/obicompactvec/src/bitmatrix/sparse_columnar.rs index 08e45b7f..ea2e8fc4 100644 --- a/src/obicompactvec/src/bitmatrix/sparse_columnar.rs +++ b/src/obicompactvec/src/bitmatrix/sparse_columnar.rs @@ -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>| { - 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, ())); }); diff --git a/src/obicompactvec/src/bitvec.rs b/src/obicompactvec/src/bitvec.rs index 8f90be49..6baed71a 100644 --- a/src/obicompactvec/src/bitvec.rs +++ b/src/obicompactvec/src/bitvec.rs @@ -230,7 +230,10 @@ impl PersistentBitVecBuilder { pub fn build_from(source: &PersistentBitVec, path: &Path) -> io::Result { 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 { diff --git a/src/obicompactvec/src/builder.rs b/src/obicompactvec/src/builder.rs index e682f9b6..69d354e3 100644 --- a/src/obicompactvec/src/builder.rs +++ b/src/obicompactvec/src/builder.rs @@ -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, } impl PersistentCompactIntVecBuilder { pub fn new(n: usize, path: &Path) -> io::Result { 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, path: &Path) -> io::Result { + pub fn from_raw_primary( + primary: &[u8], + overflow: HashMap, + path: &Path, + ) -> io::Result { 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 { 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 = 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 = 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 = 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); diff --git a/src/obicompactvec/src/colgroup.rs b/src/obicompactvec/src/colgroup.rs index 11c0f73a..ad1c76f0 100644 --- a/src/obicompactvec/src/colgroup.rs +++ b/src/obicompactvec/src/colgroup.rs @@ -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, } impl ColGroup { pub fn new(name: impl Into, indices: Vec) -> Self { - Self { name: name.into(), indices } + Self { + name: name.into(), + indices, + } } } @@ -34,13 +37,17 @@ pub(crate) fn chunked_presence_count( ) -> io::Result { 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; + fn partial_group_presence_count( + &self, + g: &ColGroup, + threshold: u32, + ) -> io::Result; /// Per-slot sum of values across all group columns. fn partial_group_sum(&self, g: &ColGroup) -> io::Result; @@ -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, threshold: u32, min_count: usize }, + PresenceGeq { + indices: Vec, + threshold: u32, + min_count: usize, + }, /// Slot passes if count of columns in `indices` with value ≥ `threshold` is ≤ `max_count`. - PresenceLeq { indices: Vec, threshold: u32, max_count: usize }, + PresenceLeq { + indices: Vec, + threshold: u32, + max_count: usize, + }, /// Slot passes if sum of values across `indices` columns is ≥ `min_sum`. SumGeq { indices: Vec, 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 { +pub fn eval_filter_mask( + expr: &FilterMask, + mat: &dyn MatrixGroupOps, + n: usize, +) -> io::Result { 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)?; diff --git a/src/obicompactvec/src/eliasfano.rs b/src/obicompactvec/src/eliasfano.rs index 52758b83..50efeeb1 100644 --- a/src/obicompactvec/src/eliasfano.rs +++ b/src/obicompactvec/src/eliasfano.rs @@ -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() } diff --git a/src/obicompactvec/src/fixedintvec.rs b/src/obicompactvec/src/fixedintvec.rs index a1b74854..e32515a0 100644 --- a/src/obicompactvec/src/fixedintvec.rs +++ b/src/obicompactvec/src/fixedintvec.rs @@ -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 { 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] { diff --git a/src/obicompactvec/src/format.rs b/src/obicompactvec/src/format.rs index b3358840..b33db502 100644 --- a/src/obicompactvec/src/format.rs +++ b/src/obicompactvec/src/format.rs @@ -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: &mut W, n: usize, n_overflow: usize) -> io::Result<()> { +pub(crate) fn write_pciv_header( + 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])?; diff --git a/src/obicompactvec/src/int_group_ops.rs b/src/obicompactvec/src/int_group_ops.rs index d0091da1..50386943 100644 --- a/src/obicompactvec/src/int_group_ops.rs +++ b/src/obicompactvec/src/int_group_ops.rs @@ -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) { diff --git a/src/obicompactvec/src/layer_meta.rs b/src/obicompactvec/src/layer_meta.rs index 9c967a2f..cd4a8b95 100644 --- a/src/obicompactvec/src/layer_meta.rs +++ b/src/obicompactvec/src/layer_meta.rs @@ -23,6 +23,8 @@ impl LayerMeta { } fn parse(s: &str) -> Option { - Some(Self { n: crate::meta::field(s, "n")? }) + Some(Self { + n: crate::meta::field(s, "n")?, + }) } } diff --git a/src/obicompactvec/src/lib.rs b/src/obicompactvec/src/lib.rs index a2cfd399..ea79a7db 100644 --- a/src/obicompactvec/src/lib.rs +++ b/src/obicompactvec/src/lib.rs @@ -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::{ diff --git a/src/obicompactvec/src/matrix_builder.rs b/src/obicompactvec/src/matrix_builder.rs index 4ba9bbfc..26d48158 100644 --- a/src/obicompactvec/src/matrix_builder.rs +++ b/src/obicompactvec/src/matrix_builder.rs @@ -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 ──────────────────────────────────────────────────────────────── diff --git a/src/obicompactvec/src/mem_builder.rs b/src/obicompactvec/src/mem_builder.rs index d92a1c05..8d304dc9 100644 --- a/src/obicompactvec/src/mem_builder.rs +++ b/src/obicompactvec/src/mem_builder.rs @@ -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| { diff --git a/src/obicompactvec/src/meta.rs b/src/obicompactvec/src/meta.rs index 09deedcf..b48bd837 100644 --- a/src/obicompactvec/src/meta.rs +++ b/src/obicompactvec/src/meta.rs @@ -20,13 +20,18 @@ impl MatrixMeta { } fn parse(s: &str) -> Option { - 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 { 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() } diff --git a/src/obicompactvec/src/mmap_file.rs b/src/obicompactvec/src/mmap_file.rs index 81d792ee..2c3e7f36 100644 --- a/src/obicompactvec/src/mmap_file.rs +++ b/src/obicompactvec/src/mmap_file.rs @@ -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: &mut W, magic: [u8; 4], pad: [u8; 4], n: usize) -> io::Result<()> { +pub(crate) fn write_std_header( + 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)) diff --git a/src/obicompactvec/src/rankselect.rs b/src/obicompactvec/src/rankselect.rs index 0a8d9e1e..82858d03 100644 --- a/src/obicompactvec/src/rankselect.rs +++ b/src/obicompactvec/src/rankselect.rs @@ -65,19 +65,34 @@ impl PersistentRankSelectBitVec { pub fn open(path: &Path) -> io::Result { 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] { diff --git a/src/obicompactvec/src/reader.rs b/src/obicompactvec/src/reader.rs index 87247a40..b9282bc0 100644 --- a/src/obicompactvec/src/reader.rs +++ b/src/obicompactvec/src/reader.rs @@ -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 { - 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 { diff --git a/src/obicompactvec/src/row_histogram.rs b/src/obicompactvec/src/row_histogram.rs index 506af7e1..345451a4 100644 --- a/src/obicompactvec/src/row_histogram.rs +++ b/src/obicompactvec/src/row_histogram.rs @@ -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. diff --git a/src/obicompactvec/src/sparse_intmatrix.rs b/src/obicompactvec/src/sparse_intmatrix.rs index 39005225..a89af716 100644 --- a/src/obicompactvec/src/sparse_intmatrix.rs +++ b/src/obicompactvec/src/sparse_intmatrix.rs @@ -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(()); diff --git a/src/obicompactvec/src/sparse_intmatrix_columnar.rs b/src/obicompactvec/src/sparse_intmatrix_columnar.rs index 5abe9df5..987dfd98 100644 --- a/src/obicompactvec/src/sparse_intmatrix_columnar.rs +++ b/src/obicompactvec/src/sparse_intmatrix_columnar.rs @@ -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)); diff --git a/src/obicompactvec/src/tempintvec.rs b/src/obicompactvec/src/tempintvec.rs index 6f0ee3b6..d3967336 100644 --- a/src/obicompactvec/src/tempintvec.rs +++ b/src/obicompactvec/src/tempintvec.rs @@ -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); + } } diff --git a/src/obicompactvec/src/tests/bitmatrix.rs b/src/obicompactvec/src/tests/bitmatrix.rs index 98ea22fa..03bfd012 100644 --- a/src/obicompactvec/src/tests/bitmatrix.rs +++ b/src/obicompactvec/src/tests/bitmatrix.rs @@ -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]); diff --git a/src/obicompactvec/src/tests/bitvec.rs b/src/obicompactvec/src/tests/bitvec.rs index 413c4804..d0dd3629 100644 --- a/src/obicompactvec/src/tests/bitvec.rs +++ b/src/obicompactvec/src/tests/bitvec.rs @@ -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 = r.iter().collect(); - let via_get: Vec = (0..bits.len()).map(|s| r.get(s)).collect(); + let via_get: Vec = (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::>(), rb.iter().collect::>()); } #[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![true, false, false, false]); + assert_eq!( + r.iter().collect::>(), + 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![false, true, false, true, false]); + assert_eq!( + r.iter().collect::>(), + 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![false, true, false, true, true, false]); + assert_eq!( + bv.iter().collect::>(), + 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![false, false, true, true, false, true]); + assert_eq!( + bv.iter().collect::>(), + 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![false, false, true, false]); + assert_eq!( + bv.iter().collect::>(), + 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]); } diff --git a/src/obicompactvec/src/tests/colgroup.rs b/src/obicompactvec/src/tests/colgroup.rs index 4d88a7f2..1fca2b38 100644 --- a/src/obicompactvec/src/tests/colgroup.rs +++ b/src/obicompactvec/src/tests/colgroup.rs @@ -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}"); diff --git a/src/obicompactvec/src/tests/eliasfano.rs b/src/obicompactvec/src/tests/eliasfano.rs index 891cce7e..6e06e5d9 100644 --- a/src/obicompactvec/src/tests/eliasfano.rs +++ b/src/obicompactvec/src/tests/eliasfano.rs @@ -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})" + ); } } diff --git a/src/obicompactvec/src/tests/int_group_ops.rs b/src/obicompactvec/src/tests/int_group_ops.rs index 931af238..2ae2525e 100644 --- a/src/obicompactvec/src/tests/int_group_ops.rs +++ b/src/obicompactvec/src/tests/int_group_ops.rs @@ -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}" + ); } } } diff --git a/src/obicompactvec/src/tests/intmatrix.rs b/src/obicompactvec/src/tests/intmatrix.rs index 5c56b5dd..4de8842f 100644 --- a/src/obicompactvec/src/tests/intmatrix.rs +++ b/src/obicompactvec/src/tests/intmatrix.rs @@ -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 { - 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}" + ); } } diff --git a/src/obicompactvec/src/tests/mem_builder.rs b/src/obicompactvec/src/tests/mem_builder.rs index 3e7160bd..0c6a1030 100644 --- a/src/obicompactvec/src/tests/mem_builder.rs +++ b/src/obicompactvec/src/tests/mem_builder.rs @@ -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(); diff --git a/src/obicompactvec/src/tests/mod.rs b/src/obicompactvec/src/tests/mod.rs index c0d7361d..76439302 100644 --- a/src/obicompactvec/src/tests/mod.rs +++ b/src/obicompactvec/src/tests/mod.rs @@ -18,7 +18,7 @@ use tempfile::tempdir; use crate::{PersistentCompactIntVec, PersistentCompactIntVecBuilder}; fn roundtrip(values: &[(usize, u32)], n: usize) -> Vec { - 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 { } 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 = r.iter().collect(); - let via_get: Vec = (0..n).map(|s| r.get(s)).collect(); + let via_get: Vec = (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::>(), rb.iter().collect::>()); } #[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}"); } } diff --git a/src/obicompactvec/src/tests/rankselect.rs b/src/obicompactvec/src/tests/rankselect.rs index 6d020ac8..e6c2201d 100644 --- a/src/obicompactvec/src/tests/rankselect.rs +++ b/src/obicompactvec/src/tests/rankselect.rs @@ -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)"); diff --git a/src/obicompactvec/src/tests/sparse.rs b/src/obicompactvec/src/tests/sparse.rs index 88039623..0025c75e 100644 --- a/src/obicompactvec/src/tests/sparse.rs +++ b/src/obicompactvec/src/tests/sparse.rs @@ -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> = (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> = (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> = (0..n).map(|s| cols.iter().map(|c| c[s]).collect()).collect(); + let rows: Vec> = (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> = (0..5).map(|s| cols.iter().map(|c| c[s]).collect()).collect(); + let rows: Vec> = (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]); } diff --git a/src/obicompactvec/src/tests/sparse_intmatrix.rs b/src/obicompactvec/src/tests/sparse_intmatrix.rs index ac12c9d1..3663a628 100644 --- a/src/obicompactvec/src/tests/sparse_intmatrix.rs +++ b/src/obicompactvec/src/tests/sparse_intmatrix.rs @@ -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}" + ); } } diff --git a/src/obicompactvec/src/tests/transpose_columnar.rs b/src/obicompactvec/src/tests/transpose_columnar.rs index 78cfdb14..bb8b31ab 100644 --- a/src/obicompactvec/src/tests/transpose_columnar.rs +++ b/src/obicompactvec/src/tests/transpose_columnar.rs @@ -81,17 +81,25 @@ fn sparse_files(dir: &Path) -> Vec<(String, Vec)> { 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); } diff --git a/src/obicompactvec/src/tests/views_scan.rs b/src/obicompactvec/src/tests/views_scan.rs index 56037b77..0bf4929e 100644 --- a/src/obicompactvec/src/tests/views_scan.rs +++ b/src/obicompactvec/src/tests/views_scan.rs @@ -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}" + ); } } } diff --git a/src/obicompactvec/src/traits.rs b/src/obicompactvec/src/traits.rs index 94a4b3b3..96af1fb3 100644 --- a/src/obicompactvec/src/traits.rs +++ b/src/obicompactvec/src/traits.rs @@ -44,8 +44,11 @@ pub trait BinaryMatrix { fn jaccard_to_mash(d_jaccard: &Array2, k: usize) -> Array2 { 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 + }; } } } diff --git a/src/obicompactvec/src/transpose.rs b/src/obicompactvec/src/transpose.rs index 636ced8a..e06d96ef 100644 --- a/src/obicompactvec/src/transpose.rs +++ b/src/obicompactvec/src/transpose.rs @@ -39,7 +39,11 @@ pub(crate) struct RowBatch { impl RowBatch { 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. diff --git a/src/obicompactvec/src/views.rs b/src/obicompactvec/src/views.rs index a66ebdbf..879fc35a 100644 --- a/src/obicompactvec/src/views.rs +++ b/src/obicompactvec/src/views.rs @@ -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 = (0..n).collect(); perm.sort_by_key(|&i| slots[i]); let sorted: Vec = 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 + 'b + pub fn enumerate_slots_values<'b>( + self, + slots: &'b [usize], + ) -> impl Iterator + '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 + 'b + pub fn enumerate_nonzero_slots<'b>( + self, + slots: &'b [usize], + ) -> impl Iterator + '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 { - 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 + '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 = (0..n).collect(); perm.sort_by_key(|&i| slots[i]); let sorted: Vec = 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 + 'b + pub fn enumerate_slots_values<'b>( + self, + slots: &'b [usize], + ) -> impl Iterator + '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 + 'b + pub fn enumerate_nonzero_slots<'b>( + self, + slots: &'b [usize], + ) -> impl Iterator + '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 + 'b + fn enumerate_nonzero_slots<'b>( + self, + slots: &'b [usize], + ) -> impl Iterator + 'b where Self: 'b; } impl<'a> NonzeroSlotsView for BitSliceView<'a> { #[inline] - fn enumerate_nonzero_slots<'b>(self, slots: &'b [usize]) -> impl Iterator + 'b + fn enumerate_nonzero_slots<'b>( + self, + slots: &'b [usize], + ) -> impl Iterator + '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 + 'b + fn enumerate_nonzero_slots<'b>( + self, + slots: &'b [usize], + ) -> impl Iterator + 'b where Self: 'b, { @@ -491,7 +616,8 @@ pub(crate) fn nonzero_triples( 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( // ── 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 { - 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 { diff --git a/src/obicompactvec/src/views_scan.rs b/src/obicompactvec/src/views_scan.rs index 76248e02..7bf0efca 100644 --- a/src/obicompactvec/src/views_scan.rs +++ b/src/obicompactvec/src/views_scan.rs @@ -19,7 +19,12 @@ impl BitSliceView<'_> { /// Panics if `range.end > self.len()`. #[inline] pub fn for_each_set_in(&self, range: Range, 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; } diff --git a/src/obidebruinj/src/debruijn/graph.rs b/src/obidebruinj/src/debruijn/graph.rs index 3771e102..02816293 100644 --- a/src/obidebruinj/src/debruijn/graph.rs +++ b/src/obidebruinj/src/debruijn/graph.rs @@ -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> { + pub(super) fn unitig_nucleotides( + &self, + kmer: CanonicalKmer, + k: usize, + direct: bool, + ) -> Option> { 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`. diff --git a/src/obidebruinj/src/debruijn/unitig_iter.rs b/src/obidebruinj/src/debruijn/unitig_iter.rs index 7d4ef523..ee8bc56c 100644 --- a/src/obidebruinj/src/debruijn/unitig_iter.rs +++ b/src/obidebruinj/src/debruijn/unitig_iter.rs @@ -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) diff --git a/src/obidebruinj/src/debruijn/walk.rs b/src/obidebruinj/src/debruijn/walk.rs index 61320a73..1832288b 100644 --- a/src/obidebruinj/src/debruijn/walk.rs +++ b/src/obidebruinj/src/debruijn/walk.rs @@ -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 { diff --git a/src/obidebruinj/src/tests/debruijn.rs b/src/obidebruinj/src/tests/debruijn.rs index 8985c51d..bf9f38ce 100644 --- a/src/obidebruinj/src/tests/debruijn.rs +++ b/src/obidebruinj/src/tests/debruijn.rs @@ -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" + ); } diff --git a/src/obifastwrite/src/fasta.rs b/src/obifastwrite/src/fasta.rs index e27ea414..6fb1fabb 100644 --- a/src/obifastwrite/src/fasta.rs +++ b/src/obifastwrite/src/fasta.rs @@ -19,10 +19,7 @@ impl fmt::Display for JsonVal<'_> { } /// Write a JSON object `{"k1":v1,"k2":v2,...}` to `writer`. -pub fn annotation( - writer: &mut W, - fields: &[(&str, JsonVal<'_>)], -) -> io::Result<()> { +pub fn annotation(writer: &mut W, fields: &[(&str, JsonVal<'_>)]) -> io::Result<()> { write!(writer, "{{")?; for (i, (k, v)) in fields.iter().enumerate() { if i > 0 { diff --git a/src/obifastwrite/src/lib.rs b/src/obifastwrite/src/lib.rs index 3df19b58..73cdf3b4 100644 --- a/src/obifastwrite/src/lib.rs +++ b/src/obifastwrite/src/lib.rs @@ -51,11 +51,11 @@ pub fn write_scatter( &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( &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( &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); } diff --git a/src/obikdump/src/dump.rs b/src/obikdump/src/dump.rs index 61eb3cf1..702b0c05 100644 --- a/src/obikdump/src/dump.rs +++ b/src/obikdump/src/dump.rs @@ -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 { filters: &[Box], 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 { let write_row = |buf: &mut Vec, 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>> = 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::::new(); - let try_write = |buf: &mut Vec, 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::::new(); + let try_write = |buf: &mut Vec, 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::::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::::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 ────────────────────────────────────────────────── diff --git a/src/obikdump/src/unitig.rs b/src/obikdump/src/unitig.rs index 5f68b594..87411d6b 100644 --- a/src/obikdump/src/unitig.rs +++ b/src/obikdump/src/unitig.rs @@ -40,15 +40,24 @@ impl IndexUnitigs for Arc { let g = (0..n) .into_par_iter() - .try_fold(GraphDeBruijn::new, |mut local_g, i| -> OKIResult { - 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 { + 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) diff --git a/src/obikentropy/build.rs b/src/obikentropy/build.rs index a14a3a21..0d0db616 100644 --- a/src/obikentropy/build.rs +++ b/src/obikentropy/build.rs @@ -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"); diff --git a/src/obikentropy/src/tests/kmer_entropy.rs b/src/obikentropy/src/tests/kmer_entropy.rs index c75522e4..52c70d73 100644 --- a/src/obikentropy/src/tests/kmer_entropy.rs +++ b/src/obikentropy/src/tests/kmer_entropy.rs @@ -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:?}" + ); } } diff --git a/src/obikentropy/src/tracker.rs b/src/obikentropy/src/tracker.rs index 4c0c8420..8896c1be 100644 --- a/src/obikentropy/src/tracker.rs +++ b/src/obikentropy/src/tracker.rs @@ -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); diff --git a/src/obikfilter/src/filter.rs b/src/obikfilter/src/filter.rs index ffb8b745..aa5c9a96 100644 --- a/src/obikfilter/src/filter.rs +++ b/src/obikfilter/src/filter.rs @@ -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 = 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, ); } diff --git a/src/obikfilter/src/filter_algo.rs b/src/obikfilter/src/filter_algo.rs index 0b202c95..ce0fec8e 100644 --- a/src/obikfilter/src/filter_algo.rs +++ b/src/obikfilter/src/filter_algo.rs @@ -31,7 +31,11 @@ pub struct Filter<'a> { } impl<'a> Filter<'a> { - pub fn new(src: Arc, output: impl Into, filters: &'a [Box]) -> Self { + pub fn new( + src: Arc, + output: impl Into, + filters: &'a [Box], + ) -> 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() { diff --git a/src/obikfilter/src/filter_partition.rs b/src/obikfilter/src/filter_partition.rs index 88e923cb..fa9b6583 100644 --- a/src/obikfilter/src/filter_partition.rs +++ b/src/obikfilter/src/filter_partition.rs @@ -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>> = 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") + }, )?; } diff --git a/src/obikfilter/src/lib.rs b/src/obikfilter/src/lib.rs index 611ef45a..0ff2a641 100644 --- a/src/obikfilter/src/lib.rs +++ b/src/obikfilter/src/lib.rs @@ -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; diff --git a/src/obikfilter/src/partition_iter.rs b/src/obikfilter/src/partition_iter.rs index 3793964e..91ca0a0e 100644 --- a/src/obikfilter/src/partition_iter.rs +++ b/src/obikfilter/src/partition_iter.rs @@ -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 { 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 { 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![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() { diff --git a/src/obikfilter/src/predicate.rs b/src/obikfilter/src/predicate.rs index 065c7cff..783002b0 100644 --- a/src/obikfilter/src/predicate.rs +++ b/src/obikfilter/src/predicate.rs @@ -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, } @@ -27,24 +33,29 @@ impl MetaPred { pub fn parse(s: &str) -> Result { 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 = 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) -> Option { - 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) -> Option 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) -> Option { 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) -> Option { // ── Genome classification ───────────────────────────────────────────────────── -enum Membership { Ingroup, Outgroup, Uncategorized } +enum Membership { + Ingroup, + Outgroup, + Uncategorized, +} fn classify( genomes: &[GenomeInfo], - ingroup: &[MetaPred], + ingroup: &[MetaPred], outgroup: &[MetaPred], ) -> Vec { - 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, - pub max_count: Option, - pub min_frac: Option, - pub max_frac: Option, + pub threshold: u32, + pub min_count: Option, + pub max_count: Option, + pub min_frac: Option, + pub max_frac: Option, pub min_outgroup_count: Option, pub max_outgroup_count: Option, - pub min_outgroup_frac: Option, - pub max_outgroup_frac: Option, + pub min_outgroup_frac: Option, + pub max_outgroup_frac: Option, } // ── Genome selector ────────────────────────────────────────────────────────── /// Result of running a [`GenomeSelector`] against an index's metadata. pub struct Selection { - pub ingroup_idx: Vec, + pub ingroup_idx: Vec, pub outgroup_idx: Vec, } pub struct GenomeSelector { - pub(crate) ingroup: Vec, + pub(crate) ingroup: Vec, pub(crate) outgroup: Vec, } impl GenomeSelector { /// Parse ingroup (AND'd) and outgroup (OR'd) predicate strings. pub fn parse(ingroup: &[String], outgroup: &[String]) -> Result { - let ingroup = ingroup.iter().map(|s| MetaPred::parse(s)).collect::, _>>()?; - let outgroup = outgroup.iter().map(|s| MetaPred::parse(s)).collect::, _>>()?; + let ingroup = ingroup + .iter() + .map(|s| MetaPred::parse(s)) + .collect::, _>>()?; + let outgroup = outgroup + .iter() + .map(|s| MetaPred::parse(s)) + .collect::, _>>()?; 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 = members.iter().enumerate() + let ingroup_idx: Vec = members + .iter() + .enumerate() .filter(|(_, m)| matches!(m, Membership::Ingroup)) - .map(|(i, _)| i).collect(); - let outgroup_idx: Vec = members.iter().enumerate() + .map(|(i, _)| i) + .collect(); + let outgroup_idx: Vec = 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 { 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 { }) } } - diff --git a/src/obikidxcache/src/index_cache.rs b/src/obikidxcache/src/index_cache.rs index 0945dc5d..edc4aa5e 100644 --- a/src/obikidxcache/src/index_cache.rs +++ b/src/obikidxcache/src/index_cache.rs @@ -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> + 'static { + pub fn iter_partition( + &self, + partition: usize, + ) -> impl Iterator> + '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)> + 'static { LayerIter { cache: Arc::clone(&self.layer_cache), - partitions: self.layer_cache.keys().copied().collect::>().into_iter(), + partitions: self + .layer_cache + .keys() + .copied() + .collect::>() + .into_iter(), current: None, } } diff --git a/src/obikindex/examples/compare_sparse.rs b/src/obikindex/examples/compare_sparse.rs index 16766b67..252507d9 100644 --- a/src/obikindex/examples/compare_sparse.rs +++ b/src/obikindex/examples/compare_sparse.rs @@ -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 "); - let dense_root = std::env::args().nth(2).expect("usage: compare_sparse "); + let sparse_root = std::env::args() + .nth(1) + .expect("usage: compare_sparse "); + let dense_root = std::env::args() + .nth(2) + .expect("usage: compare_sparse "); 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(()) diff --git a/src/obikindex/src/index/builder.rs b/src/obikindex/src/index/builder.rs index 88681005..9272a815 100644 --- a/src/obikindex/src/index/builder.rs +++ b/src/obikindex/src/index/builder.rs @@ -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>(output: P, rep: &mut Reporter, sparse: bool) -> OKIResult; + fn finalize_indexed>( + output: P, + rep: &mut Reporter, + sparse: bool, + ) -> OKIResult; /// 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>(output: P, rep: &mut Reporter, sparse: bool) -> OKIResult { + fn finalize_indexed>( + output: P, + rep: &mut Reporter, + sparse: bool, + ) -> OKIResult { 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. diff --git a/src/obikindex/src/index/error.rs b/src/obikindex/src/index/error.rs index 6f95f6ee..cc55a15c 100644 --- a/src/obikindex/src/index/error.rs +++ b/src/obikindex/src/index/error.rs @@ -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 = Result; diff --git a/src/obikindex/src/index/kmer_index.rs b/src/obikindex/src/index/kmer_index.rs index a0d2b92c..45773eda 100644 --- a/src/obikindex/src/index/kmer_index.rs +++ b/src/obikindex/src/index/kmer_index.rs @@ -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 diff --git a/src/obikindex/src/index/mod.rs b/src/obikindex/src/index/mod.rs index becde665..fe33c095 100644 --- a/src/obikindex/src/index/mod.rs +++ b/src/obikindex/src/index/mod.rs @@ -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; diff --git a/src/obikindex/src/layer/content_layer.rs b/src/obikindex/src/layer/content_layer.rs index 9702e9b6..a0eb4ffc 100644 --- a/src/obikindex/src/layer/content_layer.rs +++ b/src/obikindex/src/layer/content_layer.rs @@ -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 { 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 { 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, Array2) { 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) -> Array2 { 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) -> Array2 { 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) -> Array2 { 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, Array2) { 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 { 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") + } } } } diff --git a/src/obikindex/src/layer/evidence.rs b/src/obikindex/src/layer/evidence.rs index 15cd126c..e0c52c89 100644 --- a/src/obikindex/src/layer/evidence.rs +++ b/src/obikindex/src/layer/evidence.rs @@ -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] diff --git a/src/obikindex/src/layer/fingerprint.rs b/src/obikindex/src/layer/fingerprint.rs index c5c199d8..fa2386cf 100644 --- a/src/obikindex/src/layer/fingerprint.rs +++ b/src/obikindex/src/layer/fingerprint.rs @@ -23,10 +23,10 @@ const HEADER: usize = 16; pub struct FingerprintVec { _mmap: Mmap, - bits: &'static BitSlice, - n: usize, - b: u8, - mask: u64, + bits: &'static BitSlice, + 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::::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::() + self.bits[lo..lo + self.b as usize].load_le::() } #[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, - 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::::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 = (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)); } } diff --git a/src/obikindex/src/layer/meta.rs b/src/obikindex/src/layer/meta.rs index aa31015e..1f6bdea1 100644 --- a/src/obikindex/src/layer/meta.rs +++ b/src/obikindex/src/layer/meta.rs @@ -32,7 +32,9 @@ pub enum IndexMode { } impl Default for IndexMode { - fn default() -> Self { Self::Exact } + fn default() -> Self { + Self::Exact + } } impl IndexMode { diff --git a/src/obikindex/src/layer/mphf_layer.rs b/src/obikindex/src/layer/mphf_layer.rs index e2bd2e89..046c37a8 100644 --- a/src/obikindex/src/layer/mphf_layer.rs +++ b/src/obikindex/src/layer/mphf_layer.rs @@ -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::uncase()`, the ε-copy view into the memory-mapped file. -pub type Mphf = PtrHash>, Xxh3Int, Vec, false, true>; +pub type Mphf = + PtrHash>, Xxh3Int, Vec, 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 { 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); impl MphfOnly { pub fn open(dir: &Path) -> OKIResult { let mphf: MemCase = 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 { 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); diff --git a/src/obikindex/src/layer/tests/typed_layer.rs b/src/obikindex/src/layer/tests/typed_layer.rs index f400dee7..c07249d7 100644 --- a/src/obikindex/src/layer/tests/typed_layer.rs +++ b/src/obikindex/src/layer/tests/typed_layer.rs @@ -201,7 +201,8 @@ fn count_layer_reports_count_content_and_columnar_storage() { DEFAULT_BLOCK_BITS, &IndexMode::Exact, |_| 1, - ).unwrap(); + ) + .unwrap(); let layer = TypedLayer::::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 = reader.iter_indexed_canonical_kmers().map(|(k, _, _)| k).collect(); + let first: Vec = reader + .iter_indexed_canonical_kmers() + .map(|(k, _, _)| k) + .collect(); let reader2 = UnitigFileReader::open_sequential(&dir.path().join(UNITIGS_FILE)).unwrap(); - let second: Vec = 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 = reader2 + .iter_indexed_canonical_kmers() + .map(|(k, _, _)| k) + .collect(); + assert_eq!( + first, second, + "iter_indexed_canonical_kmers must be deterministic across calls" + ); } diff --git a/src/obikindex/src/layer/typed_layer.rs b/src/obikindex/src/layer/typed_layer.rs index c14212ba..37f7635f 100644 --- a/src/obikindex/src/layer/typed_layer.rs +++ b/src/obikindex/src/layer/typed_layer.rs @@ -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 { /// 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> { - 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`. diff --git a/src/obikindex/src/lib.rs b/src/obikindex/src/lib.rs index cba763a7..2f7ede47 100644 --- a/src/obikindex/src/lib.rs +++ b/src/obikindex/src/lib.rs @@ -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, +}; diff --git a/src/obikindexer/examples/graph_bench.rs b/src/obikindexer/examples/graph_bench.rs index 627c35a2..994acb72 100644 --- a/src/obikindexer/examples/graph_bench.rs +++ b/src/obikindexer/examples/graph_bench.rs @@ -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 = kmers.iter().map(|c| c.raw()).collect(); let outs = |a: obikseq::Kmer| -> Vec { - (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 { - let ins: Vec = 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 = + 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 = (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", diff --git a/src/obikindexer/src/algorithms/counter/count.rs b/src/obikindexer/src/algorithms/counter/count.rs index 2cc95b03..00ddf07e 100644 --- a/src/obikindexer/src/algorithms/counter/count.rs +++ b/src/obikindexer/src/algorithms/counter/count.rs @@ -15,9 +15,7 @@ use super::kmer_sort::sort_unique_kmers; fn build_mphf(unique_path: &Path, f0: usize) -> io::Result { 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. diff --git a/src/obikindexer/src/algorithms/counter/kmer_sort.rs b/src/obikindexer/src/algorithms/counter/kmer_sort.rs index 1bf8fc67..c904ad69 100644 --- a/src/obikindexer/src/algorithms/counter/kmer_sort.rs +++ b/src/obikindexer/src/algorithms/counter/kmer_sort.rs @@ -77,25 +77,33 @@ fn flush_sorted_chunk(buf: &mut Vec, work_dir: &Path, idx: usize) -> io::Re fn merge_and_dedup(chunk_paths: &[PathBuf], unique_path: &Path) -> io::Result { struct ChunkReader { mmap: Mmap, - pos: usize, + pos: usize, } impl ChunkReader { fn open(path: &Path) -> io::Result { 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 { 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 = chunk_paths.iter() + let mut readers: Vec = chunk_paths + .iter() .map(|p| ChunkReader::open(p)) .collect::>()?; @@ -106,8 +114,8 @@ fn merge_and_dedup(chunk_paths: &[PathBuf], unique_path: &Path) -> io::Result = None; while let Some(Reverse((val, idx))) = heap.pop() { diff --git a/src/obikindexer/src/algorithms/dereplicator/dereplicate.rs b/src/obikindexer/src/algorithms/dereplicator/dereplicate.rs index 1296114b..e9401027 100644 --- a/src/obikindexer/src/algorithms/dereplicator/dereplicate.rs +++ b/src/obikindexer/src/algorithms/dereplicator/dereplicate.rs @@ -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(()); diff --git a/src/obikindexer/src/algorithms/layer_builder/mod.rs b/src/obikindexer/src/algorithms/layer_builder/mod.rs index 5131d922..554b66e6 100644 --- a/src/obikindexer/src/algorithms/layer_builder/mod.rs +++ b/src/obikindexer/src/algorithms/layer_builder/mod.rs @@ -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; diff --git a/src/obikindexer/src/algorithms/mod.rs b/src/obikindexer/src/algorithms/mod.rs index 69fca0b0..c271fd0c 100644 --- a/src/obikindexer/src/algorithms/mod.rs +++ b/src/obikindexer/src/algorithms/mod.rs @@ -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 diff --git a/src/obikindexer/src/algorithms/partitionner/router.rs b/src/obikindexer/src/algorithms/partitionner/router.rs index abc3567c..7320dce5 100644 --- a/src/obikindexer/src/algorithms/partitionner/router.rs +++ b/src/obikindexer/src/algorithms/partitionner/router.rs @@ -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(); diff --git a/src/obikindexer/src/algorithms/partitionner/tests.rs b/src/obikindexer/src/algorithms/partitionner/tests.rs index c1757388..31e41b74 100644 --- a/src/obikindexer/src/algorithms/partitionner/tests.rs +++ b/src/obikindexer/src/algorithms/partitionner/tests.rs @@ -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; diff --git a/src/obikindexer/src/extensions/private_builder.rs b/src/obikindexer/src/extensions/private_builder.rs index 89199c37..2e9f6c62 100644 --- a/src/obikindexer/src/extensions/private_builder.rs +++ b/src/obikindexer/src/extensions/private_builder.rs @@ -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 = 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 }; diff --git a/src/obikindexer/src/graph_pipeline.rs b/src/obikindexer/src/graph_pipeline.rs index c7e842f1..c351fd66 100644 --- a/src/obikindexer/src/graph_pipeline.rs +++ b/src/obikindexer/src/graph_pipeline.rs @@ -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>, - delta: &PipelineSender| - { + delta: &PipelineSender| { 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), - make_transform!(KmerGraphData, { - let filter = Arc::clone(&filter); - move |batch: Vec| -> Vec { - batch.into_iter().filter(|k| filter(*k)).collect() - } - }, RawBatch, FilteredBatch), + make_transform!( + KmerGraphData, + { + let filter = Arc::clone(&filter); + move |batch: Vec| -> Vec { + batch.into_iter().filter(|k| filter(*k)).collect() + } + }, + RawBatch, + FilteredBatch + ), ], - make_sink!(KmerGraphData, { - move |batch: Vec| { - let mut g = g_sink.lock().unwrap(); - for kmer in batch { - g.push(kmer); + make_sink!( + KmerGraphData, + { + move |batch: Vec| { + let mut g = g_sink.lock().unwrap(); + for kmer in batch { + g.push(kmer); + } } - } - }, FilteredBatch), + }, + FilteredBatch + ), ); WorkerPool::new(pipeline, n_workers, capacity).run(); diff --git a/src/obikindexer/src/lib.rs b/src/obikindexer/src/lib.rs index 514f69a2..16c346f6 100644 --- a/src/obikindexer/src/lib.rs +++ b/src/obikindexer/src/lib.rs @@ -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, +}; diff --git a/src/obikmer/src/cli.rs b/src/obikmer/src/cli.rs index 8a1abb06..bc2ac876 100644 --- a/src/obikmer/src/cli.rs +++ b/src/obikmer/src/cli.rs @@ -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 {} - diff --git a/src/obikmer/src/cmd/annotate/mod.rs b/src/obikmer/src/cmd/annotate/mod.rs index ec4ffe09..3ca84f53 100644 --- a/src/obikmer/src/cmd/annotate/mod.rs +++ b/src/obikmer/src/cmd/annotate/mod.rs @@ -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() diff --git a/src/obikmer/src/cmd/convert/mod.rs b/src/obikmer/src/cmd/convert/mod.rs index 9f05c8e2..529b7870 100644 --- a/src/obikmer/src/cmd/convert/mod.rs +++ b/src/obikmer/src/cmd/convert/mod.rs @@ -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(); } diff --git a/src/obikmer/src/cmd/dump/mod.rs b/src/obikmer/src/cmd/dump/mod.rs index 63bcfebb..b5a0093a 100644 --- a/src/obikmer/src/cmd/dump/mod.rs +++ b/src/obikmer/src/cmd/dump/mod.rs @@ -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> = vec![Box::new(args.group_filter.build_filter(&idx.meta()))]; + let filters: Vec> = + 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(); } diff --git a/src/obikmer/src/cmd/estimate/mod.rs b/src/obikmer/src/cmd/estimate/mod.rs index d32cf53e..130db842 100644 --- a/src/obikmer/src/cmd/estimate/mod.rs +++ b/src/obikmer/src/cmd/estimate/mod.rs @@ -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 + ); } diff --git a/src/obikmer/src/cmd/estimate/sharing.rs b/src/obikmer/src/cmd/estimate/sharing.rs index 9d63e4d7..dae9ae25 100644 --- a/src/obikmer/src/cmd/estimate/sharing.rs +++ b/src/obikmer/src/cmd/estimate/sharing.rs @@ -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" + ); } } diff --git a/src/obikmer/src/cmd/filter/mod.rs b/src/obikmer/src/cmd/filter/mod.rs index 831f4b51..c9a60b1e 100644 --- a/src/obikmer/src/cmd/filter/mod.rs +++ b/src/obikmer/src/cmd/filter/mod.rs @@ -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(); diff --git a/src/obikmer/src/cmd/mod.rs b/src/obikmer/src/cmd/mod.rs index bf381257..e195a36d 100644 --- a/src/obikmer/src/cmd/mod.rs +++ b/src/obikmer/src/cmd/mod.rs @@ -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; diff --git a/src/obikmer/src/cmd/pack/mod.rs b/src/obikmer/src/cmd/pack/mod.rs index 0e00048e..16e85bf6 100644 --- a/src/obikmer/src/cmd/pack/mod.rs +++ b/src/obikmer/src/cmd/pack/mod.rs @@ -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(), diff --git a/src/obikmer/src/cmd/phylo/alignment_out.rs b/src/obikmer/src/cmd/phylo/alignment_out.rs index 01f05985..615ed85a 100644 --- a/src/obikmer/src/cmd/phylo/alignment_out.rs +++ b/src/obikmer/src/cmd/phylo/alignment_out.rs @@ -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}"); } diff --git a/src/obikmer/src/cmd/phylo/iqtree.rs b/src/obikmer/src/cmd/phylo/iqtree.rs index ef552385..424bf711 100644 --- a/src/obikmer/src/cmd/phylo/iqtree.rs +++ b/src/obikmer/src/cmd/phylo/iqtree.rs @@ -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 = seq .iter() .map(|&b| { @@ -391,7 +403,11 @@ mod tests { fn alignment(sequences: Vec>) -> 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(); diff --git a/src/obikmer/src/cmd/phylo/mod.rs b/src/obikmer/src/cmd/phylo/mod.rs index 20a49868..9001a3da 100644 --- a/src/obikmer/src/cmd/phylo/mod.rs +++ b/src/obikmer/src/cmd/phylo/mod.rs @@ -1,13 +1,13 @@ mod alignment_out; mod args; -mod shared; -mod values; mod iqtree; mod phyg; mod phylip; mod sankoff; +mod shared; mod stats; mod tnt; +mod values; use std::io::{self, BufWriter, Write}; use std::sync::Arc; @@ -23,14 +23,14 @@ use obisys::{Reporter, Stage}; use tracing::info; use alignment_out::write_alignment_outputs; -use shared::write_shared_kmers; -use values::{DistanceArg, NSitesArg, distance_to_compute}; use iqtree::write_iqtree; use phyg::write_sankoff_phyg; -use stats::{write_sample_plan, write_sample_stats}; use phylip::write_phylip_relaxed; use sankoff::{write_sankoff_alignment_fasta, write_sankoff_matrix_csv, write_sankoff_params}; +use shared::write_shared_kmers; +use stats::{write_sample_plan, write_sample_stats}; use tnt::write_sankoff_tnt; +use values::{DistanceArg, NSitesArg, distance_to_compute}; pub use args::{PhyloArgs, WORKFLOW_HELP}; @@ -63,7 +63,9 @@ pub fn run(args: PhyloArgs) { match labels.iter().position(|l| l == label) { Some(i) => mask[i] = true, None => { - eprintln!("error: --exclude-genome {label:?} does not match any genome in this index"); + eprintln!( + "error: --exclude-genome {label:?} does not match any genome in this index" + ); std::process::exit(1); } } @@ -88,10 +90,12 @@ pub fn run(args: PhyloArgs) { // so a concurrent run on the same index can't corrupt these writes. info!("building sibling-count/minorant annex"); let t = Stage::start("sibling_annex"); - cache.build_sibling_annex(&args.annex_selection()).unwrap_or_else(|e| { - eprintln!("error building sibling annex: {e}"); - std::process::exit(1); - }); + cache + .build_sibling_annex(&args.annex_selection()) + .unwrap_or_else(|e| { + eprintln!("error building sibling annex: {e}"); + std::process::exit(1); + }); rep.push(t.stop()); } @@ -104,7 +108,9 @@ pub fn run(args: PhyloArgs) { }); rep.push(t.stop()); - let path = args.output.as_ref() + let path = args + .output + .as_ref() .map(|p| format!("{}_siblings.csv", p.display())) .unwrap_or_else(|| "siblings.csv".into()); let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| { @@ -119,12 +125,19 @@ pub fn run(args: PhyloArgs) { // otherwise be counted once per genome it appears in). writeln!(f, "genome,1,2,3,4").unwrap(); for (label, counts) in labels.iter().zip(stats.per_genome.iter()) { - writeln!(f, "{label},{},{},{},{}", counts[0], counts[1], counts[2], counts[3]).unwrap(); + writeln!( + f, + "{label},{},{},{},{}", + counts[0], counts[1], counts[2], counts[3] + ) + .unwrap(); } writeln!( - f, "global,{},{},{},{}", + f, + "global,{},{},{},{}", stats.counts[0], stats.counts[1], stats.counts[2], stats.counts[3], - ).unwrap(); + ) + .unwrap(); info!("sibling-count distribution → {path}"); } @@ -137,7 +150,9 @@ pub fn run(args: PhyloArgs) { }); rep.push(t.stop()); - let path = args.output.as_ref() + let path = args + .output + .as_ref() .map(|p| format!("{}_sibling_hist.csv", p.display())) .unwrap_or_else(|| "sibling_hist.csv".into()); let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| { @@ -164,7 +179,9 @@ pub fn run(args: PhyloArgs) { }); rep.push(t.stop()); - let path = args.output.as_ref() + let path = args + .output + .as_ref() .map(|p| format!("{}_family_overlap.csv", p.display())) .unwrap_or_else(|| "family_overlap.csv".into()); let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| { @@ -172,11 +189,15 @@ pub fn run(args: PhyloArgs) { std::process::exit(1); })); write!(f, "genome").unwrap(); - for label in &labels { write!(f, ",{label}").unwrap(); } + for label in &labels { + write!(f, ",{label}").unwrap(); + } writeln!(f).unwrap(); for (i, label) in labels.iter().enumerate() { write!(f, "{label}").unwrap(); - for j in 0..n { write!(f, ",{}", overlap.get(i, j)).unwrap(); } + for j in 0..n { + write!(f, ",{}", overlap.get(i, j)).unwrap(); + } writeln!(f).unwrap(); } info!("family-overlap matrix → {path}"); @@ -184,30 +205,38 @@ pub fn run(args: PhyloArgs) { // ── Shannon entropy report (`--shannon`) ──────────────────────────────────── if args.annex.shannon { - let path = args.output.as_ref() + let path = args + .output + .as_ref() .map(|p| format!("{}_entropy.csv", p.display())) .unwrap_or_else(|| "entropy.csv".into()); info!("computing per-family Shannon entropy"); let t = Stage::start("shannon_entropy"); - cache.shannon_entropy_csv(std::path::Path::new(&path)).unwrap_or_else(|e| { - eprintln!("error computing Shannon entropy: {e}"); - std::process::exit(1); - }); + cache + .shannon_entropy_csv(std::path::Path::new(&path)) + .unwrap_or_else(|e| { + eprintln!("error computing Shannon entropy: {e}"); + std::process::exit(1); + }); rep.push(t.stop()); info!("entropy report → {path}"); } // ── Shannon entropy distribution (`--shannon-summary`) ────────────────────── if args.annex.shannon_summary { - let path = args.output.as_ref() + let path = args + .output + .as_ref() .map(|p| format!("{}_shannon_summary.csv", p.display())) .unwrap_or_else(|| "shannon_summary.csv".into()); info!("summarising per-family Shannon entropy"); let t = Stage::start("shannon_summary"); - cache.shannon_entropy_summary(std::path::Path::new(&path)).unwrap_or_else(|e| { - eprintln!("error summarising Shannon entropy: {e}"); - std::process::exit(1); - }); + cache + .shannon_entropy_summary(std::path::Path::new(&path)) + .unwrap_or_else(|e| { + eprintln!("error summarising Shannon entropy: {e}"); + std::process::exit(1); + }); rep.push(t.stop()); info!("entropy summary → {path}"); } @@ -287,7 +316,8 @@ pub fn run(args: PhyloArgs) { // instead of each running its own scan (which used to silently draw a // different sample per flag — see `obikphylo::siblings::LayerReducer`'s // own module docs). - let sankoff_requested = args.costs.sankoff || args.costs.tnt || args.costs.phyg || args.costs.iqtree; + let sankoff_requested = + args.costs.sankoff || args.costs.tnt || args.costs.phyg || args.costs.iqtree; let distance = distance_to_compute(args.dist.distance, args.dist.nj, args.dist.upgma); let snp_kind = distance.and_then(DistanceArg::as_snp); let need_alignment = args.alignment_output() || sankoff_requested; @@ -311,11 +341,13 @@ pub fn run(args: PhyloArgs) { std::process::exit(1); } - let mut alignment_reducer = - need_alignment.then(|| obikphylo::siblings::AlignmentReducer::new(&cache, &snp_exclude_mask)); + let mut alignment_reducer = need_alignment + .then(|| obikphylo::siblings::AlignmentReducer::new(&cache, &snp_exclude_mask)); let mut pairwise_reducer = need_pairwise.then(|| obikphylo::siblings::PairwiseReducer::new(n)); - let mut stats_reducer = - args.sample.sample_stats.then(|| obikphylo::siblings::SampleStatsReducer::new(n, &snp_exclude_mask)); + let mut stats_reducer = args + .sample + .sample_stats + .then(|| obikphylo::siblings::SampleStatsReducer::new(n, &snp_exclude_mask)); let mut sample_plan = None; if need_alignment || need_pairwise { @@ -339,11 +371,17 @@ pub fn run(args: PhyloArgs) { ); let t = Stage::start("sampled_scan"); sample_plan = Some( - obikphylo::siblings::sampled_scan(&cache, target, sampling, &snp_exclude_mask, &mut reducers) - .unwrap_or_else(|e| { - eprintln!("error sampling SNP sites: {e}"); - std::process::exit(1); - }), + obikphylo::siblings::sampled_scan( + &cache, + target, + sampling, + &snp_exclude_mask, + &mut reducers, + ) + .unwrap_or_else(|e| { + eprintln!("error sampling SNP sites: {e}"); + std::process::exit(1); + }), ); rep.push(t.stop()); } @@ -353,7 +391,10 @@ pub fn run(args: PhyloArgs) { write_sample_stats(&reducer.finish(), &labels, &snp_exclude_mask, &args.output); } if args.sample.sample_plan { - write_sample_plan(&sample_plan.expect("scanned above: need_alignment || need_pairwise"), &args.output); + write_sample_plan( + &sample_plan.expect("scanned above: need_alignment || need_pairwise"), + &args.output, + ); } // Finished once here (not left as reducers) so `--pseudo-alignment` @@ -376,7 +417,9 @@ pub fn run(args: PhyloArgs) { let mut bundle = None; if sankoff_requested { let alignment = alignment.clone().expect("scanned above: need_alignment"); - let pairwise = pairwise_reducer.take().expect("scanned above: need_pairwise"); + let pairwise = pairwise_reducer + .take() + .expect("scanned above: need_pairwise"); let b = obikphylo::siblings::SankoffBundle::finish( alignment, pairwise, @@ -434,10 +477,12 @@ pub fn run(args: PhyloArgs) { if args.dist.shared_kmers { info!("computing shared k-mer counts for {n} genome(s)"); let t = Stage::start("shared_kmers"); - let shared = cache.shared_kmers(args.dist.presence_threshold).unwrap_or_else(|e| { - eprintln!("error computing shared k-mer counts: {e}"); - std::process::exit(1); - }); + let shared = cache + .shared_kmers(args.dist.presence_threshold) + .unwrap_or_else(|e| { + eprintln!("error computing shared k-mer counts: {e}"); + std::process::exit(1); + }); rep.push(t.stop()); let kept: Vec = (0..n).filter(|&i| !exclude_mask[i]).collect(); write_shared_kmers(&shared, &labels, &kept, &args.output); @@ -467,7 +512,10 @@ pub fn run(args: PhyloArgs) { std::process::exit(1); } let kind = snp_kind.expect("DistanceArg is always classic or snp"); - let gamma_shape = args.dist.gamma_shape.map_or(GammaShape::Disabled, Into::into); + let gamma_shape = args + .dist + .gamma_shape + .map_or(GammaShape::Disabled, Into::into); let t = Stage::start("snp_distance"); let matrix = match &bundle { Some(b) => { @@ -501,7 +549,9 @@ pub fn run(args: PhyloArgs) { let write_dist = |w: &mut dyn Write| { if args.dist.csv { write!(w, "genome").unwrap(); - for &j in &kept { write!(w, ",{}", labels[j]).unwrap(); } + for &j in &kept { + write!(w, ",{}", labels[j]).unwrap(); + } writeln!(w).unwrap(); for &i in &kept { write!(w, "{}", labels[i]).unwrap(); @@ -517,7 +567,11 @@ pub fn run(args: PhyloArgs) { match &args.output { Some(prefix) => { - let suffix = if args.dist.csv { "_dist.csv" } else { "_dist.phy" }; + let suffix = if args.dist.csv { + "_dist.csv" + } else { + "_dist.phy" + }; let path = format!("{}{suffix}", prefix.display()); let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| { eprintln!("error creating {path}: {e}"); @@ -545,7 +599,9 @@ pub fn run(args: PhyloArgs) { std::process::exit(1); }); let newick = tree.to_newick(); - let path = args.output.as_ref() + let path = args + .output + .as_ref() .map(|p| format!("{}_nj.nwk", p.display())) .unwrap_or_else(|| "nj.nwk".into()); std::fs::write(&path, &newick).unwrap_or_else(|e| { @@ -558,7 +614,9 @@ pub fn run(args: PhyloArgs) { // ── UPGMA tree ─────────────────────────────────────────────────────────────── if args.dist.upgma { let newick = upgma(&matrix, &labels).to_newick(); - let path = args.output.as_ref() + let path = args + .output + .as_ref() .map(|p| format!("{}_upgma.nwk", p.display())) .unwrap_or_else(|| "upgma.nwk".into()); std::fs::write(&path, &newick).unwrap_or_else(|e| { diff --git a/src/obikmer/src/cmd/phylo/phyg.rs b/src/obikmer/src/cmd/phylo/phyg.rs index e746a4d9..dce80e98 100644 --- a/src/obikmer/src/cmd/phylo/phyg.rs +++ b/src/obikmer/src/cmd/phylo/phyg.rs @@ -18,17 +18,23 @@ use super::sankoff::{STATE_SYMBOL, scaled_metric_matrix}; // as the closest principled value for a state that, in practice, is never // actually triggered. -pub(super) fn write_sankoff_phyg(matrix: &[[f64; 16]; 16], output: &Option, cost_scale: f64) { +pub(super) fn write_sankoff_phyg( + matrix: &[[f64; 16]; 16], + output: &Option, + cost_scale: f64, +) { let scaled_matrix = scaled_metric_matrix(matrix, cost_scale); let basename = |suffix: &str| -> String { - output.as_ref() + output + .as_ref() .and_then(|p| p.file_name()) .map(|n| format!("{}{suffix}", n.to_string_lossy())) .unwrap_or_else(|| format!("sankoff{suffix}")) }; let full_path = |suffix: &str| -> String { - output.as_ref() + output + .as_ref() .map(|p| format!("{}{suffix}", p.display())) .unwrap_or_else(|| format!("sankoff{suffix}")) }; @@ -38,16 +44,37 @@ pub(super) fn write_sankoff_phyg(matrix: &[[f64; 16]; 16], output: &Option>().join(" "); + let alphabet_line = STATE_SYMBOL + .iter() + .map(|c| c.to_string()) + .collect::>() + .join(" "); writeln!(f, "{alphabet_line}").unwrap(); for i in 0..16 { let mut row: Vec = (0..16).map(|j| scaled_matrix[i][j]).collect(); row.push(scaled_matrix[i][0]); // gap column: same cost as to/from ∅ - writeln!(f, "{}", row.iter().map(|v| v.to_string()).collect::>().join(" ")).unwrap(); + writeln!( + f, + "{}", + row.iter() + .map(|v| v.to_string()) + .collect::>() + .join(" ") + ) + .unwrap(); } let mut gap_row: Vec = (0..16).map(|j| scaled_matrix[0][j]).collect(); gap_row.push(0); - writeln!(f, "{}", gap_row.iter().map(|v| v.to_string()).collect::>().join(" ")).unwrap(); + writeln!( + f, + "{}", + gap_row + .iter() + .map(|v| v.to_string()) + .collect::>() + .join(" ") + ) + .unwrap(); info!("PhyG TCM → {tcm_path}"); let pg_path = full_path("_sankoff.pg"); @@ -62,11 +89,13 @@ pub(super) fn write_sankoff_phyg(matrix: &[[f64; 16]; 16], output: &Option) { +pub(super) fn write_phylip_relaxed( + w: &mut dyn Write, + labels: &[String], + indices: &[usize], + matrix: &Array2, +) { writeln!(w, "{}", indices.len()).unwrap(); for &i in indices { write!(w, "{}", labels[i]).unwrap(); diff --git a/src/obikmer/src/cmd/phylo/sankoff.rs b/src/obikmer/src/cmd/phylo/sankoff.rs index 9168c80f..e67c91ab 100644 --- a/src/obikmer/src/cmd/phylo/sankoff.rs +++ b/src/obikmer/src/cmd/phylo/sankoff.rs @@ -29,7 +29,8 @@ pub(super) fn write_sankoff_alignment_fasta( output: &Option, free_loss: bool, ) { - let path = output.as_ref() + let path = output + .as_ref() .map(|p| format!("{}_sankoff.fasta", p.display())) .unwrap_or_else(|| "sankoff.fasta".into()); let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| { @@ -38,13 +39,25 @@ pub(super) fn write_sankoff_alignment_fasta( })); let absent_symbol = if free_loss { b'?' } else { b'0' }; let n_sites = alignment.sequences.first().map_or(0, Vec::len); - for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) { - let recoded: Vec = seq.iter().map(|&b| if b == b'-' { absent_symbol } else { b }).collect(); - write_record(&recoded, &labels[g], &[("n_sites", JsonVal::Num(n_sites as u64))], &mut f) - .unwrap_or_else(|e| { - eprintln!("error writing {path}: {e}"); - std::process::exit(1); - }); + for (&g, seq) in alignment + .genome_indices + .iter() + .zip(alignment.sequences.iter()) + { + let recoded: Vec = seq + .iter() + .map(|&b| if b == b'-' { absent_symbol } else { b }) + .collect(); + write_record( + &recoded, + &labels[g], + &[("n_sites", JsonVal::Num(n_sites as u64))], + &mut f, + ) + .unwrap_or_else(|e| { + eprintln!("error writing {path}: {e}"); + std::process::exit(1); + }); } info!("Sankoff pseudo-alignment ({n_sites} site(s)) → {path}"); } @@ -78,7 +91,8 @@ pub(super) fn state_index_table() -> [u8; 128] { } pub(super) fn write_sankoff_matrix_csv(matrix: &[[f64; 16]; 16], output: &Option) { - let path = output.as_ref() + let path = output + .as_ref() .map(|p| format!("{}_sankoff_matrix.csv", p.display())) .unwrap_or_else(|| "sankoff_matrix.csv".into()); let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| { @@ -86,11 +100,15 @@ pub(super) fn write_sankoff_matrix_csv(matrix: &[[f64; 16]; 16], output: &Option std::process::exit(1); })); write!(f, "state").unwrap(); - for sym in STATE_SYMBOL { write!(f, ",{sym}").unwrap(); } + for sym in STATE_SYMBOL { + write!(f, ",{sym}").unwrap(); + } writeln!(f).unwrap(); for (s, row) in matrix.iter().enumerate() { write!(f, "{}", STATE_SYMBOL[s]).unwrap(); - for cost in row { write!(f, ",{cost:.4}").unwrap(); } + for cost in row { + write!(f, ",{cost:.4}").unwrap(); + } writeln!(f).unwrap(); } info!("Sankoff cost matrix → {path}"); @@ -152,7 +170,11 @@ pub(super) fn write_sankoff_params( let mut composition_transitions = Vec::with_capacity(16); for a in 0..4 { for b in 0..4 { - let count = if a == b { base_tally.same[a] } else { base_tally.counts[a][b] }; + let count = if a == b { + base_tally.same[a] + } else { + base_tally.counts[a][b] + }; composition_transitions.push(CompositionTransition { from: BASE_LETTER[a], to: BASE_LETTER[b], @@ -162,9 +184,14 @@ pub(super) fn write_sankoff_params( } } - let report = SankoffParamsReport { ratio_ceiling, cardinality_transitions, composition_transitions }; + let report = SankoffParamsReport { + ratio_ceiling, + cardinality_transitions, + composition_transitions, + }; - let path = output.as_ref() + let path = output + .as_ref() .map(|p| format!("{}_sankoff_params.yaml", p.display())) .unwrap_or_else(|| "sankoff_params.yaml".into()); let f = std::fs::File::create(&path).unwrap_or_else(|e| { diff --git a/src/obikmer/src/cmd/phylo/stats.rs b/src/obikmer/src/cmd/phylo/stats.rs index ff2b326e..c49a4f3a 100644 --- a/src/obikmer/src/cmd/phylo/stats.rs +++ b/src/obikmer/src/cmd/phylo/stats.rs @@ -45,9 +45,17 @@ pub fn write_sample_stats( let path = output_path(output, "sample_genomes.csv"); let mut f = create(&path); - writeln!(f, "genome,excluded,sites_with_call,share_of_sites,informative_sites").unwrap(); + writeln!( + f, + "genome,excluded,sites_with_call,share_of_sites,informative_sites" + ) + .unwrap(); for g in 0..n { - let share = if stats.n_sites == 0 { 0.0 } else { stats.calls[g] as f64 / stats.n_sites as f64 }; + let share = if stats.n_sites == 0 { + 0.0 + } else { + stats.calls[g] as f64 / stats.n_sites as f64 + }; writeln!( f, "{},{},{},{:.6},{}", @@ -64,8 +72,11 @@ pub fn write_sample_stats( let path = output_path(output, "sample_carriers.csv"); let mut f = create(&path); writeln!(f, "n_carriers,sites,informative_sites").unwrap(); - for (carriers, (&sites, &informative)) in - stats.sites_by_carriers.iter().zip(&stats.informative_by_carriers).enumerate() + for (carriers, (&sites, &informative)) in stats + .sites_by_carriers + .iter() + .zip(&stats.informative_by_carriers) + .enumerate() { if sites > 0 { writeln!(f, "{carriers},{sites},{informative}").unwrap(); @@ -103,7 +114,13 @@ pub fn write_sample_plan(plan: &SamplePlan, output: &Option) { writeln!( f, "{},{},{},{:.6},{},{},{}", - layer.partition, layer.layer, layer.eligible, layer.mass, layer.quota, layer.resolved, layer.kept + layer.partition, + layer.layer, + layer.eligible, + layer.mass, + layer.quota, + layer.resolved, + layer.kept ) .unwrap(); } diff --git a/src/obikmer/src/cmd/phylo/tnt.rs b/src/obikmer/src/cmd/phylo/tnt.rs index e9aa45bc..c3c8f20a 100644 --- a/src/obikmer/src/cmd/phylo/tnt.rs +++ b/src/obikmer/src/cmd/phylo/tnt.rs @@ -45,7 +45,11 @@ pub(super) fn write_sankoff_tnt( let iupac_to_state = state_index_table(); let n_sites = alignment.sequences.first().map(|s| s.len()).unwrap_or(0); - let kept_labels: Vec<&String> = alignment.genome_indices.iter().map(|&g| &labels[g]).collect(); + let kept_labels: Vec<&String> = alignment + .genome_indices + .iter() + .map(|&g| &labels[g]) + .collect(); writeln!(f, "xread").unwrap(); writeln!(f, "mxram 16000;").unwrap(); writeln!(f, "taxname =;").unwrap(); diff --git a/src/obikmer/src/cmd/phylo/values.rs b/src/obikmer/src/cmd/phylo/values.rs index 45727a22..6fea4b3d 100644 --- a/src/obikmer/src/cmd/phylo/values.rs +++ b/src/obikmer/src/cmd/phylo/values.rs @@ -24,9 +24,11 @@ pub fn parse_gamma_shape(s: &str) -> Result { if s.eq_ignore_ascii_case("auto") || s.eq_ignore_ascii_case("estimate") { return Ok(GammaShapeArg::Auto); } - s.parse::() - .map(GammaShapeArg::Fixed) - .map_err(|_| format!("invalid --gamma-shape value {s:?}: expected a positive number or \"auto\"/\"estimate\"")) + s.parse::().map(GammaShapeArg::Fixed).map_err(|_| { + format!( + "invalid --gamma-shape value {s:?}: expected a positive number or \"auto\"/\"estimate\"" + ) + }) } /// `--n-sites` CLI value: a number of sites to draw, or `all` for every site @@ -54,9 +56,9 @@ pub fn parse_n_sites(s: &str) -> Result { if s.eq_ignore_ascii_case("all") { return Ok(NSitesArg::All); } - s.parse::() - .map(NSitesArg::N) - .map_err(|_| format!("invalid --n-sites value {s:?}: expected a non-negative integer or \"all\"")) + s.parse::().map(NSitesArg::N).map_err(|_| { + format!("invalid --n-sites value {s:?}: expected a non-negative integer or \"all\"") + }) } /// `--distance` value — either one of `obikphylo::DistanceMetric`'s @@ -103,7 +105,11 @@ pub enum DistanceArg { /// work from, else none — a matrix is never computed (nor written) just /// because nothing said otherwise. `--shared-kmers` asks for its own matrix, /// not for a distance. -pub fn distance_to_compute(distance: Option, nj: bool, upgma: bool) -> Option { +pub fn distance_to_compute( + distance: Option, + nj: bool, + upgma: bool, +) -> Option { distance.or_else(|| (nj || upgma).then_some(DistanceArg::Jaccard)) } @@ -119,7 +125,10 @@ mod distance_tests { #[test] fn tree_outputs_imply_jaccard() { for (nj, upgma) in [(true, false), (false, true)] { - assert!(matches!(distance_to_compute(None, nj, upgma), Some(DistanceArg::Jaccard))); + assert!(matches!( + distance_to_compute(None, nj, upgma), + Some(DistanceArg::Jaccard) + )); } } @@ -140,14 +149,14 @@ impl DistanceArg { /// `Some` for the whole-index metrics, `None` for `snp-*` values. pub fn as_classic(self) -> Option { Some(match self { - DistanceArg::Jaccard => DistanceMetric::Jaccard, - DistanceArg::Mash => DistanceMetric::Mash, - DistanceArg::Hamming => DistanceMetric::Hamming, - DistanceArg::BrayCurtis => DistanceMetric::BrayCurtis, - DistanceArg::RelfreqBrayCurtis => DistanceMetric::RelfreqBrayCurtis, - DistanceArg::Euclidean => DistanceMetric::Euclidean, - DistanceArg::RelfreqEuclidean => DistanceMetric::RelfreqEuclidean, - DistanceArg::Hellinger => DistanceMetric::Hellinger, + DistanceArg::Jaccard => DistanceMetric::Jaccard, + DistanceArg::Mash => DistanceMetric::Mash, + DistanceArg::Hamming => DistanceMetric::Hamming, + DistanceArg::BrayCurtis => DistanceMetric::BrayCurtis, + DistanceArg::RelfreqBrayCurtis => DistanceMetric::RelfreqBrayCurtis, + DistanceArg::Euclidean => DistanceMetric::Euclidean, + DistanceArg::RelfreqEuclidean => DistanceMetric::RelfreqEuclidean, + DistanceArg::Hellinger => DistanceMetric::Hellinger, DistanceArg::HellingerEuclidean => DistanceMetric::HellingerEuclidean, _ => return None, }) @@ -156,14 +165,14 @@ impl DistanceArg { /// `Some` for the `snp-*` values, `None` for the whole-index metrics. pub fn as_snp(self) -> Option { Some(match self { - DistanceArg::SnpRaw => SnpDistanceKind::Raw, - DistanceArg::SnpJc => SnpDistanceKind::Jc, - DistanceArg::SnpK2p => SnpDistanceKind::K2p, - DistanceArg::SnpK81 => SnpDistanceKind::K81, - DistanceArg::SnpF81 => SnpDistanceKind::F81, - DistanceArg::SnpT92 => SnpDistanceKind::T92, + DistanceArg::SnpRaw => SnpDistanceKind::Raw, + DistanceArg::SnpJc => SnpDistanceKind::Jc, + DistanceArg::SnpK2p => SnpDistanceKind::K2p, + DistanceArg::SnpK81 => SnpDistanceKind::K81, + DistanceArg::SnpF81 => SnpDistanceKind::F81, + DistanceArg::SnpT92 => SnpDistanceKind::T92, DistanceArg::SnpTn93 => SnpDistanceKind::Tn93, - DistanceArg::SnpTv => SnpDistanceKind::Tv, + DistanceArg::SnpTv => SnpDistanceKind::Tv, _ => return None, }) } diff --git a/src/obikmer/src/cmd/query/mod.rs b/src/obikmer/src/cmd/query/mod.rs index 26f5c811..72bbc056 100644 --- a/src/obikmer/src/cmd/query/mod.rs +++ b/src/obikmer/src/cmd/query/mod.rs @@ -10,7 +10,7 @@ use obikindex::KmerIndex; use obikindex::layer::IndexMode; use obikquery::process_chunk; use obikrope::Rope; -use obipipeline::{Throttled, ThrottleGuard, throttle}; +use obipipeline::{ThrottleGuard, Throttled, throttle}; use obiread::chunk::read_sequence_chunks_sized; use obisys::{Reporter, Stage, available_memory_bytes, spinner}; use tracing::{debug, info}; @@ -104,8 +104,8 @@ impl QueryArgs { /// so the guard (and the throttle slot it holds) is only released once the /// file has been fully read — never earlier, never held past that point. struct GuardedChunkIter { - inner: Box + Send>, - _guard: ThrottleGuard, + inner: Box + Send>, + _guard: ThrottleGuard, files_open: Arc, } @@ -216,7 +216,8 @@ pub fn run(args: QueryArgs) { let by_memory = computed.clamp(4 * 1024 * 1024, 256 * 1024 * 1024); match input_bytes { Some(total) => { - let by_parallelism = (total / (n_workers as u64 * CHUNKS_PER_WORKER)).max(MIN_CHUNK); + let by_parallelism = + (total / (n_workers as u64 * CHUNKS_PER_WORKER)).max(MIN_CHUNK); by_memory.min(by_parallelism) as usize } None => by_memory as usize, @@ -258,7 +259,11 @@ pub fn run(args: QueryArgs) { // Throttled iterator over input file paths: at most `effective_max_open()` // files are open at once. Opening + decompressing + chunking each file is // a Flat pipeline stage, executed across the `n_workers` pool. - info!("query: chunk_size={}MiB, max_open_files={}", chunk_bytes / (1024 * 1024), args.effective_max_open()); + info!( + "query: chunk_size={}MiB, max_open_files={}", + chunk_bytes / (1024 * 1024), + args.effective_max_open() + ); let paths: Vec = args.inputs.iter().map(PathBuf::from).collect(); let path_source = throttle(paths.into_iter(), args.effective_max_open()); @@ -355,13 +360,21 @@ pub fn run(args: QueryArgs) { last_bytes = total; let bp = total as f64; let (count_str, rate_str) = if bp >= 1e9 { - (format!("{:.2} GB", bp / 1e9), format!("{:.0} MB/s", ema_rate / 1e6)) + ( + format!("{:.2} GB", bp / 1e9), + format!("{:.0} MB/s", ema_rate / 1e6), + ) } else { - (format!("{:.0} MB", bp / 1e6), format!("{:.0} MB/s", ema_rate / 1e6)) + ( + format!("{:.0} MB", bp / 1e6), + format!("{:.0} MB/s", ema_rate / 1e6), + ) }; let active = chunks_active.load(Ordering::Relaxed); let open = files_open.load(Ordering::Relaxed); - pb.set_message(format!("{count_str} {rate_str} [files open: {open}, chunks in flight: {active}]")); + pb.set_message(format!( + "{count_str} {rate_str} [files open: {open}, chunks in flight: {active}]" + )); } } out.flush().expect("flush error"); diff --git a/src/obikmer/src/cmd/select/mod.rs b/src/obikmer/src/cmd/select/mod.rs index 5b5474d3..b26c3038 100644 --- a/src/obikmer/src/cmd/select/mod.rs +++ b/src/obikmer/src/cmd/select/mod.rs @@ -100,10 +100,16 @@ pub fn run(args: SelectArgs) { std::process::exit(1); }); - let group_preds: Vec<(String, String)> = - args.group.iter().map(|s| parse_name_value(s, "--group")).collect(); - let group_ops: Vec<(String, String)> = - args.group_op.iter().map(|s| parse_name_value(s, "--group-op")).collect(); + let group_preds: Vec<(String, String)> = args + .group + .iter() + .map(|s| parse_name_value(s, "--group")) + .collect(); + let group_ops: Vec<(String, String)> = args + .group_op + .iter() + .map(|s| parse_name_value(s, "--group-op")) + .collect(); let src_is_count = src.meta().config.with_counts; let (specs, output_presence) = build_output_cols( @@ -122,10 +128,14 @@ pub fn run(args: SelectArgs) { std::process::exit(1); }); - 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!( "select: {} genome(s) → {} output column(s), output={}", n_genomes, diff --git a/src/obikmer/src/cmd/unitig/mod.rs b/src/obikmer/src/cmd/unitig/mod.rs index cc1baf34..ec7e0075 100644 --- a/src/obikmer/src/cmd/unitig/mod.rs +++ b/src/obikmer/src/cmd/unitig/mod.rs @@ -32,15 +32,18 @@ pub fn run(args: UnitigArgs) { idx.kmer_size(), ); - let filters: Vec> = vec![Box::new(args.group_filter.build_filter(&idx.meta()))]; + let filters: Vec> = + vec![Box::new(args.group_filter.build_filter(&idx.meta()))]; let pb = progress_bar("unitig", idx.n_partitions() as u64, "partitions"); let mut out = BufWriter::new(io::stdout()); - let n = idx.write_unitigs(&mut out, &filters, || pb.inc(1)).unwrap_or_else(|e| { - eprintln!("unitig error: {e}"); - std::process::exit(1); - }); + let n = idx + .write_unitigs(&mut out, &filters, || pb.inc(1)) + .unwrap_or_else(|e| { + eprintln!("unitig error: {e}"); + std::process::exit(1); + }); pb.finish_and_clear(); info!("unitig: {n} unitig(s) written"); diff --git a/src/obikmer/src/cmd/utils/maintenance.rs b/src/obikmer/src/cmd/utils/maintenance.rs index 81aec0f3..8fbe76fc 100644 --- a/src/obikmer/src/cmd/utils/maintenance.rs +++ b/src/obikmer/src/cmd/utils/maintenance.rs @@ -16,10 +16,12 @@ pub(super) fn run_stats(index_path: &PathBuf) { std::process::exit(1); }); - let (total, per_genome) = GenomeKmerCounts::new(Arc::clone(&idx)).run().unwrap_or_else(|e| { - eprintln!("error computing stats: {e}"); - std::process::exit(1); - }); + let (total, per_genome) = GenomeKmerCounts::new(Arc::clone(&idx)) + .run() + .unwrap_or_else(|e| { + eprintln!("error computing stats: {e}"); + std::process::exit(1); + }); println!("genome,n_kmers"); for (g, &n) in genomes.iter().zip(per_genome.iter()) { @@ -83,10 +85,12 @@ pub(super) fn run_rename(index_path: &PathBuf, spec: &str) { std::process::exit(1); } - idx.meta().rename_genome(pos, new_label.clone()).unwrap_or_else(|e| { - eprintln!("error writing index metadata: {e}"); - std::process::exit(1); - }); + idx.meta() + .rename_genome(pos, new_label.clone()) + .unwrap_or_else(|e| { + eprintln!("error writing index metadata: {e}"); + std::process::exit(1); + }); let spectrums_dir = index_path.join("spectrums"); let old_spectrum = spectrums_dir.join(format!("{old_label}.json")); diff --git a/src/obikmer/src/cmd/utils/mod.rs b/src/obikmer/src/cmd/utils/mod.rs index fdba755b..4678121b 100644 --- a/src/obikmer/src/cmd/utils/mod.rs +++ b/src/obikmer/src/cmd/utils/mod.rs @@ -5,7 +5,7 @@ use std::path::PathBuf; use clap::Args; -use maintenance::{run_bits_per_kmer, run_stats, run_rename}; +use maintenance::{run_bits_per_kmer, run_rename, run_stats}; use partition_stats::run_partition_stats; #[derive(Args)] @@ -69,7 +69,10 @@ pub fn run(args: UtilsArgs) { fn single_index(args: &UtilsArgs) -> &PathBuf { if args.indexes.len() > 1 { - eprintln!("utils: this option requires exactly one index (got {})", args.indexes.len()); + eprintln!( + "utils: this option requires exactly one index (got {})", + args.indexes.len() + ); std::process::exit(1); } &args.indexes[0] diff --git a/src/obikmer/src/cmd/utils/partition_stats.rs b/src/obikmer/src/cmd/utils/partition_stats.rs index 6cf6de24..b0f55d0b 100644 --- a/src/obikmer/src/cmd/utils/partition_stats.rs +++ b/src/obikmer/src/cmd/utils/partition_stats.rs @@ -30,14 +30,21 @@ fn collect_rows(indexes: &[PathBuf]) -> Vec { }); for l in 0..n_layers { let p = idx.layer_unitigs_path(i, l).unwrap_or_else(|e| { - eprintln!("error reading layer {l} of partition {i} of {}: {e}", path.display()); + eprintln!( + "error reading layer {l} of partition {i} of {}: {e}", + path.display() + ); std::process::exit(1); }); if let Ok(m) = std::fs::metadata(&p) { bytes += m.len(); } } - rows.push(PartRow { partition: i, source: name.clone(), bytes }); + rows.push(PartRow { + partition: i, + source: name.clone(), + bytes, + }); } } rows @@ -106,7 +113,11 @@ fn ascii_histogram(totals: &[u64], n_buckets: usize, bar_width: usize) -> String for (i, &c) in counts.iter().enumerate() { let lo = min + (i as f64 * bucket_size) as u64; let hi = min + ((i + 1) as f64 * bucket_size) as u64; - let bar_len = if max_count > 0 { c * bar_width / max_count } else { 0 }; + let bar_len = if max_count > 0 { + c * bar_width / max_count + } else { + 0 + }; let bar = "█".repeat(bar_len); out.push_str(&format!( " {:>8} – {:>8} │{: { let ref0 = sources[0]; for src in sources { if src.state()? != IndexState::Indexed { - return Err(format!("{}: source index is not fully built", src.dir().display()).into()); + return Err( + format!("{}: source index is not fully built", src.dir().display()).into(), + ); } if src.kmer_size() != ref0.kmer_size() || src.minimizer_size() != ref0.minimizer_size() || src.n_partitions() != ref0.n_partitions() { - return Err("merge sources have incompatible k-mer size / minimizer size / partition count".into()); + return Err( + "merge sources have incompatible k-mer size / minimizer size / partition count" + .into(), + ); } if self.mode == MergeMode::Count && !src.meta().config.with_counts { return Err(format!( @@ -198,7 +203,11 @@ impl Algorithm for Merge<'_> { info!( "output evidence: {} ({}base: [{}] {})", format_evidence(&sources[base_idx].meta().config.evidence), - if needs_approx { "forced approx — " } else { "" }, + if needs_approx { + "forced approx — " + } else { + "" + }, base_idx, sources[base_idx].dir().display(), ); diff --git a/src/obikmerge/src/partition_merge/pass2.rs b/src/obikmerge/src/partition_merge/pass2.rs index 9fe78c23..aa1de49d 100644 --- a/src/obikmerge/src/partition_merge/pass2.rs +++ b/src/obikmerge/src/partition_merge/pass2.rs @@ -45,7 +45,6 @@ fn find_batch_grouped( (by_layer, not_found) } - // ── per-group pipeline ───────────────────────────────────────────────────── /// Pass 2 for one group of sources: stream each source layer's unitigs, @@ -268,4 +267,3 @@ pub(super) fn run_pass2( let new = new_locked.into_iter().map(unlock).collect(); Ok((exist, new)) } - diff --git a/src/obikphylo/src/distance.rs b/src/obikphylo/src/distance.rs index d1259634..b3a51907 100644 --- a/src/obikphylo/src/distance.rs +++ b/src/obikphylo/src/distance.rs @@ -79,7 +79,13 @@ impl AggregatedCount<'_> { self.cache.par_map_reduce( MAX_CONCURRENT_LAYERS, &identity, - |layer| if layer.content() == LayerContent::Count { per_layer(layer) } else { identity() }, + |layer| { + if layer.content() == LayerContent::Count { + per_layer(layer) + } else { + identity() + } + }, &combine, ) } @@ -92,7 +98,11 @@ impl ColumnWeights for AggregatedCount<'_> { } fn count_geq(&self, threshold: u32) -> Array1 { let n = self.n_genomes; - self.reduce(|| Array1::zeros(n), |l| l.count_geq(threshold), |a, b| a + b) + self.reduce( + || Array1::zeros(n), + |l| l.count_geq(threshold), + |a, b| a + b, + ) } } @@ -103,7 +113,11 @@ impl CountPartials for AggregatedCount<'_> { } fn partial_euclidean(&self) -> Array2 { let n = self.n_genomes; - self.reduce(|| Array2::zeros((n, n)), |l| l.partial_euclidean(), |a, b| a + b) + self.reduce( + || Array2::zeros((n, n)), + |l| l.partial_euclidean(), + |a, b| a + b, + ) } fn partial_threshold_jaccard(&self, threshold: u32) -> (Array2, Array2) { let n = self.n_genomes; @@ -115,15 +129,27 @@ impl CountPartials for AggregatedCount<'_> { } fn partial_relfreq_bray(&self, global: &Array1) -> Array2 { let n = self.n_genomes; - self.reduce(|| Array2::zeros((n, n)), |l| l.partial_relfreq_bray(global), |a, b| a + b) + self.reduce( + || Array2::zeros((n, n)), + |l| l.partial_relfreq_bray(global), + |a, b| a + b, + ) } fn partial_relfreq_euclidean(&self, global: &Array1) -> Array2 { let n = self.n_genomes; - self.reduce(|| Array2::zeros((n, n)), |l| l.partial_relfreq_euclidean(global), |a, b| a + b) + self.reduce( + || Array2::zeros((n, n)), + |l| l.partial_relfreq_euclidean(global), + |a, b| a + b, + ) } fn partial_hellinger(&self, global: &Array1) -> Array2 { let n = self.n_genomes; - self.reduce(|| Array2::zeros((n, n)), |l| l.partial_hellinger(global), |a, b| a + b) + self.reduce( + || Array2::zeros((n, n)), + |l| l.partial_hellinger(global), + |a, b| a + b, + ) } } @@ -142,7 +168,13 @@ impl AggregatedBit<'_> { self.cache.par_map_reduce( MAX_CONCURRENT_LAYERS, &identity, - |layer| if layer.content() == LayerContent::Presence { per_layer(layer) } else { identity() }, + |layer| { + if layer.content() == LayerContent::Presence { + per_layer(layer) + } else { + identity() + } + }, &combine, ) } @@ -155,7 +187,11 @@ impl ColumnWeights for AggregatedBit<'_> { } fn count_geq(&self, threshold: u32) -> Array1 { let n = self.n_genomes; - self.reduce(|| Array1::zeros(n), |l| l.count_geq(threshold), |a, b| a + b) + self.reduce( + || Array1::zeros(n), + |l| l.count_geq(threshold), + |a, b| a + b, + ) } } @@ -170,7 +206,11 @@ impl BitPartials for AggregatedBit<'_> { } fn partial_hamming(&self) -> Array2 { let n = self.n_genomes; - self.reduce(|| Array2::zeros((n, n)), |l| l.partial_hamming(), |a, b| a + b) + self.reduce( + || Array2::zeros((n, n)), + |l| l.partial_hamming(), + |a, b| a + b, + ) } } @@ -181,7 +221,12 @@ impl BitPartials for AggregatedBit<'_> { /// trait — same reasoning as every other `obikindex`/`obikidxcache` /// extension trait in this codebase. pub trait Metrics { - fn distance(&self, metric: DistanceMetric, shared_kmers: bool, presence_threshold: u32) -> OKIResult; + fn distance( + &self, + metric: DistanceMetric, + shared_kmers: bool, + presence_threshold: u32, + ) -> OKIResult; /// Genome-by-genome matrix of the number of k-mers shared by each pair of /// genomes — on a count index a k-mer is present when its count reaches @@ -199,14 +244,27 @@ impl Metrics for IndexCache { )); } let (inter, _union) = if self.meta().config().with_counts { - AggregatedCount { cache: self, n_genomes }.partial_threshold_jaccard(presence_threshold) + AggregatedCount { + cache: self, + n_genomes, + } + .partial_threshold_jaccard(presence_threshold) } else { - AggregatedBit { cache: self, n_genomes }.partial_jaccard() + AggregatedBit { + cache: self, + n_genomes, + } + .partial_jaccard() }; Ok(inter) } - fn distance(&self, metric: DistanceMetric, shared_kmers: bool, presence_threshold: u32) -> OKIResult { + fn distance( + &self, + metric: DistanceMetric, + shared_kmers: bool, + presence_threshold: u32, + ) -> OKIResult { use DistanceMetric::*; let n_genomes = self.meta().genomes().len(); @@ -218,28 +276,37 @@ impl Metrics for IndexCache { let kmer_size = self.meta().config().kmer_size; let use_counts = self.meta().config().with_counts; - let count = AggregatedCount { cache: self, n_genomes }; - let bit = AggregatedBit { cache: self, n_genomes }; + let count = AggregatedCount { + cache: self, + n_genomes, + }; + let bit = AggregatedBit { + cache: self, + n_genomes, + }; // One construction decides both what the index can serve and how: // the six count-based distances need a count index; Jaccard, Mash and // Hamming work on either (on counts, through the presence threshold). let matrix = match (use_counts, metric) { - (true, BrayCurtis) => count.bray_dist_matrix(), - (true, RelfreqBrayCurtis) => count.relfreq_bray_dist_matrix(), - (true, Euclidean) => count.euclidean_dist_matrix(), - (true, RelfreqEuclidean) => count.relfreq_euclidean_dist_matrix(), - (true, Hellinger) => count.hellinger_dist_matrix(), + (true, BrayCurtis) => count.bray_dist_matrix(), + (true, RelfreqBrayCurtis) => count.relfreq_bray_dist_matrix(), + (true, Euclidean) => count.euclidean_dist_matrix(), + (true, RelfreqEuclidean) => count.relfreq_euclidean_dist_matrix(), + (true, Hellinger) => count.hellinger_dist_matrix(), (true, HellingerEuclidean) => count.hellinger_euclidean_dist_matrix(), - (true, Jaccard) => count.threshold_jaccard_dist_matrix(presence_threshold), - (true, Mash) => count.threshold_mash_dist_matrix(kmer_size, presence_threshold), - (true, Hamming) => count.threshold_hamming_dist_matrix(presence_threshold).mapv(|v| v as f64), + (true, Jaccard) => count.threshold_jaccard_dist_matrix(presence_threshold), + (true, Mash) => count.threshold_mash_dist_matrix(kmer_size, presence_threshold), + (true, Hamming) => count + .threshold_hamming_dist_matrix(presence_threshold) + .mapv(|v| v as f64), (false, Jaccard) => bit.jaccard_dist_matrix(), - (false, Mash) => bit.mash_dist_matrix(kmer_size), + (false, Mash) => bit.mash_dist_matrix(kmer_size), (false, Hamming) => bit.hamming_dist_matrix().mapv(|v| v as f64), ( false, - BrayCurtis | RelfreqBrayCurtis | Euclidean | RelfreqEuclidean | Hellinger | HellingerEuclidean, + BrayCurtis | RelfreqBrayCurtis | Euclidean | RelfreqEuclidean | Hellinger + | HellingerEuclidean, ) => { return Err(OKIError::InvalidInput(format!( "{metric:?} requires a count index (with_counts = true); \ @@ -248,8 +315,13 @@ impl Metrics for IndexCache { } }; - let shared = shared_kmers.then(|| self.shared_kmers(presence_threshold)).transpose()?; + let shared = shared_kmers + .then(|| self.shared_kmers(presence_threshold)) + .transpose()?; - Ok(DistanceOutput { matrix, shared_kmers: shared }) + Ok(DistanceOutput { + matrix, + shared_kmers: shared, + }) } } diff --git a/src/obikphylo/src/lib.rs b/src/obikphylo/src/lib.rs index 8610d84b..68c66ccb 100644 --- a/src/obikphylo/src/lib.rs +++ b/src/obikphylo/src/lib.rs @@ -26,8 +26,8 @@ mod distance; pub mod karlin; -mod tree; pub mod siblings; +mod tree; pub use distance::{DistanceMetric, DistanceOutput, Metrics}; pub use siblings::{GammaShape, SnpDistanceKind}; diff --git a/src/obikphylo/src/siblings/algorithms/alignment.rs b/src/obikphylo/src/siblings/algorithms/alignment.rs index 5a0392a7..4577bff9 100644 --- a/src/obikphylo/src/siblings/algorithms/alignment.rs +++ b/src/obikphylo/src/siblings/algorithms/alignment.rs @@ -66,11 +66,19 @@ impl AlignmentReducer { .filter(|&g| !excluded.get(g).copied().unwrap_or(false)) .collect(); let sequences = vec![Vec::new(); genome_indices.len()]; - Self { genome_indices, sequences, sites: Vec::new() } + Self { + genome_indices, + sequences, + sites: Vec::new(), + } } pub fn finish(self) -> SnpAlignment { - SnpAlignment { sequences: self.sequences, genome_indices: self.genome_indices, sites: self.sites } + SnpAlignment { + sequences: self.sequences, + genome_indices: self.genome_indices, + sites: self.sites, + } } } @@ -90,7 +98,11 @@ impl LayerReducer for AlignmentReducer { /// (no sampling/masking logic of its own, just character encoding over /// `family.masked`, already computed upstream), the actual reduce /// [`AlignmentReducer`] wraps. -fn reduce_alignment(survivors: &[SurvivingFamily], genome_indices: &[usize], sequences: &mut [Vec]) { +fn reduce_alignment( + survivors: &[SurvivingFamily], + genome_indices: &[usize], + sequences: &mut [Vec], +) { for family in survivors { for (row, &g) in genome_indices.iter().enumerate() { let ch = family.masked[g].map(iupac_code).unwrap_or(b'?'); diff --git a/src/obikphylo/src/siblings/algorithms/alignment_vcf.rs b/src/obikphylo/src/siblings/algorithms/alignment_vcf.rs index 66ac58fe..b2496326 100644 --- a/src/obikphylo/src/siblings/algorithms/alignment_vcf.rs +++ b/src/obikphylo/src/siblings/algorithms/alignment_vcf.rs @@ -47,7 +47,13 @@ fn base_index(cell: u8) -> Option { /// than the ploidy allows, or `?`, is missing. fn cell_alleles(cell: u8, diploid: bool) -> Option<[u8; 2]> { let state = iupac_state(cell)?; - let allele = |bit: u8| if bit == 0 { ABSENT } else { BASES[bit.trailing_zeros() as usize] }; + let allele = |bit: u8| { + if bit == 0 { + ABSENT + } else { + BASES[bit.trailing_zeros() as usize] + } + }; match state.count_ones() { 0 => Some([ABSENT, ABSENT]), 1 => Some([allele(state), allele(state)]), @@ -74,12 +80,20 @@ impl SnpAlignment { /// `REF` is the per-site majority allele (each allele copy counted once). /// Returns the number of sites written: a site with no base among its /// calls has no `REF` to report and is skipped. - pub fn write_vcf(&self, labels: &[String], diploid: bool, out: &mut W) -> io::Result { + pub fn write_vcf( + &self, + labels: &[String], + diploid: bool, + out: &mut W, + ) -> io::Result { let n_sites = self.sequences.first().map_or(0, Vec::len); if self.sites.len() != n_sites { return Err(io::Error::new( io::ErrorKind::InvalidInput, - format!("alignment has {n_sites} column(s) but {} site locus record(s)", self.sites.len()), + format!( + "alignment has {n_sites} column(s) but {} site locus record(s)", + self.sites.len() + ), )); } let mut order: Vec = (0..n_sites).collect(); @@ -98,8 +112,15 @@ impl SnpAlignment { last = Some((s.partition, s.layer)); } } - writeln!(out, "##ALT=")?; - writeln!(out, "##FORMAT=", if diploid { "diploid" } else { "haploid" })?; + writeln!( + out, + "##ALT=" + )?; + writeln!( + out, + "##FORMAT=", + if diploid { "diploid" } else { "haploid" } + )?; write!(out, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT")?; for &g in &self.genome_indices { write!(out, "\t{}", labels[g])?; @@ -112,7 +133,11 @@ impl SnpAlignment { let copies = if diploid { 2 } else { 1 }; for &j in &order { calls.clear(); - calls.extend(self.sequences.iter().map(|seq| cell_alleles(seq[j], diploid))); + calls.extend( + self.sequences + .iter() + .map(|seq| cell_alleles(seq[j], diploid)), + ); let mut counts = [0usize; 4]; let mut absent = false; for call in calls.iter().flatten() { @@ -127,7 +152,11 @@ impl SnpAlignment { continue; }; let mut alleles = vec![BASES[ref_base]]; - alleles.extend((0..4).filter(|&b| b != ref_base && counts[b] > 0).map(|b| BASES[b])); + alleles.extend( + (0..4) + .filter(|&b| b != ref_base && counts[b] > 0) + .map(|b| BASES[b]), + ); if absent { alleles.push(ABSENT); } @@ -135,7 +164,13 @@ impl SnpAlignment { let s = &self.sites[j]; locus.clear(); CanonicalKmer::from_raw_unchecked(s.family_id).write_family_id_ascii(&mut locus)?; - write!(out, "obikmer_{}_{}\t{}\t", s.partition, s.layer, s.family_idx + 1)?; + write!( + out, + "obikmer_{}_{}\t{}\t", + s.partition, + s.layer, + s.family_idx + 1 + )?; out.write_all(&locus)?; write!(out, "\t{}\t", alleles[0] as char)?; if alleles.len() == 1 { @@ -156,7 +191,9 @@ impl SnpAlignment { for call in &calls { let idx = |a: u8| alleles.iter().position(|&x| x == a); match call.map(|c| (idx(c[0]), idx(c[1]))) { - Some((Some(x), Some(y))) if diploid => write!(out, "\t{}/{}", x.min(y), x.max(y))?, + Some((Some(x), Some(y))) if diploid => { + write!(out, "\t{}/{}", x.min(y), x.max(y))? + } Some((Some(x), _)) => write!(out, "\t{x}")?, _ => out.write_all(if diploid { b"\t./." } else { b"\t." })?, } @@ -185,7 +222,12 @@ mod tests { // Same global k as the crate's other tests (`siblingannex.rs`): the // global is process-wide here, so it must not conflict. obikseq::params::set_k(11); - SiteLocus { partition, layer, family_idx, family_id: 0 } + SiteLocus { + partition, + layer, + family_idx, + family_id: 0, + } } fn first_record(a: &SnpAlignment) -> Vec { @@ -238,7 +280,10 @@ mod tests { #[test] fn iupac_state_inverts_iupac_code() { for state in 0u8..16 { - assert_eq!(iupac_state(super::super::masking::iupac_code(state)), Some(state)); + assert_eq!( + iupac_state(super::super::masking::iupac_code(state)), + Some(state) + ); } assert_eq!(iupac_state(b'?'), None); } diff --git a/src/obikphylo/src/siblings/algorithms/cardcomp.rs b/src/obikphylo/src/siblings/algorithms/cardcomp.rs index 6bda4f49..c3c746e5 100644 --- a/src/obikphylo/src/siblings/algorithms/cardcomp.rs +++ b/src/obikphylo/src/siblings/algorithms/cardcomp.rs @@ -97,7 +97,11 @@ fn for_each_injection(small_len: usize, large_len: usize, visit: &mut dyn FnMut( /// *not* charged here — they're pure cardinality change, already priced by /// `P_cardinality(|A|→|B|)` in the caller. fn best_pairing_cost(lost: &[u8], gained: &[u8], p_comp: &[[f64; 4]; 4]) -> f64 { - let (small, large) = if lost.len() <= gained.len() { (lost, gained) } else { (gained, lost) }; + let (small, large) = if lost.len() <= gained.len() { + (lost, gained) + } else { + (gained, lost) + }; if small.is_empty() { return 0.0; } @@ -152,15 +156,23 @@ pub fn pairwise_cost_matrix( for a in 0u8..16 { for b in 0u8..16 { let shared = a & b; - let lost: Vec = (0..4).filter(|&i| a & (1 << i) != 0 && b & (1 << i) == 0).collect(); - let gained: Vec = (0..4).filter(|&i| b & (1 << i) != 0 && a & (1 << i) == 0).collect(); + let lost: Vec = (0..4) + .filter(|&i| a & (1 << i) != 0 && b & (1 << i) == 0) + .collect(); + let gained: Vec = (0..4) + .filter(|&i| b & (1 << i) != 0 && a & (1 << i) == 0) + .collect(); let mut lp = 0.0; // accumulate ln(P), so 0.0 = probability 1 if !free_loss { let card_a = a.count_ones() as usize; let card_b = b.count_ones() as usize; let p_c = p_card[card_a][card_b]; - lp += if p_c > 0.0 { p_c.ln() } else { f64::NEG_INFINITY }; + lp += if p_c > 0.0 { + p_c.ln() + } else { + f64::NEG_INFINITY + }; } for i in 0..4u8 { @@ -193,7 +205,12 @@ pub fn pairwise_cost_matrix( cost[a] = [f64::INFINITY; 16]; continue; } - let log_sum = row_max + log_p[a].iter().map(|&lp| (lp - row_max).exp()).sum::().ln(); + let log_sum = row_max + + log_p[a] + .iter() + .map(|&lp| (lp - row_max).exp()) + .sum::() + .ln(); for b in 0..16 { // `log_sum - log_p[a][b]` is `+∞` automatically when // `log_p[a][b] == -∞` (IEEE 754: finite − (−∞) = +∞) — no @@ -208,7 +225,11 @@ pub fn pairwise_cost_matrix( let mut sym = [[0.0f64; 16]; 16]; for a in 0..16 { for b in 0..16 { - sym[a][b] = if a == b { 0.0 } else { (cost[a][b] + cost[b][a]) / 2.0 }; + sym[a][b] = if a == b { + 0.0 + } else { + (cost[a][b] + cost[b][a]) / 2.0 + }; } } sym @@ -234,7 +255,10 @@ mod tests { #[test] fn composition_probs_include_diagonal() { - let mut tally = BasePairTally { counts: [[0u64; 4]; 4], same: [0u64; 4] }; + let mut tally = BasePairTally { + counts: [[0u64; 4]; 4], + same: [0u64; 4], + }; tally.same[0] = 90; // A stays A 90 times tally.counts[0][1] = 10; // A -> C 10 times tally.counts[1][0] = 10; @@ -266,7 +290,12 @@ mod tests { for a in 0..16 { assert_eq!(cost[a][a], 0.0); for b in 0..16 { - assert!((cost[a][b] - cost[b][a]).abs() < 1e-9, "cost[{a}][{b}]={} cost[{b}][{a}]={}", cost[a][b], cost[b][a]); + assert!( + (cost[a][b] - cost[b][a]).abs() < 1e-9, + "cost[{a}][{b}]={} cost[{b}][{a}]={}", + cost[a][b], + cost[b][a] + ); } } } @@ -297,7 +326,8 @@ mod tests { assert!( (cost_uniform[a][b] - cost_skewed[a][b]).abs() < 1e-9, "cost[{a}][{b}] differs between cardinality models under free_loss: {} vs {}", - cost_uniform[a][b], cost_skewed[a][b], + cost_uniform[a][b], + cost_skewed[a][b], ); } } diff --git a/src/obikphylo/src/siblings/algorithms/entropy.rs b/src/obikphylo/src/siblings/algorithms/entropy.rs index 52cd09db..0edc1780 100644 --- a/src/obikphylo/src/siblings/algorithms/entropy.rs +++ b/src/obikphylo/src/siblings/algorithms/entropy.rs @@ -21,7 +21,10 @@ pub(crate) fn family_entropy(genome_mask: &[u8]) -> Option<(f64, usize)> { /// [`family_entropy`] over the genomes `policy` keeps as carriers /// ([`is_carrier`]). -pub(crate) fn family_entropy_with(genome_mask: &[u8], policy: AmbiguityPolicy) -> Option<(f64, usize)> { +pub(crate) fn family_entropy_with( + genome_mask: &[u8], + policy: AmbiguityPolicy, +) -> Option<(f64, usize)> { let mut freq = [0u32; 16]; // index 0 (∅) never incremented, kept for direct `m as usize` indexing let mut present = 0u32; for &m in genome_mask { @@ -145,11 +148,13 @@ mod tests { /// members (ten states), the others being missing data. /// /// Second value: the number of genomes the entropy was computed over. -pub(crate) fn family_entropy_under(genome_mask: &[u8], policy: AmbiguityPolicy) -> Option<(f64, usize)> { +pub(crate) fn family_entropy_under( + genome_mask: &[u8], + policy: AmbiguityPolicy, +) -> Option<(f64, usize)> { match policy { AmbiguityPolicy::Keep => family_entropy(genome_mask), AmbiguityPolicy::Forbid => family_entropy_4(genome_mask), AmbiguityPolicy::OnlyDiploid => family_entropy_with(genome_mask, policy), } } - diff --git a/src/obikphylo/src/siblings/algorithms/entropy_scan.rs b/src/obikphylo/src/siblings/algorithms/entropy_scan.rs index 0f19d8c6..36ab902b 100644 --- a/src/obikphylo/src/siblings/algorithms/entropy_scan.rs +++ b/src/obikphylo/src/siblings/algorithms/entropy_scan.rs @@ -132,19 +132,32 @@ impl EntropySummary { pub(crate) fn add(&mut self, row: &FamilyEntropyRow) { *self .counts - .entry((Which::Entropy15, row.n_present, row.n_unambiguous, Self::bin(row.entropy15))) + .entry(( + Which::Entropy15, + row.n_present, + row.n_unambiguous, + Self::bin(row.entropy15), + )) .or_default() += 1; // `entropy4` is not defined without a genome carrying exactly one member if row.n_unambiguous > 0 { *self .counts - .entry((Which::Entropy4, row.n_present, row.n_unambiguous, Self::bin(row.entropy4))) + .entry(( + Which::Entropy4, + row.n_present, + row.n_unambiguous, + Self::bin(row.entropy4), + )) .or_default() += 1; } } pub(crate) fn write(&self, w: &mut impl Write) -> io::Result<()> { - writeln!(w, "entropy,n_genomes_present,n_genomes_unambiguous,bin_start,n_families")?; + writeln!( + w, + "entropy,n_genomes_present,n_genomes_unambiguous,bin_start,n_families" + )?; for (&(which, present, unambiguous, bin), &count) in &self.counts { let name = match which { Which::Entropy15 => "entropy15", @@ -164,7 +177,12 @@ impl EntropySummary { mod tests { use super::*; - fn row(entropy15: f64, entropy4: f64, n_present: usize, n_unambiguous: usize) -> FamilyEntropyRow { + fn row( + entropy15: f64, + entropy4: f64, + n_present: usize, + n_unambiguous: usize, + ) -> FamilyEntropyRow { FamilyEntropyRow { partition: 0, layer: 0, @@ -180,7 +198,11 @@ mod tests { fn written(summary: &EntropySummary) -> Vec { let mut buf = Vec::new(); summary.write(&mut buf).unwrap(); - String::from_utf8(buf).unwrap().lines().map(str::to_owned).collect() + String::from_utf8(buf) + .unwrap() + .lines() + .map(str::to_owned) + .collect() } #[test] @@ -190,7 +212,10 @@ mod tests { s.add(&row(1.02, 1.02, 4, 4)); // same 0.05 bin as 1.0 s.add(&row(0.2, 0.2, 4, 4)); let lines = written(&s); - assert_eq!(lines[0], "entropy,n_genomes_present,n_genomes_unambiguous,bin_start,n_families"); + assert_eq!( + lines[0], + "entropy,n_genomes_present,n_genomes_unambiguous,bin_start,n_families" + ); assert!(lines.contains(&"entropy15,4,4,1.00,2".to_string())); assert!(lines.contains(&"entropy15,4,4,0.20,1".to_string())); assert!(lines.contains(&"entropy4,4,4,1.00,2".to_string())); diff --git a/src/obikphylo/src/siblings/algorithms/family_annexes.rs b/src/obikphylo/src/siblings/algorithms/family_annexes.rs index 5fa36aa7..e4375972 100644 --- a/src/obikphylo/src/siblings/algorithms/family_annexes.rs +++ b/src/obikphylo/src/siblings/algorithms/family_annexes.rs @@ -58,11 +58,20 @@ pub struct AnnexSelection { impl AnnexSelection { pub(crate) fn request(&self) -> AnnexRequest { - let one = |wanted: bool| if wanted { vec![self.policy] } else { Vec::new() }; + let one = |wanted: bool| { + if wanted { + vec![self.policy] + } else { + Vec::new() + } + }; AnnexRequest { entropy: one(self.entropy), quartet: if self.quartet { - vec![QuartetConvention { policy: self.policy, free_loss: self.free_loss }] + vec![QuartetConvention { + policy: self.policy, + free_loss: self.free_loss, + }] } else { Vec::new() }, @@ -88,17 +97,27 @@ impl AnnexRequest { /// per-file existence test the builders apply, so `true` means they would /// find nothing to build and no lock is needed. Cheap (no file is opened). pub(crate) fn is_satisfied(&self, cache: &IndexCache) -> bool { - let overlap = self - .overlap_conventions() - .into_iter() - .all(|p| cache.index().dir().join(family_overlap_file_name(p)).exists()); + let overlap = self.overlap_conventions().into_iter().all(|p| { + cache + .index() + .dir() + .join(family_overlap_file_name(p)) + .exists() + }); let pair_weight = self.pair_weight_conventions(); overlap && cache.iter_indexed().all(|(_, _, layer)| { let has = |name: &str| layer.dir().join(name).exists(); - self.entropy.iter().all(|&p| has(ScalarKind::Entropy.file_name(p))) - && self.quartet.iter().all(|&p| has(quartet_annex_file_name(p))) - && pair_weight.iter().all(|&p| has(ScalarKind::PairWeight.file_name(p))) + self.entropy + .iter() + .all(|&p| has(ScalarKind::Entropy.file_name(p))) + && self + .quartet + .iter() + .all(|&p| has(quartet_annex_file_name(p))) + && pair_weight + .iter() + .all(|&p| has(ScalarKind::PairWeight.file_name(p))) }) } @@ -153,8 +172,11 @@ pub(crate) fn ensure_layer_family_annexes( let layer = cache .get_layer(partition, layer_idx) .expect("cache-consistent: caller already bounds layer_idx by n_layer(partition)"); - let missing_entropy = - missing_files(layer.dir(), |p| ScalarKind::Entropy.file_name(p), &request.entropy); + let missing_entropy = missing_files( + layer.dir(), + |p| ScalarKind::Entropy.file_name(p), + &request.entropy, + ); let missing_quartet = missing_files(layer.dir(), quartet_annex_file_name, &request.quartet); if missing_entropy.is_empty() && missing_quartet.is_empty() && overlap_accs.is_empty() { return Ok(()); @@ -235,7 +257,12 @@ pub(crate) fn ensure_layer_pair_weight_annexes( .expect("cache-consistent: caller already bounds layer_idx by n_layer(partition)"); let pending: Vec<&(AmbiguityPolicy, Vec)> = matrices .iter() - .filter(|(policy, _)| !layer.dir().join(ScalarKind::PairWeight.file_name(*policy)).exists()) + .filter(|(policy, _)| { + !layer + .dir() + .join(ScalarKind::PairWeight.file_name(*policy)) + .exists() + }) .collect(); if pending.is_empty() { return Ok(()); diff --git a/src/obikphylo/src/siblings/algorithms/family_scan.rs b/src/obikphylo/src/siblings/algorithms/family_scan.rs index 79a1dd82..ca7ecba6 100644 --- a/src/obikphylo/src/siblings/algorithms/family_scan.rs +++ b/src/obikphylo/src/siblings/algorithms/family_scan.rs @@ -175,16 +175,24 @@ pub(crate) fn scan_layer_families( // 'static`, so it can move into the pipeline workers below without // reopening/re-mmap'ing anything (see the module docs and // `IndexCache::get_layer_arc`'s own). - let mat = cache.get_layer(source_partition, source_layer).ok_or_else(|| { - OKIError::InvalidInput(format!( - "layer {source_layer} of partition {source_partition} not in this cache" - )) - })?; + let mat = cache + .get_layer(source_partition, source_layer) + .ok_or_else(|| { + OKIError::InvalidInput(format!( + "layer {source_layer} of partition {source_partition} not in this cache" + )) + })?; let n_cols = mat.n_cols().min(n_genomes); let layer_dir: &Path = mat.dir(); let annex = Arc::new(SiblingAnnex::open_in(layer_dir).map_err(OKIError::Io)?); - let ctx = Arc::new(LayerCtx { mat, n_parts, n_genomes, n_cols, k }); + let ctx = Arc::new(LayerCtx { + mat, + n_parts, + n_genomes, + n_cols, + k, + }); // Streamed straight from `iter_minorants_batch` (zips this layer's own // `iter_kmers()` with the annex, both in iteration order — never an diff --git a/src/obikphylo/src/siblings/algorithms/masking.rs b/src/obikphylo/src/siblings/algorithms/masking.rs index 638a7e9b..929637af 100644 --- a/src/obikphylo/src/siblings/algorithms/masking.rs +++ b/src/obikphylo/src/siblings/algorithms/masking.rs @@ -91,7 +91,11 @@ pub(crate) fn has_bipartition(counts: &[u32; 16]) -> bool { /// `true` is only a necessary condition, re-checked exactly by /// [`survives_quartet`] once the family is resolved. This is what the /// persisted quartet annex stores. -pub(crate) fn is_quartet_informative(genome_mask: &[u8], policy: AmbiguityPolicy, free_loss: bool) -> bool { +pub(crate) fn is_quartet_informative( + genome_mask: &[u8], + policy: AmbiguityPolicy, + free_loss: bool, +) -> bool { let mut counts = [0u32; 16]; for &m in genome_mask { if let Some(state) = masked_state(m, free_loss, policy) { @@ -128,8 +132,16 @@ mod quartet_tests { #[test] fn two_pairs_of_distinct_states_is_informative() { for free_loss in [true, false] { - assert!(is_quartet_informative(&[0b0001, 0b0001, 0b0100, 0b0100], KEEP, free_loss)); - assert!(is_quartet_informative(&[0b0001, 0b0001, 0b0100, 0b0100], FORBID, free_loss)); + assert!(is_quartet_informative( + &[0b0001, 0b0001, 0b0100, 0b0100], + KEEP, + free_loss + )); + assert!(is_quartet_informative( + &[0b0001, 0b0001, 0b0100, 0b0100], + FORBID, + free_loss + )); } } @@ -137,10 +149,22 @@ mod quartet_tests { fn singleton_variant_is_not_informative() { for free_loss in [true, false] { // three genomes in one state plus one lone variant: fits any topology - assert!(!is_quartet_informative(&[0b0001, 0b0001, 0b0001, 0b0100], KEEP, free_loss)); + assert!(!is_quartet_informative( + &[0b0001, 0b0001, 0b0001, 0b0100], + KEEP, + free_loss + )); // fewer than four genomes with a state can never be informative - assert!(!is_quartet_informative(&[0b0001, 0b0100, 0, 0], KEEP, free_loss)); - assert!(!is_quartet_informative(&[0b0001, 0b0001, 0b0100], KEEP, free_loss)); + assert!(!is_quartet_informative( + &[0b0001, 0b0100, 0, 0], + KEEP, + free_loss + )); + assert!(!is_quartet_informative( + &[0b0001, 0b0001, 0b0100], + KEEP, + free_loss + )); } } @@ -155,7 +179,11 @@ mod quartet_tests { // A A ∅ ∅ separates two pairs of genomes once ∅ is a character state assert!(is_quartet_informative(&[0b0001, 0b0001, 0, 0], KEEP, false)); // ... but a single absent genome is a lone state, like any singleton - assert!(!is_quartet_informative(&[0b0001, 0b0001, 0b0001, 0], KEEP, false)); + assert!(!is_quartet_informative( + &[0b0001, 0b0001, 0b0001, 0], + KEEP, + false + )); } #[test] @@ -182,8 +210,14 @@ mod quartet_tests { fn the_annex_rule_and_the_exact_check_agree_on_the_same_family() { let raw = [0b0001u8, 0b0001, 0, 0]; for free_loss in [true, false] { - let masked: Vec<_> = raw.iter().map(|&m| masked_state(m, free_loss, KEEP)).collect(); - assert_eq!(is_quartet_informative(&raw, KEEP, free_loss), survives_quartet(&masked, &[])); + let masked: Vec<_> = raw + .iter() + .map(|&m| masked_state(m, free_loss, KEEP)) + .collect(); + assert_eq!( + is_quartet_informative(&raw, KEEP, free_loss), + survives_quartet(&masked, &[]) + ); } } } @@ -254,7 +288,9 @@ mod tests { /// [`survives_masking`]. fn masked(raw: &[u8], free_loss: bool, no_ambiguity: bool) -> Vec> { let policy = AmbiguityPolicy::from_flags(no_ambiguity, false); - raw.iter().map(|&m| masked_state(m, free_loss, policy)).collect() + raw.iter() + .map(|&m| masked_state(m, free_loss, policy)) + .collect() } #[test] @@ -289,8 +325,14 @@ mod tests { // carries only A. Without no-ambiguity: 2 distinct states (0b0011, // 0b0001) -> survives. With no-ambiguity: genome 0 becomes "?", // only one real state left -> collapses. - assert!(survives_masking(&masked(&[0b0011, 0b0001], false, false), &[])); - assert!(!survives_masking(&masked(&[0b0011, 0b0001], false, true), &[])); + assert!(survives_masking( + &masked(&[0b0011, 0b0001], false, false), + &[] + )); + assert!(!survives_masking( + &masked(&[0b0011, 0b0001], false, true), + &[] + )); } #[test] diff --git a/src/obikphylo/src/siblings/algorithms/minorant_selection.rs b/src/obikphylo/src/siblings/algorithms/minorant_selection.rs index 79e621c5..9347f0d3 100644 --- a/src/obikphylo/src/siblings/algorithms/minorant_selection.rs +++ b/src/obikphylo/src/siblings/algorithms/minorant_selection.rs @@ -35,7 +35,9 @@ pub(crate) fn non_monomorphic_reindex_layer(layer_dir: &Path) -> OKIResult OKIResult OKIResult + use<>> { let annex = SiblingAnnex::open_in(layer_dir).map_err(OKIError::Io)?; - let scalars = - FamilyScalarAnnex::open(&layer_dir.join(kind.file_name(policy)), kind).map_err(OKIError::Io)?; + let scalars = FamilyScalarAnnex::open(&layer_dir.join(kind.file_name(policy)), kind) + .map_err(OKIError::Io)?; if scalars.policy() != policy { return Err(OKIError::Io(std::io::Error::new( std::io::ErrorKind::InvalidData, - format!("{kind:?} annex was built under {:?}, not {policy:?}", scalars.policy()), + format!( + "{kind:?} annex was built under {:?}, not {policy:?}", + scalars.policy() + ), ))); } diff --git a/src/obikphylo/src/siblings/algorithms/mod.rs b/src/obikphylo/src/siblings/algorithms/mod.rs index 197e0f34..c38cb4f7 100644 --- a/src/obikphylo/src/siblings/algorithms/mod.rs +++ b/src/obikphylo/src/siblings/algorithms/mod.rs @@ -40,11 +40,11 @@ pub use cardcomp::{ cardinality_transition_probs, composition_transition_probs, pairwise_cost_matrix, }; pub use pairwise::{BasePairTally, CardinalityTally, PairwiseReducer, RawSnpDistanceOutput}; +pub use sample_stats::{SampleStats, SampleStatsReducer}; pub use sankoff::SankoffBundle; pub use scan::{LayerReducer, sampled_scan}; pub use snp_distance::{GammaShape, SnpDistanceKind, distance_matrix}; pub use stats::SiblingAnnexStats; -pub use sample_stats::{SampleStats, SampleStatsReducer}; pub use subsample::{EntropyBias, LayerReport, SamplePlan, SamplingSpec, SurvivingFamily}; pub(crate) use annex::build_layer_sibling_annex; diff --git a/src/obikphylo/src/siblings/algorithms/pair_weight.rs b/src/obikphylo/src/siblings/algorithms/pair_weight.rs index 9c3b7248..04c72c82 100644 --- a/src/obikphylo/src/siblings/algorithms/pair_weight.rs +++ b/src/obikphylo/src/siblings/algorithms/pair_weight.rs @@ -13,8 +13,8 @@ //! Values are only meaningful relative to each other; the sampler rescales //! them per layer (`SamplingSpec::pair_balance`). -use crate::siblings::{AmbiguityPolicy, FamilyOverlap}; use crate::siblings::helpers::is_carrier; +use crate::siblings::{AmbiguityPolicy, FamilyOverlap}; /// `1 / O` for every pair of genomes, as a dense symmetric `n × n` matrix /// (diagonal and pairs sharing nothing hold `0.0`) — what @@ -46,8 +46,9 @@ pub(crate) fn pair_balance_weight( inv_overlap: &[f32], ) -> f32 { let n = genome_mask.len(); - let carriers: Vec = - (0..n).filter(|&g| is_carrier(genome_mask[g], policy)).collect(); + let carriers: Vec = (0..n) + .filter(|&g| is_carrier(genome_mask[g], policy)) + .collect(); let k = carriers.len(); if k < 2 { return 0.0; @@ -96,8 +97,14 @@ mod tests { #[test] fn fewer_than_two_carriers_weigh_nothing() { - assert_eq!(pair_balance_weight(&[1, 0, 0, 0], AmbiguityPolicy::Keep, &matrix()), 0.0); - assert_eq!(pair_balance_weight(&[0, 0, 0, 0], AmbiguityPolicy::Keep, &matrix()), 0.0); + assert_eq!( + pair_balance_weight(&[1, 0, 0, 0], AmbiguityPolicy::Keep, &matrix()), + 0.0 + ); + assert_eq!( + pair_balance_weight(&[0, 0, 0, 0], AmbiguityPolicy::Keep, &matrix()), + 0.0 + ); } #[test] diff --git a/src/obikphylo/src/siblings/algorithms/pairwise.rs b/src/obikphylo/src/siblings/algorithms/pairwise.rs index b301d69c..dd5e757a 100644 --- a/src/obikphylo/src/siblings/algorithms/pairwise.rs +++ b/src/obikphylo/src/siblings/algorithms/pairwise.rs @@ -64,7 +64,10 @@ pub struct PairwiseTally { impl PairwiseTally { pub(crate) fn new(n_genomes: usize) -> Self { let n_pairs = n_genomes.saturating_sub(1) * n_genomes / 2; - Self { n_genomes, pairs: vec![PairStats::default(); n_pairs] } + Self { + n_genomes, + pairs: vec![PairStats::default(); n_pairs], + } } pub(crate) fn n_genomes(&self) -> usize { @@ -129,7 +132,9 @@ impl PairwiseTally { if i == j { return false; } - if excluded.get(i).copied().unwrap_or(false) || excluded.get(j).copied().unwrap_or(false) { + if excluded.get(i).copied().unwrap_or(false) + || excluded.get(j).copied().unwrap_or(false) + { return false; } let (snp, shared) = self.snp_shared(i, j); @@ -390,8 +395,11 @@ impl PartitionDispersion { return None; } - let weighted_variance: f64 = - rows.iter().map(|&(rate, w)| w * (rate - mean).powi(2)).sum::() / weight_total; + let weighted_variance: f64 = rows + .iter() + .map(|&(rate, w)| w * (rate - mean).powi(2)) + .sum::() + / weight_total; let mean_eligible = weight_total / rows.len() as f64; let poisson_floor = mean / mean_eligible; let excess = weighted_variance - poisson_floor; @@ -433,9 +441,12 @@ pub(crate) fn reduce_pairwise( let mut partition_eligible: u64 = 0; for family in survivors { let single_form = |g: usize| -> Option { - family.masked[g].filter(|m| m.count_ones() == 1).map(|m| m.trailing_zeros() as u8) + family.masked[g] + .filter(|m| m.count_ones() == 1) + .map(|m| m.trailing_zeros() as u8) }; - let masked_cardinality = |g: usize| -> usize { family.masked[g].map_or(0, |m| m.count_ones() as usize) }; + let masked_cardinality = + |g: usize| -> usize { family.masked[g].map_or(0, |m| m.count_ones() as usize) }; for i in 0..n_genomes { let bi = single_form(i); @@ -482,7 +493,10 @@ impl PairwiseReducer { /// has already applied them, once, upstream in /// `subsample::sample_layer` — see that field's own docs. pub fn new(n_genomes: usize) -> Self { - Self { tally: PairwiseTally::new(n_genomes), dispersion: PartitionDispersion::default() } + Self { + tally: PairwiseTally::new(n_genomes), + dispersion: PartitionDispersion::default(), + } } pub fn finish(self) -> (PairwiseTally, PartitionDispersion) { @@ -510,7 +524,12 @@ mod cardinality_masking_tests { // `SurvivingFamily::masked`'s own docs) — the masking decision is baked // in here, not passed to `reduce_pairwise` itself anymore. fn ambiguous_vs_single(masked: Vec>) -> Vec { - vec![SurvivingFamily { family_idx: 0, kmer: obikseq::CanonicalKmer::from_raw_unchecked(0), mask: FamilyMask::EMPTY.with(0).with(1), masked }] + vec![SurvivingFamily { + family_idx: 0, + kmer: obikseq::CanonicalKmer::from_raw_unchecked(0), + mask: FamilyMask::EMPTY.with(0).with(1), + masked, + }] } #[test] @@ -520,8 +539,14 @@ mod cardinality_masking_tests { let families = ambiguous_vs_single(vec![Some(0b0011), Some(0b0001)]); reduce_pairwise(&families, 0, &mut tally, &mut dispersion); let counts = tally.cardinality_tally(&[]).counts; - assert_eq!(counts[2][1], 1, "genome 0's raw cardinality (2) should be tallied"); - assert_eq!(counts[0][1], 0, "no masking requested — nothing should collapse to 0"); + assert_eq!( + counts[2][1], 1, + "genome 0's raw cardinality (2) should be tallied" + ); + assert_eq!( + counts[0][1], 0, + "no masking requested — nothing should collapse to 0" + ); } #[test] @@ -535,8 +560,14 @@ mod cardinality_masking_tests { let families = ambiguous_vs_single(vec![None, Some(0b0001)]); reduce_pairwise(&families, 0, &mut tally, &mut dispersion); let counts = tally.cardinality_tally(&[]).counts; - assert_eq!(counts[2][1], 0, "raw cardinality must not leak through under --no-ambiguity"); - assert_eq!(counts[0][1], 1, "the ambiguous genome should be masked to cardinality 0"); + assert_eq!( + counts[2][1], 0, + "raw cardinality must not leak through under --no-ambiguity" + ); + assert_eq!( + counts[0][1], 1, + "the ambiguous genome should be masked to cardinality 0" + ); } } @@ -588,8 +619,13 @@ mod dispersion_tests { // 0.01, Poisson floor = mean/mean_eligible = 0.001, alpha = // mean² / (variance - floor) = 0.01 / 0.009. let expected = 0.01 / 0.009; - let alpha = d.estimate_alpha().expect("clear over-dispersion should yield an estimate"); + let alpha = d + .estimate_alpha() + .expect("clear over-dispersion should yield an estimate"); assert!(alpha > 0.0, "alpha should be positive, got {alpha}"); - assert!((alpha - expected).abs() < 1e-9, "got {alpha}, expected {expected}"); + assert!( + (alpha - expected).abs() < 1e-9, + "got {alpha}, expected {expected}" + ); } } diff --git a/src/obikphylo/src/siblings/algorithms/quartet.rs b/src/obikphylo/src/siblings/algorithms/quartet.rs index 5d42ea4b..0565797f 100644 --- a/src/obikphylo/src/siblings/algorithms/quartet.rs +++ b/src/obikphylo/src/siblings/algorithms/quartet.rs @@ -7,8 +7,8 @@ use obicompactvec::{PersistentBitVec, TempBitVecBuilder}; use obikindex::{OKIError, OKIResult}; use super::minorant_selection::is_non_monomorphic_minorant; -use crate::siblings::quartet_annex::{QuartetConvention, quartet_annex_file_name}; use crate::siblings::SiblingAnnex; +use crate::siblings::quartet_annex::{QuartetConvention, quartet_annex_file_name}; /// Clears, in `eligible` (indexed by `family_idx`, monomorphic minorants /// included), every family the quartet annex flags as not quartet-informative @@ -29,7 +29,9 @@ pub(crate) fn restrict_to_quartet( let mut family_idx = 0usize; let mut compact = 0usize; for slot in 0..annex.len() { - let Some(mask) = annex.get(slot) else { continue }; + let Some(mask) = annex.get(slot) else { + continue; + }; if !mask.is_minorant() { continue; } diff --git a/src/obikphylo/src/siblings/algorithms/sample_stats.rs b/src/obikphylo/src/siblings/algorithms/sample_stats.rs index 4e125393..1187404d 100644 --- a/src/obikphylo/src/siblings/algorithms/sample_stats.rs +++ b/src/obikphylo/src/siblings/algorithms/sample_stats.rs @@ -61,7 +61,9 @@ impl SampleStatsReducer { pub fn new(n_genomes: usize, excluded: &[bool]) -> Self { let n_pairs = n_genomes.saturating_sub(1) * n_genomes / 2; Self { - excluded: (0..n_genomes).map(|g| excluded.get(g).copied().unwrap_or(false)).collect(), + excluded: (0..n_genomes) + .map(|g| excluded.get(g).copied().unwrap_or(false)) + .collect(), stats: SampleStats { n_genomes, n_sites: 0, @@ -84,7 +86,9 @@ impl SampleStatsReducer { let mut counts = [0u32; 16]; let mut carriers: Vec = Vec::new(); for (g, &state) in masked.iter().enumerate() { - let Some(state) = state.filter(|_| !self.excluded[g]) else { continue }; + let Some(state) = state.filter(|_| !self.excluded[g]) else { + continue; + }; // Absence (state 0, only present without `--free-loss`) is a state // of the alignment, so it takes part in the bipartition — but its // genome carries none of the family's members. diff --git a/src/obikphylo/src/siblings/algorithms/sankoff.rs b/src/obikphylo/src/siblings/algorithms/sankoff.rs index c7117724..67c956bc 100644 --- a/src/obikphylo/src/siblings/algorithms/sankoff.rs +++ b/src/obikphylo/src/siblings/algorithms/sankoff.rs @@ -65,7 +65,14 @@ impl SankoffBundle { let included = tally.included(ratio_ceiling, excluded); let base_pair_tally = tally.base_pair_tally(&included); let cardinality_tally = tally.cardinality_tally(excluded); - Self { alignment, raw, base_pair_tally, cardinality_tally, tally, dispersion } + Self { + alignment, + raw, + base_pair_tally, + cardinality_tally, + tally, + dispersion, + } } /// A `snp-*` `--distance` matrix computed from this bundle's own @@ -78,7 +85,11 @@ impl SankoffBundle { /// that advances across calls, not reseeded each time) — defeating the /// actual point of running several algorithms together, which is /// comparing them on one identical site selection. - pub fn snp_distance(&self, kind: SnpDistanceKind, gamma_shape: GammaShape) -> OKIResult> { + pub fn snp_distance( + &self, + kind: SnpDistanceKind, + gamma_shape: GammaShape, + ) -> OKIResult> { distance_matrix(&self.tally, &self.dispersion, kind, gamma_shape) } } diff --git a/src/obikphylo/src/siblings/algorithms/scan.rs b/src/obikphylo/src/siblings/algorithms/scan.rs index 5942817d..0efdfb33 100644 --- a/src/obikphylo/src/siblings/algorithms/scan.rs +++ b/src/obikphylo/src/siblings/algorithms/scan.rs @@ -60,9 +60,16 @@ pub fn sampled_scan( if target == 0 { return Ok(SamplePlan::default()); } - sample_index(cache, target, spec, excluded, 0, |partition, layer, _raw_index, survivors| { - for reducer in reducers.iter_mut() { - reducer.reduce(partition, layer, &survivors); - } - }) + sample_index( + cache, + target, + spec, + excluded, + 0, + |partition, layer, _raw_index, survivors| { + for reducer in reducers.iter_mut() { + reducer.reduce(partition, layer, &survivors); + } + }, + ) } diff --git a/src/obikphylo/src/siblings/algorithms/snp_distance.rs b/src/obikphylo/src/siblings/algorithms/snp_distance.rs index 3584c09f..1f6c4181 100644 --- a/src/obikphylo/src/siblings/algorithms/snp_distance.rs +++ b/src/obikphylo/src/siblings/algorithms/snp_distance.rs @@ -258,10 +258,10 @@ pub fn distance_matrix( #[cfg(test)] mod tests { + use super::super::pairwise::reduce_pairwise; use super::*; use crate::siblings::FamilyMask; use crate::siblings::algorithms::SurvivingFamily; - use super::super::pairwise::reduce_pairwise; // Base bit positions, matching `PairwiseTally::categories`' convention // (0=A, 1=C, 2=G, 3=T). @@ -287,7 +287,9 @@ mod tests { families.push(SurvivingFamily { family_idx: families.len(), kmer: obikseq::CanonicalKmer::from_raw_unchecked(0), - mask: FamilyMask::EMPTY.with(a.trailing_zeros() as u8).with(b.trailing_zeros() as u8), + mask: FamilyMask::EMPTY + .with(a.trailing_zeros() as u8) + .with(b.trailing_zeros() as u8), masked: vec![Some(a), Some(b)], }); } @@ -298,7 +300,9 @@ mod tests { families.push(SurvivingFamily { family_idx: families.len(), kmer: obikseq::CanonicalKmer::from_raw_unchecked(0), - mask: FamilyMask::EMPTY.with(b.trailing_zeros() as u8).with(other.trailing_zeros() as u8), + mask: FamilyMask::EMPTY + .with(b.trailing_zeros() as u8) + .with(other.trailing_zeros() as u8), masked: vec![Some(b), Some(b)], }); } diff --git a/src/obikphylo/src/siblings/algorithms/stats.rs b/src/obikphylo/src/siblings/algorithms/stats.rs index cbd32bf5..ab5ecfb0 100644 --- a/src/obikphylo/src/siblings/algorithms/stats.rs +++ b/src/obikphylo/src/siblings/algorithms/stats.rs @@ -59,7 +59,9 @@ pub(crate) fn sibling_family_size_histogram(cache: &IndexCache) -> OKIResult<[u6 .expect("ensure_sibling_annex already made every layer's annex exist"); let mut counts = [0u64; 4]; for slot in 0..annex.len() { - let Some(mask) = annex.get(slot) else { continue }; + let Some(mask) = annex.get(slot) else { + continue; + }; if !mask.is_minorant() { continue; // family tallied once, at its minorant } diff --git a/src/obikphylo/src/siblings/algorithms/subsample.rs b/src/obikphylo/src/siblings/algorithms/subsample.rs index 6075a1a7..4a64b1d2 100644 --- a/src/obikphylo/src/siblings/algorithms/subsample.rs +++ b/src/obikphylo/src/siblings/algorithms/subsample.rs @@ -57,8 +57,8 @@ use super::family_scan::{Selection, scan_layer_families}; use super::masking::{masked_state, survives_masking, survives_quartet}; use super::minorant_selection::{eligible_bitset_layer, iter_full_scalar}; use super::{AnnexRequest, is_fast_mode, restrict_to_quartet}; -use crate::siblings::{AmbiguityPolicy, FamilyMask, QuartetConvention, ScalarKind}; use crate::siblings::extensions::SiblingBuilder; +use crate::siblings::{AmbiguityPolicy, FamilyMask, QuartetConvention, ScalarKind}; /// Resolution rounds a single layer's sampling may take before giving up on /// reaching its own quota — see the module docs on why a round batches many @@ -127,7 +127,10 @@ impl SamplingSpec { /// genomes with several members count, and whether absence is a state — /// the same two choices the post-hoc masking makes. pub(crate) fn quartet_convention(&self) -> QuartetConvention { - QuartetConvention { policy: self.ambiguity, free_loss: self.free_loss } + QuartetConvention { + policy: self.ambiguity, + free_loss: self.free_loss, + } } } @@ -268,12 +271,24 @@ pub(crate) fn sample_index( // layer, below, each under this run's `--no-ambiguity` counting // convention) — build any missing one now, once, rather than mid-walk. let request = AnnexRequest { - entropy: spec.entropy_bias.map(|_| vec![spec.ambiguity]).unwrap_or_default(), - quartet: if spec.quartet { vec![spec.quartet_convention()] } else { Vec::new() }, + entropy: spec + .entropy_bias + .map(|_| vec![spec.ambiguity]) + .unwrap_or_default(), + quartet: if spec.quartet { + vec![spec.quartet_convention()] + } else { + Vec::new() + }, overlap: Vec::new(), - pair_weight: if spec.pair_balance { vec![spec.ambiguity] } else { Vec::new() }, + pair_weight: if spec.pair_balance { + vec![spec.ambiguity] + } else { + Vec::new() + }, }; - if !request.entropy.is_empty() || !request.quartet.is_empty() || !request.pair_weight.is_empty() { + if !request.entropy.is_empty() || !request.quartet.is_empty() || !request.pair_weight.is_empty() + { cache.ensure_family_annexes(&request)?; } @@ -318,7 +333,10 @@ pub(crate) fn sample_index( pb.finish_and_clear(); let total_mass: f64 = plans.iter().map(|plan| plan.mass).sum(); - let mut report = SamplePlan { target: n, layers: Vec::with_capacity(plans.len()) }; + let mut report = SamplePlan { + target: n, + layers: Vec::with_capacity(plans.len()), + }; if total_mass <= 0.0 { return Ok(report); } @@ -385,7 +403,13 @@ fn sample_layer( excluded: &[bool], on_layer: &mut impl FnMut(usize, usize, usize, Arc>), ) -> OKIResult<(usize, usize)> { - let LayerPlan { partition, layer: layer_idx, n_minorants, mass, .. } = *plan; + let LayerPlan { + partition, + layer: layer_idx, + n_minorants, + mass, + .. + } = *plan; let eligible = &mut plan.eligible; if n_minorants == 0 || mass <= 0.0 { return Ok((0, 0)); @@ -505,7 +529,12 @@ fn sample_layer( if survives_masking(&masked, excluded) && (!spec.quartet || survives_quartet(&masked, excluded)) { - survivors.push(SurvivingFamily { family_idx, kmer, mask, masked }); + survivors.push(SurvivingFamily { + family_idx, + kmer, + mask, + masked, + }); kept += 1; } }, diff --git a/src/obikphylo/src/siblings/ambiguity.rs b/src/obikphylo/src/siblings/ambiguity.rs index 12f94527..e9db9098 100644 --- a/src/obikphylo/src/siblings/ambiguity.rs +++ b/src/obikphylo/src/siblings/ambiguity.rs @@ -28,7 +28,10 @@ impl AmbiguityPolicy { /// From the two (mutually exclusive) CLI flags. pub fn from_flags(no_ambiguity: bool, only_diploid: bool) -> Self { - debug_assert!(!(no_ambiguity && only_diploid), "--no-ambiguity and --only-diploid are exclusive"); + debug_assert!( + !(no_ambiguity && only_diploid), + "--no-ambiguity and --only-diploid are exclusive" + ); if no_ambiguity { Self::Forbid } else if only_diploid { @@ -76,9 +79,13 @@ mod tests { #[test] fn drops_follows_the_member_count() { - for (mask, keep, diploid, forbid) in - [(0b0000u8, false, false, false), (0b0100, false, false, false), (0b0101, false, false, true), (0b0111, false, true, true), (0b1111, false, true, true)] - { + for (mask, keep, diploid, forbid) in [ + (0b0000u8, false, false, false), + (0b0100, false, false, false), + (0b0101, false, false, true), + (0b0111, false, true, true), + (0b1111, false, true, true), + ] { assert_eq!(AmbiguityPolicy::Keep.drops(mask), keep); assert_eq!(AmbiguityPolicy::OnlyDiploid.drops(mask), diploid); assert_eq!(AmbiguityPolicy::Forbid.drops(mask), forbid); diff --git a/src/obikphylo/src/siblings/extensions/mod.rs b/src/obikphylo/src/siblings/extensions/mod.rs index 74a0aa94..6fc5b3ec 100644 --- a/src/obikphylo/src/siblings/extensions/mod.rs +++ b/src/obikphylo/src/siblings/extensions/mod.rs @@ -7,5 +7,5 @@ mod sibling_builder; mod sibling_ext; -pub use sibling_ext::SiblingExt; pub(crate) use sibling_builder::SiblingBuilder; +pub use sibling_ext::SiblingExt; diff --git a/src/obikphylo/src/siblings/extensions/sibling_builder.rs b/src/obikphylo/src/siblings/extensions/sibling_builder.rs index 316cbfce..5fc12e6e 100644 --- a/src/obikphylo/src/siblings/extensions/sibling_builder.rs +++ b/src/obikphylo/src/siblings/extensions/sibling_builder.rs @@ -16,8 +16,8 @@ use crate::siblings::algorithms::{ ensure_layer_pair_weight_annexes, inverse_overlap_matrix, is_fast_mode, }; use crate::siblings::{ - ANNEX_FILE_NAME, AmbiguityPolicy, FAMILY_OVERLAP_FILE_NAMES, FamilyOverlap, FamilyOverlapAccumulator, - QUARTET_ANNEX_FILE_NAMES, ScalarKind, family_overlap_file_name, + ANNEX_FILE_NAME, AmbiguityPolicy, FAMILY_OVERLAP_FILE_NAMES, FamilyOverlap, + FamilyOverlapAccumulator, QUARTET_ANNEX_FILE_NAMES, ScalarKind, family_overlap_file_name, }; pub(crate) trait SiblingBuilder { @@ -61,7 +61,10 @@ pub(crate) trait SiblingBuilder { impl SiblingBuilder for IndexCache { fn ensure_sibling_annex(&self) -> OKIResult<()> { - let missing = || self.iter_indexed().any(|(_, _, layer)| !layer.dir().join(ANNEX_FILE_NAME).exists()); + let missing = || { + self.iter_indexed() + .any(|(_, _, layer)| !layer.dir().join(ANNEX_FILE_NAME).exists()) + }; if !missing() { return Ok(()); } @@ -147,13 +150,15 @@ impl SiblingBuilder for IndexCache { if request.is_satisfied(self) { return Ok(()); } - self.index().with_lock(|| self.build_family_annexes(request)) + self.index() + .with_lock(|| self.build_family_annexes(request)) } fn build_family_annexes(&self, request: &AnnexRequest) -> OKIResult<()> { let n_genomes = self.meta().genomes().len(); let fast_mode = is_fast_mode(self); - let overlap_path = |policy: AmbiguityPolicy| self.index().dir().join(family_overlap_file_name(policy)); + let overlap_path = + |policy: AmbiguityPolicy| self.index().dir().join(family_overlap_file_name(policy)); // Sweep 1: entropy, quartet, and every family-overlap annex still missing. let mut overlap_accs: Vec<(AmbiguityPolicy, FamilyOverlapAccumulator)> = request @@ -166,7 +171,15 @@ impl SiblingBuilder for IndexCache { for part in self.partitions() { let n_layer = self.n_layer(part).unwrap_or(0); for l in 0..n_layer { - ensure_layer_family_annexes(self, part, l, n_genomes, fast_mode, request, &mut overlap_accs)?; + ensure_layer_family_annexes( + self, + part, + l, + n_genomes, + fast_mode, + request, + &mut overlap_accs, + )?; } pb.inc(1); } diff --git a/src/obikphylo/src/siblings/extensions/sibling_ext.rs b/src/obikphylo/src/siblings/extensions/sibling_ext.rs index 9f7a68e3..cd421cc7 100644 --- a/src/obikphylo/src/siblings/extensions/sibling_ext.rs +++ b/src/obikphylo/src/siblings/extensions/sibling_ext.rs @@ -13,7 +13,8 @@ use obikidxcache::index_cache::IndexCache; use obikindex::{OKIError, OKIResult}; use crate::siblings::algorithms::{ - AnnexRequest, AnnexSelection, EntropySummary, SiblingAnnexStats, scan_family_entropies, sibling_annex_stats, sibling_family_size_histogram, + AnnexRequest, AnnexSelection, EntropySummary, SiblingAnnexStats, scan_family_entropies, + sibling_annex_stats, sibling_family_size_histogram, }; use crate::siblings::extensions::SiblingBuilder; use crate::siblings::{AmbiguityPolicy, FamilyOverlap, family_overlap_file_name}; @@ -122,7 +123,10 @@ impl SiblingExt for IndexCache { if derived.is_empty() { return Ok(()); } - tracing::info!("building the requested derived annexes ({:?})", derived.policy); + tracing::info!( + "building the requested derived annexes ({:?})", + derived.policy + ); self.ensure_family_annexes(&derived.request()) }) } @@ -168,7 +172,10 @@ impl SiblingExt for IndexCache { } fn family_overlap(&self, policy: AmbiguityPolicy) -> OKIResult { - self.ensure_family_annexes(&AnnexRequest { overlap: vec![policy], ..Default::default() })?; + self.ensure_family_annexes(&AnnexRequest { + overlap: vec![policy], + ..Default::default() + })?; let path = self.index().dir().join(family_overlap_file_name(policy)); FamilyOverlap::open(&path).map_err(OKIError::Io) } diff --git a/src/obikphylo/src/siblings/family_overlap.rs b/src/obikphylo/src/siblings/family_overlap.rs index 90fd8a2b..b0b3e45c 100644 --- a/src/obikphylo/src/siblings/family_overlap.rs +++ b/src/obikphylo/src/siblings/family_overlap.rs @@ -74,7 +74,10 @@ impl FamilyOverlap { pub fn open(path: &Path) -> io::Result { let mmap = unsafe { Mmap::map(&File::open(path)?)? }; if mmap.len() < HEADER_SIZE { - return Err(io::Error::new(io::ErrorKind::InvalidData, "POVL file too short")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "POVL file too short", + )); } if mmap[0..4] != MAGIC { return Err(io::Error::new(io::ErrorKind::InvalidData, "bad POVL magic")); @@ -82,10 +85,17 @@ impl FamilyOverlap { let n_genomes = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize; let n_pairs = n_genomes.saturating_sub(1) * n_genomes / 2; if mmap.len() < HEADER_SIZE + n_pairs * 8 { - return Err(io::Error::new(io::ErrorKind::InvalidData, "POVL file truncated")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "POVL file truncated", + )); } let flags = u32::from_le_bytes(mmap[4..8].try_into().unwrap()); - Ok(Self { mmap, n_genomes, policy: AmbiguityPolicy::from_header_flags(flags) }) + Ok(Self { + mmap, + n_genomes, + policy: AmbiguityPolicy::from_header_flags(flags), + }) } pub fn n_genomes(&self) -> usize { @@ -118,7 +128,10 @@ impl FamilyOverlap { if self.n_genomes <= 1 { return 0.0; } - let sum: u64 = (0..self.n_genomes).filter(|&j| j != i).map(|j| self.get(i, j)).sum(); + let sum: u64 = (0..self.n_genomes) + .filter(|&j| j != i) + .map(|j| self.get(i, j)) + .sum(); sum as f64 / (self.n_genomes - 1) as f64 } } @@ -142,7 +155,11 @@ impl FamilyOverlapAccumulator { /// which case it shares nothing there (see [`AmbiguityPolicy::drops`]). pub(crate) fn new(n_genomes: usize, policy: AmbiguityPolicy) -> Self { let n_pairs = n_genomes.saturating_sub(1) * n_genomes / 2; - Self { n_genomes, policy, counts: vec![0u64; n_pairs] } + Self { + n_genomes, + policy, + counts: vec![0u64; n_pairs], + } } /// One variable family's contribution: every pair of genomes both @@ -204,7 +221,9 @@ mod tests { fn single_genome_mean_row_is_zero() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("test.povl"); - FamilyOverlapAccumulator::new(1, AmbiguityPolicy::Keep).write(&path).unwrap(); + FamilyOverlapAccumulator::new(1, AmbiguityPolicy::Keep) + .write(&path) + .unwrap(); let overlap = FamilyOverlap::open(&path).unwrap(); assert_eq!(overlap.mean_row(0), 0.0); } diff --git a/src/obikphylo/src/siblings/family_scalar_annex.rs b/src/obikphylo/src/siblings/family_scalar_annex.rs index d96f1514..ef2179c4 100644 --- a/src/obikphylo/src/siblings/family_scalar_annex.rs +++ b/src/obikphylo/src/siblings/family_scalar_annex.rs @@ -89,7 +89,10 @@ impl FamilyScalarAnnex { pub(crate) fn open(path: &Path, kind: ScalarKind) -> io::Result { let mmap = unsafe { Mmap::map(&File::open(path)?)? }; if mmap.len() < HEADER_SIZE { - return Err(io::Error::new(io::ErrorKind::InvalidData, "scalar annex file too short")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "scalar annex file too short", + )); } if mmap[0..4] != kind.magic() { return Err(io::Error::new( @@ -99,10 +102,17 @@ impl FamilyScalarAnnex { } let n = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize; if mmap.len() < HEADER_SIZE + n * 4 { - return Err(io::Error::new(io::ErrorKind::InvalidData, "scalar annex file truncated")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "scalar annex file truncated", + )); } let flags = u32::from_le_bytes(mmap[4..8].try_into().unwrap()); - Ok(Self { mmap, n, policy: AmbiguityPolicy::from_header_flags(flags) }) + Ok(Self { + mmap, + n, + policy: AmbiguityPolicy::from_header_flags(flags), + }) } pub fn len(&self) -> usize { @@ -133,7 +143,12 @@ impl FamilyScalarAnnexBuilder { /// minorant count) at `path`, pre-initialised to the sentinel. /// `policy` records, in the header, the counting convention the values /// will be computed under (see [`FamilyScalarAnnex::policy`]). - pub(crate) fn new(n: usize, path: &Path, kind: ScalarKind, policy: AmbiguityPolicy) -> io::Result { + pub(crate) fn new( + n: usize, + path: &Path, + kind: ScalarKind, + policy: AmbiguityPolicy, + ) -> io::Result { let file_size = HEADER_SIZE + n * 4; let file = OpenOptions::new() .read(true) @@ -151,11 +166,17 @@ impl FamilyScalarAnnexBuilder { let off = HEADER_SIZE + i * 4; mmap[off..off + 4].copy_from_slice(&SENTINEL.to_le_bytes()); } - Ok(Self { mmap, path: path.to_path_buf() }) + Ok(Self { + mmap, + path: path.to_path_buf(), + }) } pub(crate) fn set(&mut self, idx: usize, value: f32) { - debug_assert!(value >= 0.0, "stored values must be non-negative, got {value}"); + debug_assert!( + value >= 0.0, + "stored values must be non-negative, got {value}" + ); let off = HEADER_SIZE + idx * 4; self.mmap[off..off + 4].copy_from_slice(&value.to_le_bytes()); } @@ -180,7 +201,10 @@ mod tests { fn sentinel_is_negative_and_unset_entries_read_as_none() { let dir = tempdir().unwrap(); let path = dir.path().join("test.pent"); - FamilyScalarAnnexBuilder::new(4, &path, E, AmbiguityPolicy::Keep).unwrap().close().unwrap(); + FamilyScalarAnnexBuilder::new(4, &path, E, AmbiguityPolicy::Keep) + .unwrap() + .close() + .unwrap(); let annex = FamilyScalarAnnex::open(&path, E).unwrap(); for i in 0..4 { assert_eq!(annex.get(i), None); @@ -191,7 +215,8 @@ mod tests { fn roundtrip_including_zero_value() { let dir = tempdir().unwrap(); let path = dir.path().join("test.pent"); - let mut builder = FamilyScalarAnnexBuilder::new(4, &path, E, AmbiguityPolicy::Keep).unwrap(); + let mut builder = + FamilyScalarAnnexBuilder::new(4, &path, E, AmbiguityPolicy::Keep).unwrap(); let values = [0.0f32, 1.5, 3.9, 0.0001]; for (i, &v) in values.iter().enumerate() { builder.set(i, v); @@ -207,7 +232,8 @@ mod tests { fn mixed_sentinel_and_real_values() { let dir = tempdir().unwrap(); let path = dir.path().join("test.pent"); - let mut builder = FamilyScalarAnnexBuilder::new(3, &path, E, AmbiguityPolicy::Keep).unwrap(); + let mut builder = + FamilyScalarAnnexBuilder::new(3, &path, E, AmbiguityPolicy::Keep).unwrap(); builder.set(1, 2.0); builder.close().unwrap(); let annex = FamilyScalarAnnex::open(&path, E).unwrap(); @@ -223,8 +249,14 @@ mod tests { for kind in [ScalarKind::Entropy, ScalarKind::PairWeight] { for policy in AmbiguityPolicy::ALL { let path = dir.path().join(kind.file_name(policy)); - FamilyScalarAnnexBuilder::new(2, &path, kind, policy).unwrap().close().unwrap(); - assert_eq!(FamilyScalarAnnex::open(&path, kind).unwrap().policy(), policy); + FamilyScalarAnnexBuilder::new(2, &path, kind, policy) + .unwrap() + .close() + .unwrap(); + assert_eq!( + FamilyScalarAnnex::open(&path, kind).unwrap().policy(), + policy + ); } let names = kind.file_names(); assert!(names[0] != names[1] && names[1] != names[2] && names[0] != names[2]); @@ -235,7 +267,10 @@ mod tests { fn one_kind_cannot_be_read_as_the_other() { let dir = tempdir().unwrap(); let path = dir.path().join("w.ppwt"); - FamilyScalarAnnexBuilder::new(1, &path, ScalarKind::PairWeight, AmbiguityPolicy::Keep).unwrap().close().unwrap(); + FamilyScalarAnnexBuilder::new(1, &path, ScalarKind::PairWeight, AmbiguityPolicy::Keep) + .unwrap() + .close() + .unwrap(); assert!(FamilyScalarAnnex::open(&path, ScalarKind::Entropy).is_err()); assert!(FamilyScalarAnnex::open(&path, ScalarKind::PairWeight).is_ok()); } @@ -245,9 +280,15 @@ mod tests { // files written before the flag existed carried four zero bytes there let dir = tempdir().unwrap(); let path = dir.path().join("old.pent"); - FamilyScalarAnnexBuilder::new(1, &path, E, AmbiguityPolicy::Keep).unwrap().close().unwrap(); + FamilyScalarAnnexBuilder::new(1, &path, E, AmbiguityPolicy::Keep) + .unwrap() + .close() + .unwrap(); let bytes = std::fs::read(&path).unwrap(); assert_eq!(&bytes[4..8], &[0u8; 4]); - assert_eq!(FamilyScalarAnnex::open(&path, E).unwrap().policy(), AmbiguityPolicy::Keep); + assert_eq!( + FamilyScalarAnnex::open(&path, E).unwrap().policy(), + AmbiguityPolicy::Keep + ); } } diff --git a/src/obikphylo/src/siblings/mod.rs b/src/obikphylo/src/siblings/mod.rs index e0295375..0f43706a 100644 --- a/src/obikphylo/src/siblings/mod.rs +++ b/src/obikphylo/src/siblings/mod.rs @@ -29,22 +29,22 @@ pub mod iter; mod quartet_annex; mod siblingannex; +pub use ambiguity::AmbiguityPolicy; +pub use family_overlap::FamilyOverlap; pub(crate) use family_overlap::{ FAMILY_OVERLAP_FILE_NAMES, FamilyOverlapAccumulator, family_overlap_file_name, }; pub(crate) use family_scalar_annex::ScalarKind; pub use family_scalar_annex::{FamilyScalarAnnex, FamilyScalarAnnexBuilder}; -pub use family_overlap::FamilyOverlap; -pub(crate) use quartet_annex::{QUARTET_ANNEX_FILE_NAMES, QuartetConvention}; -pub use ambiguity::AmbiguityPolicy; pub use iter::{ MinorantBatchIter, MinorantIter, SiblingBatchIter, SiblingEntry, SiblingIter, SiblingLayerExt, }; +pub(crate) use quartet_annex::{QUARTET_ANNEX_FILE_NAMES, QuartetConvention}; pub use siblingannex::{FamilyMask, SiblingAnnex, SiblingAnnexBuilder}; pub use algorithms::{ - AlignmentReducer, AnnexSelection, BasePairTally, CardinalityTally, EntropyBias, GammaShape, LayerReducer, - LayerReport, PairwiseReducer, RawSnpDistanceOutput, SamplePlan, SampleStats, + AlignmentReducer, AnnexSelection, BasePairTally, CardinalityTally, EntropyBias, GammaShape, + LayerReducer, LayerReport, PairwiseReducer, RawSnpDistanceOutput, SamplePlan, SampleStats, SampleStatsReducer, SamplingSpec, SankoffBundle, SiblingAnnexStats, SiteLocus, SnpAlignment, SnpDistanceKind, cardinality_transition_probs, composition_transition_probs, distance_matrix, pairwise_cost_matrix, sampled_scan, diff --git a/src/obikphylo/src/siblings/quartet_annex.rs b/src/obikphylo/src/siblings/quartet_annex.rs index 5152889b..d4a4150f 100644 --- a/src/obikphylo/src/siblings/quartet_annex.rs +++ b/src/obikphylo/src/siblings/quartet_annex.rs @@ -44,12 +44,30 @@ impl QuartetConvention { /// Every convention, in a fixed order. #[cfg(test)] pub(crate) const ALL: [QuartetConvention; 6] = [ - QuartetConvention { policy: AmbiguityPolicy::Keep, free_loss: true }, - QuartetConvention { policy: AmbiguityPolicy::Forbid, free_loss: true }, - QuartetConvention { policy: AmbiguityPolicy::OnlyDiploid, free_loss: true }, - QuartetConvention { policy: AmbiguityPolicy::Keep, free_loss: false }, - QuartetConvention { policy: AmbiguityPolicy::Forbid, free_loss: false }, - QuartetConvention { policy: AmbiguityPolicy::OnlyDiploid, free_loss: false }, + QuartetConvention { + policy: AmbiguityPolicy::Keep, + free_loss: true, + }, + QuartetConvention { + policy: AmbiguityPolicy::Forbid, + free_loss: true, + }, + QuartetConvention { + policy: AmbiguityPolicy::OnlyDiploid, + free_loss: true, + }, + QuartetConvention { + policy: AmbiguityPolicy::Keep, + free_loss: false, + }, + QuartetConvention { + policy: AmbiguityPolicy::Forbid, + free_loss: false, + }, + QuartetConvention { + policy: AmbiguityPolicy::OnlyDiploid, + free_loss: false, + }, ]; } diff --git a/src/obikphylo/src/siblings/siblingannex.rs b/src/obikphylo/src/siblings/siblingannex.rs index deeca0df..bd5cdc9a 100644 --- a/src/obikphylo/src/siblings/siblingannex.rs +++ b/src/obikphylo/src/siblings/siblingannex.rs @@ -97,7 +97,10 @@ impl FamilyMask { #[inline] fn with_field(self, base: u8, value: u8) -> Self { - debug_assert!(value <= MAX_FIELD_VALUE, "field value out of range: {value}"); + debug_assert!( + value <= MAX_FIELD_VALUE, + "field value out of range: {value}" + ); let shift = Self::field_shift(base); let cleared = self.0 & !(FIELD_MASK << shift); FamilyMask(cleared | ((value as u16) << shift)) @@ -110,7 +113,10 @@ impl FamilyMask { /// one thread (see that module's docs), so a lock-free OR is safe. #[inline] pub(crate) fn layer_bits(base: u8, layer: usize) -> u16 { - debug_assert!(layer < MAX_FIELD_VALUE as usize, "layer out of range: {layer}"); + debug_assert!( + layer < MAX_FIELD_VALUE as usize, + "layer out of range: {layer}" + ); (layer as u16 + 1) << Self::field_shift(base) } @@ -139,7 +145,10 @@ impl FamilyMask { /// why `FamilyMask` doesn't decide that threshold itself. #[inline] pub fn with_layer(self, base: u8, layer: usize) -> Self { - debug_assert!(layer < MAX_FIELD_VALUE as usize, "layer out of range: {layer}"); + debug_assert!( + layer < MAX_FIELD_VALUE as usize, + "layer out of range: {layer}" + ); self.with_field(base, layer as u8 + 1) } @@ -208,7 +217,11 @@ impl FamilyMask { #[inline] pub fn from_bits(bits: u8) -> Self { (0..4).fold(FamilyMask::EMPTY, |mask, b| { - if bits & (1 << b) != 0 { mask.with(b) } else { mask } + if bits & (1 << b) != 0 { + mask.with(b) + } else { + mask + } }) } @@ -217,7 +230,11 @@ impl FamilyMask { /// why it's not directly a validated layer index). `owner` is this /// slot's own k-mer (any member works — the 4 canonical forms are /// invariant regardless of which member you start from). - pub fn family_members(self, owner: CanonicalKmer, k: usize) -> impl Iterator)> { + pub fn family_members( + self, + owner: CanonicalKmer, + k: usize, + ) -> impl Iterator)> { owner .central_canonical_neighbors() .into_iter() @@ -257,16 +274,26 @@ impl SiblingAnnex { pub fn open(path: &Path) -> io::Result { let mmap = unsafe { Mmap::map(&File::open(path)?)? }; if mmap.len() < HEADER_SIZE { - return Err(io::Error::new(io::ErrorKind::InvalidData, "PSIB file too short")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "PSIB file too short", + )); } if mmap[0..4] != MAGIC { return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PSIB magic")); } let n = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize; if mmap.len() < HEADER_SIZE + n * 2 { - return Err(io::Error::new(io::ErrorKind::InvalidData, "PSIB file truncated")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "PSIB file truncated", + )); } - Ok(Self { mmap, n, path: path.to_path_buf() }) + Ok(Self { + mmap, + n, + path: path.to_path_buf(), + }) } /// The annex of the layer directory `layer_dir`. Same as @@ -278,20 +305,31 @@ impl SiblingAnnex { Self::open(&path).map_err(|e| match e.kind() { io::ErrorKind::NotFound => io::Error::new( io::ErrorKind::NotFound, - format!("no sibling annex at {} — build it with `phylo --sibling-annex`", path.display()), + format!( + "no sibling annex at {} — build it with `phylo --sibling-annex`", + path.display() + ), ), _ => e, }) } - pub fn path(&self) -> &Path { &self.path } - pub fn len(&self) -> usize { self.n } - pub fn is_empty(&self) -> bool { self.n == 0 } + pub fn path(&self) -> &Path { + &self.path + } + pub fn len(&self) -> usize { + self.n + } + pub fn is_empty(&self) -> bool { + self.n == 0 + } /// `None` means the slot has not (yet) been computed — see module docs. pub fn get(&self, slot: usize) -> Option { let off = HEADER_SIZE + slot * 2; - FamilyMask::decode(u16::from_le_bytes(self.mmap[off..off + 2].try_into().unwrap())) + FamilyMask::decode(u16::from_le_bytes( + self.mmap[off..off + 2].try_into().unwrap(), + )) } } @@ -308,7 +346,10 @@ impl SiblingAnnexBuilder { pub fn new(n: usize, path: &Path) -> io::Result { let file_size = HEADER_SIZE + n * 2; let file = OpenOptions::new() - .read(true).write(true).create(true).truncate(true) + .read(true) + .write(true) + .create(true) + .truncate(true) .open(building_path(path))?; file.set_len(file_size as u64)?; let mut mmap = unsafe { MmapMut::map_mut(&file)? }; @@ -316,7 +357,10 @@ impl SiblingAnnexBuilder { mmap[4..8].copy_from_slice(&[0u8; 4]); mmap[8..16].copy_from_slice(&(n as u64).to_le_bytes()); // Data region left at 0 by `set_len`/mmap — the sentinel value. - Ok(Self { mmap, path: path.to_path_buf() }) + Ok(Self { + mmap, + path: path.to_path_buf(), + }) } /// `None` means the slot has not (yet) been computed — see module @@ -325,7 +369,9 @@ impl SiblingAnnexBuilder { /// [`set`](Self::set). pub fn get(&self, slot: usize) -> Option { let off = HEADER_SIZE + slot * 2; - FamilyMask::decode(u16::from_le_bytes(self.mmap[off..off + 2].try_into().unwrap())) + FamilyMask::decode(u16::from_le_bytes( + self.mmap[off..off + 2].try_into().unwrap(), + )) } /// Atomic handle to `slot`'s raw storage, for lock-free concurrent @@ -386,9 +432,9 @@ mod tests { let mut builder = SiblingAnnexBuilder::new(4, &path).unwrap(); let masks = [ - FamilyMask::EMPTY.with(0), // just A: family size 1 - FamilyMask::EMPTY.with(0).with(3), // A + T: size 2 - FamilyMask::EMPTY.with(1).with(2).with(3), // C+G+T: size 3 + FamilyMask::EMPTY.with(0), // just A: family size 1 + FamilyMask::EMPTY.with(0).with(3), // A + T: size 2 + FamilyMask::EMPTY.with(1).with(2).with(3), // C+G+T: size 3 FamilyMask::EMPTY.with(0).with(1).with(2).with(3), // all 4 ]; for (slot, mask) in masks.iter().enumerate() { @@ -449,8 +495,20 @@ mod tests { let mask = FamilyMask::EMPTY.with_layer(1, 0).with_layer(2, 3); // C (own) + G present let members: Vec<_> = mask.family_members(owner, K).collect(); - assert_eq!(members.len(), 2, "only the 2 present members should be yielded"); - assert!(members.iter().any(|(k, layer)| *k == owner && *layer == Some(0))); - assert!(members.iter().any(|(k, layer)| *k != owner && *layer == Some(3))); + assert_eq!( + members.len(), + 2, + "only the 2 present members should be yielded" + ); + assert!( + members + .iter() + .any(|(k, layer)| *k == owner && *layer == Some(0)) + ); + assert!( + members + .iter() + .any(|(k, layer)| *k != owner && *layer == Some(3)) + ); } } diff --git a/src/obikphylo/src/tree/nj.rs b/src/obikphylo/src/tree/nj.rs index bec4d90c..316e71cb 100644 --- a/src/obikphylo/src/tree/nj.rs +++ b/src/obikphylo/src/tree/nj.rs @@ -14,7 +14,9 @@ use super::{NodeId, Tree}; /// (genomes in `labels` order). pub fn neighbor_joining(matrix: &Array2, labels: &[String]) -> OKIResult { let n = labels.len(); - let rows: Vec> = (0..n).map(|i| (0..n).map(|j| matrix[[i, j]]).collect()).collect(); + let rows: Vec> = (0..n) + .map(|i| (0..n).map(|j| matrix[[i, j]]).collect()) + .collect(); let dm = DistanceMatrix::build(rows, labels.to_vec()) .map_err(|e| OKIError::InvalidInput(format!("building NJ distance matrix: {e}")))?; let graph = NeighborJoiningSolver::::default(dm) @@ -40,12 +42,23 @@ pub fn neighbor_joining(matrix: &Array2, labels: &[String]) -> OKIResult NodeId { +fn convert( + graph: &speedytree::Tree, + node: NodeIndex, + parent: NodeIndex, + tree: &mut Tree, +) -> NodeId { let label = &graph[node]; - let id = if label.is_empty() { tree.new_node() } else { tree.new_leaf(label.clone()) }; + let id = if label.is_empty() { + tree.new_node() + } else { + tree.new_leaf(label.clone()) + }; for child in graph.neighbors(node).filter(|&c| c != parent) { - let edge = graph.find_edge(node, child).expect("adjacent nodes must share an edge"); + let edge = graph + .find_edge(node, child) + .expect("adjacent nodes must share an edge"); let branch_length = *graph.edge_weight(edge).expect("edge must carry a weight"); let child_id = convert(graph, child, node, tree); tree.attach(id, child_id, branch_length); diff --git a/src/obikphylo/src/tree/upgma.rs b/src/obikphylo/src/tree/upgma.rs index e908b3cc..a4f20ca4 100644 --- a/src/obikphylo/src/tree/upgma.rs +++ b/src/obikphylo/src/tree/upgma.rs @@ -25,8 +25,10 @@ pub fn upgma(matrix: &Array2, labels: &[String]) -> Tree { // for each successive merge, in the order `dendro.steps()` yields them // — so appending to `node_of` as we go keeps `node_of[cluster_id]` // valid the moment a later step references it. - let mut node_of: Vec = - labels.iter().map(|label| tree.new_leaf(label.clone())).collect(); + let mut node_of: Vec = labels + .iter() + .map(|label| tree.new_leaf(label.clone())) + .collect(); // height of each node: leaves = 0, internal = dissimilarity/2 (UPGMA is // ultrametric: both children of a merge are equidistant from it). let mut heights = vec![0.0f64; 2 * n - 1]; diff --git a/src/obikquery/src/batch.rs b/src/obikquery/src/batch.rs index 87c81d59..3c5e7f83 100644 --- a/src/obikquery/src/batch.rs +++ b/src/obikquery/src/batch.rs @@ -50,10 +50,13 @@ impl QueryBatch { let part_idx = (rsk.minimizer().seq_hash() & mask) as usize; let part = &mut occurrences[part_idx]; for (j, kmer) in rsk.superkmer().iter_canonical_kmers().enumerate() { - part.push((kmer, KmerDesc { - seq_idx: seq_idx as u32, - pos: kmer_offset + j as u32, - })); + part.push(( + kmer, + KmerDesc { + seq_idx: seq_idx as u32, + pos: kmer_offset + j as u32, + }, + )); } let n = (rsk.seql() - k + 1) as u32; kmer_offset += n; diff --git a/src/obikquery/src/chunk.rs b/src/obikquery/src/chunk.rs index 1de0014c..ceefda14 100644 --- a/src/obikquery/src/chunk.rs +++ b/src/obikquery/src/chunk.rs @@ -65,9 +65,21 @@ pub fn process_chunk( // drained, only iterated by reference): this is its footprint for the // whole chunk lifetime. Measured by allocated capacity, not logical length. debug!( - n_unique_kmers_total = batch.by_partition.iter().map(|p| p.len() as u64).sum::(), - n_occurrences_total = batch.by_partition.iter().map(|p| p.n_occurrences() as u64).sum::(), - by_partition_bytes = batch.by_partition.iter().map(|p| p.allocated_bytes() as u64).sum::(), + n_unique_kmers_total = batch + .by_partition + .iter() + .map(|p| p.len() as u64) + .sum::(), + n_occurrences_total = batch + .by_partition + .iter() + .map(|p| p.n_occurrences() as u64) + .sum::(), + by_partition_bytes = batch + .by_partition + .iter() + .map(|p| p.allocated_bytes() as u64) + .sum::(), chunk_bytes, "by_partition memory retained" ); @@ -125,9 +137,9 @@ pub fn process_chunk( // total retained memory is O(actual hits), not O(total_smers × n_genomes) // — the whole point of this pass. See sparse_findere_for_genome's doc for // why run detection is equivalent to the dense scan's semantics. - let presence = force_presence || !with_counts; + let presence = force_presence || !with_counts; let threshold = presence_threshold; - let z = effective_z; + let z = effective_z; let n_kmers_out: Vec = batch .n_kmers @@ -166,7 +178,11 @@ pub fn process_chunk( n_dense_would_be, n_sparse_entries, n_runs = n_runs_total, - avg_run_len = if n_runs_total > 0 { run_len_total as f64 / n_runs_total as f64 } else { 0.0 }, + avg_run_len = if n_runs_total > 0 { + run_len_total as f64 / n_runs_total as f64 + } else { + 0.0 + }, z, "sparse Findere" ); @@ -174,8 +190,14 @@ pub fn process_chunk( // Actual bytes retained by the sparse hit structures (by_genome + // confirmed_by_genome, both alive simultaneously at this point). const HIT_ENTRY_BYTES: u64 = std::mem::size_of::<(u32, u32, u32)>() as u64; - let by_genome_bytes: u64 = by_genome.iter().map(|v| v.capacity() as u64 * HIT_ENTRY_BYTES).sum(); - let confirmed_bytes: u64 = confirmed_by_genome.iter().map(|v| v.capacity() as u64 * HIT_ENTRY_BYTES).sum(); + let by_genome_bytes: u64 = by_genome + .iter() + .map(|v| v.capacity() as u64 * HIT_ENTRY_BYTES) + .sum(); + let confirmed_bytes: u64 = confirmed_by_genome + .iter() + .map(|v| v.capacity() as u64 * HIT_ENTRY_BYTES) + .sum(); let retained_bytes = by_genome_bytes + confirmed_bytes; debug!( @@ -215,7 +237,10 @@ pub fn process_chunk( // ── Coverage (--detail): densify only when actually requested ──────────── let mut cov: Vec>> = if detail { - n_kmers_out.iter().map(|&n| vec![vec![0u32; n]; n_genomes]).collect() + n_kmers_out + .iter() + .map(|&n| vec![vec![0u32; n]; n_genomes]) + .collect() } else { Vec::new() }; diff --git a/src/obikquery/src/findere.rs b/src/obikquery/src/findere.rs index a5042276..58c6be44 100644 --- a/src/obikquery/src/findere.rs +++ b/src/obikquery/src/findere.rs @@ -58,7 +58,11 @@ pub(crate) fn sparse_findere_for_genome( let win_min = dq.front().unwrap().1; if win_min > 0 { let pos_out = pos + 1 - z as u32; - let c = if presence { u32::from(win_min >= threshold) } else { win_min }; + let c = if presence { + u32::from(win_min >= threshold) + } else { + win_min + }; confirmed.push((seq, pos_out, c)); } } diff --git a/src/obikquery/src/lib.rs b/src/obikquery/src/lib.rs index 00ad862c..b848aafe 100644 --- a/src/obikquery/src/lib.rs +++ b/src/obikquery/src/lib.rs @@ -5,14 +5,14 @@ //! the data model, never the reverse), same pattern as `obikindexer` for the //! build side. -mod partition_kmers; -mod query_layer; mod batch; mod chunk; mod findere; -mod smer_index; mod output; +mod partition_kmers; +mod query_layer; +mod smer_index; +pub use chunk::process_chunk; pub use partition_kmers::PartitionKmers; pub use query_layer::{KmerDesc, QueryHit, QueryPartition, QueryStats}; -pub use chunk::process_chunk; diff --git a/src/obikquery/src/partition_kmers.rs b/src/obikquery/src/partition_kmers.rs index b09e4a12..64df35ed 100644 --- a/src/obikquery/src/partition_kmers.rs +++ b/src/obikquery/src/partition_kmers.rs @@ -24,7 +24,11 @@ pub struct PartitionKmers { impl PartitionKmers { pub fn empty() -> Self { - Self { kmers: Vec::new(), starts: vec![0], descs: Vec::new() } + Self { + kmers: Vec::new(), + starts: vec![0], + descs: Vec::new(), + } } /// Group `occurrences` by k-mer. Consumes the (16 bytes per occurrence) @@ -45,7 +49,11 @@ impl PartitionKmers { starts.push(offset(descs.len())); kmers.shrink_to_fit(); starts.shrink_to_fit(); - Self { kmers, starts, descs } + Self { + kmers, + starts, + descs, + } } /// Number of unique k-mers. @@ -65,7 +73,10 @@ impl PartitionKmers { /// `(kmer, its occurrences)` for every unique k-mer, in k-mer order. pub fn iter(&self) -> impl Iterator + '_ { self.kmers.iter().enumerate().map(|(i, &kmer)| { - (kmer, &self.descs[self.starts[i] as usize..self.starts[i + 1] as usize]) + ( + kmer, + &self.descs[self.starts[i] as usize..self.starts[i + 1] as usize], + ) }) } @@ -78,5 +89,7 @@ impl PartitionKmers { } fn offset(i: usize) -> u32 { - u32::try_from(i).expect("more than 2^32 k-mer occurrences in one partition of one chunk — lower --chunk-size") + u32::try_from(i).expect( + "more than 2^32 k-mer occurrences in one partition of one chunk — lower --chunk-size", + ) } diff --git a/src/obikquery/src/tests/batch.rs b/src/obikquery/src/tests/batch.rs index 84589f84..98241e99 100644 --- a/src/obikquery/src/tests/batch.rs +++ b/src/obikquery/src/tests/batch.rs @@ -66,7 +66,10 @@ fn duplicated_sequence_across_records_deduplicates() { let unique = total_unique_kmers(&batch); assert!(batch.n_kmers[0] > 0); - assert_eq!(occurrences, batch.n_kmers[0] as u64 + batch.n_kmers[1] as u64); + assert_eq!( + occurrences, + batch.n_kmers[0] as u64 + batch.n_kmers[1] as u64 + ); assert!( unique <= batch.n_kmers[0] as u64, "identical sequences must not produce more unique k-mers than one copy has" @@ -86,9 +89,9 @@ fn duplicated_sequence_broadcasts_to_both_seq_indices() { let fasta = format!(">r1\n{SEQ}\n>r2\n{SEQ}\n"); let batch = batch_from_fasta(&fasta, K, 1); - let shared = batch.by_partition[0] - .iter() - .find(|(_, descs)| descs.iter().any(|d| d.seq_idx == 0) && descs.iter().any(|d| d.seq_idx == 1)); + let shared = batch.by_partition[0].iter().find(|(_, descs)| { + descs.iter().any(|d| d.seq_idx == 0) && descs.iter().any(|d| d.seq_idx == 1) + }); assert!( shared.is_some(), @@ -134,7 +137,11 @@ fn occurrences_of_a_kmer_come_out_in_query_order() { let fasta = format!(">r1\n{SEQ}\n>r2\n{SEQ}\n"); let batch = batch_from_fasta(&fasta, K, 1); for (_, descs) in batch.by_partition[0].iter() { - assert!(descs.windows(2).all(|w| (w[0].seq_idx, w[0].pos) < (w[1].seq_idx, w[1].pos))); + assert!( + descs + .windows(2) + .all(|w| (w[0].seq_idx, w[0].pos) < (w[1].seq_idx, w[1].pos)) + ); } let occ: usize = batch.by_partition[0].iter().map(|(_, d)| d.len()).sum(); assert_eq!(occ as u64, total_occurrences(&batch)); diff --git a/src/obikquery/src/tests/findere.rs b/src/obikquery/src/tests/findere.rs index 76b2b36e..1df0a086 100644 --- a/src/obikquery/src/tests/findere.rs +++ b/src/obikquery/src/tests/findere.rs @@ -40,7 +40,11 @@ fn dense_reference_findere( let win_min = dq.front().unwrap().1; if win_min > 0 { let pos_out = (i + 1 - z) as u32; - let c = if presence { u32::from(win_min >= threshold) } else { win_min }; + let c = if presence { + u32::from(win_min >= threshold) + } else { + win_min + }; confirmed.push((seq_idx as u32, pos_out, c)); } } diff --git a/src/obikrebuild/src/compact_layer.rs b/src/obikrebuild/src/compact_layer.rs index 47453250..4a9ebdeb 100644 --- a/src/obikrebuild/src/compact_layer.rs +++ b/src/obikrebuild/src/compact_layer.rs @@ -90,7 +90,12 @@ fn compact_partition( mode, !use_counts, 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") + }, )?; // ── Swap: drop every existing layer, install the combined one as layer 0 ─ diff --git a/src/obikrebuild/src/reindex.rs b/src/obikrebuild/src/reindex.rs index 053eb502..69329772 100644 --- a/src/obikrebuild/src/reindex.rs +++ b/src/obikrebuild/src/reindex.rs @@ -67,14 +67,21 @@ impl IndexReindex for KmerIndex { pb.finish_and_clear(); - self.meta().set_evidence(target, block_bits).map_err(OKIError::Io)?; + self.meta() + .set_evidence(target, block_bits) + .map_err(OKIError::Io)?; rep.push(t.stop()); Ok(()) } } /// Process every layer of partition `i`. -fn reindex_partition(index: &KmerIndex, i: usize, target: &IndexMode, block_bits: u8) -> OKIResult<()> { +fn reindex_partition( + index: &KmerIndex, + i: usize, + target: &IndexMode, + block_bits: u8, +) -> OKIResult<()> { let partition = index.partition(i)?; let n_layers = partition.n_layers(); for l in 0..n_layers { diff --git a/src/obikselect/src/group_specs.rs b/src/obikselect/src/group_specs.rs index 71b2db32..b96773bc 100644 --- a/src/obikselect/src/group_specs.rs +++ b/src/obikselect/src/group_specs.rs @@ -33,7 +33,10 @@ pub struct ColumnSpecParams<'a> { /// Resolve `p` against `meta` into an ordered list of output columns. /// /// Returns `(specs, output_presence)`. -pub fn build_output_cols(meta: &IndexMeta, p: ColumnSpecParams) -> Result<(Vec, bool), String> { +pub fn build_output_cols( + meta: &IndexMeta, + p: ColumnSpecParams, +) -> Result<(Vec, bool), String> { let genomes = meta.genomes().map_err(|e| e.to_string())?; // ── 1. group_indices: name → Vec, in definition order ────────── @@ -74,7 +77,9 @@ pub fn build_output_cols(meta: &IndexMeta, p: ColumnSpecParams) -> Result<(Vec = genomes.iter().enumerate() + let label_to_idx: HashMap<&str, usize> = genomes + .iter() + .enumerate() .map(|(i, g)| (g.label.as_str(), i)) .collect(); @@ -91,10 +96,16 @@ pub fn build_output_cols(meta: &IndexMeta, p: ColumnSpecParams) -> Result<(Vec = Vec::with_capacity(col_names.len()); for name in &col_names { if let Some(idxs) = group_indices.get(name) { - let op = group_op.get(name).copied() + let op = group_op + .get(name) + .copied() .or(global_op) .unwrap_or_else(|| AggOp::default_for(p.src_is_count)); - specs.push(OutputCol { label: name.clone(), indices: idxs.clone(), op }); + specs.push(OutputCol { + label: name.clone(), + indices: idxs.clone(), + op, + }); } else if let Some(&idx) = label_to_idx.get(name.as_str()) { specs.push(OutputCol { label: name.clone(), @@ -102,7 +113,9 @@ pub fn build_output_cols(meta: &IndexMeta, p: ColumnSpecParams) -> Result<(Vec { src: &'a KmerIndex, @@ -113,7 +113,11 @@ impl Algorithm for Select<'_> { src.n_partitions(), n_src_genomes, self.specs.len(), - if self.output_presence { "presence" } else { "count" }, + if self.output_presence { + "presence" + } else { + "count" + }, ); KmerIndex::clear_output_for_create(&output, self.force)?; @@ -138,7 +142,17 @@ impl Algorithm for Select<'_> { runner .run( &order, - |i| select_partition(&dst, src, i, self.specs, self.threshold, self.output_presence, self.force_copy), + |i| { + select_partition( + &dst, + src, + i, + self.specs, + self.threshold, + self.output_presence, + self.force_copy, + ) + }, |_, _, _| { done += 1; if let Some(cb) = on_progress.as_mut() { diff --git a/src/obikselect/src/select_layer.rs b/src/obikselect/src/select_layer.rs index 9a668905..9f1659e9 100644 --- a/src/obikselect/src/select_layer.rs +++ b/src/obikselect/src/select_layer.rs @@ -88,7 +88,11 @@ enum AggResult { /// docs for why: `sum` = the count itself, `any`/`max` = `count ≥ 1`, /// `all`/`min` = `count == group size`, `none` = `count == 0`) — no further /// matrix access needed once `count` is in hand. -fn agg_result_from_count(op: AggOp, group_len: usize, count: TempCompactIntVec) -> io::Result { +fn agg_result_from_count( + op: AggOp, + group_len: usize, + count: TempCompactIntVec, +) -> io::Result { let n = count.len(); let group_len = group_len as u32; Ok(match op { @@ -125,7 +129,11 @@ fn agg_result_from_count(op: AggOp, group_len: usize, count: TempCompactIntVec) /// bit-matrix case, `sum`/`min`/`max` are genuine per-value reductions /// already computed by `batch_int_group_stats`, not further derivations; /// only `any`/`all`/`none` still need a threshold-count comparison here. -fn agg_result_from_int_stats(op: AggOp, group_len: usize, stats: IntGroupStats) -> io::Result { +fn agg_result_from_int_stats( + op: AggOp, + group_len: usize, + stats: IntGroupStats, +) -> io::Result { let n = stats.presence_count.len(); let group_len = group_len as u32; Ok(match op { @@ -256,7 +264,8 @@ pub(crate) fn select_partition( .iter() .map(|s| ColGroup::new(s.label.clone(), s.indices.clone())) .collect(); - let stats = batch_int_group_stats(&mat, &groups, threshold).map_err(OKIError::Io)?; + let stats = + batch_int_group_stats(&mat, &groups, threshold).map_err(OKIError::Io)?; for (spec, stat) in specs.iter().zip(stats) { let r = agg_result_from_int_stats(spec.op, spec.indices.len(), stat) .map_err(OKIError::Io)?; diff --git a/src/obikseq/benches/superkmer.rs b/src/obikseq/benches/superkmer.rs index 0464390e..923a38d2 100644 --- a/src/obikseq/benches/superkmer.rs +++ b/src/obikseq/benches/superkmer.rs @@ -1,7 +1,7 @@ use criterion::{BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; +use obikseq::Sequence; use obikseq::packed_seq::PackedSeq; use obikseq::superkmer::SuperKmer; -use obikseq::Sequence; const LENGTHS: &[usize] = &[1, 4, 8, 16, 40, 64, 128, 255, 256]; @@ -57,7 +57,11 @@ fn bench_revcomp(c: &mut Criterion) { group.bench_with_input(BenchmarkId::from_parameter(len), &seq, |b, seq| { b.iter_batched( || seq.clone(), - |s| { let mut s = std::hint::black_box(s); s.revcomp_inplace(); s }, + |s| { + let mut s = std::hint::black_box(s); + s.revcomp_inplace(); + s + }, BatchSize::SmallInput, ); }); @@ -68,30 +72,37 @@ fn bench_revcomp(c: &mut Criterion) { fn bench_canonical(c: &mut Criterion) { let mut group = c.benchmark_group("canonical"); for &len in LENGTHS { - let sk_rc = SuperKmer::from_ascii(&vec![b'T'; len]); + let sk_rc = SuperKmer::from_ascii(&vec![b'T'; len]); let sk_fwd = SuperKmer::from_ascii(&vec![b'A'; len]); group.throughput(Throughput::Bytes(len as u64)); + group.bench_with_input(BenchmarkId::new("needs_revcomp", len), &sk_rc, |b, sk| { + b.iter_batched( + || sk.clone(), + |s| std::hint::black_box(s).canonical(), + BatchSize::SmallInput, + ); + }); group.bench_with_input( - BenchmarkId::new("needs_revcomp", len), &sk_rc, |b, sk| { + BenchmarkId::new("already_canonical", len), + &sk_fwd, + |b, sk| { b.iter_batched( || sk.clone(), |s| std::hint::black_box(s).canonical(), BatchSize::SmallInput, ); - } - ); - group.bench_with_input( - BenchmarkId::new("already_canonical", len), &sk_fwd, |b, sk| { - b.iter_batched( - || sk.clone(), - |s| std::hint::black_box(s).canonical(), - BatchSize::SmallInput, - ); - } + }, ); } group.finish(); } -criterion_group!(benches, bench_from_ascii, bench_to_ascii, bench_write_ascii, bench_revcomp, bench_canonical); +criterion_group!( + benches, + bench_from_ascii, + bench_to_ascii, + bench_write_ascii, + bench_revcomp, + bench_canonical +); criterion_main!(benches); diff --git a/src/obikseq/src/encoding.rs b/src/obikseq/src/encoding.rs index 7f14fd1f..d95aaf20 100644 --- a/src/obikseq/src/encoding.rs +++ b/src/obikseq/src/encoding.rs @@ -2,10 +2,10 @@ // Indexed by b & 0x1F — 32 entries, handles upper/lowercase identically, // ambiguous bases and unknowns silently map to A (0). pub(crate) static ENC: [u8; 32] = [ -// _ A B C D E F G H I J K L M N O - 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, -// P Q R S T U V W X Y Z ... - 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // _ A B C D E F G H I J K L M N O + 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, + // P Q R S T U V W X Y Z ... + 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; // DEC4: packed byte → 4 ASCII nucleotides encoded as big-endian u32. @@ -22,9 +22,9 @@ const fn build_dec4() -> [u32; 256] { let mut i = 0usize; while i < 256 { table[i] = (DECODE[(i >> 6) & 3] as u32) << 24 - | (DECODE[(i >> 4) & 3] as u32) << 16 - | (DECODE[(i >> 2) & 3] as u32) << 8 - | DECODE[i & 3] as u32; + | (DECODE[(i >> 4) & 3] as u32) << 16 + | (DECODE[(i >> 2) & 3] as u32) << 8 + | DECODE[i & 3] as u32; i += 1; } table diff --git a/src/obikseq/src/kmer.rs b/src/obikseq/src/kmer.rs index dd0af8f0..6bc7c1bb 100644 --- a/src/obikseq/src/kmer.rs +++ b/src/obikseq/src/kmer.rs @@ -212,14 +212,20 @@ impl KmerOf { pub fn push_right(self, nuc: u8) -> Self { let k = L::len(); let shifted = self.0 << 2 & (RawKmer::MAX << (KMER_BITS - 2 * (k - 1))); - KmerOf(shifted | ((nuc as RawKmer & 3) << (KMER_BITS - 2 * k)), PhantomData) + KmerOf( + shifted | ((nuc as RawKmer & 3) << (KMER_BITS - 2 * k)), + PhantomData, + ) } /// Slide the window one base to the left: drop nucleotide `L::len()-1`, prepend `nuc` at position 0. pub fn push_left(self, nuc: u8) -> Self { let k = L::len(); let shifted = (self.0 >> 2) & (RawKmer::MAX << (KMER_BITS - 2 * k)); - KmerOf(shifted | ((nuc as RawKmer & 3) << (KMER_BITS - 2)), PhantomData) + KmerOf( + shifted | ((nuc as RawKmer & 3) << (KMER_BITS - 2)), + PhantomData, + ) } /// Returns `true` if the last `L::len()-1` nucleotides of `self` equal the first `L::len()-1` of `other`. diff --git a/src/obikseq/src/lib.rs b/src/obikseq/src/lib.rs index 626f90a7..0563656d 100644 --- a/src/obikseq/src/lib.rs +++ b/src/obikseq/src/lib.rs @@ -20,7 +20,7 @@ pub mod superkmer; pub mod unitig; pub use annotations::Annotation; -pub use kmer::{CanonicalKmer, Kmer, Minimizer, RawKmer, KMER_BITS, hash_kmer}; +pub use kmer::{CanonicalKmer, KMER_BITS, Kmer, Minimizer, RawKmer, hash_kmer}; pub use packed_seq::MAX_KMERS_PER_CHUNK; pub use params::{k, m, set_k, set_m}; pub use routable::RoutableSuperKmer; diff --git a/src/obikseq/src/packed_seq.rs b/src/obikseq/src/packed_seq.rs index 580b9d8f..0614568f 100644 --- a/src/obikseq/src/packed_seq.rs +++ b/src/obikseq/src/packed_seq.rs @@ -18,7 +18,9 @@ use bitvec::prelude::*; use crate::Sequence; use crate::encoding::{DEC4, encode_base}; -use crate::kmer::{CanonicalKmer, Kmer, KmerError, KLen, KmerLength, KmerOf, MLen, Minimizer, RawKmer, KMER_BITS}; +use crate::kmer::{ + CanonicalKmer, KLen, KMER_BITS, Kmer, KmerError, KmerLength, KmerOf, MLen, Minimizer, RawKmer, +}; use crate::params::k; use crate::revcomp_lookup::REVCOMP4; @@ -143,7 +145,6 @@ impl FromIterator for PackedSeq { } impl PackedSeq { - /// Write ASCII nucleotides into `writer`. Zero allocation. pub fn write_ascii(&self, writer: &mut W) -> io::Result<()> { let seql = self.seql(); @@ -223,7 +224,11 @@ impl PackedSeq { let len = L::len(); let seql = self.seql(); if i + len > seql { - return Err(KmerError::OutOfBounds { position: i, k: len, seql }); + return Err(KmerError::OutOfBounds { + position: i, + k: len, + seql, + }); } let bits = self.seq.view_bits::(); let raw: RawKmer = bits[i * 2..(i + len) * 2].load_be(); @@ -330,7 +335,9 @@ impl PackedSeq { } impl AsRef for PackedSeq { - fn as_ref(&self) -> &PackedSeq { self } + fn as_ref(&self) -> &PackedSeq { + self + } } // ── PackedSeqKmerIter ───────────────────────────────────────────────────────── @@ -376,7 +383,14 @@ impl> PackedSeqKmerIter { } else { 0 }; - Self { seq, mask, lshift, current, pos: klen, max_pos: seql } + Self { + seq, + mask, + lshift, + current, + pos: klen, + max_pos: seql, + } } } @@ -428,7 +442,10 @@ pub(crate) fn read_varint(r: &mut R) -> io::Result { } shift += 7; if shift >= 64 { - return Err(io::Error::new(io::ErrorKind::InvalidData, "varint overflow")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "varint overflow", + )); } } Ok(val) diff --git a/src/obikseq/src/params.rs b/src/obikseq/src/params.rs index 3d0e48ec..a491a890 100644 --- a/src/obikseq/src/params.rs +++ b/src/obikseq/src/params.rs @@ -41,20 +41,30 @@ mod state { pub fn set_k(k: usize) { K.get_or_init(|| k); - assert_eq!(*K.get().unwrap(), k, "K already initialized to a different value"); + assert_eq!( + *K.get().unwrap(), + k, + "K already initialized to a different value" + ); } pub fn k() -> usize { - *K.get().expect("K not initialized — call params::set_k or params::init first") + *K.get() + .expect("K not initialized — call params::set_k or params::init first") } pub fn set_m(m: usize) { M.get_or_init(|| m); - assert_eq!(*M.get().unwrap(), m, "M already initialized to a different value"); + assert_eq!( + *M.get().unwrap(), + m, + "M already initialized to a different value" + ); } pub fn m() -> usize { - *M.get().expect("M not initialized — call params::set_m or params::init first") + *M.get() + .expect("M not initialized — call params::set_m or params::init first") } } @@ -72,10 +82,18 @@ mod state { static K: AtomicUsize = AtomicUsize::new(0); static M: AtomicUsize = AtomicUsize::new(0); - pub fn set_k(k: usize) { K.store(k, Ordering::SeqCst); } - pub fn k() -> usize { K.load(Ordering::SeqCst) } - pub fn set_m(m: usize) { M.store(m, Ordering::SeqCst); } - pub fn m() -> usize { M.load(Ordering::SeqCst) } + pub fn set_k(k: usize) { + K.store(k, Ordering::SeqCst); + } + pub fn k() -> usize { + K.load(Ordering::SeqCst) + } + pub fn set_m(m: usize) { + M.store(m, Ordering::SeqCst); + } + pub fn m() -> usize { + M.load(Ordering::SeqCst) + } } // ── Public API (identical signature in both configurations) ─────────────────── diff --git a/src/obikseq/src/revcomp_lookup.rs b/src/obikseq/src/revcomp_lookup.rs index 61a3a74b..3e3442af 100644 --- a/src/obikseq/src/revcomp_lookup.rs +++ b/src/obikseq/src/revcomp_lookup.rs @@ -3,9 +3,9 @@ pub(crate) static REVCOMP4: [u8; 256] = build_revcomp4(); pub(crate) const fn revcomp4(x: u8) -> u8 { - let x = !x; // complement all bases - let x = (x >> 4) | (x << 4); // swap nibbles - let x = ((x >> 2) & 0x33) | ((x & 0x33) << 2); // swap 2-bit groups + let x = !x; // complement all bases + let x = (x >> 4) | (x << 4); // swap nibbles + let x = ((x >> 2) & 0x33) | ((x & 0x33) << 2); // swap 2-bit groups x } diff --git a/src/obikseq/src/routable.rs b/src/obikseq/src/routable.rs index 411fcb0d..cb624a8c 100644 --- a/src/obikseq/src/routable.rs +++ b/src/obikseq/src/routable.rs @@ -47,7 +47,10 @@ impl RoutableSuperKmer { }; let minimizer = inner.mmer(adjusted_pos).unwrap(); let superkmer = SuperKmer { count: 1, inner }; - Self { superkmer, minimizer } + Self { + superkmer, + minimizer, + } } /// Borrow the canonical super-kmer sequence. diff --git a/src/obikseq/src/sequence.rs b/src/obikseq/src/sequence.rs index 4f8220df..007a3e8f 100644 --- a/src/obikseq/src/sequence.rs +++ b/src/obikseq/src/sequence.rs @@ -32,7 +32,9 @@ pub trait Sequence { /// /// Default: `BasicAnnotation { seq_length }`. Override for richer metadata. fn annotation(&self) -> impl Annotation { - BasicAnnotation { seq_length: self.seql() } + BasicAnnotation { + seq_length: self.seql(), + } } /// Decode into ASCII nucleotides, writing into `writer`. diff --git a/src/obikseq/src/superkmer.rs b/src/obikseq/src/superkmer.rs index b6c97a3a..8d373bae 100644 --- a/src/obikseq/src/superkmer.rs +++ b/src/obikseq/src/superkmer.rs @@ -114,7 +114,9 @@ impl SuperKmer { chunk.canonicalize(); write_varint(w, self.count as u64)?; chunk.write_to_binary(w)?; - if end == seql { break; } + if end == seql { + break; + } start += stride; } Ok(()) diff --git a/src/obikseq/src/tests/kmer.rs b/src/obikseq/src/tests/kmer.rs index 503b68ed..d0d1b34e 100644 --- a/src/obikseq/src/tests/kmer.rs +++ b/src/obikseq/src/tests/kmer.rs @@ -220,10 +220,20 @@ mod tests { // orientation when canonicalised (verified by hand: each is already // lexicographically <= its own reverse complement), so this case // exercises the substitution logic without the RC-flip edge case. - let ck = KmerOf::>::from_ascii(b"ACG").unwrap().canonical(); + let ck = KmerOf::>::from_ascii(b"ACG") + .unwrap() + .canonical(); let neighbours = ck.central_canonical_neighbors(); let ascii: Vec> = neighbours.iter().map(|n| n.to_ascii()).collect(); - assert_eq!(ascii, vec![b"AAG".to_vec(), b"ACG".to_vec(), b"AGG".to_vec(), b"ATG".to_vec()]); + assert_eq!( + ascii, + vec![ + b"AAG".to_vec(), + b"ACG".to_vec(), + b"AGG".to_vec(), + b"ATG".to_vec() + ] + ); // The identity substitution (centre unchanged) must reproduce `ck`. assert!(neighbours.contains(&ck)); } @@ -243,7 +253,12 @@ mod tests { ); // Every returned neighbour must itself already be canonical. for n in &neighbours { - assert_eq!(n.into_kmer().canonical(), *n, "neighbour not canonical for k={}", $n); + assert_eq!( + n.into_kmer().canonical(), + *n, + "neighbour not canonical for k={}", + $n + ); } }}; } @@ -269,8 +284,11 @@ mod tests { let ck = K::from_ascii(&ascii).unwrap().canonical(); let id = ck.family_id(); assert_eq!(id, ck.revcomp().canonical().family_id()); - let mut members: Vec<_> = - ck.central_canonical_neighbors().iter().map(|n| n.raw()).collect(); + let mut members: Vec<_> = ck + .central_canonical_neighbors() + .iter() + .map(|n| n.raw()) + .collect(); members.sort_unstable(); for n in ck.central_canonical_neighbors() { assert_eq!(n.family_id(), id, "k={}: members disagree", $n); @@ -280,7 +298,11 @@ mod tests { } // One id <=> one family: all members seen under an id share one member set. for sets in families.values() { - assert!(sets.windows(2).all(|w| w[0] == w[1]), "k={}: id merges families", $n); + assert!( + sets.windows(2).all(|w| w[0] == w[1]), + "k={}: id merges families", + $n + ); } }}; } @@ -291,13 +313,18 @@ mod tests { #[test] fn family_id_ascii_masks_centre() { - let ck = KmerOf::>::from_ascii(b"ACGTA").unwrap().canonical(); + let ck = KmerOf::>::from_ascii(b"ACGTA") + .unwrap() + .canonical(); let mut out = Vec::new(); ck.write_family_id_ascii(&mut out).unwrap(); assert_eq!(out.len(), 5); assert_eq!(out[2], b'N'); // flanks of the id are the family's two flank pairs, in either orientation let id_ascii = ck.family_id().to_ascii(); - assert_eq!([out[0], out[1], out[3], out[4]], [id_ascii[0], id_ascii[1], id_ascii[3], id_ascii[4]]); + assert_eq!( + [out[0], out[1], out[3], out[4]], + [id_ascii[0], id_ascii[1], id_ascii[3], id_ascii[4]] + ); } } diff --git a/src/obikseq/src/tests/superkmer.rs b/src/obikseq/src/tests/superkmer.rs index 3cc05627..3e63aaa7 100644 --- a/src/obikseq/src/tests/superkmer.rs +++ b/src/obikseq/src/tests/superkmer.rs @@ -70,7 +70,13 @@ fn seql_roundtrip() { fn binary_test_lengths(k: usize) -> Vec { use crate::packed_seq::MAX_KMERS_PER_CHUNK; // Only single-chunk lengths: seql in [k, MAX_KMERS_PER_CHUNK+k-1]. - (k..=k + 5).chain([MAX_KMERS_PER_CHUNK + k - 3, MAX_KMERS_PER_CHUNK + k - 2, MAX_KMERS_PER_CHUNK + k - 1]).collect() + (k..=k + 5) + .chain([ + MAX_KMERS_PER_CHUNK + k - 3, + MAX_KMERS_PER_CHUNK + k - 2, + MAX_KMERS_PER_CHUNK + k - 1, + ]) + .collect() } #[test] @@ -83,7 +89,11 @@ fn binary_roundtrip() { let mut buf = Vec::new(); sk.write_to_binary(&mut buf).unwrap(); let sk2 = SuperKmer::read_from_binary(&mut buf.as_slice()).unwrap(); - assert_eq!(sk.to_ascii(), sk2.to_ascii(), "sequence mismatch for len={len}"); + assert_eq!( + sk.to_ascii(), + sk2.to_ascii(), + "sequence mismatch for len={len}" + ); assert_eq!(sk2.count(), 42, "count mismatch for len={len}"); } } @@ -109,7 +119,7 @@ fn binary_split_roundtrip() { assert_eq!(chunk1.count(), 7); // Chunks cover the original sequence with k-1 overlap — no kmer lost. assert_eq!(chunk0.seql(), MAX_KMERS_PER_CHUNK + k - 1); - assert_eq!(chunk1.seql(), k); // 1 kmer + assert_eq!(chunk1.seql(), k); // 1 kmer } #[test] diff --git a/src/obikseq/src/tests/unitig.rs b/src/obikseq/src/tests/unitig.rs index a7b7673e..b1d75418 100644 --- a/src/obikseq/src/tests/unitig.rs +++ b/src/obikseq/src/tests/unitig.rs @@ -164,7 +164,13 @@ mod tests { use crate::packed_seq::MAX_KMERS_PER_CHUNK; set_k(4); let k = crate::params::k(); - let valid_lengths: Vec = (k..=9).chain([MAX_KMERS_PER_CHUNK + k - 3, MAX_KMERS_PER_CHUNK + k - 2, MAX_KMERS_PER_CHUNK + k - 1]).collect(); + let valid_lengths: Vec = (k..=9) + .chain([ + MAX_KMERS_PER_CHUNK + k - 3, + MAX_KMERS_PER_CHUNK + k - 2, + MAX_KMERS_PER_CHUNK + k - 1, + ]) + .collect(); for len in valid_lengths { let u = Unitig::from_ascii(&make_seq(len)); let mut buf = Vec::new(); diff --git a/src/obiksession/src/memoize.rs b/src/obiksession/src/memoize.rs index 452ff275..515e0a01 100644 --- a/src/obiksession/src/memoize.rs +++ b/src/obiksession/src/memoize.rs @@ -60,9 +60,10 @@ impl MemoizeValue for u8 { vec![*self] } fn from_bytes(bytes: &[u8]) -> io::Result { - bytes.first().copied().ok_or_else(|| { - io::Error::new(io::ErrorKind::InvalidData, "invalid u8 bytes") - }) + bytes + .first() + .copied() + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid u8 bytes")) } } @@ -183,9 +184,7 @@ impl<'a> Memoize<'a> { F: FnOnce() -> io::Result, { let key = args.memo_key(function_name); - let raw = self.get_or_compute_with_key(&key, || { - compute_fn().map(|v| v.to_bytes()) - })?; + let raw = self.get_or_compute_with_key(&key, || compute_fn().map(|v| v.to_bytes()))?; Ok(raw) } @@ -243,7 +242,6 @@ impl<'a> Memoize<'a> { } } - /// Declarative memoization macro, similar in spirit to `kash`/`cached`. /// /// Wraps a function so that every call transparently consults the @@ -307,9 +305,13 @@ mod tests { let dir = tmp.path().join("session"); let session = Session::open(&dir, b"params", false).unwrap().unwrap(); let memo = Memoize::new(&session); - let computed = memo.get_or_compute_with_key("key1", || Ok(b"value1".to_vec())).unwrap(); + let computed = memo + .get_or_compute_with_key("key1", || Ok(b"value1".to_vec())) + .unwrap(); assert_eq!(&computed[..], b"value1"); - let cached = memo.get_or_compute_with_key("key1", || panic!("should not be called")).unwrap(); + let cached = memo + .get_or_compute_with_key("key1", || panic!("should not be called")) + .unwrap(); assert_eq!(&cached[..], b"value1"); } @@ -319,7 +321,8 @@ mod tests { let dir = tmp.path().join("session"); let session = Session::open(&dir, b"params", false).unwrap().unwrap(); let memo = Memoize::new(&session); - memo.get_or_compute_with_key("key1", || Ok(b"value1".to_vec())).unwrap(); + memo.get_or_compute_with_key("key1", || Ok(b"value1".to_vec())) + .unwrap(); assert!(memo.invalidate("key1").unwrap()); assert!(memo.restore_raw("key1").unwrap().is_none()); assert!(!memo.invalidate("key1").unwrap()); @@ -350,7 +353,10 @@ mod tests { x: u64, y: String, } - let args = Args { x: 42, y: "hello".into() }; + let args = Args { + x: 42, + y: "hello".into(), + }; let key1 = args.memo_key("my_fn"); let key2 = args.memo_key("my_fn"); assert_eq!(key1, key2); @@ -415,7 +421,6 @@ mod tests { approx::assert_relative_eq!(result2, 9.0); } - #[test] fn session_memoize_macro_persists_across_sessions() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/obiksession/src/session.rs b/src/obiksession/src/session.rs index 878929a2..cf189fa6 100644 --- a/src/obiksession/src/session.rs +++ b/src/obiksession/src/session.rs @@ -62,7 +62,11 @@ impl Session { /// outcomes. Blocks until the directory's lock is free (see /// [`obisys::DirLock::acquire`]) — a second process pointed at the /// same session directory waits rather than racing it. - pub fn open(dir: &Path, params: &[u8], force: bool) -> io::Result> { + pub fn open( + dir: &Path, + params: &[u8], + force: bool, + ) -> io::Result> { let lock = DirLock::acquire(dir)?; let params_path = dir.join(PARAMS_FILE); @@ -74,7 +78,10 @@ impl Session { _lock: lock, memo_locks: Mutex::new(HashMap::new()), })), - Some(saved) if !force => Ok(Err(ParamsConflict { saved, requested: params.to_vec() })), + Some(saved) if !force => Ok(Err(ParamsConflict { + saved, + requested: params.to_vec(), + })), _ => { // No saved params yet, or a mismatch with `force: true`: // start clean. Any artifact or memoized entry cached under @@ -162,7 +169,10 @@ impl Session { pub(crate) fn with_key_lock(&self, key: &str, f: impl FnOnce() -> T) -> T { let entry = { let mut table = self.memo_locks.lock().unwrap(); - table.entry(key.to_string()).or_insert_with(|| Arc::new(Mutex::new(()))).clone() + table + .entry(key.to_string()) + .or_insert_with(|| Arc::new(Mutex::new(()))) + .clone() }; let guard = entry.lock().unwrap(); @@ -297,7 +307,9 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let dir = tmp.path().join("session"); Session::open(&dir, b"params-v1", false).unwrap().unwrap(); - let conflict = Session::open(&dir, b"params-v2", false).unwrap().unwrap_err(); + let conflict = Session::open(&dir, b"params-v2", false) + .unwrap() + .unwrap_err(); assert_eq!(conflict.saved, b"params-v1"); assert_eq!(conflict.requested, b"params-v2"); } diff --git a/src/obikstats/src/null_model.rs b/src/obikstats/src/null_model.rs index da5a6580..d0c3d731 100644 --- a/src/obikstats/src/null_model.rs +++ b/src/obikstats/src/null_model.rs @@ -39,7 +39,13 @@ impl SharingNullModel { /// `genome_kmers[i]` is `N_i`; `k` is the (indexed) k-mer size, odd. pub fn new(genome_kmers: &[u64], k: usize) -> Self { let m = 4f64.powi(k as i32) / 2.0; - Self { m, p: genome_kmers.iter().map(|&n| (n as f64 / m).min(1.0)).collect() } + Self { + m, + p: genome_kmers + .iter() + .map(|&n| (n as f64 / m).min(1.0)) + .collect(), + } } /// `P(X >= r)` for `r = 0..=S`, by the dynamic programme of `kmers.md` @@ -83,7 +89,11 @@ impl SharingNullModel { let expected = if p1 > 0.0 { tail[r] / p1 } else { 0.0 }; let k_r = k_at_least[r]; let expected_false_positives = self.m * tail[r]; - let fdr = if k_r == 0 { 1.0 } else { (expected_false_positives / k_r as f64).min(1.0) }; + let fdr = if k_r == 0 { + 1.0 + } else { + (expected_false_positives / k_r as f64).min(1.0) + }; SharingRow { r, k_r, @@ -113,9 +123,14 @@ mod tests { let tail = m.tail(); let (p, s) = (0.25f64, 4usize); for r in 0..=s { - let expected: f64 = - (r..=s).map(|j| binom(s, j) * p.powi(j as i32) * (1.0 - p).powi((s - j) as i32)).sum(); - assert!((tail[r] - expected).abs() < 1e-12, "r={r}: {} vs {expected}", tail[r]); + let expected: f64 = (r..=s) + .map(|j| binom(s, j) * p.powi(j as i32) * (1.0 - p).powi((s - j) as i32)) + .sum(); + assert!( + (tail[r] - expected).abs() < 1e-12, + "r={r}: {} vs {expected}", + tail[r] + ); } assert!((tail[0] - 1.0).abs() < 1e-12); } @@ -123,7 +138,10 @@ mod tests { #[test] fn unequal_probabilities_two_genomes() { // p = (0.5, 0.25): P(X>=1) = 1 - 0.5*0.75, P(X>=2) = 0.125. - let m = SharingNullModel { m: 1.0, p: vec![0.5, 0.25] }; + let m = SharingNullModel { + m: 1.0, + p: vec![0.5, 0.25], + }; let t = m.tail(); assert!((t[1] - 0.625).abs() < 1e-15); assert!((t[2] - 0.125).abs() < 1e-15); @@ -140,8 +158,13 @@ mod tests { #[test] fn compare_first_row_has_zero_deviation() { - let spectrum = SharingSpectrum { genome_kmers: vec![10, 10], hist: vec![0, 15, 5] }; - let rows = SharingNullModel::new(&spectrum.genome_kmers, 11).compare(&spectrum).unwrap(); + let spectrum = SharingSpectrum { + genome_kmers: vec![10, 10], + hist: vec![0, 15, 5], + }; + let rows = SharingNullModel::new(&spectrum.genome_kmers, 11) + .compare(&spectrum) + .unwrap(); assert_eq!(rows.len(), 2); assert_eq!(rows[0].k_r, 20); assert_eq!(rows[1].k_r, 5); @@ -155,7 +178,10 @@ mod tests { // k = 3: M = 32; N = (8, 8) → p = 0.25 each; P(X>=2) = 0.0625. let model = SharingNullModel::new(&[8, 8], 3); // 10 k-mers in exactly 1 genome, 2 in both → k_1 = 12, k_2 = 2. - let spectrum = SharingSpectrum { genome_kmers: vec![8, 8], hist: vec![0, 10, 2] }; + let spectrum = SharingSpectrum { + genome_kmers: vec![8, 8], + hist: vec![0, 10, 2], + }; let rows = model.compare(&spectrum).unwrap(); // r = 2: FP = 32 * 0.0625 = 2; FDR = 2 / 2 = 1 (not below the cap). assert!((rows[1].expected_false_positives - 2.0).abs() < 1e-12); @@ -164,7 +190,10 @@ mod tests { assert!((rows[0].expected_false_positives - 14.0).abs() < 1e-12); assert!((rows[0].fdr - 1.0).abs() < 1e-12); // Fewer expected false positives than observed: 20 of 22 k-mers shared. - let spectrum = SharingSpectrum { genome_kmers: vec![8, 8], hist: vec![0, 2, 20] }; + let spectrum = SharingSpectrum { + genome_kmers: vec![8, 8], + hist: vec![0, 2, 20], + }; let rows = model.compare(&spectrum).unwrap(); assert!((rows[1].fdr - 2.0 / 20.0).abs() < 1e-12); } @@ -172,7 +201,10 @@ mod tests { #[test] fn fdr_is_one_when_no_kmer_reaches_r() { let model = SharingNullModel::new(&[8, 8, 8], 3); - let spectrum = SharingSpectrum { genome_kmers: vec![8, 8, 8], hist: vec![0, 12, 0, 0] }; + let spectrum = SharingSpectrum { + genome_kmers: vec![8, 8, 8], + hist: vec![0, 12, 0, 0], + }; let rows = model.compare(&spectrum).unwrap(); assert_eq!(rows[2].k_r, 0); assert_eq!(rows[2].fdr, 1.0); @@ -180,7 +212,14 @@ mod tests { #[test] fn empty_index_is_an_error() { - let spectrum = SharingSpectrum { genome_kmers: vec![0, 0], hist: vec![0, 0, 0] }; - assert!(SharingNullModel::new(&spectrum.genome_kmers, 11).compare(&spectrum).is_err()); + let spectrum = SharingSpectrum { + genome_kmers: vec![0, 0], + hist: vec![0, 0, 0], + }; + assert!( + SharingNullModel::new(&spectrum.genome_kmers, 11) + .compare(&spectrum) + .is_err() + ); } } diff --git a/src/obipipeline/src/scheduler/macros.rs b/src/obipipeline/src/scheduler/macros.rs index 145b47ff..0164c352 100644 --- a/src/obipipeline/src/scheduler/macros.rs +++ b/src/obipipeline/src/scheduler/macros.rs @@ -12,8 +12,7 @@ macro_rules! make_source { None => Err($crate::PipelineError::EndOfStream), } }, - ) - as Box ::std::result::Result<$enum, $crate::PipelineError> + Send> + ) as Box ::std::result::Result<$enum, $crate::PipelineError> + Send> }}; } @@ -30,8 +29,7 @@ macro_rules! make_source_fallible { None => Err($crate::PipelineError::EndOfStream), } }, - ) - as Box ::std::result::Result<$enum, $crate::PipelineError> + Send> + ) as Box ::std::result::Result<$enum, $crate::PipelineError> + Send> }}; } @@ -40,21 +38,17 @@ macro_rules! make_source_fallible { macro_rules! make_transform { ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ let __f = $func; - $crate::Stage::Transform( - ::std::sync::Arc::from(Box::new( - move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> { - match data { - $enum::$input(x) => Ok($enum::$output(__f(x))), - _ => Err($crate::PipelineError::TypeMismatch), - } - }, - ) - as Box< - dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> - + Send - + Sync, - >) + $crate::Stage::Transform(::std::sync::Arc::from(Box::new( + move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> { + match data { + $enum::$input(x) => Ok($enum::$output(__f(x))), + _ => Err($crate::PipelineError::TypeMismatch), + } + }, ) + as Box< + dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> + Send + Sync, + >)) }}; } @@ -63,25 +57,21 @@ macro_rules! make_transform { macro_rules! make_transform_fallible { ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ let __f = $func; - $crate::Stage::Transform( - ::std::sync::Arc::from(Box::new( - move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> { - match data { - $enum::$input(inner) => { - let result = __f(inner) - .map_err(|e| $crate::PipelineError::StepError(Box::new(e)))?; - Ok($enum::$output(result)) - } - _ => Err($crate::PipelineError::TypeMismatch), + $crate::Stage::Transform(::std::sync::Arc::from(Box::new( + move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> { + match data { + $enum::$input(inner) => { + let result = __f(inner) + .map_err(|e| $crate::PipelineError::StepError(Box::new(e)))?; + Ok($enum::$output(result)) } - }, - ) - as Box< - dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> - + Send - + Sync, - >) + _ => Err($crate::PipelineError::TypeMismatch), + } + }, ) + as Box< + dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> + Send + Sync, + >)) }}; } @@ -94,30 +84,28 @@ macro_rules! make_transform_fallible { macro_rules! make_flat_transform { ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ let __f = $func; - $crate::Stage::Flat( - ::std::sync::Arc::new( - move |data: $enum, - push: &$crate::PipelineSender< - ::std::result::Result<$enum, $crate::PipelineError>, - >, - delta: &$crate::PipelineSender| { - match data { - $enum::$input(inner) => { - let mut count: isize = 0; - for item in __f(inner) { - push.send(Ok($enum::$output(item))).ok(); - count += 1; - } - delta.send(count - 1).ok(); - } - _ => { - push.send(Err($crate::PipelineError::TypeMismatch)).ok(); - delta.send(0).ok(); + $crate::Stage::Flat(::std::sync::Arc::new( + move |data: $enum, + push: &$crate::PipelineSender< + ::std::result::Result<$enum, $crate::PipelineError>, + >, + delta: &$crate::PipelineSender| { + match data { + $enum::$input(inner) => { + let mut count: isize = 0; + for item in __f(inner) { + push.send(Ok($enum::$output(item))).ok(); + count += 1; } + delta.send(count - 1).ok(); } - }, - ) as $crate::SharedFlatFn<$enum> - ) + _ => { + push.send(Err($crate::PipelineError::TypeMismatch)).ok(); + delta.send(0).ok(); + } + } + }, + ) as $crate::SharedFlatFn<$enum>) }}; } @@ -130,37 +118,35 @@ macro_rules! make_flat_transform { macro_rules! make_flat_transform_fallible { ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ let __f = $func; - $crate::Stage::Flat( - ::std::sync::Arc::new( - move |data: $enum, - push: &$crate::PipelineSender< - ::std::result::Result<$enum, $crate::PipelineError>, - >, - delta: &$crate::PipelineSender| { - match data { - $enum::$input(inner) => match __f(inner) { - Ok(iter) => { - let mut count: isize = 0; - for item in iter { - push.send(Ok($enum::$output(item))).ok(); - count += 1; - } - delta.send(count - 1).ok(); + $crate::Stage::Flat(::std::sync::Arc::new( + move |data: $enum, + push: &$crate::PipelineSender< + ::std::result::Result<$enum, $crate::PipelineError>, + >, + delta: &$crate::PipelineSender| { + match data { + $enum::$input(inner) => match __f(inner) { + Ok(iter) => { + let mut count: isize = 0; + for item in iter { + push.send(Ok($enum::$output(item))).ok(); + count += 1; } - Err(e) => { - push.send(Err($crate::PipelineError::StepError(Box::new(e)))) - .ok(); - delta.send(0).ok(); - } - }, - _ => { - push.send(Err($crate::PipelineError::TypeMismatch)).ok(); + delta.send(count - 1).ok(); + } + Err(e) => { + push.send(Err($crate::PipelineError::StepError(Box::new(e)))) + .ok(); delta.send(0).ok(); } + }, + _ => { + push.send(Err($crate::PipelineError::TypeMismatch)).ok(); + delta.send(0).ok(); } - }, - ) as $crate::SharedFlatFn<$enum> - ) + } + }, + ) as $crate::SharedFlatFn<$enum>) }}; } @@ -179,8 +165,7 @@ macro_rules! make_sink { _ => Err($crate::PipelineError::TypeMismatch), } }, - ) - as Box ::std::result::Result<(), $crate::PipelineError> + Send> + ) as Box ::std::result::Result<(), $crate::PipelineError> + Send> }}; } @@ -198,8 +183,7 @@ macro_rules! make_sink_fallible { _ => Err($crate::PipelineError::TypeMismatch), } }, - ) - as Box ::std::result::Result<(), $crate::PipelineError> + Send> + ) as Box ::std::result::Result<(), $crate::PipelineError> + Send> }}; } diff --git a/src/obipipeline/src/scheduler/pipe.rs b/src/obipipeline/src/scheduler/pipe.rs index 41eb62c9..32e27a3c 100644 --- a/src/obipipeline/src/scheduler/pipe.rs +++ b/src/obipipeline/src/scheduler/pipe.rs @@ -18,9 +18,9 @@ use super::types::{SinkFn, SourceFn, Stage}; /// Compose two pipes with `.then()`: the resulting `Pipe` holds the concatenated /// stage list, so a single scheduler is created when `.apply()` is eventually called. pub struct Pipe { - stages: Vec>, - wrap: Arc D + Send + Sync>, - unwrap: Arc Out + Send + Sync>, + stages: Vec>, + wrap: Arc D + Send + Sync>, + unwrap: Arc Out + Send + Sync>, _phantom: PhantomData<(In, Out)>, } @@ -28,11 +28,16 @@ impl Pipe { /// Build a `Pipe` from stages and wrap/unwrap converters. /// Prefer the `make_pipe!` macro. pub fn new( - stages: Vec>, - wrap: Arc D + Send + Sync>, - unwrap: Arc Out + Send + Sync>, + stages: Vec>, + wrap: Arc D + Send + Sync>, + unwrap: Arc Out + Send + Sync>, ) -> Self { - Self { stages, wrap, unwrap, _phantom: PhantomData } + Self { + stages, + wrap, + unwrap, + _phantom: PhantomData, + } } /// Concatenate stages from two pipes into one. @@ -41,9 +46,9 @@ impl Pipe { /// created at `.apply()` time sees the full combined stage list. pub fn then(self, other: Pipe) -> Pipe { Pipe { - stages: self.stages.into_iter().chain(other.stages).collect(), - wrap: self.wrap, - unwrap: other.unwrap, + stages: self.stages.into_iter().chain(other.stages).collect(), + wrap: self.wrap, + unwrap: other.unwrap, _phantom: PhantomData, } } @@ -51,24 +56,24 @@ impl Pipe { impl Pipe where - D: Send + Sync + 'static, - In: Send + 'static, + D: Send + Sync + 'static, + In: Send + 'static, Out: Send + 'static, { /// Run the pipeline in a background thread; returns an iterator over the output. pub fn apply( self, - input: impl Iterator + Send + 'static, + input: impl Iterator + Send + 'static, n_workers: usize, - capacity: usize, + capacity: usize, ) -> PipeIter { - let wrap = Arc::clone(&self.wrap); + let wrap = Arc::clone(&self.wrap); let unwrap = Arc::clone(&self.unwrap); let mut iter = input; let source: SourceFn = Box::new(move || match iter.next() { Some(x) => Ok(wrap(x)), - None => Err(PipelineError::EndOfStream), + None => Err(PipelineError::EndOfStream), }); let (out_tx, out_rx) = bounded::(capacity); @@ -86,7 +91,10 @@ where WorkerPool::new(pipeline, n_workers, capacity).run(); }); - PipeIter { rx: out_rx, handle: Some(handle) } + PipeIter { + rx: out_rx, + handle: Some(handle), + } } } @@ -94,7 +102,7 @@ where /// Iterator over the output of `Pipe::apply()`. pub struct PipeIter { - rx: Receiver, + rx: Receiver, handle: Option>, } diff --git a/src/obipipeline/src/scheduler/pool.rs b/src/obipipeline/src/scheduler/pool.rs index 7c7774b8..117539e8 100644 --- a/src/obipipeline/src/scheduler/pool.rs +++ b/src/obipipeline/src/scheduler/pool.rs @@ -13,12 +13,12 @@ pub struct Pipeline { } impl Pipeline { - pub fn new( - source: SourceFn, - stages: Vec>, - sink: SinkFn, - ) -> Self { - Self { source, stages, sink } + pub fn new(source: SourceFn, stages: Vec>, sink: SinkFn) -> Self { + Self { + source, + stages, + sink, + } } } @@ -121,13 +121,13 @@ where } let mut sel = Select::new_biased(); - sel.recv(&sink_err_rx); // index 0 - sel.recv(&flat_delta_rx); // index 1 + sel.recv(&sink_err_rx); // index 0 + sel.recv(&flat_delta_rx); // index 1 for rx in stage_rxs.iter().rev() { - sel.recv(rx); // indices 2..=n+1 + sel.recv(rx); // indices 2..=n+1 } let src_idx = if !source_done { - Some(sel.recv(&source_rx)) // index n+2 + Some(sel.recv(&source_rx)) // index n+2 } else { None }; @@ -138,7 +138,10 @@ where if k == 0 { // ── Erreur du sink ──────────────────────────────────── match oper.recv(&sink_err_rx) { - Ok(e) => { eprintln!("Sink error: {:?}", e); break; } + Ok(e) => { + eprintln!("Sink error: {:?}", e); + break; + } Err(_) => break, } } else if k == 1 { @@ -159,11 +162,7 @@ where let _ = sink_tx.send(data); } else { in_flight += 1; - dispatch( - data, 0, - &stages, &worker_tx, - &mut flat_workers_active, - ); + dispatch(data, 0, &stages, &worker_tx, &mut flat_workers_active); } } Ok(Err(e)) => eprintln!("Source error: {:?}", e), @@ -180,8 +179,10 @@ where let _ = sink_tx.send(data); } else { dispatch( - data, stage + 1, - &stages, &worker_tx, + data, + stage + 1, + &stages, + &worker_tx, &mut flat_workers_active, ); } diff --git a/src/obipipeline/src/throttle.rs b/src/obipipeline/src/throttle.rs index ed03640c..1dca89f6 100644 --- a/src/obipipeline/src/throttle.rs +++ b/src/obipipeline/src/throttle.rs @@ -10,14 +10,18 @@ use std::sync::{Arc, Condvar, Mutex}; /// Flat worker finishes processing the item). Acquisition must never happen /// inside a worker — only in the source thread — to prevent deadlocks. pub struct Throttle { - count: Mutex, + count: Mutex, condvar: Condvar, - max: usize, + max: usize, } impl Throttle { pub fn new(max: usize) -> Self { - Self { count: Mutex::new(0), condvar: Condvar::new(), max } + Self { + count: Mutex::new(0), + condvar: Condvar::new(), + max, + } } pub fn acquire(&self) { @@ -67,7 +71,7 @@ impl Drop for ThrottleGuard { /// pipeline stage, carry the guard inside the worker closure until the item /// is fully processed, then let it drop. pub struct Throttled { - pub item: T, + pub item: T, pub guard: ThrottleGuard, } @@ -94,6 +98,9 @@ where let t = Arc::new(Throttle::new(max_concurrent)); source.map(move |item| { t.acquire(); - Throttled { item, guard: ThrottleGuard(Arc::clone(&t)) } + Throttled { + item, + guard: ThrottleGuard(Arc::clone(&t)), + } }) } diff --git a/src/obiread/src/chunk.rs b/src/obiread/src/chunk.rs index 63fea7e4..034f8e34 100644 --- a/src/obiread/src/chunk.rs +++ b/src/obiread/src/chunk.rs @@ -166,10 +166,18 @@ pub fn read_sequence_chunks_sized( ) -> io::Result>>> { let input = match xopen(path) { Ok(mut i) => match i.mime_type() { - Some("text/fasta") => SeqChunkIter::new(i, block_size, - fasta::end_of_last_fasta_entry, Some("text/fasta")), - Some("text/fastq") => SeqChunkIter::new(i, block_size, - fastq::end_of_last_fastq_entry, Some("text/fastq")), + Some("text/fasta") => SeqChunkIter::new( + i, + block_size, + fasta::end_of_last_fasta_entry, + Some("text/fasta"), + ), + Some("text/fastq") => SeqChunkIter::new( + i, + block_size, + fastq::end_of_last_fastq_entry, + Some("text/fastq"), + ), _ => { return Err(io::Error::new( io::ErrorKind::InvalidData, diff --git a/src/obiread/src/mimetype.rs b/src/obiread/src/mimetype.rs index ab7ea5c9..8c3e209a 100644 --- a/src/obiread/src/mimetype.rs +++ b/src/obiread/src/mimetype.rs @@ -34,7 +34,7 @@ fn is_text(buf: &[u8]) -> bool { // Most specific formats (fastq, fasta) come before the generic text/plain fallback. static INFER: LazyLock = LazyLock::new(|| { let mut infer = Infer::new(); - infer.add("text/gbff", "gbff", is_gbff); + infer.add("text/gbff", "gbff", is_gbff); infer.add("text/fastq", "fastq", is_fastq); infer.add("text/fasta", "fasta", is_fasta); infer.add("text/plain", "txt", is_text); diff --git a/src/obiread/src/record.rs b/src/obiread/src/record.rs index fb5e1418..3d687257 100644 --- a/src/obiread/src/record.rs +++ b/src/obiread/src/record.rs @@ -32,16 +32,22 @@ pub fn parse_chunk(rope: &Rope, k: usize) -> Vec { // ── Shared state accumulated while scanning one sequence ────────────────────── struct RecordBuilder { - id: String, - sequence: Vec, // raw ASCII, no newlines - norm: Vec, // ACGT\x00 segments being built - seg_start: usize, // index in norm where current segment started - k: usize, + id: String, + sequence: Vec, // raw ASCII, no newlines + norm: Vec, // ACGT\x00 segments being built + seg_start: usize, // index in norm where current segment started + k: usize, } impl RecordBuilder { fn new(k: usize) -> Self { - Self { id: String::new(), sequence: Vec::new(), norm: Vec::new(), seg_start: 0, k } + Self { + id: String::new(), + sequence: Vec::new(), + norm: Vec::new(), + seg_start: 0, + k, + } } fn reset(&mut self, id: String) { @@ -82,7 +88,11 @@ impl RecordBuilder { if !self.norm.is_empty() { rope.push(self.norm); } - Some(SeqRecord { id: self.id, sequence: self.sequence, normalized: rope }) + Some(SeqRecord { + id: self.id, + sequence: self.sequence, + normalized: rope, + }) } } diff --git a/src/obiread/src/tests/chunk.rs b/src/obiread/src/tests/chunk.rs index ec5a51c2..2f434396 100644 --- a/src/obiread/src/tests/chunk.rs +++ b/src/obiread/src/tests/chunk.rs @@ -74,8 +74,7 @@ fn fastq_single_record_one_chunk() { #[test] fn fastq_at_in_quality_handled() { let data = Box::leak( - make_fastq(&[(b"ACGTACGT", b"@@@@IIII"), (b"TTTTTTTT", b"HHHHHHHH")]) - .into_boxed_slice(), + make_fastq(&[(b"ACGTACGT", b"@@@@IIII"), (b"TTTTTTTT", b"HHHHHHHH")]).into_boxed_slice(), ); let chunks: Vec<_> = fastq_iter(data, 16).collect::>().unwrap(); let all: Vec = chunks.iter().flat_map(|r| rope_to_vec(r)).collect(); diff --git a/src/obiread/src/tests/path_iterator.rs b/src/obiread/src/tests/path_iterator.rs index 583fd45a..2d47f420 100644 --- a/src/obiread/src/tests/path_iterator.rs +++ b/src/obiread/src/tests/path_iterator.rs @@ -19,13 +19,29 @@ fn names(it: PathIter) -> Vec { #[test] fn ncbi_and_common_fasta_extensions_are_recognised() { for name in [ - "g.fna", "g.fna.gz", "g.ffn", "g.fas", "g.fsa.gz", "g.fasta", "g.fa.gz", "g.fq", "g.fastq.gz", - "g.gbff", "g.gbk.gz", "g.gb", + "g.fna", + "g.fna.gz", + "g.ffn", + "g.fas", + "g.fsa.gz", + "g.fasta", + "g.fa.gz", + "g.fq", + "g.fastq.gz", + "g.gbff", + "g.gbk.gz", + "g.gb", ] { - assert!(is_fasta_or_fastq(Path::new(name)), "{name} should be recognised"); + assert!( + is_fasta_or_fastq(Path::new(name)), + "{name} should be recognised" + ); } for name in ["g.txt", "g.gz", "g.fna.txt", "g", "g.bam"] { - assert!(!is_fasta_or_fastq(Path::new(name)), "{name} should not be recognised"); + assert!( + !is_fasta_or_fastq(Path::new(name)), + "{name} should not be recognised" + ); } } @@ -44,8 +60,14 @@ fn explicit_file_with_unknown_extension_is_not_dropped() { #[test] fn explicit_missing_path_is_handed_to_the_reader() { // Not silently skipped: opening it later yields the real I/O error. - let missing = std::env::temp_dir().join(format!("obiread_pathiter_{}_missing.xyz", std::process::id())); - assert_eq!(PathIter::new(vec![missing.clone()]).collect::>(), vec![missing]); + let missing = std::env::temp_dir().join(format!( + "obiread_pathiter_{}_missing.xyz", + std::process::id() + )); + assert_eq!( + PathIter::new(vec![missing.clone()]).collect::>(), + vec![missing] + ); } #[test] @@ -65,5 +87,8 @@ fn directory_expansion_still_filters_by_extension() { #[test] fn stdin_sentinel_passes_through() { - assert_eq!(PathIter::new(vec![PathBuf::from("-")]).collect::>(), vec![PathBuf::from("-")]); + assert_eq!( + PathIter::new(vec![PathBuf::from("-")]).collect::>(), + vec![PathBuf::from("-")] + ); } diff --git a/src/obiread/src/tests/xopen.rs b/src/obiread/src/tests/xopen.rs index 4d715b2e..630c9ffa 100644 --- a/src/obiread/src/tests/xopen.rs +++ b/src/obiread/src/tests/xopen.rs @@ -3,7 +3,10 @@ use std::io::Write; fn temp_file(name: &str, content: &[u8]) -> std::path::PathBuf { let path = std::env::temp_dir().join(format!("obiread_xopen_{}_{name}", std::process::id())); - std::fs::File::create(&path).unwrap().write_all(content).unwrap(); + std::fs::File::create(&path) + .unwrap() + .write_all(content) + .unwrap(); path } @@ -33,6 +36,12 @@ fn estimate_scales_compressed_files_by_magic_not_extension() { #[test] fn estimate_is_unknown_for_streams_and_missing_files() { assert_eq!(estimated_decompressed_len("-"), None); - assert_eq!(estimated_decompressed_len("https://example.org/x.fa.gz"), None); - assert_eq!(estimated_decompressed_len("/nonexistent/obiread/file"), None); + assert_eq!( + estimated_decompressed_len("https://example.org/x.fa.gz"), + None + ); + assert_eq!( + estimated_decompressed_len("/nonexistent/obiread/file"), + None + ); } diff --git a/src/obiskbuilder/benches/superkmer_stream.rs b/src/obiskbuilder/benches/superkmer_stream.rs index 776e6d30..b62d820d 100644 --- a/src/obiskbuilder/benches/superkmer_stream.rs +++ b/src/obiskbuilder/benches/superkmer_stream.rs @@ -47,9 +47,7 @@ fn bench_build_superkmers(c: &mut Criterion) { let mut group = c.benchmark_group("build_superkmers"); group.throughput(Throughput::Bytes(SEQ_LEN as u64)); group.bench_function("stream", |b| { - b.iter(|| { - SuperKmerIter::new(std::hint::black_box(&rope), K, LEVEL_MAX, THETA).count() - }); + b.iter(|| SuperKmerIter::new(std::hint::black_box(&rope), K, LEVEL_MAX, THETA).count()); }); group.finish(); } diff --git a/src/obiskbuilder/src/lib.rs b/src/obiskbuilder/src/lib.rs index 65d15dad..6a8c1540 100644 --- a/src/obiskbuilder/src/lib.rs +++ b/src/obiskbuilder/src/lib.rs @@ -6,8 +6,8 @@ #![deny(missing_docs)] pub mod iter; -pub mod stream_iter; mod scratch; +pub mod stream_iter; pub(crate) mod encoding; #[allow(missing_docs)] @@ -17,9 +17,9 @@ pub use iter::SuperKmerIter; pub use scratch::SuperKmerScratch; pub use stream_iter::SuperKmerStreamIter; -use obiread::NucPage; use obikrope::Rope; use obikseq::RoutableSuperKmer; +use obiread::NucPage; /// Collect all super-kmers from a normalised [`NucPage`]. pub fn build_superkmers_page( diff --git a/src/obiskbuilder/src/rolling_stat.rs b/src/obiskbuilder/src/rolling_stat.rs index e8f1bc12..02ef174c 100644 --- a/src/obiskbuilder/src/rolling_stat.rs +++ b/src/obiskbuilder/src/rolling_stat.rs @@ -62,7 +62,6 @@ impl Ring { None } } - } // ── MmerItem ────────────────────────────────────────────────────────────────── diff --git a/src/obiskbuilder/src/stream_iter.rs b/src/obiskbuilder/src/stream_iter.rs index dabb72b5..1fea3fdd 100644 --- a/src/obiskbuilder/src/stream_iter.rs +++ b/src/obiskbuilder/src/stream_iter.rs @@ -1,8 +1,8 @@ //! Streaming superkmer iterator over a [`NucPageCursor`]. -use obiread::NucPageCursor; use obikseq::RoutableSuperKmer; use obikseq::kmer::Minimizer; +use obiread::NucPageCursor; use crate::rolling_stat::RollingStat; use crate::scratch::SuperKmerScratch; @@ -17,12 +17,12 @@ use crate::scratch::SuperKmerScratch; /// | minimizer changed | k | /// | super-kmer length = 256| k | pub struct SuperKmerStreamIter<'a> { - cursor: NucPageCursor<'a>, - k: usize, - theta: f64, - scratch: SuperKmerScratch, - stat: RollingStat, - prev_min: Option, + cursor: NucPageCursor<'a>, + k: usize, + theta: f64, + scratch: SuperKmerScratch, + stat: RollingStat, + prev_min: Option, prev_min_pos: usize, } @@ -33,9 +33,9 @@ impl<'a> SuperKmerStreamIter<'a> { cursor, k, theta, - scratch: SuperKmerScratch::new(), - stat: RollingStat::new(level_max), - prev_min: None, + scratch: SuperKmerScratch::new(), + stat: RollingStat::new(level_max), + prev_min: None, prev_min_pos: 0, } } @@ -94,7 +94,7 @@ impl Iterator for SuperKmerStreamIter<'_> { continue; } - let min = self.stat.canonical_minimizer().unwrap(); + let min = self.stat.canonical_minimizer().unwrap(); let min_pos = self.stat.minimizer_position().unwrap_or(0); // ── 2. Minimizer change ─────────────────────────────────────────── @@ -121,7 +121,7 @@ impl Iterator for SuperKmerStreamIter<'_> { continue; } - self.prev_min = Some(min); + self.prev_min = Some(min); self.prev_min_pos = min_pos; self.scratch.push(byte); } diff --git a/src/obiskio/src/error.rs b/src/obiskio/src/error.rs index a6fbf39b..103433ed 100644 --- a/src/obiskio/src/error.rs +++ b/src/obiskio/src/error.rs @@ -6,11 +6,19 @@ pub enum SKError { Io(io::Error), Compression(niffler::Error), /// Binary file has unrecognized magic bytes. - BadMagic { expected: &'static str, got: [u8; 4] }, + BadMagic { + expected: &'static str, + got: [u8; 4], + }, /// File is too short to contain a required field. - Truncated { context: &'static str }, + Truncated { + context: &'static str, + }, /// A field value is outside its valid range or cannot be parsed. - InvalidData { context: &'static str, detail: String }, + InvalidData { + context: &'static str, + detail: String, + }, } pub type SKResult = Result; @@ -21,7 +29,12 @@ impl fmt::Display for SKError { SKError::Io(e) => write!(f, "I/O error: {e}"), SKError::Compression(e) => write!(f, "compression error: {e}"), SKError::BadMagic { expected, got } => { - write!(f, "bad magic: expected {:?}, got {:?}", expected.as_bytes(), got) + write!( + f, + "bad magic: expected {:?}, got {:?}", + expected.as_bytes(), + got + ) } SKError::Truncated { context } => write!(f, "truncated file: {context}"), SKError::InvalidData { context, detail } => { diff --git a/src/obiskio/src/lib.rs b/src/obiskio/src/lib.rs index 61d96502..61903271 100644 --- a/src/obiskio/src/lib.rs +++ b/src/obiskio/src/lib.rs @@ -8,8 +8,9 @@ pub use error::{SKError, SKResult}; pub use meta::SKFileMeta; pub use pool::{SKFilePool, SKFileWriter, SharedPool, create_token, create_token_with}; pub use reader::{SKFileIter, SKFileReader}; -pub use unitig_index::{UnitigFileReader, UnitigFileWriter, build_unitig_idx, DEFAULT_BLOCK_BITS, - CanonicalKmerIter}; +pub use unitig_index::{ + CanonicalKmerIter, DEFAULT_BLOCK_BITS, UnitigFileReader, UnitigFileWriter, build_unitig_idx, +}; use std::path::{Path, PathBuf}; diff --git a/src/obiskio/src/meta.rs b/src/obiskio/src/meta.rs index 4b8983e8..3534ad46 100644 --- a/src/obiskio/src/meta.rs +++ b/src/obiskio/src/meta.rs @@ -1,6 +1,6 @@ -use std::path::{Path, PathBuf}; -use serde::{Deserialize, Serialize}; use crate::error::{SKError, SKResult}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; /// Statistics sidecar written alongside each SuperKmer file on close. /// @@ -17,7 +17,11 @@ pub struct SKFileMeta { impl SKFileMeta { pub(crate) fn zero() -> Self { - Self { instances: 0, count_sum: 0, length_sum: 0 } + Self { + instances: 0, + count_sum: 0, + length_sum: 0, + } } /// Path of the sidecar file for a given SuperKmer file path. @@ -31,9 +35,11 @@ impl SKFileMeta { // Read whole, parse from memory: `from_reader` on a bare `File` is one // syscall per byte. match std::fs::read(&path) { - Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes).map_err(|e| SKError::InvalidData { - context: "SKFileMeta sidecar", - detail: e.to_string(), + Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes).map_err(|e| { + SKError::InvalidData { + context: "SKFileMeta sidecar", + detail: e.to_string(), + } })?)), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e.into()), diff --git a/src/obiskio/src/reader.rs b/src/obiskio/src/reader.rs index e39e5169..8e62d260 100644 --- a/src/obiskio/src/reader.rs +++ b/src/obiskio/src/reader.rs @@ -78,14 +78,13 @@ pub struct SKFileIter<'a> { } impl<'a> SKFileIter<'a> { - - /// Read the next SuperKmer, or `None` at EOF. - pub fn read(&mut self) -> SKResult> { - match self.reader.read()? { - Some(sk) => Ok(Some(sk)), - None => Ok(None), - } - } + /// Read the next SuperKmer, or `None` at EOF. + pub fn read(&mut self) -> SKResult> { + match self.reader.read()? { + Some(sk) => Ok(Some(sk)), + None => Ok(None), + } + } /// Returns the first I/O error encountered during iteration, if any. pub fn take_error(&mut self) -> Option { self.error.take() diff --git a/src/obiskio/src/tests/reader.rs b/src/obiskio/src/tests/reader.rs index 480af82a..a153af41 100644 --- a/src/obiskio/src/tests/reader.rs +++ b/src/obiskio/src/tests/reader.rs @@ -4,7 +4,6 @@ use obikseq::kmer::CanonicalKmer; use std::io::Cursor; use tempfile::NamedTempFile; - const TEST_K: usize = 4; fn setup() { @@ -77,7 +76,10 @@ fn iter_canonical_kmers_matches_per_sk() { } // Reference: collect kmers superkmer by superkmer - let expected: Vec = sks.iter().flat_map(|sk| sk.iter_canonical_kmers()).collect(); + let expected: Vec = sks + .iter() + .flat_map(|sk| sk.iter_canonical_kmers()) + .collect(); let mut r = SKFileReader::open(tmp.path()).unwrap(); let got: Vec = r.iter_canonical_kmers().collect(); diff --git a/src/obiskio/src/tests/unitig_index.rs b/src/obiskio/src/tests/unitig_index.rs index fc02626e..4b67ebad 100644 --- a/src/obiskio/src/tests/unitig_index.rs +++ b/src/obiskio/src/tests/unitig_index.rs @@ -160,7 +160,11 @@ fn iter_kmers_single_chunk_count_and_order() { let kmers: Vec = r.iter_kmers().collect(); assert_eq!(kmers.len(), 3); for (rank, kmer) in kmers.iter().enumerate() { - assert_eq!(kmer.raw(), r.raw_kmer(0, rank), "kmer mismatch at rank {rank}"); + assert_eq!( + kmer.raw(), + r.raw_kmer(0, rank), + "kmer mismatch at rank {rank}" + ); } } @@ -256,10 +260,19 @@ fn chunk_ranks_fit_the_7_bit_evidence_field() { // chunks must never yield a rank above 127 — a larger one would be // silently truncated there and the kmer would no longer verify. set_k(4); - let seq: Vec = (0..1000_usize).map(|i| b"ACGT"[(i * i + i / 3) % 4]).collect(); + let seq: Vec = (0..1000_usize) + .map(|i| b"ACGT"[(i * i + i / 3) % 4]) + .collect(); let (_dir, r) = write_read(&[&seq]); - assert!(r.len() > 1, "a 997-kmer unitig must be split into several chunks"); - let max_rank = r.iter_indexed_canonical_kmers().map(|(_, _, rank)| rank).max().unwrap(); + assert!( + r.len() > 1, + "a 997-kmer unitig must be split into several chunks" + ); + let max_rank = r + .iter_indexed_canonical_kmers() + .map(|(_, _, rank)| rank) + .max() + .unwrap(); assert!(max_rank <= 127, "rank {max_rank} does not fit 7 bits"); } @@ -301,7 +314,11 @@ fn block_bits_zero_exact_offsets() { let (_dir, r) = write_read_bb(seqs, 0); assert_eq!(r.len(), seqs.len()); for (i, s) in seqs.iter().enumerate() { - assert_eq!(r.unitig(i), make_unitig(s), "block_bits=0: unitig {i} mismatch"); + assert_eq!( + r.unitig(i), + make_unitig(s), + "block_bits=0: unitig {i} mismatch" + ); } } @@ -313,7 +330,11 @@ fn block_bits_one_block_size_two() { let (_dir, r) = write_read_bb(seqs, 1); assert_eq!(r.len(), seqs.len()); for (i, s) in seqs.iter().enumerate() { - assert_eq!(r.unitig(i), make_unitig(s), "block_bits=1: unitig {i} mismatch"); + assert_eq!( + r.unitig(i), + make_unitig(s), + "block_bits=1: unitig {i} mismatch" + ); } } @@ -325,7 +346,11 @@ fn block_bits_larger_than_chunk_count() { let (_dir, r) = write_read_bb(seqs, 6); assert_eq!(r.len(), seqs.len()); for (i, s) in seqs.iter().enumerate() { - assert_eq!(r.unitig(i), make_unitig(s), "block_bits=6: unitig {i} mismatch"); + assert_eq!( + r.unitig(i), + make_unitig(s), + "block_bits=6: unitig {i} mismatch" + ); } } @@ -342,7 +367,11 @@ fn block_bits_random_access_matches_sequential() { assert_eq!(r.len(), seqs.len()); let sequential: Vec = r.iter_chunks_sequential().map(|(_, u)| u).collect(); for i in 0..seqs.len() { - assert_eq!(r.unitig(i), sequential[i], "random vs sequential mismatch at chunk {i}"); + assert_eq!( + r.unitig(i), + sequential[i], + "random vs sequential mismatch at chunk {i}" + ); } } diff --git a/src/obiskio/src/unitig_index/kmer_iter.rs b/src/obiskio/src/unitig_index/kmer_iter.rs index 4a6097f5..c06fe969 100644 --- a/src/obiskio/src/unitig_index/kmer_iter.rs +++ b/src/obiskio/src/unitig_index/kmer_iter.rs @@ -18,12 +18,12 @@ use super::kmer_raw::{canonical_raw, extract_kmer_raw}; /// iterator via `par_bridge()`) make multiple passes without ever creating /// a `.idx` file. pub struct CanonicalKmerIter { - mmap: Arc, - k: usize, - chunk_pos: usize, // byte offset of the current chunk header - data_pos: usize, // byte offset of the current chunk's sequence bytes - n_kmers: usize, // kmers in current chunk - kmer_idx: usize, // next kmer index to yield within the current chunk + mmap: Arc, + k: usize, + chunk_pos: usize, // byte offset of the current chunk header + data_pos: usize, // byte offset of the current chunk's sequence bytes + n_kmers: usize, // kmers in current chunk + kmer_idx: usize, // next kmer index to yield within the current chunk } impl CanonicalKmerIter { @@ -31,7 +31,14 @@ impl CanonicalKmerIter { let file = std::fs::File::open(path).map_err(SKError::Io)?; let mmap = Arc::new(unsafe { Mmap::map(&file).map_err(SKError::Io)? }); let k = obikseq::params::k(); - let mut s = Self { mmap, k, chunk_pos: 0, data_pos: 0, n_kmers: 0, kmer_idx: 0 }; + let mut s = Self { + mmap, + k, + chunk_pos: 0, + data_pos: 0, + n_kmers: 0, + kmer_idx: 0, + }; s.load_chunk(); Ok(s) } @@ -40,7 +47,7 @@ impl CanonicalKmerIter { fn load_chunk(&mut self) { if self.chunk_pos < self.mmap.len() { let seql_minus_k = self.mmap[self.chunk_pos] as usize; - self.n_kmers = seql_minus_k + 1; + self.n_kmers = seql_minus_k + 1; self.data_pos = self.chunk_pos + 1; self.kmer_idx = 0; } @@ -50,12 +57,12 @@ impl CanonicalKmerIter { impl Clone for CanonicalKmerIter { fn clone(&self) -> Self { let mut c = Self { - mmap: Arc::clone(&self.mmap), - k: self.k, + mmap: Arc::clone(&self.mmap), + k: self.k, chunk_pos: 0, - data_pos: 0, - n_kmers: 0, - kmer_idx: 0, + data_pos: 0, + n_kmers: 0, + kmer_idx: 0, }; c.load_chunk(); c @@ -72,14 +79,14 @@ impl Iterator for CanonicalKmerIter { return None; } if self.kmer_idx < self.n_kmers { - let raw = extract_kmer_raw(&self.mmap[self.data_pos..], self.kmer_idx, self.k); + let raw = extract_kmer_raw(&self.mmap[self.data_pos..], self.kmer_idx, self.k); let canon = canonical_raw(raw, self.k); self.kmer_idx += 1; return Some(CanonicalKmer::from_raw_unchecked(canon)); } let seql_minus_k = self.mmap[self.chunk_pos] as usize; - let byte_len = (seql_minus_k + self.k + 3) / 4; - self.chunk_pos += 1 + byte_len; + let byte_len = (seql_minus_k + self.k + 3) / 4; + self.chunk_pos += 1 + byte_len; self.load_chunk(); } } diff --git a/src/obiskio/src/unitig_index/kmer_raw.rs b/src/obiskio/src/unitig_index/kmer_raw.rs index e1d726f6..821be290 100644 --- a/src/obiskio/src/unitig_index/kmer_raw.rs +++ b/src/obiskio/src/unitig_index/kmer_raw.rs @@ -16,9 +16,9 @@ pub(super) fn canonical_raw(raw: u64, k: usize) -> u64 { #[inline] pub(super) fn extract_kmer_raw(bytes: &[u8], j: usize, k: usize) -> u64 { - let bit_start = j * 2; - let byte_start = bit_start / 8; - let bit_offset = bit_start % 8; + let bit_start = j * 2; + let byte_start = bit_start / 8; + let bit_offset = bit_start % 8; let bytes_needed = (bit_offset + 2 * k + 7) / 8; let mut acc = 0u128; @@ -27,7 +27,7 @@ pub(super) fn extract_kmer_raw(bytes: &[u8], j: usize, k: usize) -> u64 { } let shift = bytes_needed * 8 - bit_offset - 2 * k; - let mask = !0u64 >> (64 - 2 * k); - let raw = (acc >> shift) as u64 & mask; + let mask = !0u64 >> (64 - 2 * k); + let raw = (acc >> shift) as u64 & mask; raw << (64 - 2 * k) } diff --git a/src/obiskio/src/unitig_index/mod.rs b/src/obiskio/src/unitig_index/mod.rs index 38358996..5113aa5b 100644 --- a/src/obiskio/src/unitig_index/mod.rs +++ b/src/obiskio/src/unitig_index/mod.rs @@ -21,9 +21,9 @@ pub use writer::{UnitigFileWriter, build_unitig_idx}; // Only used by `tests/unitig_index.rs` (`use super::*`) below. #[cfg(test)] -use obikseq::CanonicalKmer; -#[cfg(test)] use kmer_raw::{canonical_raw, extract_kmer_raw, revcomp_raw}; +#[cfg(test)] +use obikseq::CanonicalKmer; // ── Block index parameters ──────────────────────────────────────────────────── // diff --git a/src/obiskio/src/unitig_index/reader.rs b/src/obiskio/src/unitig_index/reader.rs index 8e608cef..0b10400a 100644 --- a/src/obiskio/src/unitig_index/reader.rs +++ b/src/obiskio/src/unitig_index/reader.rs @@ -315,7 +315,10 @@ impl BlockOffsets { #[inline] fn get(&self, i: usize) -> u32 { let at = IDX_HEADER_SIZE + 4 * i; - let map = self.mmap.as_ref().expect("direct-access reader has its .idx map"); + let map = self + .mmap + .as_ref() + .expect("direct-access reader has its .idx map"); u32::from_le_bytes(map[at..at + 4].try_into().unwrap()) } } @@ -327,7 +330,9 @@ fn read_idx(path: &Path) -> SKResult<(usize, usize, u8, BlockOffsets)> { let file = File::open(path).map_err(SKError::Io)?; let len = file.metadata().map_err(SKError::Io)?.len() as usize; if len < IDX_HEADER_SIZE { - return Err(SKError::Truncated { context: "unitig index: header" }); + return Err(SKError::Truncated { + context: "unitig index: header", + }); } let data = unsafe { Mmap::map(&file).map_err(SKError::Io)? }; @@ -354,8 +359,15 @@ fn read_idx(path: &Path) -> SKResult<(usize, usize, u8, BlockOffsets)> { let n_blocks = (n_unitigs + block_size - 1) >> block_bits; let n_offsets = n_blocks + 1; if len < IDX_HEADER_SIZE + 4 * n_offsets { - return Err(SKError::Truncated { context: "unitig index: block_offsets" }); + return Err(SKError::Truncated { + context: "unitig index: block_offsets", + }); } - Ok((n_unitigs, n_kmers, block_bits, BlockOffsets { mmap: Some(data) })) + Ok(( + n_unitigs, + n_kmers, + block_bits, + BlockOffsets { mmap: Some(data) }, + )) } diff --git a/src/obiskio/src/unitig_index/writer.rs b/src/obiskio/src/unitig_index/writer.rs index 311d4044..e37b9fc4 100644 --- a/src/obiskio/src/unitig_index/writer.rs +++ b/src/obiskio/src/unitig_index/writer.rs @@ -21,14 +21,14 @@ use super::{DEFAULT_BLOCK_BITS, MAGIC, idx_path}; /// Unitigs with more than [`MAX_KMERS_PER_CHUNK`] k-mers are transparently split /// into overlapping chunks (k−1 nucleotide overlap) so no k-mer is lost. pub struct UnitigFileWriter { - file: BufWriter, + file: BufWriter, block_offsets: Vec, - chunk_count: usize, - next_offset: u32, - n_kmers: usize, - k: usize, - block_bits: u8, - mask: usize, // (1 << block_bits) - 1 + chunk_count: usize, + next_offset: u32, + n_kmers: usize, + k: usize, + block_bits: u8, + mask: usize, // (1 << block_bits) - 1 } impl UnitigFileWriter { @@ -77,7 +77,9 @@ impl UnitigFileWriter { while start < seql { let end = (start + chunk_nucl).min(seql); self.write_chunk(&unitig.sub(start, end))?; - if end == seql { break; } + if end == seql { + break; + } start += stride; } Ok(()) @@ -87,7 +89,10 @@ impl UnitigFileWriter { let seql = unitig.seql(); let byte_len = (seql + 3) / 4; - debug_assert!(seql - self.k <= u8::MAX as usize, "chunk exceeds MAX_KMERS_PER_CHUNK"); + debug_assert!( + seql - self.k <= u8::MAX as usize, + "chunk exceeds MAX_KMERS_PER_CHUNK" + ); if self.chunk_count & self.mask == 0 { self.block_offsets.push(self.next_offset); @@ -96,7 +101,9 @@ impl UnitigFileWriter { self.n_kmers += seql - self.k + 1; self.chunk_count += 1; - unitig.write_to_binary(&mut self.file).map_err(SKError::Io)?; + unitig + .write_to_binary(&mut self.file) + .map_err(SKError::Io)?; self.next_offset += 1 + byte_len as u32; Ok(()) @@ -112,9 +119,15 @@ impl UnitigFileWriter { Ok(()) } - pub fn len(&self) -> usize { self.chunk_count } - pub fn is_empty(&self) -> bool { self.chunk_count == 0 } - pub fn block_bits(&self) -> u8 { self.block_bits } + pub fn len(&self) -> usize { + self.chunk_count + } + pub fn is_empty(&self) -> bool { + self.chunk_count == 0 + } + pub fn block_bits(&self) -> u8 { + self.block_bits + } } fn write_idx( @@ -126,7 +139,8 @@ fn write_idx( ) -> SKResult<()> { let mut w = BufWriter::new(File::create(path).map_err(SKError::Io)?); w.write_all(&MAGIC).map_err(SKError::Io)?; - w.write_all(&(block_bits as u32).to_le_bytes()).map_err(SKError::Io)?; + w.write_all(&(block_bits as u32).to_le_bytes()) + .map_err(SKError::Io)?; w.write_all(&n_unitigs.to_le_bytes()).map_err(SKError::Io)?; w.write_all(&n_kmers.to_le_bytes()).map_err(SKError::Io)?; for &off in block_offsets { @@ -146,14 +160,14 @@ pub fn build_unitig_idx(unitigs_path: &Path, block_bits: u8) -> SKResult<()> { let file = File::open(unitigs_path).map_err(SKError::Io)?; let mmap = unsafe { Mmap::map(&file).map_err(SKError::Io)? }; - let k = obikseq::params::k(); + let k = obikseq::params::k(); let block_size = 1usize << block_bits; - let mask = block_size - 1; + let mask = block_size - 1; let mut block_offsets: Vec = Vec::new(); - let mut offset = 0usize; + let mut offset = 0usize; let mut chunk_count = 0usize; - let mut n_kmers = 0usize; + let mut n_kmers = 0usize; while offset < mmap.len() { if chunk_count & mask == 0 { @@ -161,8 +175,8 @@ pub fn build_unitig_idx(unitigs_path: &Path, block_bits: u8) -> SKResult<()> { } let seql_minus_k = mmap[offset] as usize; let byte_len = (seql_minus_k + k + 3) / 4; - n_kmers += seql_minus_k + 1; - offset += 1 + byte_len; + n_kmers += seql_minus_k + 1; + offset += 1 + byte_len; chunk_count += 1; } diff --git a/src/obisys/src/lock.rs b/src/obisys/src/lock.rs index b3eb59f0..19a3e056 100644 --- a/src/obisys/src/lock.rs +++ b/src/obisys/src/lock.rs @@ -95,7 +95,10 @@ struct Backoff { impl Backoff { fn new() -> Self { - Self { delay: POLL_MIN, logged: false } + Self { + delay: POLL_MIN, + logged: false, + } } fn wait(&mut self, dir: &Path, why: &str) { @@ -113,13 +116,21 @@ impl DirLock { /// and the lock files within it if needed). Logs once if the wait is /// non-trivial, so a blocked command doesn't look silently hung. pub fn acquire(dir: &Path) -> io::Result { - Self::acquire_mode(dir, LockMode::Exclusive, "waiting for other obikmer processes to release this index") + Self::acquire_mode( + dir, + LockMode::Exclusive, + "waiting for other obikmer processes to release this index", + ) } /// Block until a shared lock on `dir` is acquired — until no exclusive /// holder remains. Logs once if the wait is non-trivial. pub fn acquire_shared(dir: &Path) -> io::Result { - Self::acquire_mode(dir, LockMode::Shared, "waiting for an obikmer process writing this index") + Self::acquire_mode( + dir, + LockMode::Shared, + "waiting for an obikmer process writing this index", + ) } fn acquire_mode(dir: &Path, mode: LockMode, why: &str) -> io::Result { @@ -129,7 +140,11 @@ impl DirLock { { let _gate = gate(dir)?; if try_lock(&file, mode)? { - return Ok(Self { file, dir: dir.to_owned(), mode }); + return Ok(Self { + file, + dir: dir.to_owned(), + mode, + }); } } backoff.wait(dir, why); @@ -177,15 +192,26 @@ impl DirLock { let _gate = gate(&self.dir)?; self.file.unlock()?; if try_lock(&self.file, LockMode::Exclusive)? { - return Ok((Self { mode: LockMode::Exclusive, ..self }, true)); + return Ok(( + Self { + mode: LockMode::Exclusive, + ..self + }, + true, + )); } // Other readers remain. Nobody can hold the lock exclusively // without the gate, so taking our shared lock back succeeds. if !try_lock(&self.file, LockMode::Shared)? { - return Err(io::Error::other("lost the shared index lock during promotion")); + return Err(io::Error::other( + "lost the shared index lock during promotion", + )); } } - backoff.wait(&self.dir, "waiting for other readers of this index before writing to it"); + backoff.wait( + &self.dir, + "waiting for other readers of this index before writing to it", + ); } } @@ -198,9 +224,14 @@ impl DirLock { let held_gate = gate(&self.dir)?; self.file.unlock()?; if !try_lock(&self.file, LockMode::Shared)? { - return Err(io::Error::other("could not take the shared index lock back after writing")); + return Err(io::Error::other( + "could not take the shared index lock back after writing", + )); } drop(held_gate); - Ok(Self { mode: LockMode::Shared, ..self }) + Ok(Self { + mode: LockMode::Shared, + ..self + }) } } diff --git a/src/obisys/src/lock_slot.rs b/src/obisys/src/lock_slot.rs index 16f1e072..9c26f9b5 100644 --- a/src/obisys/src/lock_slot.rs +++ b/src/obisys/src/lock_slot.rs @@ -22,17 +22,26 @@ impl LockSlot { /// A slot holding nothing (a handle that took no lock, or one that /// reopens a directory its own builder already holds). pub fn empty(dir: &Path) -> Self { - Self { dir: dir.to_owned(), held: Mutex::new(None) } + Self { + dir: dir.to_owned(), + held: Mutex::new(None), + } } /// A slot holding a shared lock on `dir`; blocks while a writer is at work. pub fn shared(dir: &Path) -> io::Result { - Ok(Self { dir: dir.to_owned(), held: Mutex::new(Some(DirLock::acquire_shared(dir)?)) }) + Ok(Self { + dir: dir.to_owned(), + held: Mutex::new(Some(DirLock::acquire_shared(dir)?)), + }) } /// A slot holding the exclusive lock on `dir`; blocks while anyone else holds it. pub fn exclusive(dir: &Path) -> io::Result { - Ok(Self { dir: dir.to_owned(), held: Mutex::new(Some(DirLock::acquire(dir)?)) }) + Ok(Self { + dir: dir.to_owned(), + held: Mutex::new(Some(DirLock::acquire(dir)?)), + }) } /// Whether the slot holds the exclusive lock (a shared one is not write access). @@ -65,7 +74,10 @@ impl LockSlot { /// /// Restored also if `f` fails; an I/O error taking or restoring the lock /// is converted to `E`. - pub fn with_exclusive>(&self, f: impl FnOnce() -> Result) -> Result { + pub fn with_exclusive>( + &self, + f: impl FnOnce() -> Result, + ) -> Result { enum Before { Exclusive, Shared, diff --git a/src/obisys/src/lock_tests.rs b/src/obisys/src/lock_tests.rs index 15b1a3c7..cf4cf2ec 100644 --- a/src/obisys/src/lock_tests.rs +++ b/src/obisys/src/lock_tests.rs @@ -69,9 +69,13 @@ fn a_writer_waits_for_the_readers() { drop(LockSlot::exclusive(&dir).unwrap()); tx.send(()).unwrap(); }); - assert!(rx.recv_timeout(SETTLE).is_err(), "the writer must wait for the reader"); + assert!( + rx.recv_timeout(SETTLE).is_err(), + "the writer must wait for the reader" + ); drop(reader); - rx.recv_timeout(PATIENCE).expect("the writer proceeds once the reader is gone"); + rx.recv_timeout(PATIENCE) + .expect("the writer proceeds once the reader is gone"); writer.join().unwrap(); } @@ -85,9 +89,13 @@ fn a_reader_waits_for_the_writer() { drop(LockSlot::shared(&dir).unwrap()); tx.send(()).unwrap(); }); - assert!(rx.recv_timeout(SETTLE).is_err(), "the reader must wait for the writer"); + assert!( + rx.recv_timeout(SETTLE).is_err(), + "the reader must wait for the writer" + ); drop(writer); - rx.recv_timeout(PATIENCE).expect("the reader proceeds once the writer is gone"); + rx.recv_timeout(PATIENCE) + .expect("the reader proceeds once the writer is gone"); reader.join().unwrap(); } @@ -111,7 +119,10 @@ fn with_exclusive_on_a_reader_promotes_then_restores_the_shared_lock() { drop(LockSlot::exclusive(&dir).unwrap()); tx.send(()).unwrap(); }); - assert!(rx.recv_timeout(SETTLE).is_err(), "the slot must be a reader again"); + assert!( + rx.recv_timeout(SETTLE).is_err(), + "the slot must be a reader again" + ); drop(slot); rx.recv_timeout(PATIENCE).unwrap(); writer.join().unwrap(); @@ -146,7 +157,10 @@ fn with_exclusive_nests_and_keeps_a_lock_taken_at_open() { let slot = LockSlot::exclusive(&d.0).unwrap(); slot.with_exclusive::<(), io::Error>(|| { slot.with_exclusive::<(), io::Error>(|| Ok(()))?; - assert!(slot.holds_write_lock(), "an inner section must not release the outer lock"); + assert!( + slot.holds_write_lock(), + "an inner section must not release the outer lock" + ); Ok(()) }) .unwrap(); @@ -199,7 +213,10 @@ fn a_lone_promotion_is_gapless_and_a_demotion_keeps_the_lock() { let shared = DirLock::acquire_shared(&d.0).unwrap(); let (excl, gapless) = shared.promote().unwrap(); assert_eq!(excl.mode(), LockMode::Exclusive); - assert!(gapless, "nobody else was promoting: the lock was never released"); + assert!( + gapless, + "nobody else was promoting: the lock was never released" + ); let shared = excl.demote().unwrap(); assert_eq!(shared.mode(), LockMode::Shared); // Shared again: other readers get in, a writer does not. diff --git a/src/obisys/src/numa/runner.rs b/src/obisys/src/numa/runner.rs index 25d6929f..915e6d63 100644 --- a/src/obisys/src/numa/runner.rs +++ b/src/obisys/src/numa/runner.rs @@ -3,8 +3,8 @@ use std::panic::{self, AssertUnwindSafe}; use std::sync::Arc; use std::time::{Duration, Instant}; -use crossbeam_channel::unbounded; use crate::{CpuSample, IoSample}; +use crossbeam_channel::unbounded; use tracing::debug; use super::topology::{build, pin_current_thread}; @@ -84,7 +84,11 @@ impl PartitionRunner { .zip(ns.cpus_per_node) .map(|(pool, cpu_ids)| { let max_workers = cpu_ids.len(); - NodeConfig { pool, cpu_ids, max_workers } + NodeConfig { + pool, + cpu_ids, + max_workers, + } }) .collect(); Self { nodes } @@ -110,7 +114,11 @@ impl PartitionRunner { .zip(ns.cpus_per_node) .map(|(pool, cpu_ids)| { let node_cores = cpu_ids.len().max(1); - NodeConfig { pool, cpu_ids, max_workers: per_node_cap.min(node_cores) } + NodeConfig { + pool, + cpu_ids, + max_workers: per_node_cap.min(node_cores), + } }) .collect(); Self { nodes } @@ -207,7 +215,10 @@ impl PartitionRunner { let tid = std::thread::current().id(); debug!(?tid, "PartitionRunner worker: waiting on activation"); if arx.recv().is_err() { - debug!(?tid, "PartitionRunner worker: activation channel closed, exiting"); + debug!( + ?tid, + "PartitionRunner worker: activation channel closed, exiting" + ); return; } debug!(?tid, "PartitionRunner worker: activated"); @@ -215,7 +226,11 @@ impl PartitionRunner { pin_current_thread(cpu_ids); } for i in &prx { - debug!(?tid, partition = i, "PartitionRunner worker: picked partition"); + debug!( + ?tid, + partition = i, + "PartitionRunner worker: picked partition" + ); let t = Instant::now(); // Caught, not left to unwind straight through this // spawned thread: a panicking `f(i)` would @@ -232,7 +247,11 @@ impl PartitionRunner { Some(p) => p.install(|| f(i)), None => f(i), })); - debug!(?tid, partition = i, "PartitionRunner worker: partition done"); + debug!( + ?tid, + partition = i, + "PartitionRunner worker: partition done" + ); let event = match outcome { Ok(r) => WorkerEvent::Completed(i, r, t.elapsed()), Err(payload) => WorkerEvent::Panicked(i, payload), @@ -250,14 +269,21 @@ impl PartitionRunner { // ── Controller ──────────────────────────────────────────────────── let mut activation = NodeActivation::new(&activate_txs, &node_caps, max_workers); activation.activate_initial(INITIAL_DIVISOR, n_total); - debug!(n_total, activated = activation.total(), "PartitionRunner controller: initial activation"); + debug!( + n_total, + activated = activation.total(), + "PartitionRunner controller: initial activation" + ); let mut cpu_sample = CpuSample::now(); let mut io_sample = IoSample::now(); let mut completed = 0usize; while completed < n_total { - debug!(completed, n_total, "PartitionRunner controller: waiting for an event"); + debug!( + completed, + n_total, "PartitionRunner controller: waiting for an event" + ); let Ok(event) = event_rx.recv() else { debug!("PartitionRunner controller: event channel closed, stopping"); break; diff --git a/src/obisys/src/progress.rs b/src/obisys/src/progress.rs index fcfc2eb5..bdd09b56 100644 --- a/src/obisys/src/progress.rs +++ b/src/obisys/src/progress.rs @@ -1,5 +1,5 @@ -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; use indicatif::{ProgressBar, ProgressStyle}; diff --git a/src/obisys/src/resources.rs b/src/obisys/src/resources.rs index 989468bf..caf513d9 100644 --- a/src/obisys/src/resources.rs +++ b/src/obisys/src/resources.rs @@ -103,21 +103,40 @@ fn cgroup_v1_available() -> Option { /// quota is found; falls back to `available_parallelism()` otherwise (same /// convention as [`available_memory_bytes`]). pub fn effective_parallelism() -> usize { - let host = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); + let host = std::thread::available_parallelism() + .map(|n| n.get()) + .unwrap_or(1); #[cfg(target_os = "linux")] { if let Some(quota) = cgroup_v2_cpu_quota() { let effective = quota.clamp(1, host); - tracing::debug!(host, quota, effective, source = "cgroup v2", "effective_parallelism"); + tracing::debug!( + host, + quota, + effective, + source = "cgroup v2", + "effective_parallelism" + ); return effective; } if let Some(quota) = cgroup_v1_cpu_quota() { let effective = quota.clamp(1, host); - tracing::debug!(host, quota, effective, source = "cgroup v1", "effective_parallelism"); + tracing::debug!( + host, + quota, + effective, + source = "cgroup v1", + "effective_parallelism" + ); return effective; } } - tracing::debug!(host, effective = host, source = "available_parallelism (no cgroup quota found)", "effective_parallelism"); + tracing::debug!( + host, + effective = host, + source = "available_parallelism (no cgroup quota found)", + "effective_parallelism" + ); host } diff --git a/src/obitaxonomy/src/error.rs b/src/obitaxonomy/src/error.rs index 5f4f24e8..2ba949a3 100644 --- a/src/obitaxonomy/src/error.rs +++ b/src/obitaxonomy/src/error.rs @@ -19,18 +19,16 @@ pub enum TaxError { impl fmt::Display for TaxError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TaxError::MissingPrefix => - write!(f, "taxonomy path must start with \"taxonomy:/\""), - TaxError::EmptyPath => - write!(f, "taxonomy path has no segments"), - TaxError::EmptyPattern => - write!(f, "taxonomy query pattern has no segments"), - TaxError::EmptySegmentName => - write!(f, "segment has an empty name"), - TaxError::EmptyRankName { segment } => - write!(f, "segment has '@' with no rank name: {segment:?}"), - TaxError::AmbiguousRank { segment } => - write!(f, "segment contains more than one '@': {segment:?}"), + TaxError::MissingPrefix => write!(f, "taxonomy path must start with \"taxonomy:/\""), + TaxError::EmptyPath => write!(f, "taxonomy path has no segments"), + TaxError::EmptyPattern => write!(f, "taxonomy query pattern has no segments"), + TaxError::EmptySegmentName => write!(f, "segment has an empty name"), + TaxError::EmptyRankName { segment } => { + write!(f, "segment has '@' with no rank name: {segment:?}") + } + TaxError::AmbiguousRank { segment } => { + write!(f, "segment contains more than one '@': {segment:?}") + } } } } diff --git a/src/obitaxonomy/src/lib.rs b/src/obitaxonomy/src/lib.rs index aea3cff0..ad900e9f 100644 --- a/src/obitaxonomy/src/lib.rs +++ b/src/obitaxonomy/src/lib.rs @@ -1,11 +1,11 @@ mod error; -mod segment; -mod segment_pattern; mod path; mod pattern; +mod segment; +mod segment_pattern; pub use error::TaxError; +pub use path::{PREFIX, TaxPath}; +pub use pattern::TaxPattern; pub use segment::TaxSegment; pub use segment_pattern::SegmentPattern; -pub use path::{TaxPath, PREFIX}; -pub use pattern::TaxPattern; diff --git a/src/obitaxonomy/src/path.rs b/src/obitaxonomy/src/path.rs index 096c09bd..a4712018 100644 --- a/src/obitaxonomy/src/path.rs +++ b/src/obitaxonomy/src/path.rs @@ -25,7 +25,8 @@ impl TaxPath { if tail.is_empty() { return Err(TaxError::EmptyPath); } - let segments = tail.split('/') + let segments = tail + .split('/') .map(TaxSegment::parse) .collect::, _>>()?; Ok(Self { segments }) @@ -37,13 +38,17 @@ impl TaxPath { /// `self` must be a prefix of `other` at segment granularity. pub fn is_ancestor_of(&self, other: &TaxPath) -> bool { self.segments.len() <= other.segments.len() - && self.segments.iter().zip(other.segments.iter()) + && self + .segments + .iter() + .zip(other.segments.iter()) .all(|(a, b)| a.name() == b.name()) } /// Returns the name of the first segment whose rank equals `rank`, if any. pub fn name_at_rank(&self, rank: &str) -> Option<&str> { - self.segments.iter() + self.segments + .iter() .find(|s| s.rank() == Some(rank)) .map(|s| s.name()) } @@ -55,12 +60,20 @@ impl TaxPath { /// True if the path contains a segment with both the given rank and name. pub fn matches_rank(&self, rank: &str, name: &str) -> bool { - self.segments.iter().any(|s| s.rank() == Some(rank) && s.name() == name) + self.segments + .iter() + .any(|s| s.rank() == Some(rank) && s.name() == name) } - pub fn segments(&self) -> &[TaxSegment] { &self.segments } - pub fn depth(&self) -> usize { self.segments.len() } - pub fn is_empty(&self) -> bool { self.segments.is_empty() } + pub fn segments(&self) -> &[TaxSegment] { + &self.segments + } + pub fn depth(&self) -> usize { + self.segments.len() + } + pub fn is_empty(&self) -> bool { + self.segments.is_empty() + } } impl fmt::Display for TaxPath { @@ -68,7 +81,9 @@ impl fmt::Display for TaxPath { write!(f, "{}", PREFIX)?; let mut first = true; for seg in &self.segments { - if !first { write!(f, "/")?; } + if !first { + write!(f, "/")?; + } write!(f, "{seg}")?; first = false; } @@ -78,5 +93,7 @@ impl fmt::Display for TaxPath { impl FromStr for TaxPath { type Err = TaxError; - fn from_str(s: &str) -> Result { Self::parse(s) } + fn from_str(s: &str) -> Result { + Self::parse(s) + } } diff --git a/src/obitaxonomy/src/pattern.rs b/src/obitaxonomy/src/pattern.rs index c0474d8f..935bcf85 100644 --- a/src/obitaxonomy/src/pattern.rs +++ b/src/obitaxonomy/src/pattern.rs @@ -20,8 +20,8 @@ use crate::segment_pattern::SegmentPattern; #[derive(Debug, Clone, PartialEq, Eq)] pub struct TaxPattern { start_anchored: bool, - end_anchored: bool, - segments: Vec, + end_anchored: bool, + segments: Vec, } impl TaxPattern { @@ -38,11 +38,16 @@ impl TaxPattern { return Err(TaxError::EmptyPattern); } - let segments = s.split('/') + let segments = s + .split('/') .map(SegmentPattern::parse) .collect::, _>>()?; - Ok(Self { start_anchored, end_anchored, segments }) + Ok(Self { + start_anchored, + end_anchored, + segments, + }) } /// True if this pattern matches `path` according to the anchor flags. @@ -53,19 +58,22 @@ impl TaxPattern { let n = self.segments.len(); let m = path.depth(); - if n > m { return false; } + if n > m { + return false; + } let segs = path.segments(); match (self.start_anchored, self.end_anchored) { - (true, true) => n == m && self.window_matches(segs, 0), - (true, false) => self.window_matches(segs, 0), - (false, true) => self.window_matches(segs, m - n), + (true, true) => n == m && self.window_matches(segs, 0), + (true, false) => self.window_matches(segs, 0), + (false, true) => self.window_matches(segs, m - n), (false, false) => (0..=(m - n)).any(|i| self.window_matches(segs, i)), } } fn window_matches(&self, segs: &[TaxSegment], start: usize) -> bool { - self.segments.iter() + self.segments + .iter() .zip(segs[start..start + self.segments.len()].iter()) .all(|(pat, seg)| pat.matches(seg)) } diff --git a/src/obitaxonomy/src/segment.rs b/src/obitaxonomy/src/segment.rs index b06436d5..7655f50f 100644 --- a/src/obitaxonomy/src/segment.rs +++ b/src/obitaxonomy/src/segment.rs @@ -17,9 +17,13 @@ impl TaxSegment { let parts: Vec<&str> = raw.splitn(3, '@').collect(); let (name_raw, rank_raw) = match parts.as_slice() { - [name] => (*name, None), - [name, rank] => (*name, Some(*rank)), - _ => return Err(TaxError::AmbiguousRank { segment: raw.to_string() }), + [name] => (*name, None), + [name, rank] => (*name, Some(*rank)), + _ => { + return Err(TaxError::AmbiguousRank { + segment: raw.to_string(), + }); + } }; if name_raw.is_empty() { @@ -27,22 +31,33 @@ impl TaxSegment { } let rank = match rank_raw { - None => None, - Some("") => return Err(TaxError::EmptyRankName { segment: raw.to_string() }), - Some(r) => Some(r.to_string()), + None => None, + Some("") => { + return Err(TaxError::EmptyRankName { + segment: raw.to_string(), + }); + } + Some(r) => Some(r.to_string()), }; - Ok(Self { name: name_raw.to_string(), rank }) + Ok(Self { + name: name_raw.to_string(), + rank, + }) } - pub fn name(&self) -> &str { &self.name } - pub fn rank(&self) -> Option<&str> { self.rank.as_deref() } + pub fn name(&self) -> &str { + &self.name + } + pub fn rank(&self) -> Option<&str> { + self.rank.as_deref() + } } impl fmt::Display for TaxSegment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.rank { - None => write!(f, "{}", self.name), + None => write!(f, "{}", self.name), Some(r) => write!(f, "{}@{}", self.name, r), } } diff --git a/src/obitaxonomy/src/segment_pattern.rs b/src/obitaxonomy/src/segment_pattern.rs index 13895ed9..4b41ec62 100644 --- a/src/obitaxonomy/src/segment_pattern.rs +++ b/src/obitaxonomy/src/segment_pattern.rs @@ -16,26 +16,36 @@ impl SegmentPattern { pub fn parse(raw: &str) -> Result { let parts: Vec<&str> = raw.splitn(3, '@').collect(); let (name_raw, rank_raw) = match parts.as_slice() { - [name] => (*name, None), + [name] => (*name, None), [name, rank] => (*name, Some(*rank)), - _ => return Err(TaxError::AmbiguousRank { segment: raw.to_string() }), + _ => { + return Err(TaxError::AmbiguousRank { + segment: raw.to_string(), + }); + } }; if name_raw.is_empty() { return Err(TaxError::EmptySegmentName); } let rank = match rank_raw { - None => None, - Some("") => return Err(TaxError::EmptyRankName { segment: raw.to_string() }), - Some(r) => Some(r.to_string()), + None => None, + Some("") => { + return Err(TaxError::EmptyRankName { + segment: raw.to_string(), + }); + } + Some(r) => Some(r.to_string()), }; - Ok(Self { name: name_raw.to_string(), rank }) + Ok(Self { + name: name_raw.to_string(), + rank, + }) } /// True if this pattern matches `seg`. /// Name must match exactly. If a rank is specified in the pattern, the /// segment's rank must match; otherwise any rank (or no rank) is accepted. pub fn matches(&self, seg: &TaxSegment) -> bool { - self.name == seg.name() - && self.rank.as_deref().map_or(true, |r| seg.rank() == Some(r)) + self.name == seg.name() && self.rank.as_deref().map_or(true, |r| seg.rank() == Some(r)) } }