Eric Coissac f022d83394 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`
2026-12-01 17:38:49 +01:00
2026-08-17 09:28:53 +02:00

obikmer

obikmer is a Rust toolkit for indexing, querying, and comparing DNA sequences represented as sets of k-mers. It targets individual genome datasets (tens of Gbases) with maximum efficiency in computation, memory, and disk usage.

Key principles

Compact k-mer encoding. Each k-mer is stored in a u64 at 2 bits/base. k is odd, k ∈ [11, 31], fixed at runtime. The canonical form min(kmer, revcomp(kmer)) halves the effective space by collapsing both strands.

Superkmer-based partitioning. Sequences are decomposed into superkmers — maximal runs of k-mers sharing the same minimizer. Superkmers route naturally to partitions via the minimizer hash, enabling partition-parallel indexing and querying with no cross-partition communication.

Layered MPHF index. Each partition holds a stack of layers. Each layer is a minimal perfect hash function (MPHF) over the k-mers of one input genome, paired with a per-genome presence/count matrix. Queries scatter k-mers to their partition, probe each layer in order, and aggregate results.

Approximate indexing (Findere). With -z Z, the index stores k-mers of size s = k − z + 1 instead of k. At query time, results are produced at size s, then a per-genome sliding window of size z aggregates z consecutive s-mer hits into one confirmed k-mer answer. This reduces the false-positive rate from 1/2^b per s-mer to 1/2^(b·z) per k-mer, at the cost of z−1 unconfirmed positions at each sequence break. The aggregation window spans the full query sequence, not individual superkmers, to avoid false negatives at superkmer boundaries.

Multi-genome. A single index can hold any number of genomes. Each k-mer slot carries a per-genome count or presence vector. Distance matrices, NJ/UPGMA trees, and classification are derived from these vectors without rebuilding the index.

Input formats

Command              Formats accepted
───────────────────  ──────────────────────────────────────────────────────────────
index, superkmer     FASTA (.fa .fasta), FASTQ (.fq .fastq), GenBank flat file
                     (.gb .gbk .gbff), all optionally gzip-compressed.
                     Directories expanded recursively. Streaming stdin via -.
query                FASTA, FASTQ, optionally gzip-compressed. Stdin via -.

Non-ACGT characters act as hard breaks between k-mer segments in all formats.

Commands

Command    Role
─────────  ────────────────────────────────────────────────────────────────────
index      Build a genome index from sequence files.
           Runs scatter → dereplicate → count → layered MPHF.
           Resumes automatically if interrupted.
merge      Merge multiple independently built indexes into one.
           Schedules partitions largest-first under a memory budget semaphore
           to avoid OOM on machines with many cores. The worst partition runs
           alone first to calibrate the expansion estimator; subsequent
           partitions run in parallel within the budget.
           --budget-fraction F  fraction of available RAM to use as budget
                                (default 0.5; reduce if OOM persists).
filter     Filter and compact an existing index: apply count thresholds,
           drop layers, rewrite as a single-layer index.
reindex    Convert evidence in-place across all layers:
           exact (evidence.bin) ↔ approximate (fingerprint.bin).
           Does not touch the MPHF or unitigs.
query      Query an index with FASTA/FASTQ sequences.
           Annotates each sequence with per-genome k-mer match counts
           and optional per-position coverage vectors (--detail).
           Parallel over sequence chunks.
phylo      Compute pairwise evolutionary-distance proxies between all
           indexed genomes (Bray-Curtis, Jaccard, etc.), optionally
           a Newick NJ/UPGMA tree, and optionally a central-position
           SNP/Sankoff calibration with exports for external
           phylogenetic tools (TNT, PhyG, IQ-TREE).
annotate   Add or update genome metadata (taxonomy, etc.) from a CSV
           file; or dump the current metadata as CSV.
estimate   Dry-run: resolve and print approximate-index parameters
           (z, evidence bits b, FP rates) given any two of (b, z, fp).
           Does not touch any index.
dump       Dump all indexed k-mers as CSV with per-genome counts or
           presence flags.
superkmer  Extract superkmers from a sequence file and write to stdout.
           Diagnostic / pipeline use.
unitig     Dump the unitig sequences stored in a built index. Debug use.
utils      Miscellaneous utilities.
           --new-label NEW=OLD      rename a genome label in-place.
           --bits-per-kmer          print MPHF / evidence / matrix size breakdown.
           --stats                  per-genome k-mer counts as CSV.
           --partition-stats        partition size distribution across one or more
                                    indexes (markdown report to stdout). Useful to
                                    diagnose minimizer imbalance before a large merge.
           --csv FILE               write per-(partition, source) raw data to FILE
                                    (used with --partition-stats).

Quick start

# Build an exact index for each genome independently
obikmer index --kmer-size 31 --label genome_a genome_a.fa --output index_a/
obikmer index --kmer-size 31 --label genome_b genome_b.fa --output index_b/

# Merge into a single multi-genome index
obikmer merge --output index/ index_a/ index_b/

# Convert to approximate index (z=5, 8-bit fingerprints)
obikmer reindex --approx -z 5 --evidence-bits 8 index/

# Query reads
obikmer query index/ reads.fq.gz > annotated.fa

# Pairwise distances
obikmer phylo index/ > distances.tsv

Parameter constraints

Parameter              Constraint
─────────────────────  ──────────────
k  (--kmer-size)       odd, 11 ≤ k ≤ 31
m  (--minimizer-size)  odd, 3 ≤ m ≤ k−1
z  (-z, --approx only) 1 ≤ z ≤ k−1

Documentation

Extended architecture and implementation notes are in DevDocMD/. Build with make doc (requires Python + MkDocs Material). User-facing documentation is in UserDocMD/, built with make doc-user.

S
Description
No description provided
Readme
383 MiB
0 Stars 1 Watchers 0 Forks
v1.4.9
Latest
2026-12-01 17:18:35 +00:00
Languages
HTML 49.2%
Rust 41.8%
Shell 3.5%
Python 2.1%
TeX 1.9%
Other 1.4%