Files
obiskim/src/obipipeline/src/throttle.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

107 lines
3.9 KiB
Rust

use std::sync::{Arc, Condvar, Mutex};
// ── Throttle ──────────────────────────────────────────────────────────────────
/// Counting semaphore: limits how many items from a source are in-flight
/// simultaneously through the Flat stage of a pipeline.
///
/// Slots are acquired in the source thread before an item is emitted, and
/// released when the corresponding `ThrottleGuard` is dropped (i.e. when the
/// 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<usize>,
condvar: Condvar,
max: usize,
}
impl Throttle {
pub fn new(max: usize) -> Self {
Self {
count: Mutex::new(0),
condvar: Condvar::new(),
max,
}
}
pub fn acquire(&self) {
let mut count = self.count.lock().unwrap();
while *count >= self.max {
count = self.condvar.wait(count).unwrap();
}
*count += 1;
}
fn release(&self) {
let mut count = self.count.lock().unwrap();
*count -= 1;
self.condvar.notify_one();
}
}
impl Throttle {
/// Acquire one slot and return a guard that releases it on drop —
/// for callers with no natural "source iterator" to wrap via
/// [`throttle`] (e.g. bounding concurrency inside a `rayon` parallel
/// iterator's own closure, one call per item, rather than up front in
/// a single source thread). Blocks the calling thread until a slot is
/// free, same as [`throttle`]'s own per-item acquisition.
pub fn acquire_guard(self: &Arc<Self>) -> ThrottleGuard {
self.acquire();
ThrottleGuard(Arc::clone(self))
}
}
// ── ThrottleGuard ─────────────────────────────────────────────────────────────
/// RAII guard: releases one slot in the `Throttle` when dropped.
pub struct ThrottleGuard(Arc<Throttle>);
impl Drop for ThrottleGuard {
fn drop(&mut self) {
self.0.release();
}
}
// ── Throttled<T> ──────────────────────────────────────────────────────────────
/// An item paired with its throttle guard.
///
/// The guard keeps a slot acquired until this value is dropped. In a Flat
/// pipeline stage, carry the guard inside the worker closure until the item
/// is fully processed, then let it drop.
pub struct Throttled<T> {
pub item: T,
pub guard: ThrottleGuard,
}
// ── throttle() ────────────────────────────────────────────────────────────────
/// Wrap `source` so that at most `max_concurrent` items are emitted before
/// earlier ones have been fully processed (i.e. their `ThrottleGuard` dropped).
///
/// Acquisition blocks the source thread until a slot is available. This must
/// be called in the source thread, never inside a pipeline worker.
///
/// # Example
///
/// ```ignore
/// let throttled = obipipeline::throttle(file_paths, n_workers - 1);
/// // Use `throttled` as the pipeline source; carry `item.guard` through the
/// // Flat stage and let it drop when the file is fully read.
/// ```
pub fn throttle<I>(source: I, max_concurrent: usize) -> impl Iterator<Item = Throttled<I::Item>>
where
I: Iterator,
I::Item: Send + 'static,
{
let t = Arc::new(Throttle::new(max_concurrent));
source.map(move |item| {
t.acquire();
Throttled {
item,
guard: ThrottleGuard(Arc::clone(&t)),
}
})
}