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.
This commit is contained in:
Eric Coissac committed 2026-12-01 17:34:15 +01:00
1 parent 8159137f8b
commit ed0d563995
212 files changed
+4782 -1835

No files matched your search

+10 -12
View File
@@ -19,18 +19,16 @@ pub enum TaxError {
impl fmt::Display for TaxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TaxError::MissingPrefix =>
write!(f, "taxonomy path must start with \"taxonomy:/\""),
TaxError::EmptyPath =>
write!(f, "taxonomy path has no segments"),
TaxError::EmptyPattern =>
write!(f, "taxonomy query pattern has no segments"),
TaxError::EmptySegmentName =>
write!(f, "segment has an empty name"),
TaxError::EmptyRankName { segment } =>
write!(f, "segment has '@' with no rank name: {segment:?}"),
TaxError::AmbiguousRank { segment } =>
write!(f, "segment contains more than one '@': {segment:?}"),
TaxError::MissingPrefix => write!(f, "taxonomy path must start with \"taxonomy:/\""),
TaxError::EmptyPath => write!(f, "taxonomy path has no segments"),
TaxError::EmptyPattern => write!(f, "taxonomy query pattern has no segments"),
TaxError::EmptySegmentName => write!(f, "segment has an empty name"),
TaxError::EmptyRankName { segment } => {
write!(f, "segment has '@' with no rank name: {segment:?}")
}
TaxError::AmbiguousRank { segment } => {
write!(f, "segment contains more than one '@': {segment:?}")
}
}
}
}
+4 -4
View File
@@ -1,11 +1,11 @@
mod error;
mod segment;
mod segment_pattern;
mod path;
mod pattern;
mod segment;
mod segment_pattern;
pub use error::TaxError;
pub use path::{PREFIX, TaxPath};
pub use pattern::TaxPattern;
pub use segment::TaxSegment;
pub use segment_pattern::SegmentPattern;
pub use path::{TaxPath, PREFIX};
pub use pattern::TaxPattern;
+26 -9
View File
@@ -25,7 +25,8 @@ impl TaxPath {
if tail.is_empty() {
return Err(TaxError::EmptyPath);
}
let segments = tail.split('/')
let segments = tail
.split('/')
.map(TaxSegment::parse)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self { segments })
@@ -37,13 +38,17 @@ impl TaxPath {
/// `self` must be a prefix of `other` at segment granularity.
pub fn is_ancestor_of(&self, other: &TaxPath) -> bool {
self.segments.len() <= other.segments.len()
&& self.segments.iter().zip(other.segments.iter())
&& self
.segments
.iter()
.zip(other.segments.iter())
.all(|(a, b)| a.name() == b.name())
}
/// Returns the name of the first segment whose rank equals `rank`, if any.
pub fn name_at_rank(&self, rank: &str) -> Option<&str> {
self.segments.iter()
self.segments
.iter()
.find(|s| s.rank() == Some(rank))
.map(|s| s.name())
}
@@ -55,12 +60,20 @@ impl TaxPath {
/// True if the path contains a segment with both the given rank and name.
pub fn matches_rank(&self, rank: &str, name: &str) -> bool {
self.segments.iter().any(|s| s.rank() == Some(rank) && s.name() == name)
self.segments
.iter()
.any(|s| s.rank() == Some(rank) && s.name() == name)
}
pub fn segments(&self) -> &[TaxSegment] { &self.segments }
pub fn depth(&self) -> usize { self.segments.len() }
pub fn is_empty(&self) -> bool { self.segments.is_empty() }
pub fn segments(&self) -> &[TaxSegment] {
&self.segments
}
pub fn depth(&self) -> usize {
self.segments.len()
}
pub fn is_empty(&self) -> bool {
self.segments.is_empty()
}
}
impl fmt::Display for TaxPath {
@@ -68,7 +81,9 @@ impl fmt::Display for TaxPath {
write!(f, "{}", PREFIX)?;
let mut first = true;
for seg in &self.segments {
if !first { write!(f, "/")?; }
if !first {
write!(f, "/")?;
}
write!(f, "{seg}")?;
first = false;
}
@@ -78,5 +93,7 @@ impl fmt::Display for TaxPath {
impl FromStr for TaxPath {
type Err = TaxError;
fn from_str(s: &str) -> Result<Self, Self::Err> { Self::parse(s) }
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
+17 -9
View File
@@ -20,8 +20,8 @@ use crate::segment_pattern::SegmentPattern;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaxPattern {
start_anchored: bool,
end_anchored: bool,
segments: Vec<SegmentPattern>,
end_anchored: bool,
segments: Vec<SegmentPattern>,
}
impl TaxPattern {
@@ -38,11 +38,16 @@ impl TaxPattern {
return Err(TaxError::EmptyPattern);
}
let segments = s.split('/')
let segments = s
.split('/')
.map(SegmentPattern::parse)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self { start_anchored, end_anchored, segments })
Ok(Self {
start_anchored,
end_anchored,
segments,
})
}
/// True if this pattern matches `path` according to the anchor flags.
@@ -53,19 +58,22 @@ impl TaxPattern {
let n = self.segments.len();
let m = path.depth();
if n > m { return false; }
if n > m {
return false;
}
let segs = path.segments();
match (self.start_anchored, self.end_anchored) {
(true, true) => n == m && self.window_matches(segs, 0),
(true, false) => self.window_matches(segs, 0),
(false, true) => self.window_matches(segs, m - n),
(true, true) => n == m && self.window_matches(segs, 0),
(true, false) => self.window_matches(segs, 0),
(false, true) => self.window_matches(segs, m - n),
(false, false) => (0..=(m - n)).any(|i| self.window_matches(segs, i)),
}
}
fn window_matches(&self, segs: &[TaxSegment], start: usize) -> bool {
self.segments.iter()
self.segments
.iter()
.zip(segs[start..start + self.segments.len()].iter())
.all(|(pat, seg)| pat.matches(seg))
}
+25 -10
View File
@@ -17,9 +17,13 @@ impl TaxSegment {
let parts: Vec<&str> = raw.splitn(3, '@').collect();
let (name_raw, rank_raw) = match parts.as_slice() {
[name] => (*name, None),
[name, rank] => (*name, Some(*rank)),
_ => return Err(TaxError::AmbiguousRank { segment: raw.to_string() }),
[name] => (*name, None),
[name, rank] => (*name, Some(*rank)),
_ => {
return Err(TaxError::AmbiguousRank {
segment: raw.to_string(),
});
}
};
if name_raw.is_empty() {
@@ -27,22 +31,33 @@ impl TaxSegment {
}
let rank = match rank_raw {
None => None,
Some("") => return Err(TaxError::EmptyRankName { segment: raw.to_string() }),
Some(r) => Some(r.to_string()),
None => None,
Some("") => {
return Err(TaxError::EmptyRankName {
segment: raw.to_string(),
});
}
Some(r) => Some(r.to_string()),
};
Ok(Self { name: name_raw.to_string(), rank })
Ok(Self {
name: name_raw.to_string(),
rank,
})
}
pub fn name(&self) -> &str { &self.name }
pub fn rank(&self) -> Option<&str> { self.rank.as_deref() }
pub fn name(&self) -> &str {
&self.name
}
pub fn rank(&self) -> Option<&str> {
self.rank.as_deref()
}
}
impl fmt::Display for TaxSegment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.rank {
None => write!(f, "{}", self.name),
None => write!(f, "{}", self.name),
Some(r) => write!(f, "{}@{}", self.name, r),
}
}
+18 -8
View File
@@ -16,26 +16,36 @@ impl SegmentPattern {
pub fn parse(raw: &str) -> Result<Self, TaxError> {
let parts: Vec<&str> = raw.splitn(3, '@').collect();
let (name_raw, rank_raw) = match parts.as_slice() {
[name] => (*name, None),
[name] => (*name, None),
[name, rank] => (*name, Some(*rank)),
_ => return Err(TaxError::AmbiguousRank { segment: raw.to_string() }),
_ => {
return Err(TaxError::AmbiguousRank {
segment: raw.to_string(),
});
}
};
if name_raw.is_empty() {
return Err(TaxError::EmptySegmentName);
}
let rank = match rank_raw {
None => None,
Some("") => return Err(TaxError::EmptyRankName { segment: raw.to_string() }),
Some(r) => Some(r.to_string()),
None => None,
Some("") => {
return Err(TaxError::EmptyRankName {
segment: raw.to_string(),
});
}
Some(r) => Some(r.to_string()),
};
Ok(Self { name: name_raw.to_string(), rank })
Ok(Self {
name: name_raw.to_string(),
rank,
})
}
/// True if this pattern matches `seg`.
/// Name must match exactly. If a rank is specified in the pattern, the
/// segment's rank must match; otherwise any rank (or no rank) is accepted.
pub fn matches(&self, seg: &TaxSegment) -> bool {
self.name == seg.name()
&& self.rank.as_deref().map_or(true, |r| seg.rank() == Some(r))
self.name == seg.name() && self.rank.as_deref().map_or(true, |r| seg.rank() == Some(r))
}
}