refactor: modernize iteration patterns and add sparse matrix support
Update bitvector and matrix operations to use iterator-based loops, `as_chunks`, and direct references instead of index-based access. Introduce `Sparse` variants for persistent bit and integer matrices, including logic to detect and migrate stale columnar formats. Add `is_empty` methods to various data structures and implement `Default` for `PartitionRunner`. - Add `Sparse` variants to `PersistentBitMatrix` and `PersistentIntMatrix` enums, with auto-detection logic to migrate stale columnar files (`matrix.pbmx`, `matrix.pcmx`) to the new sparse format by rebuilding from columnar data. - Refactor bit manipulation functions (`or_where`, `and_where`, `xor_where`) in `bitvec.rs` to use direct references (`*word`) instead of indexed access (`words[wi]`), and update remainder handling in `set_last_word`. - Update `read_int_window` and `read_bit_window` in sparse matrix modules to use `as_chunks::<8>()` for efficient byte-to-u64 conversion, replacing `chunks_exact` and `try_into`. - Modify `inc_predicate_fast` in `builder.rs` to iterate over `primary.iter_mut().zip(col.primary_bytes())` for incrementing values, avoiding index-based access. - Add `is_empty` methods to `Evidence`, `FamilyScalarAnnex`, and `RopeCursor` to check for zero-length or empty states. - Implement `Default` for `PartitionRunner` in `obisys`, delegating to `Self::new()`. - Refactor multiple test functions across `obicompactvec`, `obikmer`, `obikphylo`, `obikquery`, and `obiskio` to use `enumerate()`, `iter()`, and `take()` instead of index-based loops, improving idiomatic Rust patterns. - Update `merge_partition` in `obikmerge` to use `clamp(4, 16)` for worker count calculation instead of chained `min`/`max` calls. - Add `#[allow(clippy::large_enum_variant)]` to `KmerLayer` and `#[allow(clippy::too_many_arguments)]` to subsample functions, with updated documentation clarifying layer types and argument independence. - Refactor `write_sankoff_phyg` and `write_sample_stats` in `obikmer` to use iterator methods (`take`, `copied`, `enumerate`) for processing matrices and labels. - Update `build_emax` and `build_log_nwords` in `obikentropy` to use `enumerate` and direct cell references, and add `WS_MAX` constant and comments in `table.rs`. - Modify `push_warmup_increments` in `obikentropy` to accept a fixed-size array `[u64; 6]` instead of individual arguments, updating `push` accordingly. - Refactor `resolve_partition_batch` and `query_partition_with` in `obikphylo` and `obikquery` to iterate over `by_layer.iter_mut().enumerate().take(n_layer)`, using direct bucket references. - Update `ascii_histogram` in `obikmer` to use `checked_div` and `unwrap_or(0)` for bar length calculation, replacing conditional checks. - Refactor `from_ascii` in `obikseq` to iterate over references `&base in &ascii[..k]` instead of indices, and update related tests to use `#[test]` attributes and new type aliases.
This commit is contained in:
1 parent
f022d83394
commit
a71e59d6f0
51 files changed
+673
-642
No files matched your search
@@ -39,7 +39,7 @@ impl PackedBitMatrix {
|
||||
"PBMX file too short",
|
||||
));
|
||||
}
|
||||
if &mmap[0..4] != &PBMX_MAGIC {
|
||||
if mmap[0..4] != PBMX_MAGIC {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PBMX magic"));
|
||||
}
|
||||
let n_rows = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize;
|
||||
|
||||
@@ -22,6 +22,11 @@ use super::sparse::PersistentSparseBitMatrix;
|
||||
/// - `Packed`: single `matrix.pbmx` file (optimised for query — one `mmap`)
|
||||
/// - `Sparse`: sparse row-major format (`sparse_meta.json` + PFIV/EF files)
|
||||
/// - `Implicit`: no file — all values are 1 (mono-genome presence/absence)
|
||||
// `Sparse` is much larger than the other variants (344 against 56 bytes). Kept as is: there is one value per
|
||||
// layer and partition (hundreds), long-lived and never copied on a hot path, so boxing it would only add an
|
||||
// indirection to the query path and change a public variant. See the backlog ticket on reducing the size of
|
||||
// `PersistentSparseBitMatrix` itself.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum PersistentBitMatrix {
|
||||
Columnar(ColumnarBitMatrix),
|
||||
Packed(PackedBitMatrix),
|
||||
|
||||
@@ -698,19 +698,19 @@ pub fn pack_sparse_bit_matrix(dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
let packed_path = dir.join("matrix.pbmx");
|
||||
|
||||
if let Ok(meta) = MatrixMeta::load(dir) {
|
||||
if packed_bit_matrix_n_cols(&packed_path).ok() != Some(meta.n_cols) {
|
||||
// Columnar data is the freshest form (any `matrix.pbmx` here is
|
||||
// stale, e.g. copied from a merge base before the layer was
|
||||
// widened): transpose it directly.
|
||||
PersistentSparseBitMatrixBuilder::build_from_columnar(dir, &meta)?.close()?;
|
||||
for c in 0..meta.n_cols {
|
||||
fs::remove_file(col_path(dir, c))?;
|
||||
}
|
||||
fs::remove_file(dir.join("meta.json"))?;
|
||||
let _ = fs::remove_file(&packed_path);
|
||||
return Ok(());
|
||||
if let Ok(meta) = MatrixMeta::load(dir)
|
||||
&& packed_bit_matrix_n_cols(&packed_path).ok() != Some(meta.n_cols)
|
||||
{
|
||||
// Columnar data is the freshest form (any `matrix.pbmx` here is
|
||||
// stale, e.g. copied from a merge base before the layer was
|
||||
// widened): transpose it directly.
|
||||
PersistentSparseBitMatrixBuilder::build_from_columnar(dir, &meta)?.close()?;
|
||||
for c in 0..meta.n_cols {
|
||||
fs::remove_file(col_path(dir, c))?;
|
||||
}
|
||||
fs::remove_file(dir.join("meta.json"))?;
|
||||
let _ = fs::remove_file(&packed_path);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Dense packed form is the current one. `pack_bit_matrix` is a no-op when
|
||||
|
||||
@@ -48,8 +48,10 @@ fn read_bit_window(
|
||||
words.clear();
|
||||
words.extend(
|
||||
bytes
|
||||
.chunks_exact(8)
|
||||
.map(|b| u64::from_le_bytes(b.try_into().unwrap())),
|
||||
.as_chunks::<8>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|b| u64::from_le_bytes(*b)),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -353,10 +353,10 @@ impl PersistentBitVecBuilder {
|
||||
for w in words.iter_mut() {
|
||||
*w ^= u64::MAX;
|
||||
}
|
||||
if rem != 0 {
|
||||
if let Some(last) = words.last_mut() {
|
||||
*last &= (1u64 << rem) - 1;
|
||||
}
|
||||
if rem != 0
|
||||
&& let Some(last) = words.last_mut()
|
||||
{
|
||||
*last &= (1u64 << rem) - 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,7 +367,7 @@ impl PersistentBitVecBuilder {
|
||||
let primary = col.primary_bytes();
|
||||
let words = self.data_words_mut();
|
||||
let nw = n_words(n);
|
||||
for wi in 0..nw {
|
||||
for (wi, word) in words.iter_mut().enumerate().take(nw) {
|
||||
let base = wi * 64;
|
||||
let limit = (base + 64).min(n);
|
||||
let mut mask = 0u64;
|
||||
@@ -377,7 +377,7 @@ impl PersistentBitVecBuilder {
|
||||
mask |= 1u64 << bit;
|
||||
}
|
||||
}
|
||||
words[wi] |= mask;
|
||||
*word |= mask;
|
||||
}
|
||||
for (slot, val) in col.overflow_entries() {
|
||||
if pred(val) {
|
||||
@@ -393,7 +393,7 @@ impl PersistentBitVecBuilder {
|
||||
let primary = col.primary_bytes();
|
||||
let words = self.data_words_mut();
|
||||
let nw = n_words(n);
|
||||
for wi in 0..nw {
|
||||
for (wi, word) in words.iter_mut().enumerate().take(nw) {
|
||||
let base = wi * 64;
|
||||
let limit = (base + 64).min(n);
|
||||
let mut mask = 0u64;
|
||||
@@ -403,7 +403,7 @@ impl PersistentBitVecBuilder {
|
||||
mask |= 1u64 << bit;
|
||||
}
|
||||
}
|
||||
words[wi] &= !mask;
|
||||
*word &= !mask;
|
||||
}
|
||||
for (slot, val) in col.overflow_entries() {
|
||||
if !pred(val) {
|
||||
@@ -419,7 +419,7 @@ impl PersistentBitVecBuilder {
|
||||
let primary = col.primary_bytes();
|
||||
let words = self.data_words_mut();
|
||||
let nw = n_words(n);
|
||||
for wi in 0..nw {
|
||||
for (wi, word) in words.iter_mut().enumerate().take(nw) {
|
||||
let base = wi * 64;
|
||||
let limit = (base + 64).min(n);
|
||||
let mut mask = 0u64;
|
||||
@@ -429,7 +429,7 @@ impl PersistentBitVecBuilder {
|
||||
mask |= 1u64 << bit;
|
||||
}
|
||||
}
|
||||
words[wi] ^= mask;
|
||||
*word ^= mask;
|
||||
}
|
||||
for (slot, val) in col.overflow_entries() {
|
||||
if pred(val) {
|
||||
|
||||
@@ -228,10 +228,9 @@ impl PersistentCompactIntVecBuilder {
|
||||
let n = col.len();
|
||||
{
|
||||
let primary = self.primary_bytes_mut();
|
||||
for slot in 0..n {
|
||||
let b = col.primary_bytes()[slot];
|
||||
for (p, &b) in primary.iter_mut().zip(col.primary_bytes()).take(n) {
|
||||
if b < 255 && pred(b as u32) {
|
||||
primary[slot] += 1;
|
||||
*p += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ impl PackedCompactIntMatrix {
|
||||
"PCMX file too short",
|
||||
));
|
||||
}
|
||||
if &mmap[0..4] != &PCMX_MAGIC {
|
||||
if mmap[0..4] != PCMX_MAGIC {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PCMX magic"));
|
||||
}
|
||||
let n_rows = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize;
|
||||
@@ -377,6 +377,11 @@ pub fn pack_compact_int_matrix(dir: &Path) -> io::Result<()> {
|
||||
|
||||
// ── PersistentCompactIntMatrix — public enum ──────────────────────────────────
|
||||
|
||||
// `Sparse` is much larger than the other variants (680 against 56 bytes). Kept as is: there is one value per
|
||||
// layer and partition (hundreds), long-lived and never copied on a hot path, so boxing it would only add an
|
||||
// indirection to the query path and change a public variant. See the backlog ticket on reducing the size of
|
||||
// `PersistentSparseCompactIntMatrix` itself.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum PersistentIntMatrix {
|
||||
Columnar(ColumnarCompactIntMatrix),
|
||||
Packed(PackedCompactIntMatrix),
|
||||
|
||||
@@ -30,7 +30,7 @@ impl PersistentCompactIntVec {
|
||||
"PCIV file too short",
|
||||
));
|
||||
}
|
||||
if &mmap[0..4] != &MAGIC {
|
||||
if mmap[0..4] != MAGIC {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PCIV magic"));
|
||||
}
|
||||
|
||||
|
||||
@@ -638,16 +638,16 @@ pub fn pack_sparse_compact_int_matrix(dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
let packed_path = dir.join("matrix.pcmx");
|
||||
|
||||
if let Ok(meta) = MatrixMeta::load(dir) {
|
||||
if packed_int_matrix_n_cols(&packed_path).ok() != Some(meta.n_cols) {
|
||||
PersistentSparseCompactIntMatrixBuilder::build_from_columnar(dir, &meta)?.close()?;
|
||||
for c in 0..meta.n_cols {
|
||||
fs::remove_file(crate::intmatrix::col_path(dir, c))?;
|
||||
}
|
||||
fs::remove_file(dir.join("meta.json"))?;
|
||||
let _ = fs::remove_file(&packed_path);
|
||||
return Ok(());
|
||||
if let Ok(meta) = MatrixMeta::load(dir)
|
||||
&& packed_int_matrix_n_cols(&packed_path).ok() != Some(meta.n_cols)
|
||||
{
|
||||
PersistentSparseCompactIntMatrixBuilder::build_from_columnar(dir, &meta)?.close()?;
|
||||
for c in 0..meta.n_cols {
|
||||
fs::remove_file(crate::intmatrix::col_path(dir, c))?;
|
||||
}
|
||||
fs::remove_file(dir.join("meta.json"))?;
|
||||
let _ = fs::remove_file(&packed_path);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
pack_compact_int_matrix(dir)?;
|
||||
|
||||
@@ -54,10 +54,10 @@ fn read_int_window(
|
||||
// pushed to `hits` with a placeholder and patched below.
|
||||
let first_hit = hits.len();
|
||||
let mut n_sentinels = 0usize;
|
||||
let mut chunks = primary.chunks_exact(8);
|
||||
let (chunks, remainder) = primary.as_chunks::<8>();
|
||||
let mut base = 0usize;
|
||||
for chunk in &mut chunks {
|
||||
if u64::from_le_bytes(chunk.try_into().unwrap()) != 0 {
|
||||
for chunk in chunks {
|
||||
if u64::from_le_bytes(*chunk) != 0 {
|
||||
for (j, &b) in chunk.iter().enumerate() {
|
||||
if b != 0 {
|
||||
n_sentinels += (b == 255) as usize;
|
||||
@@ -67,7 +67,7 @@ fn read_int_window(
|
||||
}
|
||||
base += 8;
|
||||
}
|
||||
for (j, &b) in chunks.remainder().iter().enumerate() {
|
||||
for (j, &b) in remainder.iter().enumerate() {
|
||||
if b != 0 {
|
||||
n_sentinels += (b == 255) as usize;
|
||||
hits.push(((base + j) as u32, c as u32, b as u32));
|
||||
|
||||
@@ -283,18 +283,18 @@ fn col_view_packed_values() {
|
||||
// col 0: [T, F, T, T]
|
||||
let v0 = m.col_view(0);
|
||||
assert_eq!(v0.len(), 4);
|
||||
assert_eq!(v0.get(0), true);
|
||||
assert_eq!(v0.get(1), false);
|
||||
assert_eq!(v0.get(2), true);
|
||||
assert_eq!(v0.get(3), true);
|
||||
assert!(v0.get(0));
|
||||
assert!(!v0.get(1));
|
||||
assert!(v0.get(2));
|
||||
assert!(v0.get(3));
|
||||
assert_eq!(v0.count_ones(), 3);
|
||||
|
||||
// col 1: [F, T, F, T]
|
||||
let v1 = m.col_view(1);
|
||||
assert_eq!(v1.get(0), false);
|
||||
assert_eq!(v1.get(1), true);
|
||||
assert_eq!(v1.get(2), false);
|
||||
assert_eq!(v1.get(3), true);
|
||||
assert!(!v1.get(0));
|
||||
assert!(v1.get(1));
|
||||
assert!(!v1.get(2));
|
||||
assert!(v1.get(3));
|
||||
assert_eq!(v1.count_ones(), 2);
|
||||
}
|
||||
|
||||
|
||||
@@ -106,10 +106,10 @@ fn int_partial_group_any() {
|
||||
let (_d, m) = make_int_matrix(&[&[0, 3, 0, 1], &[2, 0, 0, 0], &[0, 0, 5, 0]]);
|
||||
let g = ColGroup::new("g", vec![0, 1, 2]);
|
||||
let result = m.partial_group_any(&g, 2).unwrap();
|
||||
assert_eq!(result.get(0), true);
|
||||
assert_eq!(result.get(1), true);
|
||||
assert_eq!(result.get(2), true);
|
||||
assert_eq!(result.get(3), false);
|
||||
assert!(result.get(0));
|
||||
assert!(result.get(1));
|
||||
assert!(result.get(2));
|
||||
assert!(!result.get(3));
|
||||
}
|
||||
|
||||
// ── IntMatrix: mask_with ──────────────────────────────────────────────────────
|
||||
@@ -204,9 +204,9 @@ fn bit_partial_group_any() {
|
||||
let (_d, m) = make_bit_matrix(&[&[true, false, false], &[false, false, true]]);
|
||||
let g = ColGroup::new("g", vec![0, 1]);
|
||||
let result = m.partial_group_any(&g, 1).unwrap();
|
||||
assert_eq!(result.get(0), true);
|
||||
assert_eq!(result.get(1), false);
|
||||
assert_eq!(result.get(2), true);
|
||||
assert!(result.get(0));
|
||||
assert!(!result.get(1));
|
||||
assert!(result.get(2));
|
||||
}
|
||||
|
||||
// ── Composition: partial results are additive ─────────────────────────────────
|
||||
@@ -262,6 +262,8 @@ fn batch_presence_counts_matches_naive_for_columnar_and_sparse() {
|
||||
let sparse_dir = dir.path().join("sparse");
|
||||
let mut b = PersistentSparseBitMatrixBuilder::new(n_rows, n_cols, &sparse_dir).unwrap();
|
||||
let mut genomes = Vec::new();
|
||||
// Rows of a column-major matrix: `row` indexes inside each column, there is no row iterator to use.
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
for row in 0..n_rows {
|
||||
genomes.clear();
|
||||
genomes.extend((0..n_cols).filter(|&c| cols[c][row]).map(|c| c as u32));
|
||||
|
||||
@@ -103,7 +103,7 @@ fn naive_successor(values: &[u64], x: u64) -> Option<u64> {
|
||||
}
|
||||
|
||||
fn naive_predecessor(values: &[u64], x: u64) -> Option<u64> {
|
||||
values.iter().copied().filter(|&v| v <= x).next_back()
|
||||
values.iter().copied().rfind(|&v| v <= x)
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -407,8 +407,8 @@ fn nonzero_iter_matches_row() {
|
||||
let slots = [4usize, 0, 3, 1];
|
||||
let mut expected: Vec<(usize, usize, u32)> = Vec::new();
|
||||
for (i, &slot) in slots.iter().enumerate() {
|
||||
for c in 0..data.len() {
|
||||
let v = data[c][slot];
|
||||
for (c, col) in data.iter().enumerate() {
|
||||
let v = col[slot];
|
||||
if v != 0 {
|
||||
expected.push((i, c, v));
|
||||
}
|
||||
@@ -449,8 +449,8 @@ fn sparse_roundtrip_matches_columnar() {
|
||||
let slots = [4usize, 0, 3, 1];
|
||||
let mut expected: Vec<(usize, usize, u32)> = Vec::new();
|
||||
for (i, &slot) in slots.iter().enumerate() {
|
||||
for c in 0..data.len() {
|
||||
let v = data[c][slot];
|
||||
for (c, col) in data.iter().enumerate() {
|
||||
let v = col[slot];
|
||||
if v != 0 {
|
||||
expected.push((i, c, v));
|
||||
}
|
||||
|
||||
@@ -225,7 +225,7 @@ fn combine_add() {
|
||||
#[test]
|
||||
fn sum_aggregation() {
|
||||
let (_dir, r) = make_pciv(&[10, 200, 0, 1000, 7]);
|
||||
assert_eq!(r.sum(), 10 + 200 + 0 + 1000 + 7);
|
||||
assert_eq!(r.sum(), 10 + 200 + 1000 + 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -207,12 +207,8 @@ 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;
|
||||
}
|
||||
bits[0..=9].fill(true);
|
||||
bits[11..=20].fill(true);
|
||||
let (_dir, r) = build(&bits);
|
||||
assert_eq!(r.select1(9), 9, "select1(9)");
|
||||
assert_eq!(r.select1(10), 11, "select1(10)");
|
||||
|
||||
@@ -89,9 +89,9 @@ fn fill_row_matches_row() {
|
||||
let rows: Vec<&[u32]> = vec![&[9, 0, 2], &[0, 4, 0], &[1, 1, 1]];
|
||||
let (_dir, m) = make_sparse(&rows, 3);
|
||||
let mut buf = vec![0u32; 3];
|
||||
for slot in 0..3 {
|
||||
for (slot, row) in rows.iter().enumerate() {
|
||||
m.fill_row(slot, &mut buf);
|
||||
assert_eq!(&buf, rows[slot], "slot {slot}");
|
||||
assert_eq!(&buf, *row, "slot {slot}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,9 +31,9 @@ fn cell(c: usize, s: &mut u64) -> Option<u32> {
|
||||
let r = xorshift(s);
|
||||
let keep = match c % 4 {
|
||||
0 => false,
|
||||
1 => r % 97 == 0,
|
||||
2 => r % 7 == 0,
|
||||
_ => r % 2 == 0,
|
||||
1 => r.is_multiple_of(97),
|
||||
2 => r.is_multiple_of(7),
|
||||
_ => r.is_multiple_of(2),
|
||||
};
|
||||
keep.then(|| match (r >> 20) % 11 {
|
||||
0 => 255,
|
||||
|
||||
@@ -34,10 +34,10 @@ fn for_each_set_in_matches_get_loop_on_all_boundaries() {
|
||||
for n in [0usize, 1, 63, 64, 65, 127, 128, 129, 200, 4096, 4097] {
|
||||
for (seed, thin) in [(1u64, 0u32), (7, 1), (11, 3), (13, 6)] {
|
||||
let mut w = words(n.div_ceil(64), seed, thin);
|
||||
if n % 64 != 0 {
|
||||
if let Some(last) = w.last_mut() {
|
||||
*last &= (1u64 << (n % 64)) - 1;
|
||||
}
|
||||
if n % 64 != 0
|
||||
&& let Some(last) = w.last_mut()
|
||||
{
|
||||
*last &= (1u64 << (n % 64)) - 1;
|
||||
}
|
||||
let v = BitSliceView::new(&w, n);
|
||||
let cuts = [
|
||||
|
||||
@@ -30,8 +30,8 @@ impl BitSliceView<'_> {
|
||||
}
|
||||
let first = range.start >> 6;
|
||||
let last = (range.end - 1) >> 6;
|
||||
for w in first..=last {
|
||||
let mut word = self.words[w];
|
||||
for (w, &raw) in self.words.iter().enumerate().take(last + 1).skip(first) {
|
||||
let mut word = raw;
|
||||
if word == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ const WS_MAX: usize = 6;
|
||||
|
||||
fn build_n_log_n() -> [f64; K_MAX + 1] {
|
||||
let mut t = [0.0f64; K_MAX + 1];
|
||||
for n in 1..=K_MAX {
|
||||
t[n] = (n as f64) * (n as f64).ln();
|
||||
for (n, v) in t.iter_mut().enumerate().skip(1) {
|
||||
*v = (n as f64) * (n as f64).ln();
|
||||
}
|
||||
t
|
||||
}
|
||||
@@ -17,8 +17,13 @@ fn build_n_log_n() -> [f64; K_MAX + 1] {
|
||||
/// `DevDocMD/theory/entropy.md`.
|
||||
fn build_emax() -> [[f64; WS_MAX + 1]; K_MAX + 1] {
|
||||
let mut t = [[0.0f64; WS_MAX + 1]; K_MAX + 1];
|
||||
for k in 2..=K_MAX {
|
||||
for ws in 1..=WS_MAX.min(k - 1) {
|
||||
for (k, row) in t.iter_mut().enumerate().skip(2) {
|
||||
for (ws, cell) in row
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.take(WS_MAX.min(k - 1) + 1)
|
||||
.skip(1)
|
||||
{
|
||||
let n_raw = 1usize << (ws * 2);
|
||||
let nwords = k - ws + 1;
|
||||
let c = nwords / n_raw;
|
||||
@@ -36,7 +41,7 @@ fn build_emax() -> [[f64; WS_MAX + 1]; K_MAX + 1] {
|
||||
let f2 = (c + 1) as f64 / nf;
|
||||
r as f64 * f2 * f2.ln()
|
||||
};
|
||||
t[k][ws] = -(t1 + t2);
|
||||
*cell = -(t1 + t2);
|
||||
}
|
||||
}
|
||||
t
|
||||
@@ -44,9 +49,14 @@ fn build_emax() -> [[f64; WS_MAX + 1]; K_MAX + 1] {
|
||||
|
||||
fn build_log_nwords() -> [[f64; WS_MAX + 1]; K_MAX + 1] {
|
||||
let mut t = [[0.0f64; WS_MAX + 1]; K_MAX + 1];
|
||||
for k in 2..=K_MAX {
|
||||
for ws in 1..=WS_MAX.min(k - 1) {
|
||||
t[k][ws] = ((k - ws + 1) as f64).ln();
|
||||
for (k, row) in t.iter_mut().enumerate().skip(2) {
|
||||
for (ws, cell) in row
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.take(WS_MAX.min(k - 1) + 1)
|
||||
.skip(1)
|
||||
{
|
||||
*cell = ((k - ws + 1) as f64).ln();
|
||||
}
|
||||
}
|
||||
t
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
//! for tandem repeats), while it measurably *weakens* detection of the
|
||||
//! low-complexity sequences the filter exists to catch.
|
||||
|
||||
// The generated tables hold values of ln(n) and n·ln(n): some entries are, by construction, ln 2 or ln 10.
|
||||
// They are data, not approximations of the constants.
|
||||
#![allow(clippy::approx_constant)]
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/entropy_tables.rs"));
|
||||
|
||||
pub(crate) const WS_MAX: usize = 6;
|
||||
|
||||
@@ -174,22 +174,14 @@ impl EntropyTracker {
|
||||
self.k6c[raw6 as usize] += 1;
|
||||
self.k6q.push_back(raw6);
|
||||
} else {
|
||||
self.push_warmup_increments(received, raw1, raw2, raw3, raw4, raw5, raw6);
|
||||
self.push_warmup_increments(received, [raw1, raw2, raw3, raw4, raw5, raw6]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cold]
|
||||
#[inline(never)]
|
||||
fn push_warmup_increments(
|
||||
&mut self,
|
||||
received: usize,
|
||||
raw1: u64,
|
||||
raw2: u64,
|
||||
raw3: u64,
|
||||
raw4: u64,
|
||||
raw5: u64,
|
||||
raw6: u64,
|
||||
) {
|
||||
fn push_warmup_increments(&mut self, received: usize, raws: [u64; 6]) {
|
||||
let [raw1, raw2, raw3, raw4, raw5, raw6] = raws;
|
||||
let g1 = self.k1c[raw1 as usize] as usize;
|
||||
Self::update_sums_increment::<1>(&mut self.sum_f_log_f, g1);
|
||||
self.k1c[raw1 as usize] += 1;
|
||||
|
||||
@@ -24,6 +24,9 @@ use crate::partition_iter::FilteredPartitionIter;
|
||||
/// presence-collapsed); `output_presence` selects the destination's own
|
||||
/// matrix kind — independent, since `--presence` can force a presence
|
||||
/// output from a count source.
|
||||
// One parameter per independent setting of the rewrite (destination, source, partition, filters, the two value
|
||||
// kinds, block size, mode); a parameter struct would only rename them. Single caller.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn filter_partition(
|
||||
dst: &KmerIndex,
|
||||
src: &Arc<KmerIndex>,
|
||||
|
||||
@@ -57,6 +57,11 @@ const SK_EXT: &str = "skmer.zst";
|
||||
/// not inside `TypedLayer`/`MphfLayer`: those only ever need `dir`
|
||||
/// transiently, while opening — `KmerLayer` is what has to answer `.dir()`
|
||||
/// after the fact, so it's the one that keeps it.
|
||||
// `Count` and `Presence` embed a whole `TypedLayer` (1040 bytes for `Count`) while `Empty` is a path and an id.
|
||||
// Kept as is, like `PersistentBitMatrix`/`PersistentIntMatrix` it wraps: one value per layer and partition, long-lived,
|
||||
// not copied on a hot path; boxing would add an indirection to every query. See the backlog ticket on reducing the
|
||||
// size of the sparse matrices at the source.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum KmerLayer {
|
||||
/// Just a directory — nothing built yet. Every method below other than
|
||||
/// the path accessors panics on this variant: calling them means the
|
||||
|
||||
@@ -34,6 +34,10 @@ impl Evidence {
|
||||
pub fn len(&self) -> usize {
|
||||
self.mmap.len() / 4
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EvidenceWriter {
|
||||
|
||||
@@ -278,8 +278,8 @@ impl MphfLayer {
|
||||
///
|
||||
/// The iteration order follows the physical layout of `unitigs.bin` and is
|
||||
/// **not** correlated with MPHF slot numbers. Owns a clone of the
|
||||
/// underlying `Arc<UnitigFileReader>` rather than borrowing `self` — `Send
|
||||
/// + 'static`, so it can be handed to a threaded consumer (e.g.
|
||||
/// underlying `Arc<UnitigFileReader>` rather than borrowing `self`: it is
|
||||
/// `Send` and `'static`, so it can be handed to a threaded consumer (e.g.
|
||||
/// `obipipeline`) directly, streamed from disk, with no need to collect
|
||||
/// the layer's kmers into memory first. Multiple instances can be held
|
||||
/// concurrently for as long as the underlying file exists, because each
|
||||
|
||||
@@ -84,6 +84,7 @@ pub struct CostsArgs {
|
||||
/// Writes:
|
||||
/// - `PREFIX_sankoff.tcm`: the cost matrix;
|
||||
/// - `PREFIX_sankoff.pg`: the PhyG script.
|
||||
///
|
||||
/// The alignment is the `PREFIX_sankoff.fasta` written by --sankoff,
|
||||
/// used without recoding. Costs are turned into integers with
|
||||
/// --sankoff-cost-scale. Implies --sankoff.
|
||||
@@ -96,6 +97,7 @@ pub struct CostsArgs {
|
||||
/// - `PREFIX_iqtree.model`: a substitution model derived from the
|
||||
/// calibrated Sankoff costs;
|
||||
/// - `PREFIX_iqtree.fasta`: the alignment with recoded states.
|
||||
///
|
||||
/// The model combines the calibrated costs with the frequencies of the
|
||||
/// states observed in the alignment. Only the states that actually
|
||||
/// occur are kept, renumbered consecutively.
|
||||
|
||||
@@ -108,6 +108,7 @@ pub struct SamplingArgs {
|
||||
/// informative sites by number of carrier genomes;
|
||||
/// - `PREFIX_sample_overlap.csv`: the genome-by-genome matrix of
|
||||
/// families shared within the sample.
|
||||
///
|
||||
/// The overlap matrix can be compared with the one written by
|
||||
/// --family-overlap, to check how well the sample represents the index.
|
||||
///
|
||||
|
||||
@@ -106,6 +106,7 @@ pub struct AnnexArgs {
|
||||
/// - number of genomes carrying the family;
|
||||
/// - number of those carriers without ambiguity;
|
||||
/// - entropy bins of 0.05 bits.
|
||||
///
|
||||
/// It has a few hundred thousand lines at most, whatever the size of
|
||||
/// the index.
|
||||
#[arg(long, verbatim_doc_comment)]
|
||||
|
||||
@@ -50,9 +50,9 @@ pub(super) fn write_sankoff_phyg(
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
writeln!(f, "{alphabet_line}").unwrap();
|
||||
for i in 0..16 {
|
||||
let mut row: Vec<i64> = (0..16).map(|j| scaled_matrix[i][j]).collect();
|
||||
row.push(scaled_matrix[i][0]); // gap column: same cost as to/from ∅
|
||||
for matrix_row in scaled_matrix.iter().take(16) {
|
||||
let mut row: Vec<i64> = matrix_row.iter().take(16).copied().collect();
|
||||
row.push(matrix_row[0]); // gap column: same cost as to/from ∅
|
||||
writeln!(
|
||||
f,
|
||||
"{}",
|
||||
|
||||
@@ -91,8 +91,8 @@ pub fn write_sample_stats(
|
||||
write!(f, ",{label}").unwrap();
|
||||
}
|
||||
writeln!(f).unwrap();
|
||||
for i in 0..n {
|
||||
write!(f, "{}", labels[i]).unwrap();
|
||||
for (i, label) in labels.iter().enumerate().take(n) {
|
||||
write!(f, "{label}").unwrap();
|
||||
for j in 0..n {
|
||||
write!(f, ",{}", stats.overlap(i, j)).unwrap();
|
||||
}
|
||||
|
||||
@@ -54,7 +54,6 @@ pub fn run(args: SuperkmerArgs) {
|
||||
let pipe = obipipeline::make_pipe! {
|
||||
PipelineData : Throttled<PathBuf> => Vec<RoutableSuperKmer>,
|
||||
||? {
|
||||
let k = k;
|
||||
move |pw: Throttled<PathBuf>| {
|
||||
let path_str = pw.item.to_str().unwrap_or("").to_owned();
|
||||
let _guard = pw.guard;
|
||||
|
||||
@@ -113,11 +113,7 @@ 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 = (c * bar_width).checked_div(max_count).unwrap_or(0);
|
||||
let bar = "█".repeat(bar_len);
|
||||
out.push_str(&format!(
|
||||
" {:>8} – {:>8} │{:<width$} {}\n",
|
||||
|
||||
@@ -105,7 +105,7 @@ pub(crate) fn merge_partition(
|
||||
debug!("partition {i}: de Bruijn graph build start — {n_src_layers} source layer(s)");
|
||||
|
||||
const BATCH: usize = 4096;
|
||||
let n_workers = rayon::current_num_threads().min(16).max(4);
|
||||
let n_workers = rayon::current_num_threads().clamp(4, 16);
|
||||
// At most 2 files open simultaneously: keeps n_workers-2 workers free
|
||||
// for the Transform stage. Each open file monopolises one worker for the
|
||||
// full duration of its read, so this must stay well below n_workers.
|
||||
|
||||
@@ -193,11 +193,9 @@ pub(super) fn run_pass2(
|
||||
if hits.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for g in 0..src_n {
|
||||
let col_vals: Vec<(usize, u32)> = hits
|
||||
.iter()
|
||||
.map(|&(idx, slot)| (slot, cols[g][idx]))
|
||||
.collect();
|
||||
for (g, col) in cols.iter().enumerate().take(src_n) {
|
||||
let col_vals: Vec<(usize, u32)> =
|
||||
hits.iter().map(|&(idx, slot)| (slot, col[idx])).collect();
|
||||
ops.push((Some(dst_layer), col_offset + g, col_vals));
|
||||
}
|
||||
}
|
||||
@@ -205,11 +203,11 @@ pub(super) fn run_pass2(
|
||||
let not_found_kmers: Vec<CanonicalKmer> =
|
||||
not_found.iter().map(|&idx| kmers[idx]).collect();
|
||||
let new_slots = mphf.index_batch(¬_found_kmers);
|
||||
for g in 0..src_n {
|
||||
for (g, col) in cols.iter().enumerate().take(src_n) {
|
||||
let col_vals: Vec<(usize, u32)> = not_found
|
||||
.iter()
|
||||
.zip(new_slots.iter())
|
||||
.map(|(&idx, &slot)| (slot, cols[g][idx]))
|
||||
.map(|(&idx, &slot)| (slot, col[idx]))
|
||||
.collect();
|
||||
ops.push((None, col_offset + g, col_vals));
|
||||
}
|
||||
|
||||
@@ -88,8 +88,8 @@
|
||||
//! ```
|
||||
//!
|
||||
//! where `e_r` is the degree-`r` [elementary symmetric polynomial] in the
|
||||
//! `s` lengths, `e_r(N_1,...,N_s) = sum_{i_1 < ... < i_r} N_i1 * N_i2 * ...
|
||||
//! * N_ir`. Setting all `N_i = N` collapses `e_r` to `C(s, r) * N^r`,
|
||||
//! `s` lengths, `e_r(N_1,...,N_s) = sum_{i_1 < ... < i_r} N_i1 * N_i2 * ... * N_ir`.
|
||||
//! Setting all `N_i = N` collapses `e_r` to `C(s, r) * N^r`,
|
||||
//! recovering the equal-length formula above exactly — this is a strict
|
||||
//! generalization, not a different approximation.
|
||||
//!
|
||||
|
||||
@@ -198,8 +198,10 @@ pub(crate) fn build_layer_sibling_annex(
|
||||
// pass's per-partition locality while letting Rayon spread a single
|
||||
// oversized bucket across several threads instead of pinning it to
|
||||
// one. ─────────────────────────────────────────────────────────────
|
||||
let chunk_size = ((outgoing.iter().map(Vec::len).sum::<usize>() / n_workers).max(1)).min(4096);
|
||||
let work: Vec<(usize, &[(CanonicalKmer, usize, u8)])> = outgoing
|
||||
let chunk_size = (outgoing.iter().map(Vec::len).sum::<usize>() / n_workers).clamp(1, 4096);
|
||||
// One unit of work: destination partition and a slice of the queued `(variant, source order, base)` entries.
|
||||
type WorkItem<'a> = (usize, &'a [(CanonicalKmer, usize, u8)]);
|
||||
let work: Vec<WorkItem<'_>> = outgoing
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, q)| !q.is_empty())
|
||||
|
||||
@@ -345,8 +345,8 @@ mod tests {
|
||||
let p_card = [[0.2f64; 5]; 5];
|
||||
let tiny = 1e-200;
|
||||
let mut p_comp = [[tiny; 4]; 4];
|
||||
for i in 0..4 {
|
||||
p_comp[i][i] = 1.0 - 3.0 * tiny;
|
||||
for (i, row) in p_comp.iter_mut().enumerate() {
|
||||
row[i] = 1.0 - 3.0 * tiny;
|
||||
}
|
||||
|
||||
let cost = pairwise_cost_matrix(&p_card, &p_comp, false);
|
||||
|
||||
@@ -420,12 +420,12 @@ fn resolve_partition_batch(
|
||||
// present in an earlier layer shadows later ones.
|
||||
let mut by_layer: Vec<Vec<(usize, usize, u8)>> = vec![Vec::new(); n_layer];
|
||||
for &(variant, family_idx, base, _layer_hint) in queries {
|
||||
for li in 0..n_layer {
|
||||
for (li, bucket) in by_layer.iter_mut().enumerate().take(n_layer) {
|
||||
let layer = cache
|
||||
.get_layer(dest_partition, li)
|
||||
.expect("cache-consistent: n_layer(dest_partition) already bounds li");
|
||||
if let Some(slot) = layer.find_slot(variant) {
|
||||
by_layer[li].push((slot, family_idx, base));
|
||||
bucket.push((slot, family_idx, base));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,6 +392,9 @@ pub(crate) fn sample_index(
|
||||
/// `quota / mass × pair weight × entropy kernel` (capped at 1): the pair
|
||||
/// weight is `1` and `mass` the number of eligible families without
|
||||
/// `--pair-balance`, and the kernel `1` without an entropy bias.
|
||||
// The settings of one layer's draw are independent (plan, quota, mode, spec, exclusion mask, callback); a parameter
|
||||
// struct would only rename them. Private, single caller.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sample_layer(
|
||||
cache: &IndexCache,
|
||||
raw_index: usize,
|
||||
|
||||
@@ -119,6 +119,10 @@ impl FamilyScalarAnnex {
|
||||
self.n
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
|
||||
/// The counting convention these values were computed under.
|
||||
pub fn policy(&self) -> AmbiguityPolicy {
|
||||
self.policy
|
||||
|
||||
@@ -153,7 +153,7 @@ impl QueryPartition for IndexCache {
|
||||
break;
|
||||
}
|
||||
stats.n_unique_kmers += pending.len();
|
||||
for l in 0..n_layer {
|
||||
for (l, bucket) in by_layer.iter_mut().enumerate().take(n_layer) {
|
||||
if pending.is_empty() {
|
||||
break;
|
||||
}
|
||||
@@ -170,7 +170,7 @@ impl QueryPartition for IndexCache {
|
||||
i += 1;
|
||||
match hit {
|
||||
Some(slot) => {
|
||||
by_layer[l].insert(slot, descs);
|
||||
bucket.insert(slot, descs);
|
||||
on_event(QueryHit::Found(descs));
|
||||
stats.n_hits += 1;
|
||||
false
|
||||
|
||||
@@ -25,10 +25,8 @@ fn dense_reference_findere(
|
||||
|
||||
let mut confirmed = Vec::new();
|
||||
for (seq_idx, values) in by_seq.iter().enumerate() {
|
||||
let n = values.len();
|
||||
let mut dq: std::collections::VecDeque<(usize, u32)> = std::collections::VecDeque::new();
|
||||
for i in 0..n {
|
||||
let v_i = values[i];
|
||||
for (i, &v_i) in values.iter().enumerate() {
|
||||
while dq.front().is_some_and(|&(f, _)| f + z <= i) {
|
||||
dq.pop_front();
|
||||
}
|
||||
|
||||
@@ -93,6 +93,11 @@ pub trait RopeCursor<'a> {
|
||||
self.rope().len().saturating_sub(self.state().offset.get())
|
||||
}
|
||||
|
||||
/// `true` if no byte is visible through this cursor (`len() == 0`).
|
||||
fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
/// Reset the cursor to its initial state (positioned before the first
|
||||
/// byte of its local view). Equivalent to `seek(0, Absolute)` on a
|
||||
/// fresh cursor, but works even when `current` is `None`.
|
||||
|
||||
@@ -166,8 +166,8 @@ impl<L: KmerLength> KmerOf<L> {
|
||||
});
|
||||
}
|
||||
let mut val: RawKmer = 0;
|
||||
for i in 0..k {
|
||||
val = (val << 2) | encode_base(ascii[i]) as RawKmer;
|
||||
for &base in &ascii[..k] {
|
||||
val = (val << 2) | encode_base(base) as RawKmer;
|
||||
}
|
||||
Ok(KmerOf(val << (KMER_BITS - 2 * k), PhantomData))
|
||||
}
|
||||
|
||||
+317
-322
@@ -1,330 +1,325 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
// Tests use ConstLen<N> — no dependency on global params singletons.
|
||||
type K1 = KmerOf<ConstLen<1>>;
|
||||
type K4 = KmerOf<ConstLen<4>>;
|
||||
|
||||
// Tests use ConstLen<N> — no dependency on global params singletons.
|
||||
type K1 = KmerOf<ConstLen<1>>;
|
||||
type K4 = KmerOf<ConstLen<4>>;
|
||||
fn ascii_revcomp(seq: &[u8]) -> Vec<u8> {
|
||||
seq.iter()
|
||||
.rev()
|
||||
.map(|&b| match b {
|
||||
b'A' => b'T',
|
||||
b'T' => b'A',
|
||||
b'C' => b'G',
|
||||
b'G' => b'C',
|
||||
_ => b'A',
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn ascii_revcomp(seq: &[u8]) -> Vec<u8> {
|
||||
seq.iter()
|
||||
.rev()
|
||||
.map(|&b| match b {
|
||||
b'A' => b'T',
|
||||
b'T' => b'A',
|
||||
b'C' => b'G',
|
||||
b'G' => b'C',
|
||||
_ => b'A',
|
||||
})
|
||||
.collect()
|
||||
fn make_seq<const N: usize>() -> Vec<u8> {
|
||||
(0..N).map(|i| b"ACGT"[i % 4]).collect()
|
||||
}
|
||||
|
||||
// ── from_ascii / to_ascii ─────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn ascii_roundtrip() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ascii = make_seq::<$n>();
|
||||
let kmer = KmerOf::<ConstLen<$n>>::from_ascii(&ascii).unwrap();
|
||||
assert_eq!(kmer.to_ascii(), ascii, "roundtrip failed for k={}", $n);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(2);
|
||||
check!(3);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(11);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
fn make_seq<const N: usize>() -> Vec<u8> {
|
||||
(0..N).map(|i| b"ACGT"[i % 4]).collect()
|
||||
}
|
||||
|
||||
// ── from_ascii / to_ascii ─────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn ascii_roundtrip() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ascii = make_seq::<$n>();
|
||||
let kmer = KmerOf::<ConstLen<$n>>::from_ascii(&ascii).unwrap();
|
||||
assert_eq!(kmer.to_ascii(), ascii, "roundtrip failed for k={}", $n);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(2);
|
||||
check!(3);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(11);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_ascii_all_bases() {
|
||||
for (base, expected) in [(b'A', b'A'), (b'C', b'C'), (b'G', b'G'), (b'T', b'T')] {
|
||||
let kmer = K1::from_ascii(&[base]).unwrap();
|
||||
assert_eq!(kmer.to_ascii(), vec![expected]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_ascii_invalid_k() {
|
||||
assert!(KmerOf::<ConstLen<0>>::from_ascii(b"A").is_err());
|
||||
assert!(KmerOf::<ConstLen<33>>::from_ascii(b"ACGT").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_ascii_too_short() {
|
||||
assert!(KmerOf::<ConstLen<4>>::from_ascii(b"ACG").is_err());
|
||||
}
|
||||
|
||||
// ── nucleotide ────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn nucleotide_extraction() {
|
||||
let kmer = K4::from_ascii(b"ACGT").unwrap();
|
||||
assert_eq!(kmer.nucleotide(0), 0b00); // A
|
||||
assert_eq!(kmer.nucleotide(1), 0b01); // C
|
||||
assert_eq!(kmer.nucleotide(2), 0b10); // G
|
||||
assert_eq!(kmer.nucleotide(3), 0b11); // T
|
||||
}
|
||||
|
||||
// ── revcomp ───────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn revcomp_known_values() {
|
||||
let cases: &[(&[u8], &[u8])] = &[
|
||||
(b"A", b"T"),
|
||||
(b"AC", b"GT"),
|
||||
(b"ACG", b"CGT"),
|
||||
(b"ACGT", b"ACGT"),
|
||||
(b"AAAA", b"TTTT"),
|
||||
(b"TTTT", b"AAAA"),
|
||||
];
|
||||
for (seq, expected) in cases {
|
||||
macro_rules! check_len {
|
||||
($n:expr) => {
|
||||
if seq.len() == $n {
|
||||
let kmer = KmerOf::<ConstLen<$n>>::from_ascii(seq).unwrap();
|
||||
assert_eq!(
|
||||
kmer.revcomp().to_ascii(),
|
||||
*expected,
|
||||
"revcomp wrong for \"{}\"",
|
||||
std::str::from_utf8(seq).unwrap()
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
check_len!(1);
|
||||
check_len!(2);
|
||||
check_len!(3);
|
||||
check_len!(4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcomp_vs_reference() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ascii = make_seq::<$n>();
|
||||
let expected = ascii_revcomp(&ascii);
|
||||
let rc = KmerOf::<ConstLen<$n>>::from_ascii(&ascii)
|
||||
.unwrap()
|
||||
.revcomp();
|
||||
assert_eq!(rc.to_ascii(), expected, "revcomp wrong for k={}", $n);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(11);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcomp_involution() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ascii = make_seq::<$n>();
|
||||
let kmer = KmerOf::<ConstLen<$n>>::from_ascii(&ascii).unwrap();
|
||||
assert_eq!(
|
||||
kmer.revcomp().revcomp(),
|
||||
kmer,
|
||||
"revcomp∘revcomp≠id for k={}",
|
||||
$n
|
||||
);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
// ── canonical ─────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn canonical_palindrome() {
|
||||
let kmer = K4::from_ascii(b"ACGT").unwrap();
|
||||
assert_eq!(kmer.canonical().into_kmer(), kmer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_chooses_lesser() {
|
||||
let kmer = K4::from_ascii(b"TTTT").unwrap();
|
||||
let expected = K4::from_ascii(b"AAAA").unwrap();
|
||||
assert_eq!(kmer.canonical().into_kmer(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_is_minimal() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ascii = make_seq::<$n>();
|
||||
let ck = KmerOf::<ConstLen<$n>>::from_ascii(&ascii)
|
||||
.unwrap()
|
||||
.canonical();
|
||||
let rc = ck.revcomp();
|
||||
assert!(ck.raw() <= rc.raw(), "canonical not minimal for k={}", $n);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_idempotent() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ck = KmerOf::<ConstLen<$n>>::from_ascii(&make_seq::<$n>())
|
||||
.unwrap()
|
||||
.canonical();
|
||||
assert_eq!(
|
||||
ck.into_kmer().canonical(),
|
||||
ck,
|
||||
"canonical not idempotent for k={}",
|
||||
$n
|
||||
);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
// ── central_canonical_neighbors ─────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn central_canonical_neighbors_hand_checked_k3() {
|
||||
// k=3, centre = index 1. For "ACG", every one of the 4 central
|
||||
// substitutions ("AAG","ACG","AGG","ATG") happens to stay in forward
|
||||
// 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::<ConstLen<3>>::from_ascii(b"ACG")
|
||||
.unwrap()
|
||||
.canonical();
|
||||
let neighbours = ck.central_canonical_neighbors();
|
||||
let ascii: Vec<Vec<u8>> = 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()
|
||||
]
|
||||
);
|
||||
// The identity substitution (centre unchanged) must reproduce `ck`.
|
||||
assert!(neighbours.contains(&ck));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn central_canonical_neighbors_identity_present_for_various_k() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ck = KmerOf::<ConstLen<$n>>::from_ascii(&make_seq::<$n>())
|
||||
.unwrap()
|
||||
.canonical();
|
||||
let neighbours = ck.central_canonical_neighbors();
|
||||
assert!(
|
||||
neighbours.contains(&ck),
|
||||
"identity substitution missing from central_canonical_neighbors for k={}",
|
||||
$n
|
||||
);
|
||||
// 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
|
||||
);
|
||||
}
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(3);
|
||||
check!(5);
|
||||
check!(31);
|
||||
}
|
||||
|
||||
// ── family_id ───────────────────────────────────────────────────────────
|
||||
|
||||
/// Exhaustive: `family_id` is shared by every member of a family (and by
|
||||
/// each member's reverse complement) and separates distinct families —
|
||||
/// the latter checked against `central_canonical_neighbors` as ground truth.
|
||||
#[test]
|
||||
fn family_id_partitions_kmers_into_families() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
type K = KmerOf<ConstLen<$n>>;
|
||||
let mut families: std::collections::HashMap<_, Vec<_>> = Default::default();
|
||||
for code in 0..4usize.pow($n) {
|
||||
let ascii: Vec<u8> = (0..$n).map(|i| b"ACGT"[(code >> (2 * i)) & 3]).collect();
|
||||
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();
|
||||
members.sort_unstable();
|
||||
for n in ck.central_canonical_neighbors() {
|
||||
assert_eq!(n.family_id(), id, "k={}: members disagree", $n);
|
||||
}
|
||||
assert_eq!(id, id.family_id(), "k={}: family_id not idempotent", $n);
|
||||
families.entry(id).or_default().push(members);
|
||||
}
|
||||
// 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
|
||||
);
|
||||
}
|
||||
}};
|
||||
}
|
||||
check!(3);
|
||||
check!(5);
|
||||
check!(7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn family_id_ascii_masks_centre() {
|
||||
let ck = KmerOf::<ConstLen<5>>::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]]
|
||||
);
|
||||
#[test]
|
||||
fn from_ascii_all_bases() {
|
||||
for (base, expected) in [(b'A', b'A'), (b'C', b'C'), (b'G', b'G'), (b'T', b'T')] {
|
||||
let kmer = K1::from_ascii(&[base]).unwrap();
|
||||
assert_eq!(kmer.to_ascii(), vec![expected]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_ascii_invalid_k() {
|
||||
assert!(KmerOf::<ConstLen<0>>::from_ascii(b"A").is_err());
|
||||
assert!(KmerOf::<ConstLen<33>>::from_ascii(b"ACGT").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_ascii_too_short() {
|
||||
assert!(KmerOf::<ConstLen<4>>::from_ascii(b"ACG").is_err());
|
||||
}
|
||||
|
||||
// ── nucleotide ────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn nucleotide_extraction() {
|
||||
let kmer = K4::from_ascii(b"ACGT").unwrap();
|
||||
assert_eq!(kmer.nucleotide(0), 0b00); // A
|
||||
assert_eq!(kmer.nucleotide(1), 0b01); // C
|
||||
assert_eq!(kmer.nucleotide(2), 0b10); // G
|
||||
assert_eq!(kmer.nucleotide(3), 0b11); // T
|
||||
}
|
||||
|
||||
// ── revcomp ───────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn revcomp_known_values() {
|
||||
let cases: &[(&[u8], &[u8])] = &[
|
||||
(b"A", b"T"),
|
||||
(b"AC", b"GT"),
|
||||
(b"ACG", b"CGT"),
|
||||
(b"ACGT", b"ACGT"),
|
||||
(b"AAAA", b"TTTT"),
|
||||
(b"TTTT", b"AAAA"),
|
||||
];
|
||||
for (seq, expected) in cases {
|
||||
macro_rules! check_len {
|
||||
($n:expr) => {
|
||||
if seq.len() == $n {
|
||||
let kmer = KmerOf::<ConstLen<$n>>::from_ascii(seq).unwrap();
|
||||
assert_eq!(
|
||||
kmer.revcomp().to_ascii(),
|
||||
*expected,
|
||||
"revcomp wrong for \"{}\"",
|
||||
std::str::from_utf8(seq).unwrap()
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
check_len!(1);
|
||||
check_len!(2);
|
||||
check_len!(3);
|
||||
check_len!(4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcomp_vs_reference() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ascii = make_seq::<$n>();
|
||||
let expected = ascii_revcomp(&ascii);
|
||||
let rc = KmerOf::<ConstLen<$n>>::from_ascii(&ascii)
|
||||
.unwrap()
|
||||
.revcomp();
|
||||
assert_eq!(rc.to_ascii(), expected, "revcomp wrong for k={}", $n);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(11);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcomp_involution() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ascii = make_seq::<$n>();
|
||||
let kmer = KmerOf::<ConstLen<$n>>::from_ascii(&ascii).unwrap();
|
||||
assert_eq!(
|
||||
kmer.revcomp().revcomp(),
|
||||
kmer,
|
||||
"revcomp∘revcomp≠id for k={}",
|
||||
$n
|
||||
);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
// ── canonical ─────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn canonical_palindrome() {
|
||||
let kmer = K4::from_ascii(b"ACGT").unwrap();
|
||||
assert_eq!(kmer.canonical().into_kmer(), kmer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_chooses_lesser() {
|
||||
let kmer = K4::from_ascii(b"TTTT").unwrap();
|
||||
let expected = K4::from_ascii(b"AAAA").unwrap();
|
||||
assert_eq!(kmer.canonical().into_kmer(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_is_minimal() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ascii = make_seq::<$n>();
|
||||
let ck = KmerOf::<ConstLen<$n>>::from_ascii(&ascii)
|
||||
.unwrap()
|
||||
.canonical();
|
||||
let rc = ck.revcomp();
|
||||
assert!(ck.raw() <= rc.raw(), "canonical not minimal for k={}", $n);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_idempotent() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ck = KmerOf::<ConstLen<$n>>::from_ascii(&make_seq::<$n>())
|
||||
.unwrap()
|
||||
.canonical();
|
||||
assert_eq!(
|
||||
ck.into_kmer().canonical(),
|
||||
ck,
|
||||
"canonical not idempotent for k={}",
|
||||
$n
|
||||
);
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(4);
|
||||
check!(8);
|
||||
check!(16);
|
||||
check!(31);
|
||||
check!(32);
|
||||
}
|
||||
|
||||
// ── central_canonical_neighbors ─────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn central_canonical_neighbors_hand_checked_k3() {
|
||||
// k=3, centre = index 1. For "ACG", every one of the 4 central
|
||||
// substitutions ("AAG","ACG","AGG","ATG") happens to stay in forward
|
||||
// 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::<ConstLen<3>>::from_ascii(b"ACG")
|
||||
.unwrap()
|
||||
.canonical();
|
||||
let neighbours = ck.central_canonical_neighbors();
|
||||
let ascii: Vec<Vec<u8>> = 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()
|
||||
]
|
||||
);
|
||||
// The identity substitution (centre unchanged) must reproduce `ck`.
|
||||
assert!(neighbours.contains(&ck));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn central_canonical_neighbors_identity_present_for_various_k() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
let ck = KmerOf::<ConstLen<$n>>::from_ascii(&make_seq::<$n>())
|
||||
.unwrap()
|
||||
.canonical();
|
||||
let neighbours = ck.central_canonical_neighbors();
|
||||
assert!(
|
||||
neighbours.contains(&ck),
|
||||
"identity substitution missing from central_canonical_neighbors for k={}",
|
||||
$n
|
||||
);
|
||||
// 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
|
||||
);
|
||||
}
|
||||
}};
|
||||
}
|
||||
check!(1);
|
||||
check!(3);
|
||||
check!(5);
|
||||
check!(31);
|
||||
}
|
||||
|
||||
// ── family_id ───────────────────────────────────────────────────────────
|
||||
|
||||
/// Exhaustive: `family_id` is shared by every member of a family (and by
|
||||
/// each member's reverse complement) and separates distinct families —
|
||||
/// the latter checked against `central_canonical_neighbors` as ground truth.
|
||||
#[test]
|
||||
fn family_id_partitions_kmers_into_families() {
|
||||
macro_rules! check {
|
||||
($n:expr) => {{
|
||||
type K = KmerOf<ConstLen<$n>>;
|
||||
let mut families: std::collections::HashMap<_, Vec<_>> = Default::default();
|
||||
for code in 0..4usize.pow($n) {
|
||||
let ascii: Vec<u8> = (0..$n).map(|i| b"ACGT"[(code >> (2 * i)) & 3]).collect();
|
||||
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();
|
||||
members.sort_unstable();
|
||||
for n in ck.central_canonical_neighbors() {
|
||||
assert_eq!(n.family_id(), id, "k={}: members disagree", $n);
|
||||
}
|
||||
assert_eq!(id, id.family_id(), "k={}: family_id not idempotent", $n);
|
||||
families.entry(id).or_default().push(members);
|
||||
}
|
||||
// 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
|
||||
);
|
||||
}
|
||||
}};
|
||||
}
|
||||
check!(3);
|
||||
check!(5);
|
||||
check!(7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn family_id_ascii_masks_centre() {
|
||||
let ck = KmerOf::<ConstLen<5>>::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]]
|
||||
);
|
||||
}
|
||||
+169
-172
@@ -1,182 +1,179 @@
|
||||
// ── tests ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::packed_seq::PackedSeq as Unitig;
|
||||
use crate::set_k;
|
||||
use crate::packed_seq::PackedSeq as Unitig;
|
||||
use crate::set_k;
|
||||
|
||||
fn make_seq(len: usize) -> Vec<u8> {
|
||||
(0..len).map(|i| b"ACGT"[i % 4]).collect()
|
||||
}
|
||||
fn make_seq(len: usize) -> Vec<u8> {
|
||||
(0..len).map(|i| b"ACGT"[i % 4]).collect()
|
||||
}
|
||||
|
||||
fn ascii_revcomp(seq: &[u8]) -> Vec<u8> {
|
||||
seq.iter()
|
||||
.rev()
|
||||
.map(|&b| match b {
|
||||
b'A' => b'T',
|
||||
b'T' => b'A',
|
||||
b'C' => b'G',
|
||||
b'G' => b'C',
|
||||
_ => b'A',
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn ascii_revcomp(seq: &[u8]) -> Vec<u8> {
|
||||
seq.iter()
|
||||
.rev()
|
||||
.map(|&b| match b {
|
||||
b'A' => b'T',
|
||||
b'T' => b'A',
|
||||
b'C' => b'G',
|
||||
b'G' => b'C',
|
||||
_ => b'A',
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn test_lengths() -> impl Iterator<Item = usize> {
|
||||
(1..=9).chain([255, 256, 257, 1000, 10_000])
|
||||
}
|
||||
fn test_lengths() -> impl Iterator<Item = usize> {
|
||||
(1..=9).chain([255, 256, 257, 1000, 10_000])
|
||||
}
|
||||
|
||||
// ── from_ascii / to_ascii ─────────────────────────────────────────────────
|
||||
// ── from_ascii / to_ascii ─────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn ascii_roundtrip_all_lengths() {
|
||||
for len in test_lengths() {
|
||||
let ascii = make_seq(len);
|
||||
let u = Unitig::from_ascii(&ascii);
|
||||
assert_eq!(u.to_ascii(), ascii, "roundtrip failed for len={len}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── seql ──────────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn seql_roundtrip() {
|
||||
for len in test_lengths() {
|
||||
let u = Unitig::from_ascii(&make_seq(len));
|
||||
assert_eq!(u.seql(), len);
|
||||
}
|
||||
}
|
||||
|
||||
// ── revcomp ───────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn revcomp_known_values() {
|
||||
let cases = [
|
||||
("A", "T"),
|
||||
("AC", "GT"),
|
||||
("ACG", "CGT"),
|
||||
("ACGT", "ACGT"),
|
||||
("ACGTA", "TACGT"),
|
||||
];
|
||||
for (seq, expected) in cases {
|
||||
let mut u = Unitig::from_ascii(seq.as_bytes());
|
||||
u.revcomp_inplace();
|
||||
assert_eq!(
|
||||
u.to_ascii(),
|
||||
expected.as_bytes(),
|
||||
"revcomp wrong for \"{seq}\""
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcomp_vs_reference_all_lengths() {
|
||||
for len in test_lengths() {
|
||||
let ascii = make_seq(len);
|
||||
let expected = ascii_revcomp(&ascii);
|
||||
let mut u = Unitig::from_ascii(&ascii);
|
||||
u.revcomp_inplace();
|
||||
assert_eq!(u.to_ascii(), expected, "revcomp wrong for len={len}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcomp_involution_all_lengths() {
|
||||
for len in test_lengths() {
|
||||
let ascii = make_seq(len);
|
||||
let mut u = Unitig::from_ascii(&ascii);
|
||||
u.revcomp_inplace();
|
||||
u.revcomp_inplace();
|
||||
assert_eq!(u.to_ascii(), ascii, "revcomp∘revcomp≠id for len={len}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── canonicalize ──────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn canonical_palindrome_unchanged() {
|
||||
let mut u = Unitig::from_ascii(b"ACGT");
|
||||
u.canonicalize();
|
||||
assert_eq!(u.to_ascii(), b"ACGT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_chooses_revcomp() {
|
||||
let mut u = Unitig::from_ascii(b"TTTT");
|
||||
u.canonicalize();
|
||||
assert_eq!(u.to_ascii(), b"AAAA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_is_minimal_all_lengths() {
|
||||
for len in test_lengths() {
|
||||
let ascii = make_seq(len);
|
||||
let mut u = Unitig::from_ascii(&ascii);
|
||||
u.canonicalize();
|
||||
let fwd = u.to_ascii();
|
||||
let rev = ascii_revcomp(&fwd);
|
||||
assert!(fwd <= rev, "canonical not minimal for len={len}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── kmer extraction ───────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn kmer_all_positions() {
|
||||
set_k(4);
|
||||
let k = crate::params::k();
|
||||
let ascii = b"ACGTACGTACGT";
|
||||
let u = Unitig::from_ascii(ascii);
|
||||
for i in 0..=ascii.len() - k {
|
||||
let kmer = u.kmer(i).unwrap();
|
||||
let expected = crate::kmer::Kmer::from_ascii(&ascii[i..i + k]).unwrap();
|
||||
assert_eq!(kmer, expected, "mismatch at position {i}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── iter_kmers ────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn iter_kmers_matches_kmer_at_each_position() {
|
||||
set_k(4);
|
||||
let ascii = make_seq(20);
|
||||
#[test]
|
||||
fn ascii_roundtrip_all_lengths() {
|
||||
for len in test_lengths() {
|
||||
let ascii = make_seq(len);
|
||||
let u = Unitig::from_ascii(&ascii);
|
||||
let kmers: Vec<crate::kmer::Kmer> = u.iter_kmers().collect();
|
||||
for (i, &km) in kmers.iter().enumerate() {
|
||||
assert_eq!(km, u.kmer(i).unwrap(), "pos={i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iter_kmers_long_unitig() {
|
||||
set_k(4);
|
||||
let k = crate::params::k();
|
||||
let ascii = make_seq(10_000);
|
||||
let u = Unitig::from_ascii(&ascii);
|
||||
assert_eq!(u.iter_kmers().count(), 10_000 - k + 1);
|
||||
}
|
||||
|
||||
// ── binary serialisation ──────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn binary_roundtrip_all_lengths() {
|
||||
// write_to_binary encodes a single chunk: seql must be in [k, MAX_KMERS_PER_CHUNK+k-1].
|
||||
use crate::packed_seq::MAX_KMERS_PER_CHUNK;
|
||||
set_k(4);
|
||||
let k = crate::params::k();
|
||||
let valid_lengths: Vec<usize> = (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();
|
||||
u.write_to_binary(&mut buf).unwrap();
|
||||
let u2 = Unitig::read_from_binary(&mut buf.as_slice()).unwrap();
|
||||
assert_eq!(u, u2, "binary roundtrip failed for len={len}");
|
||||
}
|
||||
assert_eq!(u.to_ascii(), ascii, "roundtrip failed for len={len}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── seql ──────────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn seql_roundtrip() {
|
||||
for len in test_lengths() {
|
||||
let u = Unitig::from_ascii(&make_seq(len));
|
||||
assert_eq!(u.seql(), len);
|
||||
}
|
||||
}
|
||||
|
||||
// ── revcomp ───────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn revcomp_known_values() {
|
||||
let cases = [
|
||||
("A", "T"),
|
||||
("AC", "GT"),
|
||||
("ACG", "CGT"),
|
||||
("ACGT", "ACGT"),
|
||||
("ACGTA", "TACGT"),
|
||||
];
|
||||
for (seq, expected) in cases {
|
||||
let mut u = Unitig::from_ascii(seq.as_bytes());
|
||||
u.revcomp_inplace();
|
||||
assert_eq!(
|
||||
u.to_ascii(),
|
||||
expected.as_bytes(),
|
||||
"revcomp wrong for \"{seq}\""
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcomp_vs_reference_all_lengths() {
|
||||
for len in test_lengths() {
|
||||
let ascii = make_seq(len);
|
||||
let expected = ascii_revcomp(&ascii);
|
||||
let mut u = Unitig::from_ascii(&ascii);
|
||||
u.revcomp_inplace();
|
||||
assert_eq!(u.to_ascii(), expected, "revcomp wrong for len={len}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcomp_involution_all_lengths() {
|
||||
for len in test_lengths() {
|
||||
let ascii = make_seq(len);
|
||||
let mut u = Unitig::from_ascii(&ascii);
|
||||
u.revcomp_inplace();
|
||||
u.revcomp_inplace();
|
||||
assert_eq!(u.to_ascii(), ascii, "revcomp∘revcomp≠id for len={len}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── canonicalize ──────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn canonical_palindrome_unchanged() {
|
||||
let mut u = Unitig::from_ascii(b"ACGT");
|
||||
u.canonicalize();
|
||||
assert_eq!(u.to_ascii(), b"ACGT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_chooses_revcomp() {
|
||||
let mut u = Unitig::from_ascii(b"TTTT");
|
||||
u.canonicalize();
|
||||
assert_eq!(u.to_ascii(), b"AAAA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_is_minimal_all_lengths() {
|
||||
for len in test_lengths() {
|
||||
let ascii = make_seq(len);
|
||||
let mut u = Unitig::from_ascii(&ascii);
|
||||
u.canonicalize();
|
||||
let fwd = u.to_ascii();
|
||||
let rev = ascii_revcomp(&fwd);
|
||||
assert!(fwd <= rev, "canonical not minimal for len={len}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── kmer extraction ───────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn kmer_all_positions() {
|
||||
set_k(4);
|
||||
let k = crate::params::k();
|
||||
let ascii = b"ACGTACGTACGT";
|
||||
let u = Unitig::from_ascii(ascii);
|
||||
for i in 0..=ascii.len() - k {
|
||||
let kmer = u.kmer(i).unwrap();
|
||||
let expected = crate::kmer::Kmer::from_ascii(&ascii[i..i + k]).unwrap();
|
||||
assert_eq!(kmer, expected, "mismatch at position {i}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── iter_kmers ────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn iter_kmers_matches_kmer_at_each_position() {
|
||||
set_k(4);
|
||||
let ascii = make_seq(20);
|
||||
let u = Unitig::from_ascii(&ascii);
|
||||
let kmers: Vec<crate::kmer::Kmer> = u.iter_kmers().collect();
|
||||
for (i, &km) in kmers.iter().enumerate() {
|
||||
assert_eq!(km, u.kmer(i).unwrap(), "pos={i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iter_kmers_long_unitig() {
|
||||
set_k(4);
|
||||
let k = crate::params::k();
|
||||
let ascii = make_seq(10_000);
|
||||
let u = Unitig::from_ascii(&ascii);
|
||||
assert_eq!(u.iter_kmers().count(), 10_000 - k + 1);
|
||||
}
|
||||
|
||||
// ── binary serialisation ──────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn binary_roundtrip_all_lengths() {
|
||||
// write_to_binary encodes a single chunk: seql must be in [k, MAX_KMERS_PER_CHUNK+k-1].
|
||||
use crate::packed_seq::MAX_KMERS_PER_CHUNK;
|
||||
set_k(4);
|
||||
let k = crate::params::k();
|
||||
let valid_lengths: Vec<usize> = (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();
|
||||
u.write_to_binary(&mut buf).unwrap();
|
||||
let u2 = Unitig::read_from_binary(&mut buf.as_slice()).unwrap();
|
||||
assert_eq!(u, u2, "binary roundtrip failed for len={len}");
|
||||
}
|
||||
}
|
||||
@@ -122,15 +122,11 @@ mod tests {
|
||||
let m = SharingNullModel::new(&[8, 8, 8, 8], 3);
|
||||
let tail = m.tail();
|
||||
let (p, s) = (0.25f64, 4usize);
|
||||
for r in 0..=s {
|
||||
for (r, &t) in tail.iter().enumerate().take(s + 1) {
|
||||
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!((t - expected).abs() < 1e-12, "r={r}: {t} vs {expected}");
|
||||
}
|
||||
assert!((tail[0] - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
@@ -176,8 +176,8 @@ fn iter_kmers_two_chunks_order() {
|
||||
let kmers: Vec<Kmer> = r.iter_kmers().collect();
|
||||
assert_eq!(kmers.len(), 6);
|
||||
// Chunk 0 first
|
||||
for rank in 0..3 {
|
||||
assert_eq!(kmers[rank].raw(), r.raw_kmer(0, rank));
|
||||
for (rank, kmer) in kmers.iter().enumerate().take(3) {
|
||||
assert_eq!(kmer.raw(), r.raw_kmer(0, rank));
|
||||
}
|
||||
// Chunk 1 after
|
||||
for rank in 0..3 {
|
||||
@@ -207,8 +207,7 @@ fn iter_indexed_chunk_id_and_rank_two_chunks() {
|
||||
let items: Vec<(CanonicalKmer, usize, usize)> = r.iter_indexed_canonical_kmers().collect();
|
||||
assert_eq!(items.len(), 6);
|
||||
// First 3 items: chunk_id=0, rank 0..2
|
||||
for rank in 0..3 {
|
||||
let (kmer, chunk_id, item_rank) = items[rank];
|
||||
for (rank, &(kmer, chunk_id, item_rank)) in items.iter().enumerate().take(3) {
|
||||
assert_eq!(chunk_id, 0);
|
||||
assert_eq!(item_rank, rank);
|
||||
assert!(r.verify_canonical_kmer(0, rank, kmer));
|
||||
@@ -366,10 +365,11 @@ fn block_bits_random_access_matches_sequential() {
|
||||
let (_dir, r) = write_read_bb(&seq_refs, 2);
|
||||
assert_eq!(r.len(), seqs.len());
|
||||
let sequential: Vec<Unitig> = r.iter_chunks_sequential().map(|(_, u)| u).collect();
|
||||
for i in 0..seqs.len() {
|
||||
assert_eq!(sequential.len(), seqs.len());
|
||||
for (i, expected) in sequential.iter().enumerate() {
|
||||
assert_eq!(
|
||||
r.unitig(i),
|
||||
sequential[i],
|
||||
*expected,
|
||||
"random vs sequential mismatch at chunk {i}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -57,6 +57,13 @@ pub struct PartitionRunner {
|
||||
nodes: Vec<NodeConfig>,
|
||||
}
|
||||
|
||||
impl Default for PartitionRunner {
|
||||
/// Same as [`PartitionRunner::new`].
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartitionRunner {
|
||||
/// Total worker slots across all nodes.
|
||||
pub fn max_workers(&self) -> usize {
|
||||
|
||||
Reference in new issue
Block a user