refactor(query): deduplicate k-mers upfront and split MPHF lookup

Refactor `QueryBatch` construction to perform canonical k-mer deduplication and partition routing during initialization, eliminating post-batch splitting. Split the `QueryLayer` MPHF lookup into separate `find_slot` and `fill_row` methods, updating callbacks to pass occurrence descriptors instead of indices. Introduce `QueryStats` for tracking MPHF calls and dereplication ratios, and add comprehensive unit tests for batch construction, stats arithmetic, and safe partition handling. Expose new query-layer types in the public API.
This commit is contained in:
Eric Coissac committed 2026-07-07 18:36:25 +02:00
1 parent 9d7ced4493
commit a348637f3b
5 files changed
+330 -134

No files matched your search

+78 -87
View File
@@ -1,7 +1,8 @@
use std::collections::HashMap;
use std::path::Path;
use obicompactvec::{PersistentBitMatrix, PersistentCompactIntMatrix};
use obikseq::{CanonicalKmer, RoutableSuperKmer};
use obikseq::CanonicalKmer;
use obiskio::{SKError, SKResult};
use obilayeredmap::{IndexMode, MphfLayer, OLMError};
use obilayeredmap::meta::PartitionMeta;
@@ -44,53 +45,86 @@ impl QueryLayer {
}
}
/// Write per-genome values into `buf` if `kmer` is indexed; returns true on hit.
fn find_into(&self, kmer: CanonicalKmer, n_genomes: usize, buf: &mut [u32]) -> bool {
/// MPHF lookup only — no matrix access. `Some(slot)` on hit.
fn find_slot(&self, kmer: CanonicalKmer) -> Option<usize> {
match self {
QueryLayer::Presence(mphf, mat) => {
if let Some(slot) = mphf.find(kmer) {
mat.fill_row(slot, &mut buf[..n_genomes]);
true
} else {
false
}
}
QueryLayer::Count(mphf, mat) => {
if let Some(slot) = mphf.find(kmer) {
mat.fill_row(slot, &mut buf[..n_genomes]);
true
} else {
false
}
}
QueryLayer::Presence(mphf, _) | QueryLayer::Count(mphf, _) => mphf.find(kmer),
}
}
/// Write per-genome values for `slot` into `buf`. `slot` must come from
/// [`find_slot`] on this same layer.
fn fill_row(&self, slot: usize, n_genomes: usize, buf: &mut [u32]) {
match self {
QueryLayer::Presence(_, mat) => mat.fill_row(slot, &mut buf[..n_genomes]),
QueryLayer::Count(_, mat) => mat.fill_row(slot, &mut buf[..n_genomes]),
}
}
}
// ── KmerPartition::query_partition* ──────────────────────────────────────────
// ── KmerDesc — one occurrence of a k-mer in the query batch ──────────────────
/// Describes one occurrence of a (deduplicated) k-mer in the query batch:
/// which sequence it came from, and its absolute s-mer position within it.
#[derive(Debug, Clone, Copy)]
pub struct KmerDesc {
pub seq_idx: u32,
pub pos: u32,
}
/// Aggregate counters for one `query_partition_with` call — feeds the
/// dedup-ratio logging in `obikmer::cmd::query` (occurrences vs. unique
/// k-mers is the whole justification for k-mer-level dereplication).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct QueryStats {
/// Distinct canonical k-mers queried in this partition.
pub n_unique_kmers: usize,
/// Total `MphfLayer::find` calls issued (a k-mer tried against more than
/// one layer before a hit, or against all layers on a miss, counts once
/// per layer attempted).
pub n_mphf_calls: usize,
/// Distinct canonical k-mers that matched some layer.
pub n_hits: usize,
}
impl std::ops::AddAssign for QueryStats {
fn add_assign(&mut self, other: Self) {
self.n_unique_kmers += other.n_unique_kmers;
self.n_mphf_calls += other.n_mphf_calls;
self.n_hits += other.n_hits;
}
}
// ── KmerPartition::query_partition_with ──────────────────────────────────────
impl KmerPartition {
/// Query a single partition, calling `on_hit(sk_idx, kmer_idx, row)` for
/// every found k-mer without allocating intermediate result vectors.
/// Query a single partition for a pre-deduplicated map of canonical
/// k-mers → their occurrences (`seq_idx`, `pos`) in the query batch.
///
/// Each unique k-mer triggers at most one MPHF lookup per layer (stopping
/// at the first hit) and, on hit, one matrix row fetch — regardless of
/// how many times that k-mer occurs across the batch. `on_hit(descs, row)`
/// is called once per hit, with every occurrence to broadcast the row to.
pub fn query_partition_with<F>(
&self,
part_idx: usize,
superkmers: &[&RoutableSuperKmer],
_k: usize,
kmers: &HashMap<CanonicalKmer, Vec<KmerDesc>>,
n_genomes: usize,
with_counts: bool,
mut on_hit: F,
) -> SKResult<()>
) -> SKResult<QueryStats>
where
F: FnMut(usize, usize, &[u32]),
F: FnMut(&[KmerDesc], &[u32]),
{
if superkmers.is_empty() {
return Ok(());
let mut stats = QueryStats::default();
if kmers.is_empty() {
return Ok(stats);
}
let index_dir = self.part_dir(part_idx).join(INDEX_SUBDIR);
if !index_dir.exists() {
return Ok(());
return Ok(stats);
}
let meta = PartitionMeta::load(&index_dir).map_err(olm_to_sk)?;
@@ -100,67 +134,24 @@ impl KmerPartition {
let mut buf = vec![0u32; n_genomes];
for (sk_idx, rsk) in superkmers.iter().enumerate() {
for (kmer_idx, kmer) in rsk.superkmer().iter_canonical_kmers().enumerate() {
for layer in &layers {
if layer.find_into(kmer, n_genomes, &mut buf) {
on_hit(sk_idx, kmer_idx, &buf);
buf.fill(0);
break;
}
for (kmer, descs) in kmers {
stats.n_unique_kmers += 1;
for layer in &layers {
stats.n_mphf_calls += 1;
if let Some(slot) = layer.find_slot(*kmer) {
layer.fill_row(slot, n_genomes, &mut buf);
on_hit(descs, &buf);
buf.fill(0);
stats.n_hits += 1;
break;
}
}
}
Ok(())
}
/// Query a single partition for a slice of super-kmers, returning per-kmer rows.
/// Prefer [`query_partition_with`] to avoid per-kmer heap allocations.
pub fn query_partition(
&self,
part_idx: usize,
superkmers: &[&RoutableSuperKmer],
_k: usize,
n_genomes: usize,
with_counts: bool,
) -> SKResult<Vec<Vec<Option<Box<[u32]>>>>> {
if superkmers.is_empty() {
return Ok(Vec::new());
}
let index_dir = self.part_dir(part_idx).join(INDEX_SUBDIR);
if !index_dir.exists() {
return Ok(superkmers
.iter()
.map(|rsk| vec![None; rsk.seql()])
.collect());
}
let meta = PartitionMeta::load(&index_dir).map_err(olm_to_sk)?;
let layers: Vec<QueryLayer> = (0..meta.n_layers)
.map(|i| QueryLayer::open(&index_dir.join(format!("layer_{i}")), with_counts, &meta.mode))
.collect::<SKResult<_>>()?;
let mut buf = vec![0u32; n_genomes];
Ok(superkmers
.iter()
.map(|rsk| {
rsk.superkmer()
.iter_canonical_kmers()
.map(|kmer| {
for layer in &layers {
if layer.find_into(kmer, n_genomes, &mut buf) {
let row: Box<[u32]> = buf[..n_genomes].into();
buf.fill(0);
return Some(row);
}
}
None
})
.collect()
})
.collect())
Ok(stats)
}
}
#[cfg(test)]
#[path = "tests/query_layer.rs"]
mod tests;