Files
obiskim/src/obikindexer/src/algorithms/partitionner/router.rs
T
Eric Coissac ed0d563995 refactor: overhaul compact vector storage, phylo algorithms, and CLI interfaces
Refactor the core compact vector library to support sparse matrices, overflow handling, and improved distance metrics. Update phylogenetic algorithms to handle ambiguity policies and quartet conventions, and standardize error handling and CLI argument parsing across all tools.

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

337 lines
12 KiB
Rust

use std::io;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::time::Instant;
use obikindex::KmerIndex;
use obikindex::layer::KmerLayer;
use obikseq::RoutableSuperKmer;
use obiskio::SKResult;
use obisys::Progress;
use tracing::info;
use niffler::Level;
use niffler::send::compression::Format;
use obiskio::SKFileWriter;
use obipipeline::{ThrottleGuard, Throttled, throttle};
use obiread::NucPage;
use crate::extensions::PrivateBuilder;
use obikalgorithm::Algorithm;
// ── Pipeline plumbing, private to `run` ─────────────────────────────────────
/// Carrier enum for `obipipeline::make_pipe!`'s two-stage transform — local
/// to this crate, not `obikmer`'s own `PipelineData` (which stays scoped to
/// its other CLI commands): a library crate can't depend on the binary
/// that consumes it, so this is a self-contained duplicate of the same
/// shape, not a shared type.
enum PipelineData {
Path(Throttled<PathBuf>),
NucPage(NucPage),
Batch(Vec<RoutableSuperKmer>),
}
unsafe impl Send for PipelineData {}
unsafe impl Sync for PipelineData {}
/// Keeps a file's throttle-slot guard alive until the file's page iterator
/// is exhausted, so the next queued file can only start once this one has
/// actually finished producing pages, not merely been dequeued.
struct GuardedIter {
inner: Box<dyn Iterator<Item = NucPage> + Send>,
_guard: ThrottleGuard,
flat_active: Arc<AtomicU32>,
}
impl Iterator for GuardedIter {
type Item = NucPage;
fn next(&mut self) -> Option<NucPage> {
self.inner.next()
}
}
impl Drop for GuardedIter {
fn drop(&mut self) {
self.flat_active.fetch_sub(1, Ordering::Relaxed);
}
}
// ── PartitionRouter ──────────────────────────────────────────────────────────
/// Routes raw super-kmers into per-partition, layer-0 files — the entry
/// point of the indexing pipeline. Dereplication
/// ([`crate::algorithms::dereplicator`]) and counting
/// ([`crate::algorithms::counter`]) are separate sibling algorithms that
/// run after this one, on the layer-0 content it produces (see
/// `DevDocMD/implementation/partition_layer_cache.md`).
///
/// Holds `&mut KmerIndex` — this is an algorithm operating on an index, not
/// a data structure of its own; it owns no path-naming knowledge (every
/// path comes from `index.index_dir`/`obikindex::layer::layer_dir`/
/// `Layer::create`), only the transient routing state a run needs.
///
/// Two-phase construction: `new` + optional setters (`level_max`/`theta`/
/// `workers`/`max_open`) configure the run, `run` executes it. `run` takes
/// an `Option` progress callback — the router reports raw `(position,
/// total)` ticks via [`obisys::Progress`] and stays unaware of *how* (or
/// whether) the caller displays them; rendering a spinner/progress bar is
/// the caller's decision, not this crate's.
pub struct PartitionRouter<'a> {
index: &'a KmerIndex,
partitions_mask: u64,
writers: Vec<Option<SKFileWriter>>,
level: Level,
closed: bool,
level_max: usize,
theta: f64,
workers: usize,
max_open: usize,
files: Option<Box<dyn Iterator<Item = PathBuf> + Send>>,
on_progress: Option<Box<dyn FnMut(Progress) + 'a>>,
}
impl<'a> PartitionRouter<'a> {
/// Configure a router for `index`'s partition layout. Doesn't touch
/// disk by itself — partitions and their layer-0 shells are created
/// lazily, on the first super-kmer routed to each of them.
pub fn new(index: &'a KmerIndex) -> Self {
let n_bits = index.n_bits();
let n_partitions = 1usize << n_bits;
let workers = obisys::effective_parallelism();
Self {
index,
partitions_mask: (1u64 << n_bits) - 1,
writers: (0..n_partitions).map(|_| None).collect(),
level: Level::One,
closed: false,
level_max: 6,
theta: 0.7,
workers,
max_open: (workers / 4).max(1),
files: None,
on_progress: None,
}
}
/// Maximum sub-word size for entropy computation (superkmer building).
pub fn level_max(mut self, v: usize) -> Self {
self.level_max = v;
self
}
/// Entropy threshold (k-mers with score ≤ theta are rejected).
pub fn theta(mut self, v: f64) -> Self {
self.theta = v;
self
}
/// Number of worker threads for `run`'s file-reading/superkmer-building pipeline.
pub fn workers(mut self, v: usize) -> Self {
self.workers = v;
self
}
/// Maximum number of input files `run` opens simultaneously.
pub fn max_open(mut self, v: usize) -> Self {
self.max_open = v;
self
}
/// Input files for `run`'s file-driven pipeline. Required before
/// calling `run` — `write`/`write_batch` callers (e.g. tests feeding
/// in-memory superkmers directly) don't need this at all.
pub fn files(mut self, path_source: impl Iterator<Item = PathBuf> + Send + 'static) -> Self {
self.files = Some(Box::new(path_source));
self
}
/// Progress callback for `run`'s file-driven pipeline — called
/// periodically (rate-limited, not once per batch) with cumulative
/// bases processed so far (`total: None`, unknown without pre-scanning
/// every input file). Optional — if never set, `run` reports nothing.
/// Sequential single-thread invocation, hence plain `FnMut`, no `Send`
/// bound needed (unlike `LayerBuilder::on_progress`).
pub fn on_progress(mut self, cb: impl FnMut(Progress) + 'a) -> Self {
self.on_progress = Some(Box::new(cb));
self
}
/// Route and write one super-kmer to its partition's raw super-kmer file.
pub fn write(&mut self, rsk: RoutableSuperKmer) -> SKResult<()> {
self.check_not_closed()?;
let partition = (rsk.minimizer().seq_hash() & self.partitions_mask) as usize;
let sk = rsk.into_superkmer();
self.ensure_writer(partition)?.write(&sk)
}
/// Route and write a batch of super-kmers.
pub fn write_batch(&mut self, rsks: Vec<RoutableSuperKmer>) -> SKResult<()> {
self.check_not_closed()?;
for rsk in rsks {
let partition = (rsk.minimizer().seq_hash() & self.partitions_mask) as usize;
let sk = rsk.into_superkmer();
self.ensure_writer(partition)?.write(&sk)?;
}
Ok(())
}
pub fn flush(&mut self) -> SKResult<()> {
self.check_not_closed()?;
for writer in self.writers.iter_mut().flatten() {
writer.flush()?;
}
Ok(())
}
/// Closes every open writer and marks scatter as complete
/// (`scatter.done`) — the single completion point shared by `run`
/// (the file-driven pipeline) and manual `write`/`write_batch` callers
/// (e.g. tests feeding in-memory superkmers directly): whichever path
/// was used, `close` is what both agree means "scatter is done".
/// Idempotent — a second call is a no-op, sentinel included.
pub fn close(&mut self) -> SKResult<()> {
if self.closed {
return Ok(());
}
self.closed = true;
for writer in self.writers.iter_mut().flatten() {
writer.close()?;
}
self.index
.mark_scattered()
.map_err(|e| std::io::Error::other(e.to_string()))?;
Ok(())
}
pub fn is_open(&self) -> bool {
!self.closed
}
// ── private ───────────────────────────────────────────────────────────────
fn check_not_closed(&self) -> SKResult<()> {
if self.closed {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "write to closed PartitionRouter").into())
} else {
Ok(())
}
}
fn ensure_writer(&mut self, partition: usize) -> SKResult<&mut SKFileWriter> {
if self.writers[partition].is_none() {
let part = self
.index
.partition(partition)
.map_err(|e| io::Error::other(e.to_string()))?;
let layer = KmerLayer::new(&part, 0)
.create()
.map_err(|e| io::Error::other(e.to_string()))?;
let file_path = layer.raw_superkmers_path();
let writer = SKFileWriter::create_with(file_path, Format::Zstd, self.level)?;
self.writers[partition] = Some(writer);
}
Ok(self.writers[partition].as_mut().unwrap())
}
}
impl Drop for PartitionRouter<'_> {
fn drop(&mut self) {
let _ = self.close();
}
}
impl Algorithm for PartitionRouter<'_> {
type Output = ();
/// Run the full scatter pipeline: normalise every file from `.files(...)`
/// -> build super-kmers -> route -> write, then close.
/// `.on_progress(...)`, when set, is called periodically (rate-limited,
/// not once per batch) with cumulative bases processed so far —
/// `total: None`, since the total isn't known without pre-scanning
/// every input file.
///
/// 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",
)
})?;
let k = self.index.kmer_size();
let level_max = self.level_max;
let theta = self.theta;
let n_workers = self.workers;
let max_open = self.max_open;
// Throttle in the source thread — never in a worker — to prevent deadlock.
let throttled = throttle(path_source, max_open);
let file_count = Arc::new(AtomicU64::new(0));
let flat_active = Arc::new(AtomicU32::new(0));
let transform_active = Arc::new(AtomicU32::new(0));
let pipe = obipipeline::make_pipe! {
PipelineData : Throttled<PathBuf> => Vec<RoutableSuperKmer>,
||? {
let file_count = Arc::clone(&file_count);
let flat_active = Arc::clone(&flat_active);
move |pw: Throttled<PathBuf>| {
let path = pw.item;
let guard = pw.guard;
let n = file_count.fetch_add(1, Ordering::Relaxed) + 1;
info!("indexing [{}]: {}", n, path.display());
let path_str = path.to_str().unwrap_or("").to_owned();
flat_active.fetch_add(1, Ordering::Relaxed);
obiread::open_nuc_stream(&path_str, k)
.map(|iter| GuardedIter { inner: iter, _guard: guard, flat_active: Arc::clone(&flat_active) })
}
} : Path => NucPage,
| {
let transform_active = Arc::clone(&transform_active);
move |page| {
transform_active.fetch_add(1, Ordering::Relaxed);
let result = obiskbuilder::build_superkmers_page(page, k, level_max, theta);
transform_active.fetch_sub(1, Ordering::Relaxed);
result
}
} : NucPage => Batch,
};
let mut total_bases: u64 = 0;
let mut last_report = Instant::now();
let kmer_overlap = (k - 1) as u64;
const REPORT_INTERVAL: f64 = 0.1;
for batch in pipe.apply(throttled, n_workers, 1) {
total_bases += batch
.iter()
.map(|sk| (sk.seql() as u64).saturating_sub(kmer_overlap))
.sum::<u64>();
if let Some(cb) = self.on_progress.as_mut() {
let now = Instant::now();
if now.duration_since(last_report).as_secs_f64() > REPORT_INTERVAL {
last_report = now;
cb(Progress {
position: total_bases,
total: None,
});
}
}
self.write_batch(batch)?;
}
if let Some(cb) = self.on_progress.as_mut() {
cb(Progress {
position: total_bases,
total: None,
});
}
self.close()?;
Ok(())
}
}