refactor: modernize arithmetic, control flow, and error handling

Replace manual ceiling division with `div_ceil`, update `map_or` patterns to `is_some_and`/`is_ok_and`, and simplify error handling across the codebase. Move the `default` function for `GraphDeBruijn` from the index layer module to the De Bruijn graph module.

- Move `default` from `src/obikindex/src/layer/meta.rs` to `src/obidebruinj/src/debruijn/graph.rs` and implement `Default` for `GraphDeBruijn`
- Simplify `IndexBuilder::state`, `KmerIndex::genomes`, and `n_layers_per_partition` in `src/obikindex` by removing redundant `Ok` wrappers
- Replace manual ceiling division with `div_ceil` in `src/obikindex/src/layer/fingerprint.rs` for data slicing and byte calculations
- Update `Mphf` operations in `src/obikindex/src/layer/mphf_layer.rs` to use `mmap`, `load_full`, and `store` directly, and switch size calculations to `div_ceil`
- Refine `IndexMode` in `src/obikindex/src/layer/meta.rs` to derive `Default` with `#[default]` on `Exact`
- Update `count_partition` in `src/obikindexer/src/algorithms/counter/count.rs` to use `io::Error::other` with string conversion for error mapping
- Switch `optimal_buckets` in `src/obikindexer/src/algorithms/dereplicator/dereplicate.rs` to use `div_ceil` for average sequence bytes and bucket estimation
- Replace `max_or` and `map_or` with `is_none_or` and direct checks in `src/obikindexer/src/extensions/private_builder.rs` for layer building and artifact removal
- Enforce odd k-mer and minimizer sizes in `src/obikmer/src/cli.rs` using `is_multiple_of` and update validation ranges
- Update `resolve_approx_params` in `src/obikmer/src/cmd/index/mod.rs` to use `div_ceil` for parameter calculations
- Add documentation for `DistanceArg` in `src/obikmer/src/cmd/phylo/values.rs` and clean up test modules
- Refactor median calculation in `src/obikmer/src/cmd/utils/partition_stats.rs` to explicitly handle even and odd lengths
- Replace `g.len() > 0` with `!g.is_empty()` in `src/obikmerge/src/partition_merge/mod.rs`
- Use `isolate_lowest_one` in `src/obikphylo/src/siblings/algorithms/alignment_vcf.rs` for diploid allele calculation
- Add documentation for `family_entropy` in `src/obikphylo/src/siblings/algorithms/entropy.rs` and remove empty test blocks
- Replace `map_or` with `is_some_and` in `src/obikquery/src/findere.rs` and `src/obikquery/src/tests/findere.rs` for deque pruning logic
- Simplify `remove_if_exists` in `src/obikrebuild/src/reindex.rs` to warn only on non-`NotFound` errors
- Store `mime_type` by value in `src/obikrope/src/rope.rs` and update `mime_type` and `split_off` accordingly
- Replace manual ceiling division with `div_ceil` in `src/obikseq/src/packed_seq.rs` for byte length and iteration logic
- Update `build_dec4` in `src/obikseq/src/encoding.rs` to use a string slice literal for the decode table
- Refactor `revcomp4` in `src/obikseq/src/revcomp_lookup.rs` to use `rotate_left` for nibble swapping
- Simplify `run` in `src/obipipeline/src/scheduler/pool.rs` to use `if let Ok` for delta handling
- Simplify MIME type checking in `src/obiread/src/chunk.rs` and update error handling for unsupported formats
- Replace `map_or` with `is_ok_and` in `src/obiread/src/mimetype.rs` for FASTA/FASTQ detection
- Update `normalize_fastq` and related functions in `src/obiread/src/normalize.rs` to handle `Result` returns from cursor reads
- Simplify `skip_line` in `src/obiread/src/record.rs` to check `Ok` results directly
- Simplify test assertions in `src/obiread/src/tests/chunk.rs` by removing unnecessary closures
- Update `http_reader` in `src/obiread/src/xopen.rs` to map errors to `io::Error::other` and refine `expand_tilde` logic
- Refactor minimizer change detection in `src/obiskbuilder/src/iter.rs` and `src/obiskbuilder/src/stream_iter.rs` to explicitly check `Some` and inequality
- Update `push` in `src/obiskbuilder/src/rolling_stat.rs` to use `is_some_and` for hash and position checks
- Replace manual ceiling division with `div_ceil` in `src/obiskbuilder/src/scratch.rs` for buffer slicing
- Update `next` in `src/obiskio/src/unitig_index/kmer_iter.rs` to use `div_ceil` for byte length calculation
- Replace manual ceiling division with `div_ceil` in `src/obiskio/src/unitig_index/kmer_raw.rs` for byte extraction
- Update `src/obiskio/src/unitig_index/reader.rs` to use `div_ceil` for byte lengths and direct comparison for magic bytes
- Replace manual ceiling division with `div_ceil` in `src/obiskio/src/unitig_index/writer.rs` for chunk and index writing
- Simplify CPU set mapping in `src/obisys/src/numa/topology.rs` by removing explicit type annotations
- Update `stop` in `src/obisys/src/stage.rs` to use direct delta comparisons for fault counts
- Refine `matches` in `src/obitaxonomy/src/segment_pattern.rs` to check for inequality when rank is `None`
This commit is contained in:
Eric Coissac committed 2026-12-01 17:38:49 +01:00
1 parent ed0d563995
commit f022d83394
42 files changed
+167 -180

No files matched your search

+6
View File
@@ -317,6 +317,12 @@ impl GraphDeBruijn {
} }
} }
impl Default for GraphDeBruijn {
fn default() -> Self {
Self::new()
}
}
/// Returns the count of neighbors and the index of the first /// Returns the count of neighbors and the index of the first
/// neighbor if exactly one of the four canonical neighbours exists in /// neighbor if exactly one of the four canonical neighbours exists in
/// the graph, where `i` is its index (0=A, 1=C, 2=G, 3=T). /// the graph, where `i` is its index (0=A, 1=C, 2=G, 3=T).
+1 -1
View File
@@ -121,6 +121,6 @@ impl IndexBuilder for KmerIndex {
} }
fn state(&self) -> OKIResult<IndexState> { fn state(&self) -> OKIResult<IndexState> {
Ok(self.meta.state().map_err(OKIError::Io)?) self.meta.state().map_err(OKIError::Io)
} }
} }
+2 -2
View File
@@ -199,7 +199,7 @@ impl KmerIndex {
/// Genome list — reads `index.meta` fresh (see `IndexMeta::genomes`, /// Genome list — reads `index.meta` fresh (see `IndexMeta::genomes`,
/// this can legitimately change during a run, unlike `config`). /// this can legitimately change during a run, unlike `config`).
pub fn genomes(&self) -> OKIResult<Vec<GenomeInfo>> { pub fn genomes(&self) -> OKIResult<Vec<GenomeInfo>> {
Ok(self.meta.genomes().map_err(OKIError::Io)?) self.meta.genomes().map_err(OKIError::Io)
} }
pub fn n_partitions(&self) -> usize { pub fn n_partitions(&self) -> usize {
1usize << self.meta.config.n_bits 1usize << self.meta.config.n_bits
@@ -270,7 +270,7 @@ impl KmerIndex {
/// homogeneous across all partitions — reading it off partition 0 /// homogeneous across all partitions — reading it off partition 0
/// is enough, no need to scan every partition. /// is enough, no need to scan every partition.
pub fn n_layers_per_partition(&self) -> OKIResult<usize> { pub fn n_layers_per_partition(&self) -> OKIResult<usize> {
Ok(self.n_layers(0)?) self.n_layers(0)
} }
/// Path to the unitigs file for partition `part`, layer `layer`. /// Path to the unitigs file for partition `part`, layer `layer`.
+2 -2
View File
@@ -50,7 +50,7 @@ impl FingerprintVec {
let mask: u64 = if b == 64 { u64::MAX } else { (1u64 << b) - 1 }; let mask: u64 = if b == 64 { u64::MAX } else { (1u64 << b) - 1 };
// SAFETY: the mmap lives as long as Self (kept via _mmap); data is read-only. // SAFETY: the mmap lives as long as Self (kept via _mmap); data is read-only.
let data: &'static [u8] = unsafe { let data: &'static [u8] = unsafe {
std::slice::from_raw_parts(mmap[HEADER..].as_ptr(), (n * b as usize + 7) / 8) std::slice::from_raw_parts(mmap[HEADER..].as_ptr(), (n * b as usize).div_ceil(8))
}; };
let bits = BitSlice::<u8, Lsb0>::from_slice(data); let bits = BitSlice::<u8, Lsb0>::from_slice(data);
Ok(Self { Ok(Self {
@@ -93,7 +93,7 @@ pub struct FingerprintVecWriter {
impl FingerprintVecWriter { impl FingerprintVecWriter {
pub fn new(n: usize, b: u8) -> Self { pub fn new(n: usize, b: u8) -> Self {
assert!(b > 0 && b <= 64, "fingerprint width must be 1..=64"); assert!(b > 0 && b <= 64, "fingerprint width must be 1..=64");
let data_bytes = (n * b as usize + 7) / 8; let data_bytes = (n * b as usize).div_ceil(8);
Self { Self {
buf: vec![0u8; data_bytes], buf: vec![0u8; data_bytes],
n, n,
+2 -6
View File
@@ -17,8 +17,10 @@ use crate::layer::utils::layer_dir;
/// disk, the same probe [`EvidenceKind::detect`] uses. /// disk, the same probe [`EvidenceKind::detect`] uses.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")] #[serde(tag = "type", rename_all = "snake_case")]
#[derive(Default)]
pub enum IndexMode { pub enum IndexMode {
/// Exact evidence: `evidence.bin` + `unitigs.bin.idx`. Zero false positives. /// Exact evidence: `evidence.bin` + `unitigs.bin.idx`. Zero false positives.
#[default]
Exact, Exact,
/// Approximate evidence: `fingerprint.bin` only. /// Approximate evidence: `fingerprint.bin` only.
/// `b` — fingerprint bits per slot; false-positive rate ≈ 1/2^b per query. /// `b` — fingerprint bits per slot; false-positive rate ≈ 1/2^b per query.
@@ -31,12 +33,6 @@ pub enum IndexMode {
Hybrid { b: u8, z: u8 }, Hybrid { b: u8, z: u8 },
} }
impl Default for IndexMode {
fn default() -> Self {
Self::Exact
}
}
impl IndexMode { impl IndexMode {
/// Detect the evidence mode actually on disk, from partition index /// Detect the evidence mode actually on disk, from partition index
/// directory `root`'s layer 0 — the single source of truth every layer /// directory `root`'s layer 0 — the single source of truth every layer
+9 -11
View File
@@ -418,7 +418,7 @@ pub struct MphfOnly(MemCase<Mphf>);
impl MphfOnly { impl MphfOnly {
pub fn open(dir: &Path) -> OKIResult<Self> { pub fn open(dir: &Path) -> OKIResult<Self> {
let mphf: MemCase<Mphf> = unsafe { Mphf::mmap(&dir.join(MPHF_FILE), Flags::empty()) } let mphf: MemCase<Mphf> = unsafe { Mphf::mmap(dir.join(MPHF_FILE), Flags::empty()) }
.map_err(|e| OKIError::InvalidData { .map_err(|e| OKIError::InvalidData {
context: "layer", context: "layer",
detail: e.to_string(), detail: e.to_string(),
@@ -476,15 +476,14 @@ impl MphfLayer {
return Ok(0); return Ok(0);
} }
let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }.map_err(|e| { let mphf: Mphf =
OKIError::InvalidData { unsafe { Mphf::load_full(dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData {
context: "layer", context: "layer",
detail: e.to_string(), detail: e.to_string(),
}
})?; })?;
let mut ev = EvidenceWriter::new(n); let mut ev = EvidenceWriter::new(n);
let mut seen = vec![0u8; (n + 7) / 8]; let mut seen = vec![0u8; n.div_ceil(8)];
for (slot, _, chunk_id, rank) in for (slot, _, chunk_id, rank) in
SlottedKmers::new(&mphf, unitigs.iter_indexed_canonical_kmers()) SlottedKmers::new(&mphf, unitigs.iter_indexed_canonical_kmers())
@@ -535,11 +534,10 @@ impl MphfLayer {
return Ok(0); return Ok(0);
} }
let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }.map_err(|e| { let mphf: Mphf =
OKIError::InvalidData { unsafe { Mphf::load_full(dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData {
context: "layer", context: "layer",
detail: e.to_string(), detail: e.to_string(),
}
})?; })?;
let mut fw = FingerprintVecWriter::new(n, b); let mut fw = FingerprintVecWriter::new(n, b);
@@ -590,7 +588,7 @@ impl MphfLayer {
detail: "construction failed".into(), detail: "construction failed".into(),
} }
})?; })?;
unsafe { mphf.store(&dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData { unsafe { mphf.store(dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData {
context: "layer", context: "layer",
detail: e.to_string(), detail: e.to_string(),
})?; })?;
@@ -613,14 +611,14 @@ impl MphfLayer {
let keys = CanonicalKmerIter::new(&unitig_path).map_err(sk_to_olm)?; let keys = CanonicalKmerIter::new(&unitig_path).map_err(sk_to_olm)?;
let mphf: Mphf = let mphf: Mphf =
Mphf::new_from_par_iter(n, keys.map(|k| k.raw()).par_bridge(), mphf_params()); Mphf::new_from_par_iter(n, keys.map(|k| k.raw()).par_bridge(), mphf_params());
unsafe { mphf.store(&dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData { unsafe { mphf.store(dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData {
context: "layer", context: "layer",
detail: e.to_string(), detail: e.to_string(),
})?; })?;
// ── Pass 2: fill evidence files + callback ──────────────────────────── // ── Pass 2: fill evidence files + callback ────────────────────────────
let unitigs2 = UnitigFileReader::open_sequential(&unitig_path)?; let unitigs2 = UnitigFileReader::open_sequential(&unitig_path)?;
let mut seen = vec![0u8; (n + 7) / 8]; let mut seen = vec![0u8; n.div_ceil(8)];
match mode { match mode {
IndexMode::Exact => { IndexMode::Exact => {
@@ -68,7 +68,7 @@ pub(super) fn count_partition(dir: &Path, dedup_path: &Path, chunk_kmers: usize)
) )
.map_err(io::Error::other)?; .map_err(io::Error::other)?;
unsafe { EpSerialize::store(&mphf, &dir.join("mphf1.bin")) } unsafe { EpSerialize::store(&mphf, dir.join("mphf1.bin")) }
.map_err(|e| io::Error::other(e.to_string()))?; .map_err(|e| io::Error::other(e.to_string()))?;
Ok(()) Ok(())
@@ -41,7 +41,7 @@ pub(crate) fn optimal_buckets(raw_path: &Path, available_bytes: u64) -> usize {
_ => return 1, _ => return 1,
}; };
let avg_seq_bytes = ((meta.length_sum + meta.instances - 1) / meta.instances + 3) / 4; let avg_seq_bytes = meta.length_sum.div_ceil(meta.instances).div_ceil(4);
// SuperKmer: header (4 B) + Box<[u8]> ptr+len (16 B) + heap seq bytes; value: u64 (8 B); ×1.5 for hashbrown overhead. // SuperKmer: header (4 B) + Box<[u8]> ptr+len (16 B) + heap seq bytes; value: u64 (8 B); ×1.5 for hashbrown overhead.
let bytes_per_entry = ((4 + 16 + avg_seq_bytes + 8) as f64 * 1.5) as u64; let bytes_per_entry = ((4 + 16 + avg_seq_bytes + 8) as f64 * 1.5) as u64;
let estimated = meta.instances * bytes_per_entry; let estimated = meta.instances * bytes_per_entry;
@@ -52,7 +52,7 @@ pub(crate) fn optimal_buckets(raw_path: &Path, available_bytes: u64) -> usize {
} }
// Round up to the next power of two. // Round up to the next power of two.
let n = (estimated + budget - 1) / budget; let n = estimated.div_ceil(budget);
debug!("Dereplication: estimated={estimated} budget={budget} n_temp={n}"); debug!("Dereplication: estimated={estimated} budget={budget} n_temp={n}");
n.next_power_of_two() as usize n.next_power_of_two() as usize
} }
@@ -188,7 +188,7 @@ impl PrivateBuilder for KmerIndex {
match (&mphf1_opt, &counts1_opt) { match (&mphf1_opt, &counts1_opt) {
(Some(mphf), Some(counts)) => { (Some(mphf), Some(counts)) => {
let ab = counts.get(mphf.index(&kmer.raw())); let ab = counts.get(mphf.index(&kmer.raw()));
ab >= min_ab && max_ab.map_or(true, |max| ab <= max) ab >= min_ab && max_ab.is_none_or(|max| ab <= max)
} }
_ => true, _ => true,
} }
@@ -222,7 +222,7 @@ impl PrivateBuilder for KmerIndex {
fn remove_build_artifacts(&self, i: usize) { fn remove_build_artifacts(&self, i: usize) {
// No layer 0 = empty partition: no build artifacts to remove. // No layer 0 = empty partition: no build artifacts to remove.
if self.partition(i).map_or(false, |p| p.n_layers() == 0) { if self.partition(i).is_ok_and(|p| p.n_layers() == 0) {
return; return;
} }
let layer0 = match self.layer0(i) { let layer0 = match self.layer0(i) {
@@ -244,9 +244,9 @@ impl PrivateBuilder for KmerIndex {
// ── private helpers ────────────────────────────────────────────────────── // ── private helpers ──────────────────────────────────────────────────────
fn remove_if_exists(path: &Path) { fn remove_if_exists(path: &Path) {
if let Err(e) = fs::remove_file(path) { if let Err(e) = fs::remove_file(path)
if e.kind() != io::ErrorKind::NotFound { && e.kind() != io::ErrorKind::NotFound
{
eprintln!("warning: could not remove {}: {e}", path.display()); eprintln!("warning: could not remove {}: {e}", path.display());
} }
} }
}
+3 -3
View File
@@ -69,11 +69,11 @@ impl CommonArgs {
let k = self.kmer_size; let k = self.kmer_size;
let m = self.minimizer_size; let m = self.minimizer_size;
if k < 11 || k > 31 { if !(11..=31).contains(&k) {
eprintln!("error: --kmer-size must be in [11, 31] (got {k})"); eprintln!("error: --kmer-size must be in [11, 31] (got {k})");
std::process::exit(1); std::process::exit(1);
} }
if k % 2 == 0 { if k.is_multiple_of(2) {
eprintln!("error: --kmer-size must be odd (got {k}); even k allows palindromic k-mers"); eprintln!("error: --kmer-size must be odd (got {k}); even k allows palindromic k-mers");
std::process::exit(1); std::process::exit(1);
} }
@@ -84,7 +84,7 @@ impl CommonArgs {
); );
std::process::exit(1); std::process::exit(1);
} }
if m % 2 == 0 { if m.is_multiple_of(2) {
eprintln!("error: --minimizer-size must be odd (got {m})"); eprintln!("error: --minimizer-size must be odd (got {m})");
std::process::exit(1); std::process::exit(1);
} }
+3 -3
View File
@@ -125,13 +125,13 @@ pub(crate) fn resolve_approx_params(
} }
(Some(z), None, Some(fp)) => { (Some(z), None, Some(fp)) => {
let bz = (-fp.log2()).ceil() as u32; let bz = (-fp.log2()).ceil() as u32;
let b = ((bz + z as u32 - 1) / z as u32).max(1) as u8; let b = bz.div_ceil(z as u32).max(1) as u8;
let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64; let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64;
(z, b, actual_fp) (z, b, actual_fp)
} }
(None, Some(b), Some(fp)) => { (None, Some(b), Some(fp)) => {
let bz = (-fp.log2()).ceil() as u32; let bz = (-fp.log2()).ceil() as u32;
let z = ((bz + b as u32 - 1) / b as u32).max(1) as u8; let z = bz.div_ceil(b as u32).max(1) as u8;
let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64; let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64;
(z, b, actual_fp) (z, b, actual_fp)
} }
@@ -148,7 +148,7 @@ pub(crate) fn resolve_approx_params(
} }
(None, None, Some(fp)) => { (None, None, Some(fp)) => {
let b = DEFAULT_B; let b = DEFAULT_B;
let z = ((bits_needed(fp) as u32 + b as u32 - 1) / b as u32).max(1) as u8; let z = (bits_needed(fp) as u32).div_ceil(b as u32).max(1) as u8;
let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64; let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64;
(z, b, actual_fp) (z, b, actual_fp)
} }
+32 -32
View File
@@ -113,38 +113,6 @@ pub fn distance_to_compute(
distance.or_else(|| (nj || upgma).then_some(DistanceArg::Jaccard)) distance.or_else(|| (nj || upgma).then_some(DistanceArg::Jaccard))
} }
#[cfg(test)]
mod distance_tests {
use super::*;
#[test]
fn nothing_asked_nothing_computed() {
assert!(distance_to_compute(None, false, false).is_none());
}
#[test]
fn tree_outputs_imply_jaccard() {
for (nj, upgma) in [(true, false), (false, true)] {
assert!(matches!(
distance_to_compute(None, nj, upgma),
Some(DistanceArg::Jaccard)
));
}
}
#[test]
fn an_explicit_distance_wins() {
assert!(matches!(
distance_to_compute(Some(DistanceArg::Mash), true, true),
Some(DistanceArg::Mash)
));
assert!(matches!(
distance_to_compute(Some(DistanceArg::SnpJc), false, false),
Some(DistanceArg::SnpJc)
));
}
}
impl DistanceArg { impl DistanceArg {
/// `Some` for the whole-index metrics, `None` for `snp-*` values. /// `Some` for the whole-index metrics, `None` for `snp-*` values.
pub fn as_classic(self) -> Option<DistanceMetric> { pub fn as_classic(self) -> Option<DistanceMetric> {
@@ -177,3 +145,35 @@ impl DistanceArg {
}) })
} }
} }
#[cfg(test)]
mod distance_tests {
use super::*;
#[test]
fn nothing_asked_nothing_computed() {
assert!(distance_to_compute(None, false, false).is_none());
}
#[test]
fn tree_outputs_imply_jaccard() {
for (nj, upgma) in [(true, false), (false, true)] {
assert!(matches!(
distance_to_compute(None, nj, upgma),
Some(DistanceArg::Jaccard)
));
}
}
#[test]
fn an_explicit_distance_wins() {
assert!(matches!(
distance_to_compute(Some(DistanceArg::Mash), true, true),
Some(DistanceArg::Mash)
));
assert!(matches!(
distance_to_compute(Some(DistanceArg::SnpJc), false, false),
Some(DistanceArg::SnpJc)
));
}
}
+1 -1
View File
@@ -66,7 +66,7 @@ fn stats_summary(totals: &[u64]) -> (u64, u64, f64, f64, u64, u64, u64) {
let min = sorted[0]; let min = sorted[0];
let max = sorted[n - 1]; let max = sorted[n - 1];
let mean = sorted.iter().sum::<u64>() as f64 / n as f64; let mean = sorted.iter().sum::<u64>() as f64 / n as f64;
let median = if n % 2 == 0 { let median = if n.is_multiple_of(2) {
(sorted[n / 2 - 1] + sorted[n / 2]) as f64 / 2.0 (sorted[n / 2 - 1] + sorted[n / 2]) as f64 / 2.0
} else { } else {
sorted[n / 2] as f64 sorted[n / 2] as f64
+1 -1
View File
@@ -134,7 +134,7 @@ pub(crate) fn merge_partition(
max_open, max_open,
)?; )?;
let any_new = g.len() > 0; let any_new = !g.is_empty();
debug!( debug!(
"partition {i}: de Bruijn graph done — {} new kmers", "partition {i}: de Bruijn graph done — {} new kmers",
g.len() g.len()
@@ -58,7 +58,7 @@ fn cell_alleles(cell: u8, diploid: bool) -> Option<[u8; 2]> {
0 => Some([ABSENT, ABSENT]), 0 => Some([ABSENT, ABSENT]),
1 => Some([allele(state), allele(state)]), 1 => Some([allele(state), allele(state)]),
2 if diploid => { 2 if diploid => {
let low = state & state.wrapping_neg(); let low = state.isolate_lowest_one();
Some([allele(low), allele(state ^ low)]) Some([allele(low), allele(state ^ low)])
} }
_ => None, _ => None,
@@ -82,6 +82,30 @@ pub(crate) fn family_entropy_4(genome_mask: &[u8]) -> Option<(f64, usize)> {
use crate::siblings::AmbiguityPolicy; use crate::siblings::AmbiguityPolicy;
use crate::siblings::helpers::is_carrier; use crate::siblings::helpers::is_carrier;
/// Shannon entropy (bits) of one family under the counting convention an
/// [`AmbiguityPolicy`] selects:
/// - `Keep`: [`family_entropy`] — every genome carrying the family counts,
/// a genome with several members being a state of its own;
/// - `Forbid` (`--no-ambiguity`): [`family_entropy_4`] — only the genomes
/// carrying exactly one member count, the others being missing data,
/// exactly as the alignment itself will see them. Over those genomes the
/// 15-state entropy can only ever take the four single-base states, so the
/// two definitions coincide;
/// - `OnlyDiploid`: the 15-state entropy over the genomes with one or two
/// members (ten states), the others being missing data.
///
/// Second value: the number of genomes the entropy was computed over.
pub(crate) fn family_entropy_under(
genome_mask: &[u8],
policy: AmbiguityPolicy,
) -> Option<(f64, usize)> {
match policy {
AmbiguityPolicy::Keep => family_entropy(genome_mask),
AmbiguityPolicy::Forbid => family_entropy_4(genome_mask),
AmbiguityPolicy::OnlyDiploid => family_entropy_with(genome_mask, policy),
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -134,27 +158,3 @@ mod tests {
assert!(family_entropy_4(&[]).is_none()); assert!(family_entropy_4(&[]).is_none());
} }
} }
/// Shannon entropy (bits) of one family under the counting convention an
/// [`AmbiguityPolicy`] selects:
/// - `Keep`: [`family_entropy`] — every genome carrying the family counts,
/// a genome with several members being a state of its own;
/// - `Forbid` (`--no-ambiguity`): [`family_entropy_4`] — only the genomes
/// carrying exactly one member count, the others being missing data,
/// exactly as the alignment itself will see them. Over those genomes the
/// 15-state entropy can only ever take the four single-base states, so the
/// two definitions coincide;
/// - `OnlyDiploid`: the 15-state entropy over the genomes with one or two
/// members (ten states), the others being missing data.
///
/// Second value: the number of genomes the entropy was computed over.
pub(crate) fn family_entropy_under(
genome_mask: &[u8],
policy: AmbiguityPolicy,
) -> Option<(f64, usize)> {
match policy {
AmbiguityPolicy::Keep => family_entropy(genome_mask),
AmbiguityPolicy::Forbid => family_entropy_4(genome_mask),
AmbiguityPolicy::OnlyDiploid => family_entropy_with(genome_mask, policy),
}
}
+2 -2
View File
@@ -47,11 +47,11 @@ pub(crate) fn sparse_findere_for_genome(
dq.clear(); dq.clear();
for (k, &(_, pos, val)) in run.iter().enumerate() { for (k, &(_, pos, val)) in run.iter().enumerate() {
while dq.back().map_or(false, |&(_, v)| v >= val) { while dq.back().is_some_and(|&(_, v)| v >= val) {
dq.pop_back(); dq.pop_back();
} }
dq.push_back((k, val)); dq.push_back((k, val));
while dq.front().map_or(false, |&(fk, _)| fk + z <= k) { while dq.front().is_some_and(|&(fk, _)| fk + z <= k) {
dq.pop_front(); dq.pop_front();
} }
if k + 1 >= z { if k + 1 >= z {
+2 -2
View File
@@ -29,10 +29,10 @@ fn dense_reference_findere(
let mut dq: std::collections::VecDeque<(usize, u32)> = std::collections::VecDeque::new(); let mut dq: std::collections::VecDeque<(usize, u32)> = std::collections::VecDeque::new();
for i in 0..n { for i in 0..n {
let v_i = values[i]; let v_i = values[i];
while dq.front().map_or(false, |&(f, _)| f + z <= i) { while dq.front().is_some_and(|&(f, _)| f + z <= i) {
dq.pop_front(); dq.pop_front();
} }
while dq.back().map_or(false, |&(_, v)| v >= v_i) { while dq.back().is_some_and(|&(_, v)| v >= v_i) {
dq.pop_back(); dq.pop_back();
} }
dq.push_back((i, v_i)); dq.push_back((i, v_i));
+3 -3
View File
@@ -123,9 +123,9 @@ fn remove_stale_evidence(layer: &KmerLayer, target: &IndexMode) {
} }
fn remove_if_exists(path: &std::path::Path) { fn remove_if_exists(path: &std::path::Path) {
if let Err(e) = std::fs::remove_file(path) { if let Err(e) = std::fs::remove_file(path)
if e.kind() != std::io::ErrorKind::NotFound { && e.kind() != std::io::ErrorKind::NotFound
{
eprintln!("warning: could not remove {}: {e}", path.display()); eprintln!("warning: could not remove {}: {e}", path.display());
} }
} }
}
+3 -3
View File
@@ -63,7 +63,7 @@ impl Rope {
/// The MIME type of the rope, if known. /// The MIME type of the rope, if known.
pub fn mime_type(&self) -> Option<&str> { pub fn mime_type(&self) -> Option<&str> {
self.mime_type.as_deref() self.mime_type
} }
/// Total number of blocks. /// Total number of blocks.
@@ -122,7 +122,7 @@ impl Rope {
} }
if pos == self.length { if pos == self.length {
return Ok(Rope::new(self.mime_type.clone())); return Ok(Rope::new(self.mime_type));
} }
let (block_idx, from, _) = self.lookup(pos).ok_or_else(|| { let (block_idx, from, _) = self.lookup(pos).ok_or_else(|| {
@@ -156,7 +156,7 @@ impl Rope {
self.length = pos; self.length = pos;
Ok(Rope { Ok(Rope {
mime_type: self.mime_type.clone(), mime_type: self.mime_type,
blocks: tail_blocks, blocks: tail_blocks,
length: tail_length, length: tail_length,
start_block_idx: tail_starts, start_block_idx: tail_starts,
-1
View File
@@ -1,5 +1,4 @@
use serde::Serialize; use serde::Serialize;
use serde_json;
use std::io::{self, Write}; use std::io::{self, Write};
/// Minimal annotation carrying only the sequence length. /// Minimal annotation carrying only the sequence length.
+1 -1
View File
@@ -17,7 +17,7 @@ pub(crate) fn encode_base(b: u8) -> u8 {
} }
const fn build_dec4() -> [u32; 256] { const fn build_dec4() -> [u32; 256] {
const DECODE: [u8; 4] = [b'A', b'C', b'G', b'T']; const DECODE: [u8; 4] = *b"ACGT";
let mut table = [0u32; 256]; let mut table = [0u32; 256];
let mut i = 0usize; let mut i = 0usize;
while i < 256 { while i < 256 {
+5 -5
View File
@@ -133,7 +133,7 @@ impl FromIterator<u8> for PackedSeq {
let mut seq: Vec<u8> = Vec::with_capacity(byte_len(lower.max(1))); let mut seq: Vec<u8> = Vec::with_capacity(byte_len(lower.max(1)));
let mut seql = 0usize; let mut seql = 0usize;
for nuc in iter { for nuc in iter {
if seql % 4 == 0 { if seql.is_multiple_of(4) {
seq.push(0); seq.push(0);
} }
*seq.last_mut().unwrap() |= (nuc & 0b11) << (6 - 2 * (seql % 4)); *seq.last_mut().unwrap() |= (nuc & 0b11) << (6 - 2 * (seql % 4));
@@ -295,7 +295,7 @@ impl PackedSeq {
pub fn sub(&self, start: usize, end: usize) -> Self { pub fn sub(&self, start: usize, end: usize) -> Self {
debug_assert!(end > start && end <= self.seql()); debug_assert!(end > start && end <= self.seql());
let seql = end - start; let seql = end - start;
let n = (seql + 3) / 4; let n = seql.div_ceil(4);
let mut out = vec![0u8; n]; let mut out = vec![0u8; n];
let src = self.seq.view_bits::<Msb0>(); let src = self.seq.view_bits::<Msb0>();
let dst = out.view_bits_mut::<Msb0>(); let dst = out.view_bits_mut::<Msb0>();
@@ -313,7 +313,7 @@ impl PackedSeq {
let seql = self.seql(); let seql = self.seql();
debug_assert!(seql >= k, "sequence shorter than k"); debug_assert!(seql >= k, "sequence shorter than k");
debug_assert!( debug_assert!(
seql - k + 1 <= MAX_KMERS_PER_CHUNK, seql - k < MAX_KMERS_PER_CHUNK,
"chunk exceeds MAX_KMERS_PER_CHUNK; split before calling write_to_binary" "chunk exceeds MAX_KMERS_PER_CHUNK; split before calling write_to_binary"
); );
w.write_all(&[(seql - k) as u8])?; w.write_all(&[(seql - k) as u8])?;
@@ -326,7 +326,7 @@ impl PackedSeq {
let mut buf = [0u8; 1]; let mut buf = [0u8; 1];
r.read_exact(&mut buf)?; r.read_exact(&mut buf)?;
let seql = buf[0] as usize + crate::params::k(); let seql = buf[0] as usize + crate::params::k();
let byte_len = (seql + 3) / 4; let byte_len = seql.div_ceil(4);
let tail = (seql % 4) as u8; let tail = (seql % 4) as u8;
let mut seq = vec![0u8; byte_len]; let mut seq = vec![0u8; byte_len];
r.read_exact(&mut seq)?; r.read_exact(&mut seq)?;
@@ -460,7 +460,7 @@ fn complement(base: u8) -> u8 {
#[inline] #[inline]
fn byte_len(seql: usize) -> usize { fn byte_len(seql: usize) -> usize {
(seql + 3) / 4 seql.div_ceil(4)
} }
/// Nucleotide count → `tail` value: 0 encodes 4, 1–3 are identity. /// Nucleotide count → `tail` value: 0 encodes 4, 1–3 are identity.
+1 -1
View File
@@ -4,7 +4,7 @@ pub(crate) static REVCOMP4: [u8; 256] = build_revcomp4();
pub(crate) const fn revcomp4(x: u8) -> u8 { pub(crate) const fn revcomp4(x: u8) -> u8 {
let x = !x; // complement all bases let x = !x; // complement all bases
let x = (x >> 4) | (x << 4); // swap nibbles let x = x.rotate_left(4); // swap nibbles
let x = ((x >> 2) & 0x33) | ((x & 0x33) << 2); // swap 2-bit groups let x = ((x >> 2) & 0x33) | ((x & 0x33) << 2); // swap 2-bit groups
x x
} }
+1 -4
View File
@@ -147,13 +147,10 @@ where
} else if k == 1 { } else if k == 1 {
// ── Delta d'un flat worker ──────────────────────────── // ── Delta d'un flat worker ────────────────────────────
// delta = N - 1 (N items poussés, 1 item consommé) // delta = N - 1 (N items poussés, 1 item consommé)
match oper.recv(&flat_delta_rx) { if let Ok(delta) = oper.recv(&flat_delta_rx) {
Ok(delta) => {
in_flight += delta; in_flight += delta;
flat_workers_active -= 1; flat_workers_active -= 1;
} }
Err(_) => {}
}
} else if src_idx == Some(k) { } else if src_idx == Some(k) {
// ── Nouvel item depuis la source ────────────────────── // ── Nouvel item depuis la source ──────────────────────
match oper.recv(&source_rx) { match oper.recv(&source_rx) {
+8 -12
View File
@@ -112,8 +112,8 @@ impl<R: Read> Iterator for SeqChunkIter<R> {
pub fn read_fasta_chunks( pub fn read_fasta_chunks(
path: &str, path: &str,
) -> io::Result<SeqChunkIter<MimeTypeGuesser<Box<dyn Read + Send>>>> { ) -> io::Result<SeqChunkIter<MimeTypeGuesser<Box<dyn Read + Send>>>> {
let input = match xopen(path) { let input = {
Ok(mut i) => { let mut i = xopen(path)?;
if i.mime_type() == Some("text/fasta") { if i.mime_type() == Some("text/fasta") {
i i
} else { } else {
@@ -122,8 +122,6 @@ pub fn read_fasta_chunks(
"not a FASTA file", "not a FASTA file",
)); ));
} }
}
Err(e) => return Err(e),
}; };
Ok(fasta_chunks(input)) Ok(fasta_chunks(input))
} }
@@ -132,8 +130,8 @@ pub fn read_fasta_chunks(
pub fn read_fastq_chunks( pub fn read_fastq_chunks(
path: &str, path: &str,
) -> io::Result<SeqChunkIter<MimeTypeGuesser<Box<dyn Read + Send>>>> { ) -> io::Result<SeqChunkIter<MimeTypeGuesser<Box<dyn Read + Send>>>> {
let input = match xopen(path) { let input = {
Ok(mut i) => { let mut i = xopen(path)?;
if i.mime_type() == Some("text/fastq") { if i.mime_type() == Some("text/fastq") {
i i
} else { } else {
@@ -142,8 +140,6 @@ pub fn read_fastq_chunks(
"not a FASTQ file", "not a FASTQ file",
)); ));
} }
}
Err(e) => return Err(e),
}; };
Ok(fastq_chunks(input)) Ok(fastq_chunks(input))
} }
@@ -164,8 +160,9 @@ pub fn read_sequence_chunks_sized(
path: &str, path: &str,
block_size: usize, block_size: usize,
) -> io::Result<SeqChunkIter<MimeTypeGuesser<Box<dyn Read + Send>>>> { ) -> io::Result<SeqChunkIter<MimeTypeGuesser<Box<dyn Read + Send>>>> {
let input = match xopen(path) { let input = {
Ok(mut i) => match i.mime_type() { let mut i = xopen(path)?;
match i.mime_type() {
Some("text/fasta") => SeqChunkIter::new( Some("text/fasta") => SeqChunkIter::new(
i, i,
block_size, block_size,
@@ -184,8 +181,7 @@ pub fn read_sequence_chunks_sized(
"not a FASTA or FASTQ file", "not a FASTA or FASTQ file",
)); ));
} }
}, }
Err(e) => return Err(e),
}; };
Ok(input) Ok(input)
} }
+2 -2
View File
@@ -15,12 +15,12 @@ fn is_gbff(buf: &[u8]) -> bool {
static RE_FASTA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^>[^ ]").unwrap()); static RE_FASTA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^>[^ ]").unwrap());
fn is_fasta(buf: &[u8]) -> bool { fn is_fasta(buf: &[u8]) -> bool {
std::str::from_utf8(buf).map_or(false, |s| RE_FASTA.is_match(s)) std::str::from_utf8(buf).is_ok_and(|s| RE_FASTA.is_match(s))
} }
static RE_FASTQ: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^@[^ ].*\n[A-Za-z.-]+").unwrap()); static RE_FASTQ: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^@[^ ].*\n[A-Za-z.-]+").unwrap());
fn is_fastq(buf: &[u8]) -> bool { fn is_fastq(buf: &[u8]) -> bool {
std::str::from_utf8(buf).map_or(false, |s| RE_FASTQ.is_match(s)) std::str::from_utf8(buf).is_ok_and(|s| RE_FASTQ.is_match(s))
} }
fn is_text(buf: &[u8]) -> bool { fn is_text(buf: &[u8]) -> bool {
+4 -4
View File
@@ -127,7 +127,7 @@ fn normalize_fasta(read: &ForwardCursor<'_>, wc: &mut ForwardCursor<'_>, k: usiz
/// ///
/// The k-mer size is used to determine the minimum length of Sequence /// The k-mer size is used to determine the minimum length of Sequence
/// to be considered valid. /// to be considered valid.
fn normalize_fastq(read: &ForwardCursor<'_>, mut wc: &mut ForwardCursor<'_>, k: usize) { fn normalize_fastq(read: &ForwardCursor<'_>, wc: &mut ForwardCursor<'_>, k: usize) {
loop { loop {
skip_line(read); // skip header skip_line(read); // skip header
@@ -151,7 +151,7 @@ fn normalize_fastq(read: &ForwardCursor<'_>, mut wc: &mut ForwardCursor<'_>, k:
} }
} }
end_segment(&mut wc, k); end_segment(wc, k);
skip_line(read); // skip + line skip_line(read); // skip + line
skip_line(read); // skip quality line skip_line(read); // skip quality line
@@ -180,7 +180,7 @@ fn end_segment(wc: &mut ForwardCursor<'_>, k: usize) {
} }
fn skip_line(read: &ForwardCursor<'_>) { fn skip_line(read: &ForwardCursor<'_>) {
while let Some(c) = read.read_next().ok() { while let Ok(c) = read.read_next() {
if is_newline(c) { if is_newline(c) {
skip_newlines(read); skip_newlines(read);
return; return;
@@ -195,7 +195,7 @@ fn skip_newlines(read: &ForwardCursor<'_>) {
} }
fn skip_until_acgt_or_newline(read: &ForwardCursor<'_>) { fn skip_until_acgt_or_newline(read: &ForwardCursor<'_>) {
while let Some(c) = read.read_ahead(1).ok() { while let Ok(c) = read.read_ahead(1) {
if is_newline(c) || is_acgt(c & !0x20u8) { if is_newline(c) || is_acgt(c & !0x20u8) {
return; return;
} }
+1 -1
View File
@@ -224,7 +224,7 @@ fn read_id(cursor: &ForwardCursor<'_>) -> String {
} }
fn skip_line(cursor: &ForwardCursor<'_>) { fn skip_line(cursor: &ForwardCursor<'_>) {
while let Some(c) = cursor.read_next().ok() { while let Ok(c) = cursor.read_next() {
if c == b'\n' { if c == b'\n' {
return; return;
} }
+2 -2
View File
@@ -28,7 +28,7 @@ fn fasta_single_record_one_chunk() {
fn fasta_two_records_split_across_chunks() { fn fasta_two_records_split_across_chunks() {
let data: &[u8] = b">s1\nACGT\n>s2\nTTTT\n"; let data: &[u8] = b">s1\nACGT\n>s2\nTTTT\n";
let chunks: Vec<_> = fasta_iter(data, 10).collect::<Result<_, _>>().unwrap(); let chunks: Vec<_> = fasta_iter(data, 10).collect::<Result<_, _>>().unwrap();
let all: Vec<u8> = chunks.iter().flat_map(|r| rope_to_vec(r)).collect(); let all: Vec<u8> = chunks.iter().flat_map(rope_to_vec).collect();
assert_eq!(all, b">s1\nACGT\n>s2\nTTTT\n"); assert_eq!(all, b">s1\nACGT\n>s2\nTTTT\n");
} }
@@ -77,7 +77,7 @@ fn fastq_at_in_quality_handled() {
make_fastq(&[(b"ACGTACGT", b"@@@@IIII"), (b"TTTTTTTT", b"HHHHHHHH")]).into_boxed_slice(), make_fastq(&[(b"ACGTACGT", b"@@@@IIII"), (b"TTTTTTTT", b"HHHHHHHH")]).into_boxed_slice(),
); );
let chunks: Vec<_> = fastq_iter(data, 16).collect::<Result<_, _>>().unwrap(); let chunks: Vec<_> = fastq_iter(data, 16).collect::<Result<_, _>>().unwrap();
let all: Vec<u8> = chunks.iter().flat_map(|r| rope_to_vec(r)).collect(); let all: Vec<u8> = chunks.iter().flat_map(rope_to_vec).collect();
assert_eq!(all, *data); assert_eq!(all, *data);
} }
+4 -4
View File
@@ -82,7 +82,7 @@ pub fn estimated_decompressed_len(source: &str) -> Option<u64> {
fn http_reader(url: &str) -> io::Result<Box<dyn Read + Send>> { fn http_reader(url: &str) -> io::Result<Box<dyn Read + Send>> {
ureq::get(url) ureq::get(url)
.call() .call()
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string())) .map_err(|e| io::Error::other(e.to_string()))
.map(|resp| -> Box<dyn Read + Send> { Box::new(resp.into_body().into_reader()) }) .map(|resp| -> Box<dyn Read + Send> { Box::new(resp.into_body().into_reader()) })
} }
@@ -93,13 +93,13 @@ fn decompress(raw: Box<dyn Read + Send>) -> io::Result<Box<dyn Read + Send>> {
} }
fn expand_tilde(path: &str) -> std::borrow::Cow<'_, str> { fn expand_tilde(path: &str) -> std::borrow::Cow<'_, str> {
if path.starts_with("~/") { if path.starts_with("~/")
if let Some(home) = std::env::var_os("HOME") { && let Some(home) = std::env::var_os("HOME")
{
let mut expanded = home.to_string_lossy().into_owned(); let mut expanded = home.to_string_lossy().into_owned();
expanded.push_str(&path[1..]); expanded.push_str(&path[1..]);
return std::borrow::Cow::Owned(expanded); return std::borrow::Cow::Owned(expanded);
} }
}
std::borrow::Cow::Borrowed(path) std::borrow::Cow::Borrowed(path)
} }
+3 -3
View File
@@ -116,8 +116,9 @@ impl Iterator for SuperKmerIter<'_> {
let min_pos = self.stat.minimizer_position().unwrap_or(0); let min_pos = self.stat.minimizer_position().unwrap_or(0);
// ── 2. Minimizer change check ───────────────────────────────────── // ── 2. Minimizer change check ─────────────────────────────────────
if let Some(prev) = self.prev_min { if let Some(prev) = self.prev_min
if min != prev { && min != prev
{
let result = self.try_emit(); let result = self.try_emit();
self.cursor.rewind(self.k).ok(); self.cursor.rewind(self.k).ok();
self.reset(); self.reset();
@@ -126,7 +127,6 @@ impl Iterator for SuperKmerIter<'_> {
} }
continue; continue;
} }
}
// ── 3. Super-kmer length check ──────────────────────────────────── // ── 3. Super-kmer length check ────────────────────────────────────
if self.scratch.len() == 256 { if self.scratch.len() == 256 {
+3 -3
View File
@@ -140,13 +140,13 @@ impl RollingStat {
if self.received >= m { if self.received >= m {
let possible_canonical_m = let possible_canonical_m =
(self.rolling_k & self.m_mask).min(self.rolling_rck >> ((k - m) * 2)); (self.rolling_k & self.m_mask).min(self.rolling_rck >> ((k - m) * 2));
let possible_hash_m = hash_kmer(possible_canonical_m << 64 - m * 2); let possible_hash_m = hash_kmer(possible_canonical_m << (64 - m * 2));
let possible_pos_m = self.received - m; let possible_pos_m = self.received - m;
while self while self
.minimier .minimier
.back() .back()
.map_or(false, |it| it.hash >= possible_hash_m) .is_some_and(|it| it.hash >= possible_hash_m)
{ {
self.minimier.pop_back(); self.minimier.pop_back();
} }
@@ -160,7 +160,7 @@ impl RollingStat {
while self while self
.minimier .minimier
.front() .front()
.map_or(false, |it| it.position + k < self.received) .is_some_and(|it| it.position + k < self.received)
{ {
self.minimier.pop_front(); self.minimier.pop_front();
} }
+3 -3
View File
@@ -58,8 +58,8 @@ impl SuperKmerScratch {
/// Resets the buffer to empty afterward. /// Resets the buffer to empty afterward.
pub fn emit(&mut self, min_pos: usize) -> RoutableSuperKmer { pub fn emit(&mut self, min_pos: usize) -> RoutableSuperKmer {
let seql = self.len; let seql = self.len;
debug_assert!(seql >= 1 && seql <= MAX_SUPERKMER_LEN); debug_assert!((1..=MAX_SUPERKMER_LEN).contains(&seql));
let n = (seql + 3) / 4; let n = seql.div_ceil(4);
let seq: Box<[u8]> = self.buf[..n].into(); let seq: Box<[u8]> = self.buf[..n].into();
self.buf[..n].fill(0); self.buf[..n].fill(0);
self.len = 0; self.len = 0;
@@ -67,7 +67,7 @@ impl SuperKmerScratch {
} }
/// Discard all accumulated nucleotides without producing a [`SuperKmer`]. /// Discard all accumulated nucleotides without producing a [`SuperKmer`].
pub fn reset(&mut self) { pub fn reset(&mut self) {
let n = (self.len + 3) / 4; let n = self.len.div_ceil(4);
self.buf[..n].fill(0); self.buf[..n].fill(0);
self.len = 0; self.len = 0;
} }
+3 -3
View File
@@ -98,8 +98,9 @@ impl Iterator for SuperKmerStreamIter<'_> {
let min_pos = self.stat.minimizer_position().unwrap_or(0); let min_pos = self.stat.minimizer_position().unwrap_or(0);
// ── 2. Minimizer change ─────────────────────────────────────────── // ── 2. Minimizer change ───────────────────────────────────────────
if let Some(prev) = self.prev_min { if let Some(prev) = self.prev_min
if min != prev { && min != prev
{
let result = self.try_emit(); let result = self.try_emit();
self.cursor.rewind(self.k); self.cursor.rewind(self.k);
self.reset(); self.reset();
@@ -108,7 +109,6 @@ impl Iterator for SuperKmerStreamIter<'_> {
} }
continue; continue;
} }
}
// ── 3. Super-kmer length cap ────────────────────────────────────── // ── 3. Super-kmer length cap ──────────────────────────────────────
if self.scratch.len() == 256 { if self.scratch.len() == 256 {
+1 -1
View File
@@ -85,7 +85,7 @@ impl Iterator for CanonicalKmerIter {
return Some(CanonicalKmer::from_raw_unchecked(canon)); return Some(CanonicalKmer::from_raw_unchecked(canon));
} }
let seql_minus_k = self.mmap[self.chunk_pos] as usize; let seql_minus_k = self.mmap[self.chunk_pos] as usize;
let byte_len = (seql_minus_k + self.k + 3) / 4; let byte_len = (seql_minus_k + self.k).div_ceil(4);
self.chunk_pos += 1 + byte_len; self.chunk_pos += 1 + byte_len;
self.load_chunk(); self.load_chunk();
} }
+1 -1
View File
@@ -19,7 +19,7 @@ pub(super) fn extract_kmer_raw(bytes: &[u8], j: usize, k: usize) -> u64 {
let bit_start = j * 2; let bit_start = j * 2;
let byte_start = bit_start / 8; let byte_start = bit_start / 8;
let bit_offset = bit_start % 8; let bit_offset = bit_start % 8;
let bytes_needed = (bit_offset + 2 * k + 7) / 8; let bytes_needed = (bit_offset + 2 * k).div_ceil(8);
let mut acc = 0u128; let mut acc = 0u128;
for idx in 0..bytes_needed { for idx in 0..bytes_needed {
+8 -8
View File
@@ -58,7 +58,7 @@ impl UnitigFileReader {
while offset < mmap.len() { while offset < mmap.len() {
let seql_minus_k = mmap[offset] as usize; let seql_minus_k = mmap[offset] as usize;
n_kmers += seql_minus_k + 1; n_kmers += seql_minus_k + 1;
offset += 1 + (seql_minus_k + k + 3) / 4; offset += 1 + (seql_minus_k + k).div_ceil(4);
n_unitigs += 1; n_unitigs += 1;
} }
@@ -126,14 +126,14 @@ impl UnitigFileReader {
let mut offset = self.block_offsets.get(block) as usize; let mut offset = self.block_offsets.get(block) as usize;
for _ in 0..rem { for _ in 0..rem {
let seql_minus_k = self.mmap[offset] as usize; let seql_minus_k = self.mmap[offset] as usize;
offset += 1 + (seql_minus_k + self.k + 3) / 4; offset += 1 + (seql_minus_k + self.k).div_ceil(4);
} }
offset offset
} else { } else {
let mut offset = 0usize; let mut offset = 0usize;
for _ in 0..i { for _ in 0..i {
let seql_minus_k = self.mmap[offset] as usize; let seql_minus_k = self.mmap[offset] as usize;
offset += 1 + (seql_minus_k + self.k + 3) / 4; offset += 1 + (seql_minus_k + self.k).div_ceil(4);
} }
offset offset
} }
@@ -149,7 +149,7 @@ impl UnitigFileReader {
pub fn unitig(&self, i: usize) -> Unitig { pub fn unitig(&self, i: usize) -> Unitig {
let offset = self.chunk_start(i); let offset = self.chunk_start(i);
let seql = self.mmap[offset] as usize + self.k; let seql = self.mmap[offset] as usize + self.k;
let byte_len = (seql + 3) / 4; let byte_len = seql.div_ceil(4);
let bytes = self.mmap[offset + 1..offset + 1 + byte_len] let bytes = self.mmap[offset + 1..offset + 1 + byte_len]
.to_vec() .to_vec()
.into_boxed_slice(); .into_boxed_slice();
@@ -190,7 +190,7 @@ impl UnitigFileReader {
let mut offset = 0usize; let mut offset = 0usize;
(0..n).map(move |chunk_id| { (0..n).map(move |chunk_id| {
let seql = mmap[offset] as usize + k; let seql = mmap[offset] as usize + k;
let byte_len = (seql + 3) / 4; let byte_len = seql.div_ceil(4);
let bytes = mmap[offset + 1..offset + 1 + byte_len] let bytes = mmap[offset + 1..offset + 1 + byte_len]
.to_vec() .to_vec()
.into_boxed_slice(); .into_boxed_slice();
@@ -224,7 +224,7 @@ impl UnitigFileReader {
(0..n).map(move |chunk_id| { (0..n).map(move |chunk_id| {
let mmap = &*this.mmap; let mmap = &*this.mmap;
let seql = mmap[offset] as usize + k; let seql = mmap[offset] as usize + k;
let byte_len = (seql + 3) / 4; let byte_len = seql.div_ceil(4);
let bytes = mmap[offset + 1..offset + 1 + byte_len] let bytes = mmap[offset + 1..offset + 1 + byte_len]
.to_vec() .to_vec()
.into_boxed_slice(); .into_boxed_slice();
@@ -277,7 +277,7 @@ impl UnitigFileReader {
.map(move |chunk_id| { .map(move |chunk_id| {
let mmap = &*this.mmap; let mmap = &*this.mmap;
let seql = mmap[offset] as usize + k; let seql = mmap[offset] as usize + k;
let byte_len = (seql + 3) / 4; let byte_len = seql.div_ceil(4);
let bytes = mmap[offset + 1..offset + 1 + byte_len] let bytes = mmap[offset + 1..offset + 1 + byte_len]
.to_vec() .to_vec()
.into_boxed_slice(); .into_boxed_slice();
@@ -337,7 +337,7 @@ fn read_idx(path: &Path) -> SKResult<(usize, usize, u8, BlockOffsets)> {
let data = unsafe { Mmap::map(&file).map_err(SKError::Io)? }; let data = unsafe { Mmap::map(&file).map_err(SKError::Io)? };
let magic_bytes = &data[0..4]; let magic_bytes = &data[0..4];
if magic_bytes != &MAGIC { if magic_bytes != MAGIC {
return Err(SKError::BadMagic { return Err(SKError::BadMagic {
expected: "UIX3", expected: "UIX3",
got: magic_bytes.try_into().unwrap(), got: magic_bytes.try_into().unwrap(),
+2 -2
View File
@@ -87,7 +87,7 @@ impl UnitigFileWriter {
fn write_chunk(&mut self, unitig: &Unitig) -> SKResult<()> { fn write_chunk(&mut self, unitig: &Unitig) -> SKResult<()> {
let seql = unitig.seql(); let seql = unitig.seql();
let byte_len = (seql + 3) / 4; let byte_len = seql.div_ceil(4);
debug_assert!( debug_assert!(
seql - self.k <= u8::MAX as usize, seql - self.k <= u8::MAX as usize,
@@ -174,7 +174,7 @@ pub fn build_unitig_idx(unitigs_path: &Path, block_bits: u8) -> SKResult<()> {
block_offsets.push(offset as u32); block_offsets.push(offset as u32);
} }
let seql_minus_k = mmap[offset] as usize; let seql_minus_k = mmap[offset] as usize;
let byte_len = (seql_minus_k + k + 3) / 4; let byte_len = (seql_minus_k + k).div_ceil(4);
n_kmers += seql_minus_k + 1; n_kmers += seql_minus_k + 1;
offset += 1 + byte_len; offset += 1 + byte_len;
chunk_count += 1; chunk_count += 1;
+1 -6
View File
@@ -37,12 +37,7 @@ pub fn build() -> NumaSetup {
let mut nodes: Vec<Vec<usize>> = topology let mut nodes: Vec<Vec<usize>> = topology
.objects_with_type(ObjectType::NUMANode) .objects_with_type(ObjectType::NUMANode)
.filter_map(|obj| obj.cpuset()) .filter_map(|obj| obj.cpuset())
.map(|cpuset| { .map(|cpuset| cpuset.iter_set().map(usize::from).collect::<Vec<_>>())
cpuset
.iter_set()
.map(|idx| usize::from(idx))
.collect::<Vec<_>>()
})
.filter(|v| !v.is_empty()) .filter(|v| !v.is_empty())
.collect(); .collect();
+7 -7
View File
@@ -36,13 +36,13 @@ impl Stage {
user_secs: tv_to_secs(end.ru_utime) - tv_to_secs(self.ru.ru_utime), user_secs: tv_to_secs(end.ru_utime) - tv_to_secs(self.ru.ru_utime),
sys_secs: tv_to_secs(end.ru_stime) - tv_to_secs(self.ru.ru_stime), sys_secs: tv_to_secs(end.ru_stime) - tv_to_secs(self.ru.ru_stime),
max_rss_bytes: rss_to_bytes(&end), max_rss_bytes: rss_to_bytes(&end),
minor_faults: delta(end.ru_minflt as i64, self.ru.ru_minflt as i64), minor_faults: delta(end.ru_minflt, self.ru.ru_minflt),
major_faults: delta(end.ru_majflt as i64, self.ru.ru_majflt as i64), major_faults: delta(end.ru_majflt, self.ru.ru_majflt),
vol_ctx: delta(end.ru_nvcsw as i64, self.ru.ru_nvcsw as i64), vol_ctx: delta(end.ru_nvcsw, self.ru.ru_nvcsw),
invol_ctx: delta(end.ru_nivcsw as i64, self.ru.ru_nivcsw as i64), invol_ctx: delta(end.ru_nivcsw, self.ru.ru_nivcsw),
in_blocks: delta(end.ru_inblock as i64, self.ru.ru_inblock as i64), in_blocks: delta(end.ru_inblock, self.ru.ru_inblock),
out_blocks: delta(end.ru_oublock as i64, self.ru.ru_oublock as i64), out_blocks: delta(end.ru_oublock, self.ru.ru_oublock),
swaps: delta(end.ru_nswap as i64, self.ru.ru_nswap as i64), swaps: delta(end.ru_nswap, self.ru.ru_nswap),
}; };
info!( info!(
stage = %stats.label, stage = %stats.label,
+1 -1
View File
@@ -46,6 +46,6 @@ impl SegmentPattern {
/// Name must match exactly. If a rank is specified in the pattern, the /// 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. /// segment's rank must match; otherwise any rank (or no rank) is accepted.
pub fn matches(&self, seg: &TaxSegment) -> bool { 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().is_none_or(|r| seg.rank() == Some(r))
} }
} }