refactor: rename project from obikmer to obiskim
Release / create-release (push) Successful in 32s
Release / build-linux-x86_64 (push) Successful in 6m18s
Release / build-macos-arm64 (push) Failing after 2m15s

Update the project name, binary, and all associated documentation, scripts, and configuration files from `obikmer` to `obiskim`. This change ensures consistency across the codebase, including lock files, VCF outputs, benchmark targets, and user-facing documentation.

- Update `mkdocs.yml` and `.crate-kit/VERSION` to reflect the new project name and version 0.3.4.
- Rename all references in `DevDocMD/` documentation, including architecture, implementation, and theory sections, from `obikmer` to `obiskim`.
- Update `UserDocMD/` files to use `.obiskim.lock` and `.obiskim.gate` for lock files, and update VCF contig IDs to `obiskim_<partition>_<layer>`.
- Modify `benchmark/` scripts and Makefiles to use `obiskim` binary names and `obiskim_dist/` directories for distribution and comparison tasks.
- Update `prompts/` files to reference the `obiskim` repository and commands instead of `obikmer`.
- Rename temporary directories in `scripts/` smoke tests from `obikmer_*` to `obiskim_*`.
- Update `src/obikphylo/src/siblings/algorithms/alignment_vcf.rs` to use `obiskim` in VCF source identifiers and assertions.
- Update `src/obiskim/Cargo.toml` version to 1.4.9 and update `src/obiskim/src/cmd/phylo/args/outputs.rs` documentation.
- Update `src/obisys/src/lock.rs` to use `.obiskim.lock`, `.obiskim.gate`, and `.obiskim.promote` file names.
This commit is contained in:
Eric Coissac committed 2026-12-01 18:17:47 +01:00
1 parent 42d5b881ec
commit 917cb26186
48 files changed
+236 -209

No files matched your search

+1 -1
View File
@@ -1 +1 @@
0.3.3+0.1.1 0.3.4+0.1.1
@@ -37,7 +37,7 @@ Reproduced on the 1x testbed (20 genomes, 512 layers): derived annexes deleted,
**Not covered.** The builders outside that path still write at their final name: `PersistentCompactIntVecBuilder`, the int/sparse matrix builders, `EliasFanoBuilder`, `TempBitVecBuilder`/`TempCompactIntVecBuilder` (temporary by nature) and the index-construction files that use them. The same reasoning applies to them as soon as a stage built on them has to be resumed; not audited. The in-memory overlap accumulator is still lost on a kill (a sweep restarts), now without leaving a corrupt file. **Not covered.** The builders outside that path still write at their final name: `PersistentCompactIntVecBuilder`, the int/sparse matrix builders, `EliasFanoBuilder`, `TempBitVecBuilder`/`TempCompactIntVecBuilder` (temporary by nature) and the index-construction files that use them. The same reasoning applies to them as soon as a stage built on them has to be resumed; not audited. The in-memory overlap accumulator is still lost on a kill (a sweep restarts), now without leaving a corrupt file.
**`obiksession` crate** (`src/obiksession/`): `Session` (named directory, opaque parameter blob checked on open, whole-lifetime `DirLock`, artifacts checksummed with xxh3 and mmap-restored) and `Memoize` (`get_or_compute[_with_key]`, `invalidate`, `cached_keys`, `MemoKey` from `Debug` + xxh3, the `session_memoize!` macro). Compiles, 15 tests pass, **no caller**: `obikmer` lists the dependency without using it. `phylo --session` exits with an error (`cmd/phylo/mod.rs:271`) since `session_cache.rs` (the consumer tied to `PairwiseTally`/`PartitionDispersion`/`SnpAlignment`) was removed. `sample_index(skip_layers)` remains as a seam, never called with a non-zero value. **`obiksession` crate** (`src/obiksession/`): `Session` (named directory, opaque parameter blob checked on open, whole-lifetime `DirLock`, artifacts checksummed with xxh3 and mmap-restored) and `Memoize` (`get_or_compute[_with_key]`, `invalidate`, `cached_keys`, `MemoKey` from `Debug` + xxh3, the `session_memoize!` macro). Compiles, 15 tests pass, **no caller**: `obiskim` lists the dependency without using it. `phylo --session` exits with an error (`cmd/phylo/mod.rs:271`) since `session_cache.rs` (the consumer tied to `PairwiseTally`/`PartitionDispersion`/`SnpAlignment`) was removed. `sample_index(skip_layers)` remains as a seam, never called with a non-zero value.
**Previous design and why it missed the goal** (`theory/evolutionary_distances.md`, section "Explicit `--session`"): one session per *exact* parameter tuple (changing `--n-sites` made another session), artifacts specific to the sampling result, resume only inside the draw (checkpoint every 8 layers or 30 s). Reuse across commands existed only for the sample. An exhaustive-sample cache from which smaller samples would be drawn was proposed and never done. User judgement: this version did not answer the objective. **Previous design and why it missed the goal** (`theory/evolutionary_distances.md`, section "Explicit `--session`"): one session per *exact* parameter tuple (changing `--n-sites` made another session), artifacts specific to the sampling result, resume only inside the draw (checkpoint every 8 layers or 30 s). Reuse across commands existed only for the sample. An exhaustive-sample cache from which smaller samples would be drawn was proposed and never done. User judgement: this version did not answer the objective.
+14 -14
View File
@@ -203,7 +203,7 @@ Genome keys follow the iteration order of `meta.genomes`.
## CLI ## CLI
``` ```
obikmer query <index> [--detail] [--mismatch] [--count-missing] obiskim query <index> [--detail] [--mismatch] [--count-missing]
[--force-presence] [--presence-threshold <n>] [--force-presence] [--presence-threshold <n>]
[-z <z>] [-T <threads>] [--chunk-size <MiB>] [-z <z>] [-T <threads>] [--chunk-size <MiB>]
<query.fa> [<query2.fa> ...] <query.fa> [<query2.fa> ...]
@@ -259,7 +259,7 @@ replacing the `CanonicalKmer` key by the resolved `slot` (compact integer, and e
**7. Partition-level parallelism is currently absent — and a NUMA-aware mechanism for exactly this already exists, unused, in `obikindex`.** **7. Partition-level parallelism is currently absent — and a NUMA-aware mechanism for exactly this already exists, unused, in `obikindex`.**
`process_chunk`'s partition loop (`query.rs:250-278`, `for (part_idx, part_sks) in by_part.iter().enumerate()`) processes every partition of a chunk sequentially on the single worker thread that owns that chunk. This is a parallelism axis on its own, independent of the column question below. `process_chunk`'s partition loop (`query.rs:250-278`, `for (part_idx, part_sks) in by_part.iter().enumerate()`) processes every partition of a chunk sequentially on the single worker thread that owns that chunk. This is a parallelism axis on its own, independent of the column question below.
More importantly: `docmd/architecture/numa_partition_runner.md` and `numa_worker_pools.md` document `PartitionRunner` (`obikindex/src/numa.rs`), **already implemented** and already used by `merge.rs`, `index.rs` (`build_layers`), `select.rs`, `reindex.rs`, `rebuild.rs` — one controller thread per NUMA node, a Rayon pool pinned to that node's CPUs (`hwlocality`, `numa` feature, default-on in `obikindex/Cargo.toml`), adaptive worker activation driven by *both* a CPU-efficiency signal and an I/O-throughput signal (`CpuSample`/`IoSample`, `/proc/self/io` on Linux). It exists precisely because a naive `into_par_iter()` on the global Rayon pool measurably degrades ×60 on this codebase's own 192-core/8-NUMA reference machine (`numa_worker_pools.md`, § Problem) once workers contend for cross-socket memory bandwidth on shared mmap'd/hashed structures — exactly the shape of the matrix-column scan in point 8 below. More importantly: `docmd/architecture/numa_partition_runner.md` and `numa_worker_pools.md` document `PartitionRunner` (`obikindex/src/numa.rs`), **already implemented** and already used by `merge.rs`, `index.rs` (`build_layers`), `select.rs`, `reindex.rs`, `rebuild.rs` — one controller thread per NUMA node, a Rayon pool pinned to that node's CPUs (`hwlocality`, `numa` feature, default-on in `obikindex/Cargo.toml`), adaptive worker activation driven by *both* a CPU-efficiency signal and an I/O-throughput signal (`CpuSample`/`IoSample`, `/proc/self/io` on Linux). It exists precisely because a naive `into_par_iter()` on the global Rayon pool measurably degrades ×60 on this codebase's own 192-core/8-NUMA reference machine (`numa_worker_pools.md`, § Problem) once workers contend for cross-socket memory bandwidth on shared mmap'd/hashed structures — exactly the shape of the matrix-column scan in point 8 below.
`obikmer` already depends on `obikindex` (`obikmer/Cargo.toml`, for `KmerIndex`), so `PartitionRunner` is directly reachable from `cmd/query.rs` — no new dependency. Both the partition-level loop and (see point 8) the genome-column scan should be driven through it rather than through ad-hoc `rayon::into_par_iter()`, to avoid reproducing the already-measured-and-fixed contention problem. Also relevant: the "CPU-only signal stalls on I/O-bound stages" issue documented for `pack_matrices` (mmap-heavy, page-fault-bound) applies just as much to a column-major mmap scan over persistent matrices — reuse the existing dual CPU/IO activation signal rather than re-deriving one. `obiskim` already depends on `obikindex` (`obiskim/Cargo.toml`, for `KmerIndex`), so `PartitionRunner` is directly reachable from `cmd/query.rs` — no new dependency. Both the partition-level loop and (see point 8) the genome-column scan should be driven through it rather than through ad-hoc `rayon::into_par_iter()`, to avoid reproducing the already-measured-and-fixed contention problem. Also relevant: the "CPU-only signal stalls on I/O-bound stages" issue documented for `pack_matrices` (mmap-heavy, page-fault-bound) applies just as much to a column-major mmap scan over persistent matrices — reuse the existing dual CPU/IO activation signal rather than re-deriving one.
> >
> **Correction from implementation (Phase 4 below)**: this turned out not to be viable as described. `PartitionRunner::run()`'s actual body spawns roughly one OS thread per worker slot across every NUMA node **on every call** (confirmed by reading `numa.rs`, not just its doc comments) — fine for the one-call-per-command-invocation batch usage in `merge`/`build_layers`, but `query_partition_with` runs once per `(chunk, partition)`, far too frequently to absorb that spawn cost. Partition-level parallelism via `PartitionRunner` is deferred, not implemented. See Phase 4's "What did not ship, and why" for the detail. > **Correction from implementation (Phase 4 below)**: this turned out not to be viable as described. `PartitionRunner::run()`'s actual body spawns roughly one OS thread per worker slot across every NUMA node **on every call** (confirmed by reading `numa.rs`, not just its doc comments) — fine for the one-call-per-command-invocation batch usage in `merge`/`build_layers`, but `query_partition_with` runs once per `(chunk, partition)`, far too frequently to absorb that spawn cost. Partition-level parallelism via `PartitionRunner` is deferred, not implemented. See Phase 4's "What did not ship, and why" for the detail.
@@ -285,7 +285,7 @@ None of this is implemented yet — parked here as a coherent roadmap while the
## Implementation plan ## Implementation plan
Concrete, phased translation of the roadmap above. Phases 0–2 are small, independent, low-risk, and each individually testable against current `query` output — land them first, in order, and measure on the reference 192-core/8-NUMA machine before deciding whether phases 3–5 (the staged/sparse engine, the larger structural payoff) are still worth their cost. Phases 3–5 are one coordinated change spanning `obikmer`, `obikindex::partition`, and `obicompactvec` — they should not be split across releases mid-way, because the intermediate state (e.g. k-mer-level dedup feeding the old dense `KmerResults`) has no correctness or performance benefit on its own. Phase 6 is unrelated to phases 0–5 and can happen any time, independently, if `rapidgzip-rs` is validated (see [chunkreader.md](../implementation/chunkreader.md#future-work--parallel-gzip-decompression-in-xopen)). Concrete, phased translation of the roadmap above. Phases 0–2 are small, independent, low-risk, and each individually testable against current `query` output — land them first, in order, and measure on the reference 192-core/8-NUMA machine before deciding whether phases 3–5 (the staged/sparse engine, the larger structural payoff) are still worth their cost. Phases 3–5 are one coordinated change spanning `obiskim`, `obikindex::partition`, and `obicompactvec` — they should not be split across releases mid-way, because the intermediate state (e.g. k-mer-level dedup feeding the old dense `KmerResults`) has no correctness or performance benefit on its own. Phase 6 is unrelated to phases 0–5 and can happen any time, independently, if `rapidgzip-rs` is validated (see [chunkreader.md](../implementation/chunkreader.md#future-work--parallel-gzip-decompression-in-xopen)).
Instrumentation is deliberately sequenced *before* the I/O fix (reordering the roadmap's own listed order), because every later phase's justification rests on a measurement ("to be measured, not assumed" appears throughout the roadmap above) — without it, phases 3–5 would be undertaken on faith. Instrumentation is deliberately sequenced *before* the I/O fix (reordering the roadmap's own listed order), because every later phase's justification rests on a measurement ("to be measured, not assumed" appears throughout the roadmap above) — without it, phases 3–5 would be undertaken on faith.
@@ -295,7 +295,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**Debug logging.** Every phase that changes an algorithmic choice (not phase 0, which *is* the logging) adds `tracing::debug!`/`trace!` at points that let a cluster run's logs answer "did this help": counts, ratios, and timings that quantify the specific claim that phase makes — e.g. phase 3 must log how many MPHF `find` calls were saved by k-mer-level dedup (the whole justification for that phase), phase 4 must log per-column scan timings, phase 5 must log actual retained-memory / sparsity ratios achieved. Prefer one structured `debug!` per chunk (fields, not prose) over free-text — the cluster logs will be the only evidence available for judging these choices, so they need to be grep/awk-able, not just readable. **Debug logging.** Every phase that changes an algorithmic choice (not phase 0, which *is* the logging) adds `tracing::debug!`/`trace!` at points that let a cluster run's logs answer "did this help": counts, ratios, and timings that quantify the specific claim that phase makes — e.g. phase 3 must log how many MPHF `find` calls were saved by k-mer-level dedup (the whole justification for that phase), phase 4 must log per-column scan timings, phase 5 must log actual retained-memory / sparsity ratios achieved. Prefer one structured `debug!` per chunk (fields, not prose) over free-text — the cluster logs will be the only evidence available for judging these choices, so they need to be grep/awk-able, not just readable.
**Unit tests.** This project's convention (`obiread`, `obikseq`, `obidebruinj`, `obicompactvec`, `obikindex::layer`, `obiskio`, `obifastwrite`) is `#[cfg(test)] #[path = "tests/<name>.rs"] mod tests;` at the bottom of the source file, with the actual test code in a sibling `src/tests/<name>.rs`. Neither `obikmer` nor `obikindex::partition` (the two crates phases 3 and 5 touch most) currently have a `src/tests/` directory at all — this needs creating, following the existing pattern exactly, not inventing a new one. **Unit tests.** This project's convention (`obiread`, `obikseq`, `obidebruinj`, `obicompactvec`, `obikindex::layer`, `obiskio`, `obifastwrite`) is `#[cfg(test)] #[path = "tests/<name>.rs"] mod tests;` at the bottom of the source file, with the actual test code in a sibling `src/tests/<name>.rs`. Neither `obiskim` nor `obikindex::partition` (the two crates phases 3 and 5 touch most) currently have a `src/tests/` directory at all — this needs creating, following the existing pattern exactly, not inventing a new one.
**Workflow (`jj`).** Work happens in a fresh `jj` commit, easy to abandon. `jj new` between phases is reasonable where it helps isolate a phase for review, but only when the working copy compiles at that point (project convention) — phase 3's internal sub-steps (batch dedup change, then `query_layer.rs` split, then the new return shape) will likely not each compile independently since they're one coupled change, so treat "commit boundary" and "plan phase boundary" as related but not forced to match 1:1; use judgement per phase rather than mechanically splitting on every bullet. **Workflow (`jj`).** Work happens in a fresh `jj` commit, easy to abandon. `jj new` between phases is reasonable where it helps isolate a phase for review, but only when the working copy compiles at that point (project convention) — phase 3's internal sub-steps (batch dedup change, then `query_layer.rs` split, then the new return shape) will likely not each compile independently since they're one coupled change, so treat "commit boundary" and "plan phase boundary" as related but not forced to match 1:1; use judgement per phase rather than mechanically splitting on every bullet.
@@ -303,9 +303,9 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**Goal**: make core utilization, throughput, and per-stage timing visible on a real run, so phases 1–5 can be justified with numbers instead of assumption. **Goal**: make core utilization, throughput, and per-stage timing visible on a real run, so phases 1–5 can be justified with numbers instead of assumption.
- `obikmer/src/cmd/query.rs`: wrap `run()`'s main loop with `obisys::Reporter`/`Stage::start("query")`/`.stop()`, printed at the end via `rep.print()` — same pattern as `index.rs`/`filter.rs`. - `obiskim/src/cmd/query.rs`: wrap `run()`'s main loop with `obisys::Reporter`/`Stage::start("query")`/`.stop()`, printed at the end via `rep.print()` — same pattern as `index.rs`/`filter.rs`.
- Add an `obisys::spinner("query")` progress bar around the `pipe.apply(...)` loop, with an EMA throughput readout (bases/s or k-mers/s, mirroring `steps::scatter`'s `ema_rate` computation, `scatter.rs:88-118`) and live gauges for "chunks in flight" / "workers busy" — reuse the `AtomicU32` counter pattern from `scatter.rs` (`flat_active`, `transform_active`) rather than inventing a new one. - Add an `obisys::spinner("query")` progress bar around the `pipe.apply(...)` loop, with an EMA throughput readout (bases/s or k-mers/s, mirroring `steps::scatter`'s `ema_rate` computation, `scatter.rs:88-118`) and live gauges for "chunks in flight" / "workers busy" — reuse the `AtomicU32` counter pattern from `scatter.rs` (`flat_active`, `transform_active`) rather than inventing a new one.
- Add `max_open_files: Option<usize>` to `QueryArgs` and a `effective_max_open()` method mirroring `CommonArgs::effective_max_open()` (`obikmer/src/cli.rs:90-94`) — needed by phase 1's `throttle()` call. (`QueryArgs` can't just embed `CommonArgs` — it doesn't take `kmer_size`/`minimizer_size`/`partitions`/`level_max`/`theta` from the CLI, those come from the index metadata — so this is a small standalone addition, not a flatten.) - Add `max_open_files: Option<usize>` to `QueryArgs` and a `effective_max_open()` method mirroring `CommonArgs::effective_max_open()` (`obiskim/src/cli.rs:90-94`) — needed by phase 1's `throttle()` call. (`QueryArgs` can't just embed `CommonArgs` — it doesn't take `kmer_size`/`minimizer_size`/`partitions`/`level_max`/`theta` from the CLI, those come from the index metadata — so this is a small standalone addition, not a flatten.)
- Add one structured `debug!` per `process_chunk` call: chunk byte size, sequence count, s-mer count, wall time, and (once later phases exist) the fields they add — this single log line is the baseline every later phase's own logging gets compared against. - Add one structured `debug!` per `process_chunk` call: chunk byte size, sequence count, s-mer count, wall time, and (once later phases exist) the fields they add — this single log line is the baseline every later phase's own logging gets compared against.
- **Validation**: none needed beyond "the numbers appear and look sane" — this phase changes no query logic or output. - **Validation**: none needed beyond "the numbers appear and look sane" — this phase changes no query logic or output.
- **Deliverable used by every phase below**: a before/after throughput and core-utilization measurement on the reference machine. - **Deliverable used by every phase below**: a before/after throughput and core-utilization measurement on the reference machine.
@@ -314,7 +314,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**Goal**: file opening, decompression, and chunk-boundary parsing run across the `n_workers` pool instead of serially in the pipe's dedicated source thread. **Goal**: file opening, decompression, and chunk-boundary parsing run across the `n_workers` pool instead of serially in the pipe's dedicated source thread.
- `obikmer/src/cmd/query.rs`: - `obiskim/src/cmd/query.rs`:
- Replace the `paths.into_iter().flat_map(read_sequence_chunks_sized(...))` construction (current `run()`, building `all_chunks`) with `obipipeline::throttle(paths.into_iter(), args.effective_max_open())`, passed as the pipe's `input`. - Replace the `paths.into_iter().flat_map(read_sequence_chunks_sized(...))` construction (current `run()`, building `all_chunks`) with `obipipeline::throttle(paths.into_iter(), args.effective_max_open())`, passed as the pipe's `input`.
- Add a new `QueryData::Path(PathBuf)` variant (alongside `Chunk`/`Output`) to carry the throttled path through the pipe's type-erasure mechanism. - Add a new `QueryData::Path(PathBuf)` variant (alongside `Chunk`/`Output`) to carry the throttled path through the pipe's type-erasure mechanism.
- Add a new **first** pipe stage, `Flat`/fallible (`||?`), modeled on `scatter.rs:60-86` and `superkmer.rs:54-65`: given a `Throttled<PathBuf>`, call `read_sequence_chunks_sized(path, chunk_bytes)` and yield each `Rope` chunk, keeping `pw.guard` alive until the file's iterator is exhausted (reuse or adapt `scatter.rs`'s `GuardedIter` wrapper — same lifetime problem, same fix). - Add a new **first** pipe stage, `Flat`/fallible (`||?`), modeled on `scatter.rs:60-86` and `superkmer.rs:54-65`: given a `Throttled<PathBuf>`, call `read_sequence_chunks_sized(path, chunk_bytes)` and yield each `Rope` chunk, keeping `pw.guard` alive until the file's iterator is exhausted (reuse or adapt `scatter.rs`'s `GuardedIter` wrapper — same lifetime problem, same fix).
@@ -328,7 +328,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**Goal**: `chunk_bytes` reflects actual per-chunk memory (`O(n_genomes)`), not a fixed multiplier. **Goal**: `chunk_bytes` reflects actual per-chunk memory (`O(n_genomes)`), not a fixed multiplier.
- `obikmer/src/cmd/query.rs`, `run()`: `n_genomes` and `args.detail` are already computed above the `chunk_bytes` calculation (`n_genomes` at the top of `run()`, before line 407 in the current file) — reorder if needed, then replace: - `obiskim/src/cmd/query.rs`, `run()`: `n_genomes` and `args.detail` are already computed above the `chunk_bytes` calculation (`n_genomes` at the top of `run()`, before line 407 in the current file) — reorder if needed, then replace:
```rust ```rust
let computed = avail / (n_workers as u64 * 16); let computed = avail / (n_workers as u64 * 16);
``` ```
@@ -342,7 +342,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**Goal**: replace superkmer-level dedup with k-mer-level dedup (roadmap point 5), and split the fused MPHF-find/matrix-fetch (point 4) so stage 1's output is bucketed by layer and MPHF slot (point 6). **Goal**: replace superkmer-level dedup with k-mer-level dedup (roadmap point 5), and split the fused MPHF-find/matrix-fetch (point 4) so stage 1's output is bucketed by layer and MPHF slot (point 6).
- `obikmer/src/cmd/query.rs`: - `obiskim/src/cmd/query.rs`:
- Replace `QueryBatch::from_records`'s dedup map (`HashMap<RoutableSuperKmer, Vec<SKDesc>>`, current `query.rs:112`) with a per-partition `HashMap<CanonicalKmer, Vec<(seq_idx: u32, pos: u32)>>`, built in the same `SuperKmerIter` pass: superkmer construction and partition routing (`part_idx` from the superkmer's minimizer hash) are unchanged, only the granularity of what gets deduplicated changes — each `CanonicalKmer` within a superkmer is inserted individually instead of the whole superkmer being the dedup key. - Replace `QueryBatch::from_records`'s dedup map (`HashMap<RoutableSuperKmer, Vec<SKDesc>>`, current `query.rs:112`) with a per-partition `HashMap<CanonicalKmer, Vec<(seq_idx: u32, pos: u32)>>`, built in the same `SuperKmerIter` pass: superkmer construction and partition routing (`part_idx` from the superkmer's minimizer hash) are unchanged, only the granularity of what gets deduplicated changes — each `CanonicalKmer` within a superkmer is inserted individually instead of the whole superkmer being the dedup key.
- **Verified**: `CanonicalKmer` (`obikseq/src/kmer.rs:390`, `pub type CanonicalKmer = CanonicalKmerOf<KLen>`) — the underlying `CanonicalKmerOf<L>` derives `Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash` (`kmer.rs:269`). Usable as a `HashMap`/`HashSet` key as-is, no change needed. - **Verified**: `CanonicalKmer` (`obikseq/src/kmer.rs:390`, `pub type CanonicalKmer = CanonicalKmerOf<KLen>`) — the underlying `CanonicalKmerOf<L>` derives `Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash` (`kmer.rs:269`). Usable as a `HashMap`/`HashSet` key as-is, no change needed.
- `obikindex/src/partition/query_layer.rs`: - `obikindex/src/partition/query_layer.rs`:
@@ -351,7 +351,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
- New return shape for the partition-level query, replacing today's `on_hit(sk_idx, kmer_idx, row)` callback: `HashMap<layer_idx, HashMap<slot, Vec<(seq_idx, pos)>>>` (roadmap point 6) — built directly from the k-mer dedup map's `Vec<(seq_idx,pos)>` values, keyed by the resolved slot instead of the k-mer. - New return shape for the partition-level query, replacing today's `on_hit(sk_idx, kmer_idx, row)` callback: `HashMap<layer_idx, HashMap<slot, Vec<(seq_idx, pos)>>>` (roadmap point 6) — built directly from the k-mer dedup map's `Vec<(seq_idx,pos)>` values, keyed by the resolved slot instead of the k-mer.
- **This phase alone has no throughput benefit yet** (matrix fetch still happens, just deferred) beyond the k-mer-level dedup itself (fewer MPHF calls when queries have overlapping/repeated k-mers) — its purpose is to produce the input phase 4 needs. Land phase 3+4 together, not phase 3 alone, per the "don't split 3–5 across releases" note above. - **This phase alone has no throughput benefit yet** (matrix fetch still happens, just deferred) beyond the k-mer-level dedup itself (fewer MPHF calls when queries have overlapping/repeated k-mers) — its purpose is to produce the input phase 4 needs. Land phase 3+4 together, not phase 3 alone, per the "don't split 3–5 across releases" note above.
- Log, per chunk: total k-mer occurrences vs. unique `CanonicalKmer` count (the dedup ratio — the entire justification for this phase) and the resulting MPHF `find` call count. If the dedup ratio is close to `1.0` on real query data (little redundancy), that's the cluster run telling us this phase wasn't worth it — the logging needs to be able to say that, not just confirm the happy path. - Log, per chunk: total k-mer occurrences vs. unique `CanonicalKmer` count (the dedup ratio — the entire justification for this phase) and the resulting MPHF `find` call count. If the dedup ratio is close to `1.0` on real query data (little redundancy), that's the cluster run telling us this phase wasn't worth it — the logging needs to be able to say that, not just confirm the happy path.
- **Unit tests**: create `obikmer/src/cmd/tests/query.rs` (new `src/tests/` dir for this crate, following the project's `#[cfg(test)] #[path = "tests/query.rs"] mod tests;` convention) and `obikindex/src/partition/tests/query_layer.rs` (likewise new for this crate). Cover: the k-mer-level dedup map construction on synthetic sequences with known repeated/overlapping k-mers (assert unique-kmer count and occurrence lists); the `find_slot`/bucket-by-layer-and-slot construction against a small hand-built `QueryLayer` fixture, asserting the `(layer_idx, slot, seq_idx, pos)` tuples match what the old per-occurrence loop would have produced. - **Unit tests**: create `obiskim/src/cmd/tests/query.rs` (new `src/tests/` dir for this crate, following the project's `#[cfg(test)] #[path = "tests/query.rs"] mod tests;` convention) and `obikindex/src/partition/tests/query_layer.rs` (likewise new for this crate). Cover: the k-mer-level dedup map construction on synthetic sequences with known repeated/overlapping k-mers (assert unique-kmer count and occurrence lists); the `find_slot`/bucket-by-layer-and-slot construction against a small hand-built `QueryLayer` fixture, asserting the `(layer_idx, slot, seq_idx, pos)` tuples match what the old per-occurrence loop would have produced.
### Phase 4 — Column-major matrix fetch (roadmap points 7–8) — implemented, NUMA parallelism deferred ### Phase 4 — Column-major matrix fetch (roadmap points 7–8) — implemented, NUMA parallelism deferred
@@ -360,7 +360,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**What shipped:** **What shipped:**
- `obicompactvec`: the per-column accessors this phase needed **already existed** — `PersistentCompactIntMatrix::col_view(c)` and `PersistentBitMatrix::col_view(c)` are public, and `IntSliceView::get(slot)`/`BitSliceView::get(slot)` are public — the original plan underestimated how much of this plumbing the pairwise-distance code (`dump`/`select`/`stats`) had already required. The one real gap: `PersistentBitMatrix::col_view()` panics on the `Implicit` variant (the documented mono-genome fast path, `bitmatrix.rs`). Added `PersistentBitMatrix::get(c, slot) -> u32` (`bitmatrix.rs`), a non-panicking column-major point lookup that returns `1` for `Implicit` regardless of `c` — the smallest surface needed, not a new `col_get` API from scratch. - `obicompactvec`: the per-column accessors this phase needed **already existed** — `PersistentCompactIntMatrix::col_view(c)` and `PersistentBitMatrix::col_view(c)` are public, and `IntSliceView::get(slot)`/`BitSliceView::get(slot)` are public — the original plan underestimated how much of this plumbing the pairwise-distance code (`dump`/`select`/`stats`) had already required. The one real gap: `PersistentBitMatrix::col_view()` panics on the `Implicit` variant (the documented mono-genome fast path, `bitmatrix.rs`). Added `PersistentBitMatrix::get(c, slot) -> u32` (`bitmatrix.rs`), a non-panicking column-major point lookup that returns `1` for `Implicit` regardless of `c` — the smallest surface needed, not a new `col_get` API from scratch.
- `obikindex/src/partition/query_layer.rs`: `query_partition_with` is now two explicit stages, matching roadmap points 6–8: **stage 1** (MPHF-only, per unique k-mer, bucket hits by `(layer_idx, slot)`, emits `QueryHit::Found`) then **stage 2** (per layer with ≥1 hit, column-major: for each genome column `g` in `0..layer.n_cols().min(n_genomes)`, scan that layer's bucketed slots and call `col_value(g, slot)`, emitting `QueryHit::Value(descs, g, value)` on nonzero). `QueryHit` is a single enum delivered through one `FnMut(QueryHit)` callback — an earlier two-closure design (`on_found` + `on_value`) didn't borrow-check, since the caller's single mutable accumulator (`KmerResults`) can't be captured by two separate `FnMut` closures passed to the same call. - `obikindex/src/partition/query_layer.rs`: `query_partition_with` is now two explicit stages, matching roadmap points 6–8: **stage 1** (MPHF-only, per unique k-mer, bucket hits by `(layer_idx, slot)`, emits `QueryHit::Found`) then **stage 2** (per layer with ≥1 hit, column-major: for each genome column `g` in `0..layer.n_cols().min(n_genomes)`, scan that layer's bucketed slots and call `col_value(g, slot)`, emitting `QueryHit::Value(descs, g, value)` on nonzero). `QueryHit` is a single enum delivered through one `FnMut(QueryHit)` callback — an earlier two-closure design (`on_found` + `on_value`) didn't borrow-check, since the caller's single mutable accumulator (`KmerResults`) can't be captured by two separate `FnMut` closures passed to the same call.
- `obikmer/src/cmd/query.rs`: `KmerResults::set` (row-major, whole-row-at-once) replaced by `mark_found` (stage 1: flag a position as indexed, independent of any genome's value) and `set_one` (stage 2: write one genome's value at one position). `QueryStats` extended with `n_columns_scanned`/`n_col_get_calls`, logged per chunk. - `obiskim/src/cmd/query.rs`: `KmerResults::set` (row-major, whole-row-at-once) replaced by `mark_found` (stage 1: flag a position as indexed, independent of any genome's value) and `set_one` (stage 2: write one genome's value at one position). `QueryStats` extended with `n_columns_scanned`/`n_col_get_calls`, logged per chunk.
- Total `get()`-equivalent calls are unchanged from the row-major version (`n_hits × n_cols` in the worst case, confirmed by `n_col_get_calls` in the debug log) — the win is locality (sequential access within one layer's column at a time, across `mmap`'d regions, instead of jumping across all columns per hit), exactly as predicted. - Total `get()`-equivalent calls are unchanged from the row-major version (`n_hits × n_cols` in the worst case, confirmed by `n_col_get_calls` in the debug log) — the win is locality (sequential access within one layer's column at a time, across `mmap`'d regions, instead of jumping across all columns per hit), exactly as predicted.
**What did not ship, and why — `PartitionRunner` is architecturally the wrong tool here:** **What did not ship, and why — `PartitionRunner` is architecturally the wrong tool here:**
@@ -375,14 +375,14 @@ The column-major loop in stage 2 is therefore a **plain sequential loop** for no
**Goal**: replace the dense `KmerResults`/`win_min` sliding-window scan with one operating on phase 4's sparse per-genome output. **Goal**: replace the dense `KmerResults`/`win_min` sliding-window scan with one operating on phase 4's sparse per-genome output.
- `obikmer/src/cmd/query.rs`, `process_chunk`: - `obiskim/src/cmd/query.rs`, `process_chunk`:
- Remove `KmerResults` (`query.rs:157-202`) and the dense `win_min` allocation (`query.rs:290-291`, sized `max_n_kmers × n_genomes`). - Remove `KmerResults` (`query.rs:157-202`) and the dense `win_min` allocation (`query.rs:290-291`, sized `max_n_kmers × n_genomes`).
- Keep a lightweight dense `in_index: Vec<bool>` per chunk (sized `total_kmers`, independent of `n_genomes`) from phase 3's stage 1 — still needed for `kmer_missing` bookkeeping (leftmost-s-mer-of-window membership test), which phase 4's sparse structure doesn't carry (a k-mer with no genome hit has no entry there at all). - Keep a lightweight dense `in_index: Vec<bool>` per chunk (sized `total_kmers`, independent of `n_genomes`) from phase 3's stage 1 — still needed for `kmer_missing` bookkeeping (leftmost-s-mer-of-window membership test), which phase 4's sparse structure doesn't carry (a k-mer with no genome hit has no entry there at all).
- New per-`(seq_idx, genome)` scan: for each genome's `Vec<(seq_idx, pos, count)>` (sorted, per phase 4), group by `seq_idx` (contiguous after sort), then within each sequence's positions detect runs of `pos, pos+1, pos+2, ...` of length ≥ `z`; within each run, the existing monotone-deque window-minimum logic (`query.rs`'s current `dq` loop, conceptually unchanged) applies — but the deque now only scans real entries in the run, never zero-filled gaps. - New per-`(seq_idx, genome)` scan: for each genome's `Vec<(seq_idx, pos, count)>` (sorted, per phase 4), group by `seq_idx` (contiguous after sort), then within each sequence's positions detect runs of `pos, pos+1, pos+2, ...` of length ≥ `z`; within each run, the existing monotone-deque window-minimum logic (`query.rs`'s current `dq` loop, conceptually unchanged) applies — but the deque now only scans real entries in the run, never zero-filled gaps.
- Update `SeqAcc` accumulation and `emit_batch` to consume this per-genome sparse iteration instead of `results.val`/`results.is_in_index`. - Update `SeqAcc` accumulation and `emit_batch` to consume this per-genome sparse iteration instead of `results.val`/`results.is_in_index`.
- `--detail`/`cov`: build sparsely during the same scan (only positions with a confirmed contribution get an entry), densify into the `[u32]` JSON array only in `emit_batch`, only for genomes/sequences actually being serialized (per roadmap point 9's note, `query.rs:304-308`'s current dense allocation goes away). - `--detail`/`cov`: build sparsely during the same scan (only positions with a confirmed contribution get an entry), densify into the `[u32]` JSON array only in `emit_batch`, only for genomes/sequences actually being serialized (per roadmap point 9's note, `query.rs:304-308`'s current dense allocation goes away).
- Log, per chunk: total sparse entries retained vs. what the old dense `KmerResults` would have allocated (`total_smers × n_genomes`) — the sparsity ratio is this phase's entire reason for existing, so it must be directly visible in the logs, not inferred from process RSS. Also log the run-detection stats (number of runs found, average run length) — a low average run length relative to `z` would mean most positions still fail to form a full window, worth knowing. - Log, per chunk: total sparse entries retained vs. what the old dense `KmerResults` would have allocated (`total_smers × n_genomes`) — the sparsity ratio is this phase's entire reason for existing, so it must be directly visible in the logs, not inferred from process RSS. Also log the run-detection stats (number of runs found, average run length) — a low average run length relative to `z` would mean most positions still fail to form a full window, worth knowing.
- **Unit tests**: `obikmer/src/cmd/tests/query.rs` (extended from phase 3) — the property test described below is the primary deliverable here, not an afterthought; write it as an actual `#[test]` (or a small internal fuzz/property-style loop over randomized fixtures if a property-testing crate isn't already a dependency — check before adding one, per this project's dependency-approval rule) rather than a one-off manual comparison. - **Unit tests**: `obiskim/src/cmd/tests/query.rs` (extended from phase 3) — the property test described below is the primary deliverable here, not an afterthought; write it as an actual `#[test]` (or a small internal fuzz/property-style loop over randomized fixtures if a property-testing crate isn't already a dependency — check before adding one, per this project's dependency-approval rule) rather than a one-off manual comparison.
- **Validation — this is the correctness-critical phase**: property-test comparing old (dense, pre-phase-3) and new (sparse) implementations on the same randomized input/index fixtures, asserting identical `kmer_count`, `kmer_missing`, `kmer_strict_matches`, and (with `--detail`) `coverage` for every sequence. Keep both implementations compiled side by side (behind a debug-only flag or a temporary parallel code path) only for the duration of this validation; delete the dense path once parity is confirmed — per this project's own convention, superseded code is not kept "just in case." - **Validation — this is the correctness-critical phase**: property-test comparing old (dense, pre-phase-3) and new (sparse) implementations on the same randomized input/index fixtures, asserting identical `kmer_count`, `kmer_missing`, `kmer_strict_matches`, and (with `--detail`) `coverage` for every sequence. Keep both implementations compiled side by side (behind a debug-only flag or a temporary parallel code path) only for the duration of this validation; delete the dense path once parity is confirmed — per this project's own convention, superseded code is not kept "just in case."
- **Update `docmd/architecture/query.md` itself**: once this phase lands, the "Findere z-window filter" section (which currently — correctly — describes the dense deque-over-`0..n_smers` scan) needs another pass to describe the sparse run-detection algorithm instead, as already flagged when this phase was discussed. - **Update `docmd/architecture/query.md` itself**: once this phase lands, the "Findere z-window filter" section (which currently — correctly — describes the dense deque-over-`0..n_smers` scan) needs another pass to describe the sparse run-detection algorithm instead, as already flagged when this phase was discussed.
@@ -391,7 +391,7 @@ The column-major loop in stage 2 is therefore a **plain sequential loop** for no
- New `sparse_findere_for_genome(hits, z, presence, threshold) -> (Vec<ConfirmedHit>, n_runs, total_run_len)` (`query.rs`): sorts one genome's raw hits by `(seq_idx, pos)`, detects maximal runs of consecutive `pos` within one sequence, runs the same monotone-deque window-minimum as before but scoped to each run (run-relative indices for eviction, absolute `pos` for computing `pos_out`). Presence/count adjustment (`u32::from(win_min >= threshold)` vs. raw) is applied inside this function, once per confirmed hit, rather than later during accumulation. - New `sparse_findere_for_genome(hits, z, presence, threshold) -> (Vec<ConfirmedHit>, n_runs, total_run_len)` (`query.rs`): sorts one genome's raw hits by `(seq_idx, pos)`, detects maximal runs of consecutive `pos` within one sequence, runs the same monotone-deque window-minimum as before but scoped to each run (run-relative indices for eviction, absolute `pos` for computing `pos_out`). Presence/count adjustment (`u32::from(win_min >= threshold)` vs. raw) is applied inside this function, once per confirmed hit, rather than later during accumulation.
- `process_chunk` restructured into three passes after the partition loop: (1) run `sparse_findere_for_genome` per genome, collecting `confirmed_by_genome` and run-detection stats; (2) accumulate `genome_totals` directly from `confirmed_by_genome` and mark a `confirmed_any: Vec<bool>` (sized `total_kmers_out`, not `× n_genomes`); (3) a position-only pass (`O(total_kmers_out)`, no genome factor) computing `kmer_count`/`kmer_missing` from `confirmed_any` + `SmerIndex`. `cov` (`--detail`) is populated by re-scanning `confirmed_by_genome` — only when `--detail` is actually set, otherwise skipped entirely. - `process_chunk` restructured into three passes after the partition loop: (1) run `sparse_findere_for_genome` per genome, collecting `confirmed_by_genome` and run-detection stats; (2) accumulate `genome_totals` directly from `confirmed_by_genome` and mark a `confirmed_any: Vec<bool>` (sized `total_kmers_out`, not `× n_genomes`); (3) a position-only pass (`O(total_kmers_out)`, no genome factor) computing `kmer_count`/`kmer_missing` from `confirmed_any` + `SmerIndex`. `cov` (`--detail`) is populated by re-scanning `confirmed_by_genome` — only when `--detail` is actually set, otherwise skipped entirely.
- Debug log added (`"sparse Findere"`): `n_dense_would_be` (`n_occurrences × n_genomes` — what the deleted dense path would have allocated), `n_sparse_entries` (what's actually retained), `n_runs`/`avg_run_len` (per the plan's ask, to see whether hits mostly fail to form complete windows). - Debug log added (`"sparse Findere"`): `n_dense_would_be` (`n_occurrences × n_genomes` — what the deleted dense path would have allocated), `n_sparse_entries` (what's actually retained), `n_runs`/`avg_run_len` (per the plan's ask, to see whether hits mostly fail to form complete windows).
- **Unit tests**: `sparse_findere_matches_dense_reference_on_random_inputs` (`obikmer/src/cmd/tests/query.rs`) — 200 randomized cases (sequence count/length, `z`, presence/count mode, threshold, hit density from sparse to fully-dense) comparing `sparse_findere_for_genome` against `dense_reference_findere`, a faithful reimplementation of the deleted dense algorithm kept only as a test-local correctness oracle (no property-testing crate added — checked first, none was a workspace dependency; a small `std`-only xorshift64 PRNG stands in for one, deterministic and dependency-free). All 200 cases pass. - **Unit tests**: `sparse_findere_matches_dense_reference_on_random_inputs` (`obiskim/src/cmd/tests/query.rs`) — 200 randomized cases (sequence count/length, `z`, presence/count mode, threshold, hit density from sparse to fully-dense) comparing `sparse_findere_for_genome` against `dense_reference_findere`, a faithful reimplementation of the deleted dense algorithm kept only as a test-local correctness oracle (no property-testing crate added — checked first, none was a workspace dependency; a small `std`-only xorshift64 PRNG stands in for one, deterministic and dependency-free). All 200 cases pass.
- **Functional validation performed**: full workspace build + `cargo test --workspace`, zero failures. End-to-end against real indexes: baseline output (no flags) unchanged from pre-phase-5 recorded values on the same fixtures; `--count-missing` correct (`kmer_missing: 0` on a self-match); `--detail` correct — coverage array length matches `kmer_count`, and critically, re-ran the two-genome cross-contamination check from phase 4 with `--detail --count-missing`: `genomeA` reads show coverage sum `106` for `genomeA` and `0` for `genomeB` (and vice versa) — confirms the sparse-to-dense `cov` reconstruction doesn't leak across genomes either, not just the scalar `kmer_strict_matches` path. - **Functional validation performed**: full workspace build + `cargo test --workspace`, zero failures. End-to-end against real indexes: baseline output (no flags) unchanged from pre-phase-5 recorded values on the same fixtures; `--count-missing` correct (`kmer_missing: 0` on a self-match); `--detail` correct — coverage array length matches `kmer_count`, and critically, re-ran the two-genome cross-contamination check from phase 4 with `--detail --count-missing`: `genomeA` reads show coverage sum `106` for `genomeA` and `0` for `genomeB` (and vice versa) — confirms the sparse-to-dense `cov` reconstruction doesn't leak across genomes either, not just the scalar `kmer_strict_matches` path.
- This phase's roadmap item ("update the Findere z-window filter section") — done, see above; the "Algorithm" section's pseudocode was also updated, since it still named `KmerResults`/`SKDesc` from before phases 3–4. - This phase's roadmap item ("update the Findere z-window filter section") — done, see above; the "Algorithm" section's pseudocode was also updated, since it still named `KmerResults`/`SKDesc` from before phases 3–4.
+1 -1
View File
@@ -3,7 +3,7 @@
## Code couvert ## Code couvert
- `obikmer/src/cmd/query.rs` — commande query, format de sortie - `obiskim/src/cmd/query.rs` — commande query, format de sortie
- `obikindex/src/partition/query_layer.rs` — routage de la requête à travers les partitions - `obikindex/src/partition/query_layer.rs` — routage de la requête à travers les partitions
- `obiread/src/lib.rs` — lecture des séquences d'entrée pour la requête - `obiread/src/lib.rs` — lecture des séquences d'entrée pour la requête
+1 -1
View File
@@ -140,7 +140,7 @@ operations with no cross-invocation sharing concern: `build_sibling_annex`,
`shannon_entropy_csv`, `sibling_family_size_histogram`/`sibling_annex_stats`, `shannon_entropy_csv`, `sibling_family_size_histogram`/`sibling_annex_stats`,
`family_overlap`. The sampled SNP path (`sampled_scan`, `AlignmentReducer`, `family_overlap`. The sampled SNP path (`sampled_scan`, `AlignmentReducer`,
`PairwiseReducer`, `distance_matrix`, `SankoffBundle`) is **not** wrapped in `PairwiseReducer`, `distance_matrix`, `SankoffBundle`) is **not** wrapped in
trait methods — the CLI (`obikmer::cmd::phylo`) composes them directly, trait methods — the CLI (`obiskim::cmd::phylo`) composes them directly,
because it alone knows the union of reducers a given invocation needs because it alone knows the union of reducers a given invocation needs
(`--pseudo-alignment`/Sankoff group/`snp-*` `--distance` can combine in one (`--pseudo-alignment`/Sankoff group/`snp-*` `--distance` can combine in one
call). A per-output trait method would have to either duplicate that call). A per-output trait method would have to either duplicate that
@@ -2,8 +2,8 @@
`benchmark/Makefile` exercises indexing, merge, and phylo distance `benchmark/Makefile` exercises indexing, merge, and phylo distance
reconstruction against simulated bacterial genomes. It now also covers reconstruction against simulated bacterial genomes. It now also covers
`obikmer query` — the read-matching path — and the sparse packed `obiskim query` — the read-matching path — and the sparse packed
presence-matrix format (`obikmer pack --sparse`), previously untested by presence-matrix format (`obiskim pack --sparse`), previously untested by
this pipeline. this pipeline.
## Motivation ## Motivation
@@ -42,7 +42,7 @@ without duplicating the exhaustive per-specimen coverage
## Sparse global index ## Sparse global index
`global_index_presence_sparse/` is built by `pack_sparse.sh`: copy `global_index_presence_sparse/` is built by `pack_sparse.sh`: copy
`global_index_presence/` wholesale, then `obikmer pack --sparse` in place. `global_index_presence/` wholesale, then `obiskim pack --sparse` in place.
This works directly because `merge`'s pack stage (`merge.rs:252`, This works directly because `merge`'s pack stage (`merge.rs:252`,
`pack_matrices(false)`) keeps the per-genome column files on disk after `pack_matrices(false)`) keeps the per-genome column files on disk after
dense-packing — `pack_sparse_bit_matrix` (`obicompactvec/src/bitmatrix/sparse.rs:447`) dense-packing — `pack_sparse_bit_matrix` (`obicompactvec/src/bitmatrix/sparse.rs:447`)
@@ -52,7 +52,7 @@ afterward. No separate merge run needed.
## Query runs ## Query runs
`query_one.sh dense|sparse SPECIMEN` runs `obikmer query --count-missing` `query_one.sh dense|sparse SPECIMEN` runs `obiskim query --count-missing`
against `global_index_presence` or `global_index_presence_sparse`, output against `global_index_presence` or `global_index_presence_sparse`, output
gzipped to `query_{dense,sparse}/SPECIMEN.fasta.gz`, Reporter wall/RSS gzipped to `query_{dense,sparse}/SPECIMEN.fasta.gz`, Reporter wall/RSS
captured to `stats/query_{dense,sparse}/SPECIMEN.stats` (same captured to `stats/query_{dense,sparse}/SPECIMEN.stats` (same
@@ -7,9 +7,9 @@
- `obikindex/src/layer/mphf_layer.rs` — build_approx_evidence(dir, b, z), find_approx() - `obikindex/src/layer/mphf_layer.rs` — build_approx_evidence(dir, b, z), find_approx()
- `obikindex/src/layer/meta.rs` — EvidenceKind::Approx { b, z }, LayerMeta - `obikindex/src/layer/meta.rs` — EvidenceKind::Approx { b, z }, LayerMeta
- `obikindex/src/reindex.rs` — KmerIndex::reindex(), conversion exact↔approx en place - `obikindex/src/reindex.rs` — KmerIndex::reindex(), conversion exact↔approx en place
- `obikmer/src/cmd/reindex.rs` — CLI reindex, options --approx, -z, --evidence-bits, --fp, --block-size - `obiskim/src/cmd/reindex.rs` — CLI reindex, options --approx, -z, --evidence-bits, --fp, --block-size
- `obikmer/src/cmd/index.rs` — resolve_approx_params(), options --approx, -z, --evidence-bits, --fp - `obiskim/src/cmd/index.rs` — resolve_approx_params(), options --approx, -z, --evidence-bits, --fp
- `obikmer/src/cmd/estimate.rs` — commande estimate (dry-run des paramètres) - `obiskim/src/cmd/estimate.rs` — commande estimate (dry-run des paramètres)
## Notes ## Notes
+11 -11
View File
@@ -206,7 +206,7 @@ Keep k-mers specific to *Betula nana* — present in at least 2 *B. nana* genome
and absent from every other genome in the index: and absent from every other genome in the index:
```sh ```sh
obikmer filter src --output dst \ obiskim filter src --output dst \
--ingroup "species=Betula_nana" \ --ingroup "species=Betula_nana" \
--outgroup "*" \ --outgroup "*" \
--min-count 2 \ --min-count 2 \
@@ -217,7 +217,7 @@ Keep k-mers found in at least 2 *Betula nana* genomes and absent from all
other *Betula*: other *Betula*:
```sh ```sh
obikmer filter src --output dst \ obiskim filter src --output dst \
--ingroup "species=Betula_nana" \ --ingroup "species=Betula_nana" \
--outgroup "genus=Betula" \ --outgroup "genus=Betula" \
--min-count 2 \ --min-count 2 \
@@ -228,7 +228,7 @@ Use taxonomic paths — keep k-mers present in ≥ 50 % of the *Betula* clade
and in fewer than 10 % of everything outside *Betulaceae*: and in fewer than 10 % of everything outside *Betulaceae*:
```sh ```sh
obikmer filter src --output dst \ obiskim filter src --output dst \
--ingroup "taxon~/Betulaceae/Betula" \ --ingroup "taxon~/Betulaceae/Betula" \
--outgroup "taxon!~/Betulaceae" \ --outgroup "taxon!~/Betulaceae" \
--min-frac 0.5 \ --min-frac 0.5 \
@@ -238,7 +238,7 @@ obikmer filter src --output dst \
Multiple outgroup predicates (OR): exclude k-mers present in *Alnus* or *Carpinus*: Multiple outgroup predicates (OR): exclude k-mers present in *Alnus* or *Carpinus*:
```sh ```sh
obikmer filter src --output dst \ obiskim filter src --output dst \
--ingroup "genus=Betula" \ --ingroup "genus=Betula" \
--outgroup "genus=Alnus" \ --outgroup "genus=Alnus" \
--outgroup "genus=Carpinus" \ --outgroup "genus=Carpinus" \
@@ -249,7 +249,7 @@ Noise-tolerant core — keep k-mers present in *all but one* ingroup genome
(`-1` = `n−1`) and absent from *all but one* of the outgroup: (`-1` = `n−1`) and absent from *all but one* of the outgroup:
```sh ```sh
obikmer filter src --output dst \ obiskim filter src --output dst \
--ingroup "genus=Betula" \ --ingroup "genus=Betula" \
--outgroup "*" \ --outgroup "*" \
--min-count -1 \ --min-count -1 \
@@ -259,7 +259,7 @@ obikmer filter src --output dst \
To dump only k-mers specific to *Betula nana*: To dump only k-mers specific to *Betula nana*:
```sh ```sh
obikmer dump myindex \ obiskim dump myindex \
--ingroup "species=Betula_nana" \ --ingroup "species=Betula_nana" \
--outgroup "*" \ --outgroup "*" \
--min-count 1 \ --min-count 1 \
@@ -269,7 +269,7 @@ obikmer dump myindex \
To enumerate unitigs of the *Betula*-specific subgraph: To enumerate unitigs of the *Betula*-specific subgraph:
```sh ```sh
obikmer unitig myindex \ obiskim unitig myindex \
--ingroup "genus=Betula" \ --ingroup "genus=Betula" \
--outgroup "*" \ --outgroup "*" \
--min-count 2 \ --min-count 2 \
@@ -285,8 +285,8 @@ Iteration terminates immediately — subsequent partitions and layers are not sc
Useful for quick inspection of large indexes without loading the entire dataset. Useful for quick inspection of large indexes without loading the entire dataset.
```sh ```sh
obikmer dump myindex --head 100 obiskim dump myindex --head 100
obikmer dump myindex --head 20 --ingroup "species=Betula_nana" --min-count 1 obiskim dump myindex --head 20 --ingroup "species=Betula_nana" --min-count 1
``` ```
### `phylo --presence-threshold N` ### `phylo --presence-threshold N`
@@ -296,7 +296,7 @@ This option is independent of the `--presence-threshold` used in filtering.
```sh ```sh
# Jaccard treating kmers with count ≥ 2 as present # Jaccard treating kmers with count ≥ 2 as present
obikmer phylo myindex --metric jaccard --presence-threshold 2 obiskim phylo myindex --metric jaccard --presence-threshold 2
``` ```
This parameter has no effect on presence/absence indexes (where values are already 0/1) or on metrics other than Jaccard. This parameter has no effect on presence/absence indexes (where values are already 0/1) or on metrics other than Jaccard.
@@ -309,7 +309,7 @@ This parameter has no effect on presence/absence indexes (where values are alrea
once before any iteration; each k-mer row evaluation is a simple index once before any iteration; each k-mer row evaluation is a simple index
lookup and counter. lookup and counter.
- **`obikmer::cmd::predicate::FilterArgs`** — shared `clap` argument group - **`obiskim::cmd::predicate::FilterArgs`** — shared `clap` argument group
embedded via `#[command(flatten)]` in `FilterArgs`, `DumpArgs`, and embedded via `#[command(flatten)]` in `FilterArgs`, `DumpArgs`, and
`UnitigArgs`. `FilterArgs::build_filters()` returns a ready-to-use filter `UnitigArgs`. `FilterArgs::build_filters()` returns a ready-to-use filter
list. list.
+3 -3
View File
@@ -2,7 +2,7 @@
## Purpose ## Purpose
`obikmer merge` combines multiple existing kmer indexes into a single index. The result contains all kmers from all sources, with per-genome presence/absence or count data for every genome across every layer. `obiskim merge` combines multiple existing kmer indexes into a single index. The result contains all kmers from all sources, with per-genome presence/absence or count data for every genome across every layer.
--- ---
@@ -64,7 +64,7 @@ Check all sources against the constraints above. Abort on any mismatch.
### 2. Bootstrap output from the base source ### 2. Bootstrap output from the base source
The base is chosen by `choose_base` (`merge.rs`): the source with the largest total `unitigs.bin` size (restricted to approximate-evidence sources when the output must be approximate). It is not necessarily `sources[0]`, and the genome columns follow the base first. Because `obikmer index` is not byte-reproducible (unitig segmentation varies), two near-equal sources can swap roles between runs. Its directory is copied to `output` (hard links for files `merge_partition` never rewrites, see below). Immediately after the copy: The base is chosen by `choose_base` (`merge.rs`): the source with the largest total `unitigs.bin` size (restricted to approximate-evidence sources when the output must be approximate). It is not necessarily `sources[0]`, and the genome columns follow the base first. Because `obiskim index` is not byte-reproducible (unitig segmentation varies), two near-equal sources can swap roles between runs. Its directory is copied to `output` (hard links for files `merge_partition` never rewrites, see below). Immediately after the copy:
- `index.meta` is rewritten with the final genome list (all sources, possibly renamed) and the effective evidence kind. - `index.meta` is rewritten with the final genome list (all sources, possibly renamed) and the effective evidence kind.
- In `Presence` mode, any `counts/` directories inherited from source_0 are removed. - In `Presence` mode, any `counts/` directories inherited from source_0 are removed.
@@ -185,7 +185,7 @@ index.meta ← complete genome list + evidence kind written at
## Known issue (not yet fixed, 2026-08-28) ## Known issue (not yet fixed, 2026-08-28)
Merging an index against itself — literally the same directory passed twice as separate source arguments (e.g. `obikmer merge -o out IDX IDX --rename-duplicates`) — panics deep in the MPHF's rank-select structure (`common_traits::select_in_word`, `assertion failed: rank < self.count_ones()`), inside `MphfLayer::find` called from `merge_partition`'s "is this source kmer already in dst" check against the bootstrap-copied `dst_layers`. Root cause not identified; ruled out so far: Merging an index against itself — literally the same directory passed twice as separate source arguments (e.g. `obiskim merge -o out IDX IDX --rename-duplicates`) — panics deep in the MPHF's rank-select structure (`common_traits::select_in_word`, `assertion failed: rank < self.count_ones()`), inside `MphfLayer::find` called from `merge_partition`'s "is this source kmer already in dst" check against the bootstrap-copied `dst_layers`. Root cause not identified; ruled out so far:
- **Not an empty-new-layer issue**: a source contributing zero new kmers (verified both as the sole additional source and as a third, fully-redundant source in a 3-way merge) is handled correctly — no layer is created for it, no crash, exit 0. - **Not an empty-new-layer issue**: a source contributing zero new kmers (verified both as the sole additional source and as a third, fully-redundant source in a 3-way merge) is handled correctly — no layer is created for it, no crash, exit 0.
- **Not caused by the hard-link change above**: verified via checksum that a normal (two distinct sources) merge leaves every source file byte-identical. - **Not caused by the hard-link change above**: verified via checksum that a normal (two distinct sources) merge leaves every source file byte-identical.
+2 -2
View File
@@ -2,7 +2,7 @@
## Problem observed ## Problem observed
Running `obikmer merge` over 109 indexes (108 sources + 1 bootstrap) on a 192-core machine Running `obiskim merge` over 109 indexes (108 sources + 1 bootstrap) on a 192-core machine
produces a fatal OOM during the `merge_partitions` stage: produces a fatal OOM during the `merge_partitions` stage:
``` ```
@@ -58,7 +58,7 @@ Plausible for the largest partition of 108 Salix/Betula sources (~450 Mbp each).
## Partition size distribution ## Partition size distribution
`obikmer utils --partition-stats` measures the sum of `unitigs.bin` file sizes `obiskim utils --partition-stats` measures the sum of `unitigs.bin` file sizes
per partition across all source indexes (pure `stat()` syscalls, negligible cost). per partition across all source indexes (pure `stat()` syscalls, negligible cost).
Observed on a 9-genome pilot (256 partitions): Observed on a 9-genome pilot (256 partitions):
+1 -1
View File
@@ -38,4 +38,4 @@ Merge discovers values **column by column** (source by source), in **random slot
## Related findings ## Related findings
- The module header of `bitmatrix/sparse.rs` says "not used by any production code path yet". This is stale: `finalize_indexed` packs to sparse by default. - The module header of `bitmatrix/sparse.rs` says "not used by any production code path yet". This is stale: `finalize_indexed` packs to sparse by default.
- The new layer of a merge is not byte-reproducible run to run: unitig segmentation varies, so the MPHF, evidence and matrix row order vary with it (measured 2026-11-17, `layer_1/*` differs in all 256 partitions; `layer_0` and metadata are identical). `obikmer index` shows the same behaviour. Merge oracles therefore compare sorted dumps, not file hashes. Where the non-determinism originates (parallel graph fill or unitig walk) is not established. - The new layer of a merge is not byte-reproducible run to run: unitig segmentation varies, so the MPHF, evidence and matrix row order vary with it (measured 2026-11-17, `layer_1/*` differs in all 256 partitions; `layer_0` and metadata are identical). `obiskim index` shows the same behaviour. Merge oracles therefore compare sorted dumps, not file hashes. Where the non-determinism originates (parallel graph fill or unitig walk) is not established.
@@ -112,8 +112,8 @@ About −5 % wall and −5.5 % CPU, ranges non-overlapping **[measured]**. All o
Prerequisites: the simulated reads (`benchmark/run/simulated_data/`) and query reads (`benchmark/run/query_data/`) produced by `gmake simulate simulate_query`; macOS BSD `time -l` and `md5 -q` (the script uses both), Python 3. Prerequisites: the simulated reads (`benchmark/run/simulated_data/`) and query reads (`benchmark/run/query_data/`) produced by `gmake simulate simulate_query`; macOS BSD `time -l` and `md5 -q` (the script uses both), Python 3.
1. Build the binary to measure and **copy it** under a name that identifies it (cargo overwrites `target/release/obikmer`): `cp src/target/release/obikmer benchmark/run/bench_mphf/obikmer_<label>`. 1. Build the binary to measure and **copy it** under a name that identifies it (cargo overwrites `target/release/obiskim`): `cp src/target/release/obiskim benchmark/run/bench_mphf/obiskim_<label>`.
2. `BINARY=$PWD/run/bench_mphf/obikmer_<label> benchmark/bench_mphf.sh <label>` (from `benchmark/`; `REPS=3` by default, `CPU_MAX=n` to restrict cores). The first call builds the shared data set in `run/bench_mphf/data/` with that binary (≈ 2 min); keep it for every label — the on-disk format must not differ between the binaries compared, otherwise delete `data/` and rebuild. 2. `BINARY=$PWD/run/bench_mphf/obiskim_<label> benchmark/bench_mphf.sh <label>` (from `benchmark/`; `REPS=3` by default, `CPU_MAX=n` to restrict cores). The first call builds the shared data set in `run/bench_mphf/data/` with that binary (≈ 2 min); keep it for every label — the on-disk format must not differ between the binaries compared, otherwise delete `data/` and rebuild.
3. Output: `run/bench_mphf/<label>/results.csv` (wall and peak RSS per step and repetition, plus one row `step:stage` per Reporter stage) and `checksums.txt`. 3. Output: `run/bench_mphf/<label>/results.csv` (wall and peak RSS per step and repetition, plus one row `step:stage` per Reporter stage) and `checksums.txt`.
4. Compare: `python3 benchmark/summarize_bench.py <ref_label> <new_label>` (medians and ratio) and `diff run/bench_mphf/<ref>/checksums.txt run/bench_mphf/<new>/checksums.txt` — **any difference is a bug**, not a performance matter. 4. Compare: `python3 benchmark/summarize_bench.py <ref_label> <new_label>` (medians and ratio) and `diff run/bench_mphf/<ref>/checksums.txt run/bench_mphf/<new>/checksums.txt` — **any difference is a bug**, not a performance matter.
5. A ratio is only a candidate effect. Check the spread by running the **same** binary twice under two labels (the script's own noise floor was ±10–40 % per step on a loaded laptop), or confirm with interleaved A/B runs of the single command (alternate the two binaries, ≥ 8 runs, compare ranges of wall and user CPU from `/usr/bin/time -l`). 5. A ratio is only a candidate effect. Check the spread by running the **same** binary twice under two labels (the script's own noise floor was ±10–40 % per step on a loaded laptop), or confirm with interleaved A/B runs of the single command (alternate the two binaries, ≥ 8 runs, compare ranges of wall and user CPU from `/usr/bin/time -l`).
@@ -214,7 +214,7 @@ Tests: `cargo test --workspace` green; `scripts/smoke_test_index.sh` PASS; `benc
Follow-up of §14 (search for the same family of problems: file content handled inefficiently at open). Static search over `src/` for `fs::read`, `read_to_end`, `load_full`, `from_reader`, bare `File` readers and mmap `to_vec`: every persistent structure of `obicompactvec`, `obikindex` and the `obikphylo` annexes is already mmapped; the two real findings were *unbuffered* readers. Follow-up of §14 (search for the same family of problems: file content handled inefficiently at open). Static search over `src/` for `fs::read`, `read_to_end`, `load_full`, `from_reader`, bare `File` readers and mmap `to_vec`: every persistent structure of `obicompactvec`, `obikindex` and the `obikphylo` annexes is already mmapped; the two real findings were *unbuffered* readers.
**1. `IndexMeta::read_full` (`obikindex/src/index/meta.rs`)** passed a bare `File` to `serde_json::from_reader`, which issues **one `read` syscall per byte**. `index.meta` of the 91-genome index is 20 KB and is read afresh by every `state()`/`genomes()` call (stateless design, §obikindex audit), so each call cost ≈ 0.35 s here (macOS). Profile of `obikmer dump --head 10` (`sample`): ≈ 20 000 samples in `read`, called from `Bytes<File>::next` ← `serde_json` ← `IndexMeta`. Fix: `fs::read` then `serde_json::from_slice`. **`dump --head 10`: 9.0–10.0 s (91–102 s of system CPU) → 0.16–0.84 s**; the same change applies to `SKFileMeta::read` (`obiskio/src/meta.rs`, per-superkmer-file sidecars). **1. `IndexMeta::read_full` (`obikindex/src/index/meta.rs`)** passed a bare `File` to `serde_json::from_reader`, which issues **one `read` syscall per byte**. `index.meta` of the 91-genome index is 20 KB and is read afresh by every `state()`/`genomes()` call (stateless design, §obikindex audit), so each call cost ≈ 0.35 s here (macOS). Profile of `obiskim dump --head 10` (`sample`): ≈ 20 000 samples in `read`, called from `Bytes<File>::next` ← `serde_json` ← `IndexMeta`. Fix: `fs::read` then `serde_json::from_slice`. **`dump --head 10`: 9.0–10.0 s (91–102 s of system CPU) → 0.16–0.84 s**; the same change applies to `SKFileMeta::read` (`obiskio/src/meta.rs`, per-superkmer-file sidecars).
**2. `SKFileReader::open` (`obiskio/src/reader.rs`)**: for an uncompressed file `niffler::get_reader` returns the sniffed bytes chained to the bare `File`, and `read_superkmer` reads each field with its own small `read_exact`. Fix: wrap the file in a 64 KiB `BufReader` before `niffler`. Effect on `index` (E. coli, 4 interleaved runs each): `count_kmer` 0.51–0.56 s → 0.42–0.50 s (≈ −12 %), total wall unchanged (≈ 1.95 s). Small, low risk, kept. **2. `SKFileReader::open` (`obiskio/src/reader.rs`)**: for an uncompressed file `niffler::get_reader` returns the sniffed bytes chained to the bare `File`, and `read_superkmer` reads each field with its own small `read_exact`. Fix: wrap the file in a 64 KiB `BufReader` before `niffler`. Effect on `index` (E. coli, 4 interleaved runs each): `count_kmer` 0.51–0.56 s → 0.42–0.50 s (≈ −12 %), total wall unchanged (≈ 1.95 s). Small, low risk, kept.
@@ -226,7 +226,7 @@ Tests: `cargo test --workspace` 549 passed / 0 failed; `scripts/smoke_test_index
## 16. Profile of `index` on E. coli reads (2026-10-15) ## 16. Profile of `index` on E. coli reads (2026-10-15)
`sample` (1 ms stacks) of `obikmer index` on the E. coli K-12 simulated reads (2 × 15x, 16 threads, one run; the `index` stage lasted 2.4 s under the sampler vs ≈ 0.9 s normally, so proportions are approximate). Stage walls: scatter 0.40 s, dereplicate 0.14, count_kmer 0.60, index 2.36. `sample` (1 ms stacks) of `obiskim index` on the E. coli K-12 simulated reads (2 × 15x, 16 threads, one run; the `index` stage lasted 2.4 s under the sampler vs ≈ 0.9 s normally, so proportions are approximate). Stage walls: scatter 0.40 s, dereplicate 0.14, count_kmer 0.60, index 2.36.
**Threads are mostly idle.** Of ≈ 30 800 thread-samples: 24 900 blocked or yielding, 5 900 active. The ≈ 9 s of *system* CPU per run (§15) is `swtch_pri` (`sched_yield`) — 4 550 samples: ≈ 70 % rayon workers spinning for work (`WorkerThread` wait loop), ≈ 28 % `crossbeam` bounded-channel send/recv spinning, the rest in `obidebruinj` thread-locals. It is waiting, not I/O: no `read` samples remain. It costs no wall time on an otherwise idle machine, but burns CPU (visible in `user + sys` accounting and on a shared 192-core machine). **Threads are mostly idle.** Of ≈ 30 800 thread-samples: 24 900 blocked or yielding, 5 900 active. The ≈ 9 s of *system* CPU per run (§15) is `swtch_pri` (`sched_yield`) — 4 550 samples: ≈ 70 % rayon workers spinning for work (`WorkerThread` wait loop), ≈ 28 % `crossbeam` bounded-channel send/recv spinning, the rest in `obidebruinj` thread-locals. It is waiting, not I/O: no `read` samples remain. It costs no wall time on an otherwise idle machine, but burns CPU (visible in `user + sys` accounting and on a shared 192-core machine).
@@ -365,4 +365,4 @@ Side effect: `find_strict` was the only reader of the `unitigs` handle that `Hyb
Checks after the removal: `cargo build --release` without warnings, `cargo test --workspace` 555 passed / 0 failed, `scripts/smoke_test_index.sh` PASS. Checks after the removal: `cargo build --release` without warnings, `cargo test --workspace` 555 passed / 0 failed, `scripts/smoke_test_index.sh` PASS.
Scratch artifacts of this work were deleted: the intermediate binaries, the two skim indexes (`skim_p4`, `skim_p16`) and the shared data set `benchmark/run/bench_mphf/data` (rebuilt automatically, ≈ 2 min, by the next `bench_mphf.sh`). Kept in `benchmark/run/bench_mphf/`: the original binary `obikmer_baseline` (reference for A/B runs) and the per-label results and checksums (18 MB in all). The 91-genome index converted to the current MPHF format (`/Users/coissac/travail/obiskim/data/phyloalps/bench_mphf/phyloskims_sal_vac_sav_v2`, with its `index.meta` patched, original `index.meta.before_state_fix` beside it) was left in place. Scratch artifacts of this work were deleted: the intermediate binaries, the two skim indexes (`skim_p4`, `skim_p16`) and the shared data set `benchmark/run/bench_mphf/data` (rebuilt automatically, ≈ 2 min, by the next `bench_mphf.sh`). Kept in `benchmark/run/bench_mphf/`: the original binary `obiskim_baseline` (reference for A/B runs) and the per-label results and checksums (18 MB in all). The 91-genome index converted to the current MPHF format (`/Users/coissac/travail/obiskim/data/phyloalps/bench_mphf/phyloskims_sal_vac_sav_v2`, with its `index.meta` patched, original `index.meta.before_state_fix` beside it) was left in place.
+1 -1
View File
@@ -104,7 +104,7 @@ make_pipe! {
} }
``` ```
Two pipes compose with `.then(other)`. Apply to an iterator with `.apply(iter, n_workers, capacity)` to get a `PipeIter<Out>` — an iterator over the pipeline output, backed by a background `WorkerPool`. The scatter step in `obikmer` uses `make_pipe!` and `.apply()` rather than the full `make_pipeline!` / `WorkerPool` pattern. Two pipes compose with `.then(other)`. Apply to an iterator with `.apply(iter, n_workers, capacity)` to get a `PipeIter<Out>` — an iterator over the pipeline output, backed by a background `WorkerPool`. The scatter step in `obiskim` uses `make_pipe!` and `.apply()` rather than the full `make_pipeline!` / `WorkerPool` pattern.
## Scheduler architecture ## Scheduler architecture
@@ -232,7 +232,7 @@ needed — `obikindex → obikpartitionner` stays the same direction as before.
conversation as a side effect of investigating the false "independent conversation as a side effect of investigating the false "independent
lifecycle" claim. lifecycle" claim.
- `KmerIndex::partition()`/`partition_mut()` are gone; `scatter()` - `KmerIndex::partition()`/`partition_mut()` are gone; `scatter()`
(`obikmer`) and any write-side code get a transient `PartitionRouter` via (`obiskim`) and any write-side code get a transient `PartitionRouter` via
`KmerIndex::partition_router()`. `KmerIndex::partition_router()`.
- A real bug caught by the test suite during this move: - A real bug caught by the test suite during this move:
`PartitionRouter::open` initially defaulted to `closed: true` (inherited `PartitionRouter::open` initially defaulted to `closed: true` (inherited
@@ -423,7 +423,7 @@ control (tests, `obikphylo`'s test harness) still get it, `run` is a
convenience layered on top, not the only way in. convenience layered on top, not the only way in.
`run` absorbs the entire body of what used to be the free function `run` absorbs the entire body of what used to be the free function
`obikmer::steps::scatter` (now deleted, along with the `steps` module `obiskim::steps::scatter` (now deleted, along with the `steps` module
entirely) — the `obipipeline::make_pipe!` two-stage pipeline entirely) — the `obipipeline::make_pipe!` two-stage pipeline
(file→pages→superkmers), throttling, per-file logging. What changed: (file→pages→superkmers), throttling, per-file logging. What changed:
- Every `ensure_writer(partition)` call now does `Layer::create(&layer0_dir)` - Every `ensure_writer(partition)` call now does `Layer::create(&layer0_dir)`
@@ -442,7 +442,7 @@ entirely) — the `obipipeline::make_pipe!` two-stage pipeline
workspace suite exercises the real CLI's file-reading `scatter` path workspace suite exercises the real CLI's file-reading `scatter` path
end-to-end (`obikphylo`'s test harness and `obikpartitionner`'s own end-to-end (`obikphylo`'s test harness and `obikpartitionner`'s own
tests both call `write_batch` directly, bypassing `run`/file discovery tests both call `write_batch` directly, bypassing `run`/file discovery
entirely), so the whole suite stayed green while `obikmer index` on entirely), so the whole suite stayed green while `obiskim index` on
real FASTA silently indexed 0 kmers. Found by running the actual CLI real FASTA silently indexed 0 kmers. Found by running the actual CLI
against a small FASTA and noticing `count.json`'s `f0` (870, correct) against a small FASTA and noticing `count.json`'s `f0` (870, correct)
didn't match "0 total kmers indexed" at the final stage. Fixed by didn't match "0 total kmers indexed" at the final stage. Fixed by
@@ -581,7 +581,7 @@ Full workspace suite green (`cargo check --workspace --all-targets` +
`cargo test --workspace`, exit code 0), plus an end-to-end CLI smoke test `cargo test --workspace`, exit code 0), plus an end-to-end CLI smoke test
against real FASTA data (scatter → dereplicate → count → index-build → against real FASTA data (scatter → dereplicate → count → index-build →
query, same numbers as (3)'s smoke test: 870 kmers) — required this time query, same numbers as (3)'s smoke test: 870 kmers) — required this time
too, per (3)'s own lesson: no test in the suite exercises `obikmer index`'s too, per (3)'s own lesson: no test in the suite exercises `obiskim index`'s
real file-driven path. real file-driven path.
Still not done: `count_kmer`/`build_layers` staying where they are, the Still not done: `count_kmer`/`build_layers` staying where they are, the
@@ -842,7 +842,7 @@ equivalent on `Dereplicator`, which has no setters at all) — a real,
already-present parameter (`keep_intermediate` at the CLI), not a already-present parameter (`keep_intermediate` at the CLI), not a
speculative addition. speculative addition.
`count_kmer`'s three former callers (`obikmer::cmd::index`, `obikphylo`'s `count_kmer`'s three former callers (`obiskim::cmd::index`, `obikphylo`'s
test harness, `obikindexer::algorithms::partitionner`'s own test harness, `obikindexer::algorithms::partitionner`'s own
`pipeline_counts` test helper) all updated to `Counter::new(&idx). `pipeline_counts` test helper) all updated to `Counter::new(&idx).
run(...)` — the last one simplified further: it used to read back run(...)` — the last one simplified further: it used to read back
@@ -998,7 +998,7 @@ same reason.
index's kmer sequences — read by `rebuild_layer.rs` and others, well index's kmer sequences — read by `rebuild_layer.rs` and others, well
beyond construction — see [[project_unitigs_always_kept]]), beyond construction — see [[project_unitigs_always_kept]]),
`pack_matrices` (re-runnable maintenance on an already-finished index `pack_matrices` (re-runnable maintenance on an already-finished index
via `obikmer pack`, not just a pipeline step), `upgrade_layer_meta` via `obiskim pack`, not just a pipeline step), `upgrade_layer_meta`
(migration, runnable on any existing index at any time). (migration, runnable on any existing index at any time).
### The general pattern (not obikindexer-specific) ### The general pattern (not obikindexer-specific)
@@ -1117,7 +1117,7 @@ what was wanted.
**A real design decision made while wiring callers up, not a mechanical **A real design decision made while wiring callers up, not a mechanical
rename**: `PrivateBuilder` being genuinely `pub(crate)` to `obikindexer` rename**: `PrivateBuilder` being genuinely `pub(crate)` to `obikindexer`
means `obikmer::cmd::index` (a different crate) can no longer call means `obiskim::cmd::index` (a different crate) can no longer call
`mark_scattered`/`mark_counted`/`mark_indexed`/`write_spectrum` directly — `mark_scattered`/`mark_counted`/`mark_indexed`/`write_spectrum` directly —
it never could have, once privacy was real rather than aspirational. Each it never could have, once privacy was real rather than aspirational. Each
algorithm now marks its own completion as part of `run()`/`close()` algorithm now marks its own completion as part of `run()`/`close()`
@@ -1200,7 +1200,7 @@ traits, two crates, two different reasons, not a contradiction.
internal caller of these four methods needs the trait imported now that internal caller of these four methods needs the trait imported now that
they're no longer inherent — `merge.rs`, `select.rs`, `rebuild.rs`, they're no longer inherent — `merge.rs`, `select.rs`, `rebuild.rs`,
`reindex.rs` (`use crate::index::builder::IndexBuilder;`) and, externally, `reindex.rs` (`use crate::index::builder::IndexBuilder;`) and, externally,
`obikmer::cmd::index::mod` (`use obikindex::IndexBuilder;`, for the three `obiskim::cmd::index::mod` (`use obikindex::IndexBuilder;`, for the three
`idx.state() < IndexState::X` resumability checks). Call syntax at every `idx.state() < IndexState::X` resumability checks). Call syntax at every
site is unchanged (`KmerIndex::create_skeleton(...)`, site is unchanged (`KmerIndex::create_skeleton(...)`,
`self.state()`) — only trait-in-scope requirements are new, which is `self.state()`) — only trait-in-scope requirements are new, which is
@@ -1210,7 +1210,7 @@ itself.
Verification went one step further than (9): beyond Verification went one step further than (9): beyond
`cargo check --workspace --all-targets` + `cargo test --workspace` + `cargo check --workspace --all-targets` + `cargo test --workspace` +
`scripts/smoke_test_index.sh` (all green, 870 kmers again), ran `scripts/smoke_test_index.sh` (all green, 870 kmers again), ran
`obikmer merge` end to end on two freshly built indexes (exercises `obiskim merge` end to end on two freshly built indexes (exercises
`clear_output_for_create`/`finalize_indexed` directly, the two methods `clear_output_for_create`/`finalize_indexed` directly, the two methods
`scripts/smoke_test_index.sh` itself never touches) — exit 0, `pack` `scripts/smoke_test_index.sh` itself never touches) — exit 0, `pack`
stage completed. Test suite alone would not have caught a regression stage completed. Test suite alone would not have caught a regression
@@ -1310,7 +1310,7 @@ field mutation from outside `IndexMeta`). Fixed across:
`entropy.rs`/`sankoff_bundle.rs`/`stats.rs`/`tests.rs` — all had `entropy.rs`/`sankoff_bundle.rs`/`stats.rs`/`tests.rs` — all had
`self.meta().genomes.len()`-shaped reads, mechanically fixed to `self.meta().genomes.len()`-shaped reads, mechanically fixed to
`.genomes().map_err(OKIError::Io)?.len()` (tests: `.unwrap()`). `.genomes().map_err(OKIError::Io)?.len()` (tests: `.unwrap()`).
- `obikmer::cmd::*`: `annotate` (rewrote its rename path to load genomes - `obiskim::cmd::*`: `annotate` (rewrote its rename path to load genomes
once, mutate the in-memory `Vec`, then `idx.meta().set_genomes(...)` once, mutate the in-memory `Vec`, then `idx.meta().set_genomes(...)`
instead of `meta_mut()`), `filter`/`pack`/`dump`/`unitig`/`merge`/`select`/ instead of `meta_mut()`), `filter`/`pack`/`dump`/`unitig`/`merge`/`select`/
`phylo` (fetch-once-then-use pattern for genome counts/labels), `phylo` (fetch-once-then-use pattern for genome counts/labels),
@@ -1442,7 +1442,7 @@ forcing callers' progress closures to `move`-capture (and therefore clone
or `Arc`-wrap) local state like `TracedBar`/EMA-rate accumulators that or `Arc`-wrap) local state like `TracedBar`/EMA-rate accumulators that
they'd otherwise want to keep using by reference after `run()` returns. they'd otherwise want to keep using by reference after `run()` returns.
**Why a new crate, not a submodule of `obikindexer`**: `obikmer::cmd:: **Why a new crate, not a submodule of `obikindexer`**: `obiskim::cmd::
index::mod` and `obikphylo`'s own test helpers both need to call `.run()` index::mod` and `obikphylo`'s own test helpers both need to call `.run()`
on these algorithms, so the trait has to be reachable from outside on these algorithms, so the trait has to be reachable from outside
`obikindexer` — putting it in `obikindexer` itself would work file-wise `obikindexer` — putting it in `obikindexer` itself would work file-wise
@@ -1450,16 +1450,16 @@ but conflates "the trait every algorithm implements" with "one crate's
particular four implementations of it", the same reasoning that already particular four implementations of it", the same reasoning that already
separated `obikindex` (data model) from `obikindexer` (algorithms separated `obikindex` (data model) from `obikindexer` (algorithms
operating on it). `obikalgorithm` has **no dependencies at all** (see operating on it). `obikalgorithm` has **no dependencies at all** (see
above); `obikindexer`, `obikmer`, and `obikphylo` (dev-dependency, for above); `obikindexer`, `obiskim`, and `obikphylo` (dev-dependency, for
its test helper) all depend on it. its test helper) all depend on it.
**Blast radius**: `obikindexer`'s four algorithm modules (struct field + **Blast radius**: `obikindexer`'s four algorithm modules (struct field +
setter + trait impl each); `obikmer::cmd::index::mod` (three call sites: setter + trait impl each); `obiskim::cmd::index::mod` (three call sites:
`.on_progress(cb)` before `.run()`, unqualified now that the trait is in `.on_progress(cb)` before `.run()`, unqualified now that the trait is in
scope); `obikindexer::algorithms::partitionner::tests` and `obikphylo:: scope); `obikindexer::algorithms::partitionner::tests` and `obikphylo::
siblings::tests` (both had direct `.run(None::<fn(Progress)>)`-shaped siblings::tests` (both had direct `.run(None::<fn(Progress)>)`-shaped
calls needing the same treatment). New `obikalgorithm` crate registered calls needing the same treatment). New `obikalgorithm` crate registered
in the workspace `Cargo.toml`, depended on by `obikindexer`/`obikmer` in the workspace `Cargo.toml`, depended on by `obikindexer`/`obiskim`
(regular) and `obikphylo` (dev). (regular) and `obikphylo` (dev).
**Verification**: `cargo check --workspace --all-targets` and `cargo test **Verification**: `cargo check --workspace --all-targets` and `cargo test
@@ -1511,7 +1511,7 @@ auto-detection" turned up three unrelated implementations:
| `Mat` (now deleted; superseded by `obilayeredmap::Layer`) | `obikphylo::siblings::cache` | one layer, format resolved per instance from an enum of 3 `Layer<D>` variants | yes, via `PartitionCache` | | `Mat` (now deleted; superseded by `obilayeredmap::Layer`) | `obikphylo::siblings::cache` | one layer, format resolved per instance from an enum of 3 `Layer<D>` variants | yes, via `PartitionCache` |
| `QueryLayer` (unchanged, still current) | `obikindex::query_layer` (moved crates since this was written — see "Major restructuring") | one layer, `(MphfLayer, PersistentBitMatrix\|PersistentCompactIntMatrix)` pair, bypasses `TypedLayer<D>`/`Layer` entirely | **no** — opened fresh inside `query_partition_with` on every call | | `QueryLayer` (unchanged, still current) | `obikindex::query_layer` (moved crates since this was written — see "Major restructuring") | one layer, `(MphfLayer, PersistentBitMatrix\|PersistentCompactIntMatrix)` pair, bypasses `TypedLayer<D>`/`Layer` entirely | **no** — opened fresh inside `query_partition_with` on every call |
`query_partition_with` is `obikmer query`'s normal query path — the one `query_partition_with` is `obiskim query`'s normal query path — the one
most exposed to repeated cross-partition lookups — and it is still the one most exposed to repeated cross-partition lookups — and it is still the one
with no cache at all. `obikphylo` built a cache first only because with no cache at all. `obikphylo` built a cache first only because
sibling-annex construction hits the cost hardest, not because the need is sibling-annex construction hits the cost hardest, not because the need is
@@ -1605,7 +1605,7 @@ above). Concretely, in order:
`Vec<KmerPartition>` instead of `Vec<Vec<Layer>>`. `Vec<KmerPartition>` instead of `Vec<Vec<Layer>>`.
4. Migrate `obikindex::query_layer::QueryLayer`/`query_partition_with` to 4. Migrate `obikindex::query_layer::QueryLayer`/`query_partition_with` to
use `KmerPartition` too, closing the "no cache at all" gap on use `KmerPartition` too, closing the "no cache at all" gap on
`obikmer`'s normal query path (see "Three independent implementations," `obiskim`'s normal query path (see "Three independent implementations,"
historical, above). historical, above).
Open before implementing: exact API shape of `KmerPartition` (propose, Open before implementing: exact API shape of `KmerPartition` (propose,
@@ -1690,7 +1690,7 @@ storage decisions, now a *third* copy of the same logic to keep in sync)
## One bug found while reading around this (signalled, not fixed); one earlier claim retracted ## One bug found while reading around this (signalled, not fixed); one earlier claim retracted
- `obicompactvec::bitmatrix::sparse.rs`'s module doc says - `obicompactvec::bitmatrix::sparse.rs`'s module doc says
"Not used by any production code path yet" — false since `obikmer pack "Not used by any production code path yet" — false since `obiskim pack
--sparse` (`cmd/pack/mod.rs`) is wired to `pack_sparse_bit_matrix` and --sparse` (`cmd/pack/mod.rs`) is wired to `pack_sparse_bit_matrix` and
`Mat::open` already reads the result back in the sibling-annex path. `Mat::open` already reads the result back in the sibling-annex path.
Stale comment, not corrected. Stale comment, not corrected.
+2 -2
View File
@@ -8,8 +8,8 @@ The construction parameters p, n, and min_count depend on the kmer frequency spe
Two approaches are supported: Two approaches are supported:
- **External estimation (preferred):** run [NT-CARD](https://github.com/bcgsc/ntCard) on the input files and pass its histogram output to `obikmer build`. NT-CARD produces a kmer frequency histogram in a single streaming pass using ntHash and a Flajolet-Martin-style estimator; obikmer reads this file and derives p, n, and min_count automatically. - **External estimation (preferred):** run [NT-CARD](https://github.com/bcgsc/ntCard) on the input files and pass its histogram output to `obiskim build`. NT-CARD produces a kmer frequency histogram in a single streaming pass using ntHash and a Flajolet-Martin-style estimator; obiskim reads this file and derives p, n, and min_count automatically.
- **Internal estimation (future):** an `obikmer estimate` subcommand for users who prefer a single-tool workflow. The implementation would combine two components: (1) **ntHash**, a rolling hash that updates the kmer hash in O(1) per nucleotide by incrementally adding the incoming base and removing the outgoing one — Rust crates exist; (2) a **Flajolet-Martin-style streaming estimator** that maintains a small table of minimum hash values and infers the frequency histogram from their statistical distribution, as described in the NT-CARD paper [@Mohamadi2017-ok]. - **Internal estimation (future):** an `obiskim estimate` subcommand for users who prefer a single-tool workflow. The implementation would combine two components: (1) **ntHash**, a rolling hash that updates the kmer hash in O(1) per nucleotide by incrementally adding the incoming base and removing the outgoing one — Rust crates exist; (2) a **Flajolet-Martin-style streaming estimator** that maintains a small table of minimum hash values and infers the frequency histogram from their statistical distribution, as described in the NT-CARD paper [@Mohamadi2017-ok].
The histogram gives: The histogram gives:
+7 -7
View File
@@ -22,7 +22,7 @@ are preserved unchanged; only the data matrices are rewritten.
## Synopsis ## Synopsis
```sh ```sh
obikmer select <input-index> obiskim select <input-index>
--output <dir> --output <dir>
[--group <name>:<pred> ...] [--group <name>:<pred> ...]
[--group-op <name>:<op> ...] [--group-op <name>:<op> ...]
@@ -165,14 +165,14 @@ is > N.
### Aggregate by metadata group, default operators ### Aggregate by metadata group, default operators
```sh ```sh
obikmer select myindex --output out --aggregate-by group obiskim select myindex --output out --aggregate-by group
# one column per unique value of "group"; presence→any, count→sum # one column per unique value of "group"; presence→any, count→sum
``` ```
### Named groups with different operators ### Named groups with different operators
```sh ```sh
obikmer select myindex --output out \ obiskim select myindex --output out \
--group "pub:species=Betula_pubescens" \ --group "pub:species=Betula_pubescens" \
--group "nan:species=Betula_nana" \ --group "nan:species=Betula_nana" \
--group-op "pub:any" \ --group-op "pub:any" \
@@ -183,7 +183,7 @@ obikmer select myindex --output out \
### Mix aggregated group and individual genome ### Mix aggregated group and individual genome
```sh ```sh
obikmer select myindex --output out \ obiskim select myindex --output out \
--group "A:group=A" \ --group "A:group=A" \
--select "A,Betula_nana--IGA-24-39" --select "A,Betula_nana--IGA-24-39"
``` ```
@@ -191,7 +191,7 @@ obikmer select myindex --output out \
### Pure column projection (no aggregation) ### Pure column projection (no aggregation)
```sh ```sh
obikmer select myindex --output out \ obiskim select myindex --output out \
--select "Betula_nana--TROM-V-149986,Betula_nana--AG-P04-25-01" --select "Betula_nana--TROM-V-149986,Betula_nana--AG-P04-25-01"
``` ```
@@ -199,11 +199,11 @@ obikmer select myindex --output out \
```sh ```sh
# Step 1: keep only B. nana-specific k-mers # Step 1: keep only B. nana-specific k-mers
obikmer filter myindex --output filtered \ obiskim filter myindex --output filtered \
--ingroup "species=Betula_nana" --outgroup "*" --ingroup "species=Betula_nana" --outgroup "*"
# Step 2: aggregate genome columns by collection site # Step 2: aggregate genome columns by collection site
obikmer select filtered --output final --aggregate-by site obiskim select filtered --output final --aggregate-by site
``` ```
--- ---
+2 -2
View File
@@ -1,6 +1,6 @@
# obikmer # obiskim
`obikmer` is a Rust tool for manipulation, counting, indexing, and set operations on DNA sequences represented as kmer sets. `obiskim` is a Rust tool for manipulation, counting, indexing, and set operations on DNA sequences represented as kmer sets.
## Subcommands ## Subcommands
+2 -2
View File
@@ -3,8 +3,8 @@
## Code couvert ## Code couvert
- `obikmer/src/main.rs` — point d'entrée CLI, contraintes globales - `obiskim/src/main.rs` — point d'entrée CLI, contraintes globales
- `obikmer/src/cli.rs` — structure des arguments communs - `obiskim/src/cli.rs` — structure des arguments communs
## Notes ## Notes
+6 -6
View File
@@ -4,7 +4,7 @@
### Rust toolchain ### Rust toolchain
`obikmer` requires **Rust 1.85 or later** (edition 2024). Install or update via [rustup](https://rustup.rs): `obiskim` requires **Rust 1.85 or later** (edition 2024). Install or update via [rustup](https://rustup.rs):
```bash ```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
@@ -13,7 +13,7 @@ rustup update stable
### C build environment (required for hwloc) ### C build environment (required for hwloc)
`obikmer` embeds [hwloc](https://www.open-mpi.org/projects/hwloc/) (Hardware Locality) for NUMA-aware thread placement on multi-socket machines. hwloc is built from source at compile time via the `vendored` feature of the `hwlocality` crate. This requires a standard C build environment. `obiskim` embeds [hwloc](https://www.open-mpi.org/projects/hwloc/) (Hardware Locality) for NUMA-aware thread placement on multi-socket machines. hwloc is built from source at compile time via the `vendored` feature of the `hwlocality` crate. This requires a standard C build environment.
#### Linux (Debian/Ubuntu) #### Linux (Debian/Ubuntu)
@@ -47,11 +47,11 @@ brew install automake libtool autoconf pkg-config
```bash ```bash
git clone <repository-url> git clone <repository-url>
cd obikmer/src cd obiskim/src
cargo build --release cargo build --release
``` ```
The compiled binary is at `target/release/obikmer`. The compiled binary is at `target/release/obiskim`.
### Building on HPC clusters (network filesystems) ### Building on HPC clusters (network filesystems)
@@ -66,7 +66,7 @@ CARGO_TARGET_DIR=/scratch/$USER/cargo-target cargo build --release
Adapt the path to the local scratch available on your cluster (`/var/tmp`, `/tmp`, `/scratch/local`, etc.). Once built, copy the binary to a permanent location: Adapt the path to the local scratch available on your cluster (`/var/tmp`, `/tmp`, `/scratch/local`, etc.). Once built, copy the binary to a permanent location:
```bash ```bash
cp /scratch/$USER/cargo-target/release/obikmer ~/bin/ cp /scratch/$USER/cargo-target/release/obiskim ~/bin/
``` ```
## NUMA support ## NUMA support
@@ -80,5 +80,5 @@ NUMA-aware thread placement is active automatically on multi-socket Linux machin
## Verifying the installation ## Verifying the installation
```bash ```bash
obikmer --help obiskim --help
``` ```
+1 -1
View File
@@ -13,4 +13,4 @@
Le repli en classes d'équivalence circulaires + brin inverse (décrit dans une version antérieure de ce document) a été supprimé : voir la section « Why no equivalence classes » de `entropy.md` pour la justification théorique et numérique. Le repli en classes d'équivalence circulaires + brin inverse (décrit dans une version antérieure de ce document) a été supprimé : voir la section « Why no equivalence classes » de `entropy.md` pour la justification théorique et numérique.
Vérifier que les paramètres `theta` et `level_max` dans le CLI Vérifier que les paramètres `theta` et `level_max` dans le CLI
(`obikmer/src/cli.rs` → `CommonArgs`) correspondent bien à ce qui est décrit. (`obiskim/src/cli.rs` → `CommonArgs`) correspondent bien à ce qui est décrit.
+26 -26
View File
@@ -205,7 +205,7 @@ single-copy at that locus.
## Context, detectability, and a 3-way ordinal distance per pair ## Context, detectability, and a 3-way ordinal distance per pair
Empirical follow-up to the pseudo-alignment idea above: `obikmer phylo Empirical follow-up to the pseudo-alignment idea above: `obiskim phylo
--snp` was run on a real 20-genome benchmark index and the resulting FASTA --snp` was run on a real 20-genome benchmark index and the resulting FASTA
fed to `raxml-ng`. Two problems surfaced, both traced back to conflating fed to `raxml-ng`. Two problems surfaced, both traced back to conflating
distinct notions under one symbol. distinct notions under one symbol.
@@ -552,7 +552,7 @@ informative across domains with this character type. Exploratory only —
run entirely outside the repo (`/tmp/tnt_run`, TNT installed locally under run entirely outside the repo (`/tmp/tnt_run`, TNT installed locally under
`TNT/`), no new Rust code. Kept here as the record of what was learned. `TNT/`), no new Rust code. Kept here as the record of what was learned.
**Pipeline.** `obikmer phylo --snp` emits one IUPAC-coded pseudo-alignment **Pipeline.** `obiskim phylo --snp` emits one IUPAC-coded pseudo-alignment
row per genome (`snp_pseudo_alignment`, one column per family with row per genome (`snp_pseudo_alignment`, one column per family with
`family_size() >= 2`). A small external Python script decodes IUPAC back to `family_size() >= 2`). A small external Python script decodes IUPAC back to
the 16-state bitmask, applies the set-edit-distance formula above, and the 16-state bitmask, applies the set-edit-distance formula above, and
@@ -622,7 +622,7 @@ estimator.
### Native `--sankoff --tnt`/`--phyg` export (2026-08-12), superseding the external scripts above ### Native `--sankoff --tnt`/`--phyg` export (2026-08-12), superseding the external scripts above
The ad hoc Python glue from the previous section is superseded: `obikmer The ad hoc Python glue from the previous section is superseded: `obiskim
distance --sankoff` now calibrates the matrix natively (`p_hat`, 6-category distance --sankoff` now calibrates the matrix natively (`p_hat`, 6-category
substitution costs, `c_ctx` weighted by `mean_sub_cost` — see the worked substitution costs, `c_ctx` weighted by `mean_sub_cost` — see the worked
example above) and `--tnt`/`--phyg` each write a ready-to-run script from example above) and `--tnt`/`--phyg` each write a ready-to-run script from
@@ -630,7 +630,7 @@ it, no external script needed. `∅` is an ordinary 16th state throughout
(never `-`), specifically to avoid gap-semantics confusion in downstream (never `-`), specifically to avoid gap-semantics confusion in downstream
tools — see "A concrete Sankoff cost matrix" above for why. tools — see "A concrete Sankoff cost matrix" above for why.
**TNT (`--tnt`).** `write_sankoff_tnt` (`obikmer/src/cmd/phylo/mod.rs`) **TNT (`--tnt`).** `write_sankoff_tnt` (`obiskim/src/cmd/phylo/mod.rs`)
recodes to TNT's own `0-9A-F` xread alphabet (its default reader rejects recodes to TNT's own `0-9A-F` xread alphabet (its default reader rejects
the wider IUPAC set otherwise), scales and rounds costs to integers the wider IUPAC set otherwise), scales and rounds costs to integers
(`smatrix`/`cost` reject decimals), then re-runs integer Floyd-Warshall on (`smatrix`/`cost` reject decimals), then re-runs integer Floyd-Warshall on
@@ -767,7 +767,7 @@ from the alignment") does **not** work as a shortcut for this — for a
custom-file morphology model, `readParameters` always requires the file's custom-file morphology model, `readParameters` always requires the file's
own frequency line unconditionally; omitting it and passing `+F` instead own frequency line unconditionally; omitting it and passing `+F` instead
just fails (`ERROR: State frequencies could not be read`). `π` has to be just fails (`ERROR: State frequencies could not be read`). `π` has to be
computed by `obikmer` and written into the file, not left to IQ-TREE. computed by `obiskim` and written into the file, not left to IQ-TREE.
Net effect: no free-rate ML estimation needed for this piece at all (the Net effect: no free-rate ML estimation needed for this piece at all (the
mistaken assumption that motivated most of this discussion — that mistaken assumption that motivated most of this discussion — that
@@ -843,12 +843,12 @@ with no error to catch it. **Checked against the real biological alignment**
symbol `N` (IUPAC "all four bases ambiguous," state index 15) occurs 1383 symbol `N` (IUPAC "all four bases ambiguous," state index 15) occurs 1383
times across 13 of the 20 sequences — present, so this specific real times across 13 of the 20 sequences — present, so this specific real
dataset is not at risk. Still worth a real, general presence check inside dataset is not at risk. Still worth a real, general presence check inside
`obikmer` before this is wired in, rather than assuming every future `obiskim` before this is wired in, rather than assuming every future
dataset will have `N` too (nothing in IQ-TREE would catch it if not). dataset will have `N` too (nothing in IQ-TREE would catch it if not).
**Resolution: subset + compact-renumber, not rely on all 16 appearing.** **Resolution: subset + compact-renumber, not rely on all 16 appearing.**
Since IQ-TREE always infers `N` from the alignment's own content and Since IQ-TREE always infers `N` from the alignment's own content and
nothing overrides that, the fix is to make the file `obikmer` writes match nothing overrides that, the fix is to make the file `obiskim` writes match
that inference *by construction*, for every run, rather than hope the that inference *by construction*, for every run, rather than hope the
16th (or any particular) state happens to occur: 16th (or any particular) state happens to occur:
1. Scan the real alignment for which of the 16 canonical states actually 1. Scan the real alignment for which of the 16 canonical states actually
@@ -902,7 +902,7 @@ sections below, which implement and then substantially revise this.
### `R`/`π` implemented; `--exclude-genome` added; rogue-taxon test negative (2026-08-12) ### `R`/`π` implemented; `--exclude-genome` added; rogue-taxon test negative (2026-08-12)
`write_iqtree` (`obikmer/src/cmd/phylo/iqtree.rs`) implements exactly `write_iqtree` (`obiskim/src/cmd/phylo/iqtree.rs`) implements exactly
the `R = exp(-cost)` / empirical-`π` design above: writes the `R = exp(-cost)` / empirical-`π` design above: writes
`<prefix>_iqtree.model` (lower-triangular `R`, PAML order, then `π`) and `<prefix>_iqtree.model` (lower-triangular `R`, PAML order, then `π`) and
`<prefix>_iqtree.fasta` (alignment recoded to the compact `0..k-1` `<prefix>_iqtree.fasta` (alignment recoded to the compact `0..k-1`
@@ -949,7 +949,7 @@ tell: with `n_eligible=1`, the ratio can only be exactly `0` or `1`, so
possibly ascertainment bias — see below — or possibly a few genuinely possibly ascertainment bias — see below — or possibly a few genuinely
ultra-conserved loci; not resolved). ultra-conserved loci; not resolved).
**`--exclude-genome LABEL`** (repeatable, `obikmer phylo`) added for **`--exclude-genome LABEL`** (repeatable, `obiskim phylo`) added for
exactly this kind of test: zeroes the excluded genome's row/column in exactly this kind of test: zeroes the excluded genome's row/column in
`RawSnpDistanceOutput` after `raw_snp_distance` runs (a pair with zero `RawSnpDistanceOutput` after `raw_snp_distance` runs (a pair with zero
counts is already skipped by `calibrate_p_hat`/`base_pair_tally` — no counts is already skipped by `calibrate_p_hat`/`base_pair_tally` — no
@@ -1165,7 +1165,7 @@ silently wrong data for TNT/PhyG, and a hard failure for IQ-TREE's `+ASC`
(verified: excluding 2 taxa on the benchmark left 116,351 such columns — (verified: excluding 2 taxa on the benchmark left 116,351 such columns —
matches the manual `+ASC` failures hit earlier in this same investigation, matches the manual `+ASC` failures hit earlier in this same investigation,
before `--exclude-genome` existed). Fixed in `drop_excluded` before `--exclude-genome` existed). Fixed in `drop_excluded`
(`obikmer/src/cmd/phylo/mod.rs`): after dropping excluded rows, (`obiskim/src/cmd/phylo/mod.rs`): after dropping excluded rows,
re-scan each column among the *surviving* sequences and drop any that are re-scan each column among the *surviving* sequences and drop any that are
now constant. Verified: 908,723 → 792,372 sites after excluding 2 taxa, now constant. Verified: 908,723 → 792,372 sites after excluding 2 taxa,
zero monomorphic columns remain, `π` recomputed from the corrected zero monomorphic columns remain, `π` recomputed from the corrected
@@ -1465,7 +1465,7 @@ Two helpers do not yet exist and are prerequisites:
takes the min by `seq_hash()` — the same selection `RollingStat` performs, takes the min by `seq_hash()` — the same selection `RollingStat` performs,
evaluated once. Partition index is then evaluated once. Partition index is then
`(minimizer.seq_hash() & (n_partitions - 1)) as usize`, exactly as `(minimizer.seq_hash() & (n_partitions - 1)) as usize`, exactly as
`QueryBatch::from_records` (`obikmer/src/cmd/query.rs:142`); `n_partitions` `QueryBatch::from_records` (`obiskim/src/cmd/query.rs:142`); `n_partitions`
is a power of two so the mask is valid. is a power of two so the mask is valid.
### Step 1 — the tally accumulator (`obikindex`) ### Step 1 — the tally accumulator (`obikindex`)
@@ -1586,7 +1586,7 @@ ever queries. Instead: compute it lazily, on first `phylo` call against a
given index, and persist the result alongside that index for subsequent given index, and persist the result alongside that index for subsequent
calls — the same lazy-derived-cache pattern `PersistentBitMatrix` already calls — the same lazy-derived-cache pattern `PersistentBitMatrix` already
uses for `Columnar` -> `Packed`. This requires no explicit invalidation for uses for `Columnar` -> `Packed`. This requires no explicit invalidation for
`merge` or `filter` (`obikindex/src/merge.rs`, `obikmer/src/cmd/filter.rs`): `merge` or `filter` (`obikindex/src/merge.rs`, `obiskim/src/cmd/filter.rs`):
both only ever write to a fresh `--output` directory, never mutate an input both only ever write to a fresh `--output` directory, never mutate an input
index in place, so a re-merged/re-filtered index is simply a new state with index in place, so a re-merged/re-filtered index is simply a new state with
no annex yet. `select --in-place` (`select_layer.rs:139-235`) is the no annex yet. `select --in-place` (`select_layer.rs:139-235`) is the
@@ -1778,7 +1778,7 @@ above) is observed anywhere in the index — fixes both:
`bitmatrix.rs:264-287`); if absent, run step 3 and persist; if present, `bitmatrix.rs:264-287`); if absent, run step 3 and persist; if present,
mmap and reuse. mmap and reuse.
5. **Invalidation.** `merge` and `filter` always write to a fresh `--output` 5. **Invalidation.** `merge` and `filter` always write to a fresh `--output`
directory (`obikindex/src/merge.rs`, `obikmer/src/cmd/filter.rs`) so a directory (`obikindex/src/merge.rs`, `obiskim/src/cmd/filter.rs`) so a
re-merged/re-filtered index simply has no annex yet — nothing to re-merged/re-filtered index simply has no annex yet — nothing to
invalidate. `select --in-place` (`select_layer.rs:139-235`) mutates invalidate. `select --in-place` (`select_layer.rs:139-235`) mutates
columns of an existing index without changing its location, which can columns of an existing index without changing its location, which can
@@ -1810,7 +1810,7 @@ accumulated counts (same shape as `jaccard_to_mash`):
Guard the singularities (`p >= 3/4` for JC, `1-2P-Q <= 0` or `1-2Q <= 0` for Guard the singularities (`p >= 3/4` for JC, `1-2P-Q <= 0` or `1-2Q <= 0` for
K2P) by clamping to a max distance, as `jaccard_to_mash` clamps `J <= 0`. K2P) by clamping to a max distance, as `jaccard_to_mash` clamps `J <= 0`.
### Step 4 — surfacing (`obikindex` + `obikmer` CLI) ### Step 4 — surfacing (`obikindex` + `obiskim` CLI)
These metrics do not fit `DistanceMetric`'s current `LayeredStore`-partial These metrics do not fit `DistanceMetric`'s current `LayeredStore`-partial
dispatch (they need the cross-partition sweep and produce a different dispatch (they need the cross-partition sweep and produce a different
@@ -1853,7 +1853,7 @@ lookups proportionally; `p_hat` is unbiased. Off by default (exact).
1. Step 0 primitives + their unit tests (self-contained, no distance wiring). 1. Step 0 primitives + their unit tests (self-contained, no distance wiring).
This also unblocks the long-declared-but-unimplemented `query --mismatch` This also unblocks the long-declared-but-unimplemented `query --mismatch`
(`obikmer/src/cmd/query.rs:676`, currently a warning), which needs the same (`obiskim/src/cmd/query.rs:676`, currently a warning), which needs the same
neighbour + routing machinery. neighbour + routing machinery.
2. `SnpTally` + finalisation math with a brute-force (non-swept) reference 2. `SnpTally` + finalisation math with a brute-force (non-swept) reference
backend, validated on a tiny index. backend, validated on a tiny index.
@@ -1905,7 +1905,7 @@ correctness problem rather than a power problem. Not designed yet.
### `--free-loss` implemented (2026-08-13) ### `--free-loss` implemented (2026-08-13)
`obikmer phylo --sankoff --free-loss` (with `--tnt`/`--phyg`/`--iqtree`) `obiskim phylo --sankoff --free-loss` (with `--tnt`/`--phyg`/`--iqtree`)
recodes `∅` (a family's non-detection in a genome) to `?` instead of the recodes `∅` (a family's non-detection in a genome) to `?` instead of the
default ordinary, costed 16th state — the resolution of the discussion default ordinary, costed 16th state — the resolution of the discussion
above. `?`, not `-`: `-` still carries gap/indel semantics in TNT/PhyG/ above. `?`, not `-`: `-` still carries gap/indel semantics in TNT/PhyG/
@@ -1988,7 +1988,7 @@ filtered alignment — next verification step, alongside the still-open PhyG
**Diagnostic added: `--family-overlap`.** Real per-genome-pair count of **Diagnostic added: `--family-overlap`.** Real per-genome-pair count of
shared variable families (columns where neither genome is `∅`), diagonal shared variable families (columns where neither genome is `∅`), diagonal
kept (degenerates to "genome's own total family count", not a separate kept (degenerates to "genome's own total family count", not a separate
computation — see `obikmer/src/cmd/phylo/family_overlap.rs`). On the computation — see `obiskim/src/cmd/phylo/family_overlap.rs`). On the
20-genome benchmark this predicted the `--tnt`/`--iqtree` rogue-placement 20-genome benchmark this predicted the `--tnt`/`--iqtree` rogue-placement
pattern exactly: Candidozyma shares **0** families with all 19 others (hence pattern exactly: Candidozyma shares **0** families with all 19 others (hence
its ~0-length branch, placed anywhere); the mean off-diagonal shared-family its ~0-length branch, placed anywhere); the mean off-diagonal shared-family
@@ -2052,7 +2052,7 @@ it stores) from a run on one taxon set against a regenerated `iqtree.fasta`
with a different taxon count crashes with `Assertion 'i >= 0 && i < with a different taxon count crashes with `Assertion 'i >= 0 && i <
(int)seq_names.size()' failed` in `Alignment::getSeqName` / (int)seq_names.size()' failed` in `Alignment::getSeqName` /
`PhyloTree::assignLeafNames` — `--undo` tries to graft a stored tree with `PhyloTree::assignLeafNames` — `--undo` tries to graft a stored tree with
the old leaf count onto the new, smaller alignment. Not an `obikmer` bug; the old leaf count onto the new, smaller alignment. Not an `obiskim` bug;
avoid by using a fresh `--prefix` (or `-redo`) whenever the underlying avoid by using a fresh `--prefix` (or `-redo`) whenever the underlying
alignment's taxon set changes, never `--undo` across them. alignment's taxon set changes, never `--undo` across them.
@@ -2060,7 +2060,7 @@ alignment's taxon set changes, never `--undo` across them.
User-reported suspicion: `--iqtree --free-loss` state frequencies "don't User-reported suspicion: `--iqtree --free-loss` state frequencies "don't
sum to 1". Verified both by code trace and unit test sum to 1". Verified both by code trace and unit test
(`obikmer/src/cmd/phylo/iqtree.rs`, `free_loss_excludes_absent_state_and_freq_sums_to_one`) (`obiskim/src/cmd/phylo/iqtree.rs`, `free_loss_excludes_absent_state_and_freq_sums_to_one`)
— **not a bug**: `compact_alphabet`'s counting loop `continue`s on — **not a bug**: `compact_alphabet`'s counting loop `continue`s on
`free_loss && b == b'-'` *before* recoding/counting, so the absent state `free_loss && b == b'-'` *before* recoding/counting, so the absent state
never enters `occurs`/`counts`, and `freq[i] = counts[old]/total` sums to never enters `occurs`/`counts`, and `freq[i] = counts[old]/total` sums to
@@ -2152,7 +2152,7 @@ observed central bases across genomes is far more likely to be
assembly/detection noise than a genuinely ancestral, widely-preserved assembly/detection noise than a genuinely ancestral, widely-preserved
polymorphism, the same reasoning already used for `-`. polymorphism, the same reasoning already used for `-`.
**Mechanism** (`obikmer/src/cmd/phylo/iqtree.rs`, `write_iqtree`): a **Mechanism** (`obiskim/src/cmd/phylo/iqtree.rs`, `write_iqtree`): a
*second* filtering pass, active only under `--free-loss`. After the first *second* filtering pass, active only under `--free-loss`. After the first
`compact_alphabet` call (post ascertainment-filtering), any state with `compact_alphabet` call (post ascertainment-filtering), any state with
`freq < --iqtree-min-freq` (default `0.001`) has every occurrence recoded `freq < --iqtree-min-freq` (default `0.001`) has every occurrence recoded
@@ -2588,7 +2588,7 @@ generally (the same mechanism as `corrected_log`, not a coincidence — Jin &
Nei's own formula is the `θ=0` special case applied to a pairwise `D` Nei's own formula is the `θ=0` special case applied to a pairwise `D`
rather than a whole-tree one). Explicitly stated by the authors as rather than a whole-tree one). Explicitly stated by the authors as
infeasible beyond about 5–6 taxa (their own simulations stop at 5); not a infeasible beyond about 5–6 taxa (their own simulations stop at 5); not a
candidate for obikmer's typical genome counts. Notable contribution worth candidate for obiskim's typical genome counts. Notable contribution worth
keeping in mind regardless: `ρ = (1+θα)/(1+α)` is shown to be a more robust keeping in mind regardless: `ρ = (1+θα)/(1+α)` is shown to be a more robust
summary of rate heterogeneity than `α` alone whenever `θ` isn't negligible summary of rate heterogeneity than `α` alone whenever `θ` isn't negligible
— `α` and `θ` are confounded (nearly-invariant sites can come from either a — `α` and `θ` are confounded (nearly-invariant sites can come from either a
@@ -2610,7 +2610,7 @@ not a closed form; (4) the site-level `k̂` values (real-valued, not
integers) are fit to a negative binomial (Uzzell & Corbin 1971) by ML to integers) are fit to a negative binomial (Uzzell & Corbin 1971) by ML to
get α — again no closed form, numerical optimization. This is a real get α — again no closed form, numerical optimization. This is a real
per-site pipeline requiring a tree *before* distances/α can be computed — per-site pipeline requiring a tree *before* distances/α can be computed —
the reverse of obikmer's current dependency order (`snp_distance` computes the reverse of obiskim's current dependency order (`snp_distance` computes
distances, which `--nj`/`--upgma` only turn into a tree *afterward*). Their distances, which `--nj`/`--upgma` only turn into a tree *afterward*). Their
own answer to this chicken-and-egg problem is an iterative own answer to this chicken-and-egg problem is an iterative
distance→tree→α→distance loop, which they themselves flag as expensive. distance→tree→α→distance loop, which they themselves flag as expensive.
@@ -2679,7 +2679,7 @@ proper is judged not worth the effort).
**Correctness bug, not just a performance one.** `--sankoff`/`--tnt`/`--phyg`/ **Correctness bug, not just a performance one.** `--sankoff`/`--tnt`/`--phyg`/
`--iqtree` (via `SiblingExt::sankoff_bundle`) and a `snp-*` `--distance` `--iqtree` (via `SiblingExt::sankoff_bundle`) and a `snp-*` `--distance`
(via `SiblingExt::snp_distance`) always consume the *exact same* selection (via `SiblingExt::snp_distance`) always consume the *exact same* selection
parameters when requested together in one `obikmer phylo` invocation parameters when requested together in one `obiskim phylo` invocation
(`n`/`free_loss`/`no_ambiguity`/excluded-set/`entropy_bias` — the CLI has (`n`/`free_loss`/`no_ambiguity`/excluded-set/`entropy_bias` — the CLI has
no way to give them different values in one run, see `cmd/phylo/args.rs`). no way to give them different values in one run, see `cmd/phylo/args.rs`).
Before this fix, each independently called `sample_index`, and Before this fix, each independently called `sample_index`, and
@@ -2721,7 +2721,7 @@ The in-process fix above only covered reuse *within one command*.
`--session DIR` (`cmd/phylo/args.rs`) names a directory (outside the `--session DIR` (`cmd/phylo/args.rs`) names a directory (outside the
index) that persists the `snp-*` `--distance` sample — the index) that persists the `snp-*` `--distance` sample — the
`PairwiseTally`/`PartitionDispersion` pair `sample_index` would otherwise `PairwiseTally`/`PartitionDispersion` pair `sample_index` would otherwise
rebuild from scratch — across *separate* `obikmer phylo` invocations. rebuild from scratch — across *separate* `obiskim phylo` invocations.
**Crate placement, as planned**: a new **`obiksession`** crate **Crate placement, as planned**: a new **`obiksession`** crate
(`src/obiksession/`), domain-agnostic — no `PairwiseTally`/"site" concept (`src/obiksession/`), domain-agnostic — no `PairwiseTally`/"site" concept
@@ -2878,7 +2878,7 @@ their existing CSV-only format.
`phylo --vcf` writes the drawn sites of `--pseudo-alignment` as a VCF `phylo --vcf` writes the drawn sites of `--pseudo-alignment` as a VCF
(`--fasta`/`--vcf` choose the formats, FASTA is the default, both can be (`--fasta`/`--vcf` choose the formats, FASTA is the default, both can be
combined). A family has no genomic coordinate, so coordinates are virtual and combined). A family has no genomic coordinate, so coordinates are virtual and
derived from where the scan finds the family: `CHROM = obikmer_<partition>_<layer>`, derived from where the scan finds the family: `CHROM = obiskim_<partition>_<layer>`,
`POS = family_idx + 1` (`scan_layer_families`' iteration-order index inside `POS = family_idx + 1` (`scan_layer_families`' iteration-order index inside
that layer). Stable for a given index + annex, sorted by construction because that layer). Stable for a given index + annex, sorted by construction because
`on_family` is replayed in `family_idx` order. A global dense rank or a bit `on_family` is replayed in `family_idx` order. A global dense rank or a bit
@@ -2920,7 +2920,7 @@ Checked with `bcftools view`/`stats` and `tabix`: no warning, the sites with
majority base (alphabetical on ties). majority base (alphabetical on ties).
Ploidy. VCF allows any ploidy in `GT` (number of alleles written, variable Ploidy. VCF allows any ploidy in `GT` (number of alleles written, variable
per sample/site), but an obikmer cell only says *which* forms a genome per sample/site), but an obiskim cell only says *which* forms a genome
carries, not their multiplicity (`A/A/G` and `A/G/G` are both `R`), nor carries, not their multiplicity (`A/A/G` and `A/G/G` are both `R`), nor
whether several forms mean heterozygosity or paralogues. Compromise chosen: whether several forms mean heterozygosity or paralogues. Compromise chosen:
`--no-ambiguity` => haploid (ambiguous cells are already `?`); otherwise `--no-ambiguity` => haploid (ambiguous cells are already `?`); otherwise
+1 -1
View File
@@ -9,4 +9,4 @@
## Notes ## Notes
Vérifier que la doc mentionne bien que le nombre de partitions est une puissance de 2 Vérifier que la doc mentionne bien que le nombre de partitions est une puissance de 2
(converti par `partitions_to_bits` dans `obikmer/src/cli.rs`). (converti par `partitions_to_bits` dans `obiskim/src/cli.rs`).
@@ -51,7 +51,7 @@ Structural tension: path coherence (long unitigs) needs a key shared by consecut
## Open measurements (index not on this machine) ## Open measurements (index not on this machine)
1. Family-size histogram of the real index: `obikmer phylo --sibling-hist` (needs a built annex). 1. Family-size histogram of the real index: `obiskim phylo --sibling-hist` (needs a built annex).
2. Time and peak RSS of `--sibling-annex` on the Vaccinium/Salix index (`Stage` "sibling_annex" traces time; peak RSS from outside). 2. Time and peak RSS of `--sibling-annex` on the Vaccinium/Salix index (`Stage` "sibling_annex" traces time; peak RSS from outside).
3. Only if those show the sequential sweep or the probe volume is a real bottleneck: real-index test of scheme B or of a smaller $m$. 3. Only if those show the sequential sweep or the probe volume is a real bottleneck: real-index test of scheme B or of a smaller $m$.
+27
View File
@@ -0,0 +1,27 @@
# Release Notes for obiskim (Rust k-mer genomics tool), version 1.4.9
## Project Rename
- Renamed project, binary, crate, and all associated documentation, scripts, and configuration files from `obikmer` to `obiskim`.
- Updated lock files (`.obiskim.lock`, `.obiskim.gate`, `.obiskim.promote`) and VCF contig IDs (`obiskim_<partition>_<layer>`).
- Updated all references in source code, build scripts, CI workflows, and user documentation.
## Features
- **Sparse Matrix Support**: Added `Sparse` variants for `PersistentBitMatrix` and `PersistentIntMatrix` with auto-detection and migration logic for stale columnar formats.
- **Compact Vector Library**: Added support for sparse bit matrices, overflow handling, and a `transpose` module. Updated distance metrics (Jaccard, Bray, Euclidean) to accept explicit sums and thresholds.
- **Phylogenetic Algorithms**: Overhauled distance metrics to support ambiguity policies and quartet conventions. Added `sample_stats` and `subsample` modules.
- **Filtering**: Added `MinComplexity` filter with explicit threshold checks for ingroup/outgroup counts.
- **I/O and Reading**: Added `text/gbff` MIME type support. Added `stream_iter` module for streaming superkmer iteration.
- **CLI and Tools**: Standardized error handling and argument parsing across CLI commands. Added `query` and `select` modules to `obiskim` CLI.
## Fixes and Improvements
- **Iteration and Arithmetic**: Modernized iteration patterns to use idiomatic Rust methods (`as_chunks`, `enumerate`, `iter`, `take`) and replaced manual ceiling division with `div_ceil`.
- **Error Handling**: Simplified error handling using `is_some_and`, `is_ok_and`, and `is_none_or`. Standardized error types with static context and string details.
- **Concurrency and State**: Refactored De Bruijn graph traversal to use atomic fetch-or for visited masks. Updated `PartitionRunner` to implement `Default`.
- **Validation**: Enforced odd k-mer and minimizer sizes in CLI validation.
- **Performance**: Optimized bit manipulation functions (`or_where`, `and_where`, `xor_where`) and buffer slicing using direct references and `as_chunks`.
## Internal
- **Build System**: Introduced `.crate-kit` infrastructure for standardized build, testing, and release workflows using Jujutsu and Cargo.
- **License**: Added CeCILL-2.1 license files and updated all workspace crate manifests with license and repository metadata.
- **Refactoring**: Removed `migrate-mphf` tool. Updated sibling annex handling. Refactored compact vector storage, phylo algorithms, and CLI interfaces for better modularity and explicit error signaling.
- **Dependencies**: Updated `criterion2` to version 3 with `cargo_bench_support` feature. Replaced "OnceLock-based params" feature with thread-local storage description in `obikseq`.
+2 -2
View File
@@ -32,8 +32,8 @@ Three verification modes exist. The exact and approximate modes are selected at
│ evidence mode, counts stored or not), genome list │ evidence mode, counts stored or not), genome list
│ and metadata, build state (empty, scattered, │ and metadata, build state (empty, scattered,
│ counted, indexed) │ counted, indexed)
├── 📄 .obikmer.lock lock files: commands that read the index share it, ├── 📄 .obiskim.lock lock files: commands that read the index share it,
├── 📄 .obikmer.gate commands that write into it hold it exclusively ├── 📄 .obiskim.gate commands that write into it hold it exclusively
├── 📁 spectrums/ ├── 📁 spectrums/
│ └── 📄 <label>.json per-genome kmer frequency histogram │ └── 📄 <label>.json per-genome kmer frequency histogram
└── 📁 partitions/ └── 📁 partitions/
+7 -7
View File
@@ -22,14 +22,14 @@ An illustrative excerpt (columns are tab-separated in the file):
``` ```
##fileformat=VCFv4.5 ##fileformat=VCFv4.5
##source=obikmer ##source=obiskim
##contig=<ID=obikmer_0_0> ##contig=<ID=obiskim_0_0>
##contig=<ID=obikmer_0_1> ##contig=<ID=obiskim_0_1>
##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype (diploid)"> ##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype (diploid)">
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT idx0 idx1 idx2 idx3 #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT idx0 idx1 idx2 idx3
obikmer_0_0 440 CGATTNGTTAA A G . . . GT 0/0 1/1 0/0 0/0 obiskim_0_0 440 CGATTNGTTAA A G . . . GT 0/0 1/1 0/0 0/0
obikmer_0_0 1511 CACGANTGTAG A G,T . . . GT 0/0 0/0 1/1 2/2 obiskim_0_0 1511 CACGANTGTAG A G,T . . . GT 0/0 0/0 1/1 2/2
obikmer_0_1 9 TTACGNAGCTA C * . . . GT 0/0 0/0 1/1 0/0 obiskim_0_1 9 TTACGNAGCTA C * . . . GT 0/0 0/0 1/1 0/0
``` ```
There is one sample column per genome that takes part in the draw, named after the genome label, in the index's own order. A genome removed with `--exclude-genome` or `--min-shared-family` has no column at all. `QUAL`, `FILTER` and `INFO` are always `.`: obiskim applies no variant filter and attaches no annotation, and leaving them empty keeps a file of millions of sites compact. There is one sample column per genome that takes part in the draw, named after the genome label, in the index's own order. A genome removed with `--exclude-genome` or `--min-shared-family` has no column at all. `QUAL`, `FILTER` and `INFO` are always `.`: obiskim applies no variant filter and attaches no annotation, and leaving them empty keeps a file of millions of sites compact.
@@ -38,7 +38,7 @@ There is one sample column per genome that takes part in the draw, named after t
An index is organised in partitions, and each partition holds one or more layers of k-mers (see [Index construction and on-disk layout](index_layout.md)). A family always belongs to exactly one layer of one partition, and the families of a layer are visited in a fixed order. The VCF uses that structure as coordinates: An index is organised in partitions, and each partition holds one or more layers of k-mers (see [Index construction and on-disk layout](index_layout.md)). A family always belongs to exactly one layer of one partition, and the families of a layer are visited in a fixed order. The VCF uses that structure as coordinates:
- `CHROM` is `obikmer_<partition>_<layer>`, one virtual contig per layer of each partition in which at least one site was drawn; - `CHROM` is `obiskim_<partition>_<layer>`, one virtual contig per layer of each partition in which at least one site was drawn;
- `POS` is the rank of the family inside that layer, starting at 1. - `POS` is the rank of the family inside that layer, starting at 1.
For a given index and a given sibling annex, a family therefore always receives the same `CHROM` and `POS`, whatever the draw, the options or the number of sites requested. Two runs on the same index can be compared position by position. This stability is lost if the sibling annex is rebuilt, or if the index is rebuilt, merged or filtered, because the families are then enumerated again. Positions are never comparable between two different indexes; use `ID` for that. Even rebuilding an index from the very same genomes may enumerate the families in another order: on a small test index built twice from identical input, the family `CGATTNGTTAA` had `POS` 440 the first time and 371 the second, with the same `ID`. For a given index and a given sibling annex, a family therefore always receives the same `CHROM` and `POS`, whatever the draw, the options or the number of sites requested. Two runs on the same index can be compared position by position. This stability is lost if the sibling annex is rebuilt, or if the index is rebuilt, merged or filtered, because the families are then enumerated again. Positions are never comparable between two different indexes; use `ID` for that. Even rebuilding an index from the very same genomes may enumerate the families in another order: on a small test index built twice from identical input, the family `CGATTNGTTAA` had `POS` 440 the first time and 371 the second, with the same `ID`.
+17 -17
View File
@@ -19,10 +19,10 @@ REF_DIST_CSVS := $(addprefix $(RUN)/reference_dist/, \
bray_curtis_dist.csv relfreq_bray_curtis_dist.csv \ bray_curtis_dist.csv relfreq_bray_curtis_dist.csv \
euclidean_dist.csv relfreq_euclidean_dist.csv \ euclidean_dist.csv relfreq_euclidean_dist.csv \
hellinger_dist.csv hellinger_euclidean_dist.csv) hellinger_dist.csv hellinger_euclidean_dist.csv)
OBIKMER_PRESENCE_DIST := $(addprefix $(RUN)/obikmer_dist/presence/, \ OBIKMER_PRESENCE_DIST := $(addprefix $(RUN)/obiskim_dist/presence/, \
jaccard_dist.csv jaccard_shared.csv jaccard_nj.nwk \ jaccard_dist.csv jaccard_shared.csv jaccard_nj.nwk \
hamming_dist.csv hamming_nj.nwk) hamming_dist.csv hamming_nj.nwk)
OBIKMER_COUNT_DIST := $(addprefix $(RUN)/obikmer_dist/count/, \ OBIKMER_COUNT_DIST := $(addprefix $(RUN)/obiskim_dist/count/, \
jaccard_dist.csv jaccard_shared.csv jaccard_nj.nwk \ jaccard_dist.csv jaccard_shared.csv jaccard_nj.nwk \
bray_curtis_dist.csv bray_curtis_nj.nwk \ bray_curtis_dist.csv bray_curtis_nj.nwk \
relfreq_bray_curtis_dist.csv relfreq_bray_curtis_nj.nwk \ relfreq_bray_curtis_dist.csv relfreq_bray_curtis_nj.nwk \
@@ -56,7 +56,7 @@ VERIFY_QUERY_STATS := $(QUERY_SPECIMENS:%=$(RUN)/stats/verify_query/%.stats)
.NOTPARALLEL: .NOTPARALLEL:
.PHONY: all simulate reference reference_dist \ .PHONY: all simulate reference reference_dist \
obikmer_dist obikmer_dist_presence obikmer_dist_count \ obiskim_dist obiskim_dist_presence obiskim_dist_count \
dist_comparison \ dist_comparison \
index_presence index_count \ index_presence index_count \
aggregate_index_presence aggregate_index_count \ aggregate_index_presence aggregate_index_count \
@@ -124,54 +124,54 @@ reference_dist: $(REF_DIST_CSVS)
# ── obiskim phylo (presence index) ────────────────────────────────────────── # ── obiskim phylo (presence index) ──────────────────────────────────────────
$(OBIKMER_PRESENCE_DIST) &: $(RUN)/global_index_presence/index.done $(BINARY) $(OBIKMER_PRESENCE_DIST) &: $(RUN)/global_index_presence/index.done $(BINARY)
mkdir -p $(RUN)/obikmer_dist/presence mkdir -p $(RUN)/obiskim_dist/presence
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/presence/jaccard \ --output $(RUN)/obiskim_dist/presence/jaccard \
--distance jaccard --csv --shared-kmers --nj \ --distance jaccard --csv --shared-kmers --nj \
$(RUN)/global_index_presence $(RUN)/global_index_presence
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/presence/hamming \ --output $(RUN)/obiskim_dist/presence/hamming \
--distance hamming --csv --nj \ --distance hamming --csv --nj \
$(RUN)/global_index_presence $(RUN)/global_index_presence
obikmer_dist_presence: $(OBIKMER_PRESENCE_DIST) obiskim_dist_presence: $(OBIKMER_PRESENCE_DIST)
# ── obiskim phylo (count index) ───────────────────────────────────────────── # ── obiskim phylo (count index) ─────────────────────────────────────────────
$(OBIKMER_COUNT_DIST) &: $(RUN)/global_index_count/index.done $(BINARY) $(OBIKMER_COUNT_DIST) &: $(RUN)/global_index_count/index.done $(BINARY)
mkdir -p $(RUN)/obikmer_dist/count mkdir -p $(RUN)/obiskim_dist/count
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/jaccard \ --output $(RUN)/obiskim_dist/count/jaccard \
--distance jaccard --csv --shared-kmers --nj \ --distance jaccard --csv --shared-kmers --nj \
$(RUN)/global_index_count $(RUN)/global_index_count
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/bray_curtis \ --output $(RUN)/obiskim_dist/count/bray_curtis \
--distance bray-curtis --csv --nj \ --distance bray-curtis --csv --nj \
$(RUN)/global_index_count $(RUN)/global_index_count
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/relfreq_bray_curtis \ --output $(RUN)/obiskim_dist/count/relfreq_bray_curtis \
--distance relfreq-bray-curtis --csv --nj \ --distance relfreq-bray-curtis --csv --nj \
$(RUN)/global_index_count $(RUN)/global_index_count
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/euclidean \ --output $(RUN)/obiskim_dist/count/euclidean \
--distance euclidean --csv --nj \ --distance euclidean --csv --nj \
$(RUN)/global_index_count $(RUN)/global_index_count
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/relfreq_euclidean \ --output $(RUN)/obiskim_dist/count/relfreq_euclidean \
--distance relfreq-euclidean --csv --nj \ --distance relfreq-euclidean --csv --nj \
$(RUN)/global_index_count $(RUN)/global_index_count
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/hellinger \ --output $(RUN)/obiskim_dist/count/hellinger \
--distance hellinger --csv --nj \ --distance hellinger --csv --nj \
$(RUN)/global_index_count $(RUN)/global_index_count
$(BINARY) phylo \ $(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/hellinger_euclidean \ --output $(RUN)/obiskim_dist/count/hellinger_euclidean \
--distance hellinger-euclidean --csv --nj \ --distance hellinger-euclidean --csv --nj \
$(RUN)/global_index_count $(RUN)/global_index_count
obikmer_dist_count: $(OBIKMER_COUNT_DIST) obiskim_dist_count: $(OBIKMER_COUNT_DIST)
obikmer_dist: obikmer_dist_presence obikmer_dist_count obiskim_dist: obiskim_dist_presence obiskim_dist_count
# ── distance comparison ─────────────────────────────────────────────────────── # ── distance comparison ───────────────────────────────────────────────────────
+2 -2
View File
@@ -17,7 +17,7 @@ a single `benchmark/run/` entry.
```mermaid ```mermaid
flowchart TD flowchart TD
GENOMES["run/genomes/*.fna.gz"] GENOMES["run/genomes/*.fna.gz"]
BIN["obikmer binary"] BIN["obiskim binary"]
GENOMES --> simulate GENOMES --> simulate
simulate --> simdata[("run/simulated_data/")] simulate --> simdata[("run/simulated_data/")]
@@ -178,7 +178,7 @@ benchmark/
│ └── <species>/<specimen>/ │ └── <species>/<specimen>/
├── reference_index/ # reference kmer sets (.npz) ├── reference_index/ # reference kmer sets (.npz)
├── reference_dist/ # reference pairwise distance matrices ├── reference_dist/ # reference pairwise distance matrices
├── obikmer_dist/ # obikmer phylo distance matrices (presence/, count/) ├── obiskim_dist/ # obiskim phylo distance matrices (presence/, count/)
├── specimen_index_presence/ # per-specimen presence indexes ├── specimen_index_presence/ # per-specimen presence indexes
├── specimen_index_count/ # per-specimen count indexes ├── specimen_index_count/ # per-specimen count indexes
├── global_index_presence/ # merged global presence index (sparse, as merged) ├── global_index_presence/ # merged global presence index (sparse, as merged)
+14 -14
View File
@@ -3,7 +3,7 @@
Reads from: Reads from:
reference_dist/ — ground-truth matrices computed by build_reference_dist.py reference_dist/ — ground-truth matrices computed by build_reference_dist.py
obikmer_dist/ — matrices produced by `obiskim phylo` obiskim_dist/ — matrices produced by `obiskim phylo`
Handles label reordering: both matrices are sorted by genome label before Handles label reordering: both matrices are sorted by genome label before
element-wise comparison, so column/row order differences are irrelevant. element-wise comparison, so column/row order differences are irrelevant.
@@ -89,56 +89,56 @@ def compare(label: str,
# ── comparison table ────────────────────────────────────────────────────────── # ── comparison table ──────────────────────────────────────────────────────────
# (label, ref_csv, obikmer_csv) # (label, ref_csv, obiskim_csv)
# The reference jaccard/shared is presence-based, which should match both # The reference jaccard/shared is presence-based, which should match both
# presence/jaccard and count/jaccard (threshold=1). # presence/jaccard and count/jaccard (threshold=1).
COMPARISONS = [ COMPARISONS = [
# ── presence index ──────────────────────────────────────────────────────── # ── presence index ────────────────────────────────────────────────────────
('presence/jaccard_dist', ('presence/jaccard_dist',
'reference_dist/jaccard_dist.csv', 'reference_dist/jaccard_dist.csv',
'obikmer_dist/presence/jaccard_dist.csv'), 'obiskim_dist/presence/jaccard_dist.csv'),
('presence/jaccard_shared', ('presence/jaccard_shared',
'reference_dist/shared_kmers.csv', 'reference_dist/shared_kmers.csv',
'obikmer_dist/presence/jaccard_shared.csv'), 'obiskim_dist/presence/jaccard_shared.csv'),
('presence/hamming_dist', ('presence/hamming_dist',
'reference_dist/hamming_dist.csv', 'reference_dist/hamming_dist.csv',
'obikmer_dist/presence/hamming_dist.csv'), 'obiskim_dist/presence/hamming_dist.csv'),
# ── count index (jaccard cross-check) ───────────────────────────────────── # ── count index (jaccard cross-check) ─────────────────────────────────────
('count/jaccard_dist', ('count/jaccard_dist',
'reference_dist/jaccard_dist.csv', 'reference_dist/jaccard_dist.csv',
'obikmer_dist/count/jaccard_dist.csv'), 'obiskim_dist/count/jaccard_dist.csv'),
('count/jaccard_shared', ('count/jaccard_shared',
'reference_dist/shared_kmers.csv', 'reference_dist/shared_kmers.csv',
'obikmer_dist/count/jaccard_shared.csv'), 'obiskim_dist/count/jaccard_shared.csv'),
# ── count index (count-based metrics) ──────────────────────────────────── # ── count index (count-based metrics) ────────────────────────────────────
('count/bray_curtis_dist', ('count/bray_curtis_dist',
'reference_dist/bray_curtis_dist.csv', 'reference_dist/bray_curtis_dist.csv',
'obikmer_dist/count/bray_curtis_dist.csv'), 'obiskim_dist/count/bray_curtis_dist.csv'),
('count/relfreq_bray_curtis_dist', ('count/relfreq_bray_curtis_dist',
'reference_dist/relfreq_bray_curtis_dist.csv', 'reference_dist/relfreq_bray_curtis_dist.csv',
'obikmer_dist/count/relfreq_bray_curtis_dist.csv'), 'obiskim_dist/count/relfreq_bray_curtis_dist.csv'),
('count/euclidean_dist', ('count/euclidean_dist',
'reference_dist/euclidean_dist.csv', 'reference_dist/euclidean_dist.csv',
'obikmer_dist/count/euclidean_dist.csv'), 'obiskim_dist/count/euclidean_dist.csv'),
('count/relfreq_euclidean_dist', ('count/relfreq_euclidean_dist',
'reference_dist/relfreq_euclidean_dist.csv', 'reference_dist/relfreq_euclidean_dist.csv',
'obikmer_dist/count/relfreq_euclidean_dist.csv'), 'obiskim_dist/count/relfreq_euclidean_dist.csv'),
('count/hellinger_dist', ('count/hellinger_dist',
'reference_dist/hellinger_dist.csv', 'reference_dist/hellinger_dist.csv',
'obikmer_dist/count/hellinger_dist.csv'), 'obiskim_dist/count/hellinger_dist.csv'),
('count/hellinger_euclidean_dist', ('count/hellinger_euclidean_dist',
'reference_dist/hellinger_euclidean_dist.csv', 'reference_dist/hellinger_euclidean_dist.csv',
'obikmer_dist/count/hellinger_euclidean_dist.csv'), 'obiskim_dist/count/hellinger_euclidean_dist.csv'),
] ]
@@ -151,7 +151,7 @@ def main() -> None:
ap.add_argument('--tol', type=float, default=1e-4, ap.add_argument('--tol', type=float, default=1e-4,
help='Max abs diff threshold for PASS/FAIL (default 1e-4)') help='Max abs diff threshold for PASS/FAIL (default 1e-4)')
ap.add_argument('--run-dir', default='run', ap.add_argument('--run-dir', default='run',
help='Root directory holding reference_dist/ and obikmer_dist/ (default: run)') help='Root directory holding reference_dist/ and obiskim_dist/ (default: run)')
ap.add_argument('--out', default='run/stats/dist_comparison/summary.csv', ap.add_argument('--out', default='run/stats/dist_comparison/summary.csv',
help='Output summary CSV path') help='Output summary CSV path')
args = ap.parse_args() args = ap.parse_args()
+1 -1
View File
@@ -14,7 +14,7 @@ out_dir="$2"
mkdir -p "${out_dir}" mkdir -p "${out_dir}"
tmp_fasta=$(mktemp "${TMPDIR:-/tmp}/obikmer_XXXXXX.fna") tmp_fasta=$(mktemp "${TMPDIR:-/tmp}/obiskim_XXXXXX.fna")
trap 'rm -f "${tmp_fasta}"' EXIT trap 'rm -f "${tmp_fasta}"' EXIT
gzip -dc "${genome_file}" > "${tmp_fasta}" gzip -dc "${genome_file}" > "${tmp_fasta}"
+1 -1
View File
@@ -18,7 +18,7 @@ out_dir="$2"
mkdir -p "${out_dir}" mkdir -p "${out_dir}"
tmp_fasta=$(mktemp "${TMPDIR:-/tmp}/obikmer_XXXXXX.fna") tmp_fasta=$(mktemp "${TMPDIR:-/tmp}/obiskim_XXXXXX.fna")
trap 'rm -f "${tmp_fasta}"' EXIT trap 'rm -f "${tmp_fasta}"' EXIT
gzip -dc "${genome_file}" > "${tmp_fasta}" gzip -dc "${genome_file}" > "${tmp_fasta}"
+1 -1
View File
@@ -23,7 +23,7 @@ CPUS="${CPUS:-$(sysctl -n hw.logicalcpu 2>/dev/null || nproc 2>/dev/null || echo
OUT="${SCRIPT_DIR}/run/skim_${COVERAGE}x_s${SEED}" OUT="${SCRIPT_DIR}/run/skim_${COVERAGE}x_s${SEED}"
mkdir -p "${OUT}/simulated_data" "${OUT}/specimen_index_presence" mkdir -p "${OUT}/simulated_data" "${OUT}/specimen_index_presence"
tmp_fasta=$(mktemp "${TMPDIR:-/tmp}/obikmer_skim_XXXXXX.fna") tmp_fasta=$(mktemp "${TMPDIR:-/tmp}/obiskim_skim_XXXXXX.fna")
trap 'rm -f "${tmp_fasta}"' EXIT trap 'rm -f "${tmp_fasta}"' EXIT
# lines of the form run/simulated_data/<species>/<strain>/reads_R1.fastq.gz: run/genomes/<file> # lines of the form run/simulated_data/<species>/<strain>/reads_R1.fastq.gz: run/genomes/<file>
+4 -4
View File
@@ -43,9 +43,9 @@ def decode_kmer(val: int, k: int) -> str:
# ── dump parsing ────────────────────────────────────────────────────────────── # ── dump parsing ──────────────────────────────────────────────────────────────
def load_index(obikmer_bin: str, index_dir: str) -> tuple[np.ndarray, np.ndarray]: def load_index(obiskim_bin: str, index_dir: str) -> tuple[np.ndarray, np.ndarray]:
"""Stream `obiskim dump` and return (kmers_sorted_uint64, counts_uint32).""" """Stream `obiskim dump` and return (kmers_sorted_uint64, counts_uint32)."""
cmd = [obikmer_bin, 'dump', index_dir] cmd = [obiskim_bin, 'dump', index_dir]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True) text=True)
kmers, counts = [], [] kmers, counts = [], []
@@ -126,7 +126,7 @@ def main() -> None:
return return
# Detect k # Detect k
cmd1 = [args.obikmer, 'dump', '--head', '1', args.index] cmd1 = [args.obiskim, 'dump', '--head', '1', args.index]
out1 = subprocess.check_output(cmd1, stderr=subprocess.DEVNULL, text=True) out1 = subprocess.check_output(cmd1, stderr=subprocess.DEVNULL, text=True)
k = len(out1.splitlines()[1].split(',')[0]) k = len(out1.splitlines()[1].split(',')[0])
@@ -138,7 +138,7 @@ def main() -> None:
# Load index # Load index
print(f'Streaming dump (k={k}): {args.index}', file=sys.stderr) print(f'Streaming dump (k={k}): {args.index}', file=sys.stderr)
idx_kmers, idx_counts = load_index(args.obikmer, args.index) idx_kmers, idx_counts = load_index(args.obiskim, args.index)
print(f'k={k} ref={len(ref_kmers):,} idx={len(idx_kmers):,}', file=sys.stderr) print(f'k={k} ref={len(ref_kmers):,} idx={len(idx_kmers):,}', file=sys.stderr)
+4 -4
View File
@@ -41,7 +41,7 @@ def decode_kmer(val: int, k: int) -> str:
# ── single-pass dump ────────────────────────────────────────────────────────── # ── single-pass dump ──────────────────────────────────────────────────────────
def stream_merged_dump(obikmer_bin: str, index_dir: str, def stream_merged_dump(obiskim_bin: str, index_dir: str,
) -> tuple[list[str], dict[str, tuple[list[int], list[int]]]]: ) -> tuple[list[str], dict[str, tuple[list[int], list[int]]]]:
"""Stream the merged dump once. """Stream the merged dump once.
@@ -49,7 +49,7 @@ def stream_merged_dump(obikmer_bin: str, index_dir: str,
specimen_names : column labels in dump order specimen_names : column labels in dump order
per_specimen : mapping label → (kmer_ints, counts) for entries > 0 per_specimen : mapping label → (kmer_ints, counts) for entries > 0
""" """
cmd = [obikmer_bin, 'dump', index_dir] cmd = [obiskim_bin, 'dump', index_dir]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True) text=True)
@@ -181,12 +181,12 @@ def main() -> None:
if d: d.mkdir(parents=True, exist_ok=True) if d: d.mkdir(parents=True, exist_ok=True)
out1 = subprocess.check_output( out1 = subprocess.check_output(
[args.obikmer, 'dump', '--head', '1', args.index], [args.obiskim, 'dump', '--head', '1', args.index],
stderr=subprocess.DEVNULL, text=True) stderr=subprocess.DEVNULL, text=True)
k = len(out1.splitlines()[1].split(',')[0]) k = len(out1.splitlines()[1].split(',')[0])
print(f'k={k} streaming merged dump: {args.index}', file=sys.stderr) print(f'k={k} streaming merged dump: {args.index}', file=sys.stderr)
specimen_names, per_specimen = stream_merged_dump(args.obikmer, args.index) specimen_names, per_specimen = stream_merged_dump(args.obiskim, args.index)
print(f'{len(specimen_names)} specimen columns loaded', file=sys.stderr) print(f'{len(specimen_names)} specimen columns loaded', file=sys.stderr)
for name in specimen_names: for name in specimen_names:
+4 -4
View File
@@ -40,7 +40,7 @@ def decode_kmer(val: int, k: int) -> str:
# ── single-pass dump ────────────────────────────────────────────────────────── # ── single-pass dump ──────────────────────────────────────────────────────────
def stream_merged_dump(obikmer_bin: str, index_dir: str, def stream_merged_dump(obiskim_bin: str, index_dir: str,
) -> tuple[list[str], dict[str, list[int]]]: ) -> tuple[list[str], dict[str, list[int]]]:
"""Stream the merged dump once. """Stream the merged dump once.
@@ -48,7 +48,7 @@ def stream_merged_dump(obikmer_bin: str, index_dir: str,
specimen_names : column labels in dump order (excluding 'kmer') specimen_names : column labels in dump order (excluding 'kmer')
per_specimen : mapping label → list of kmer ints where presence > 0 per_specimen : mapping label → list of kmer ints where presence > 0
""" """
cmd = [obikmer_bin, 'dump', index_dir] cmd = [obiskim_bin, 'dump', index_dir]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True) text=True)
@@ -152,12 +152,12 @@ def main() -> None:
# Detect k # Detect k
out1 = subprocess.check_output( out1 = subprocess.check_output(
[args.obikmer, 'dump', '--head', '1', args.index], [args.obiskim, 'dump', '--head', '1', args.index],
stderr=subprocess.DEVNULL, text=True) stderr=subprocess.DEVNULL, text=True)
k = len(out1.splitlines()[1].split(',')[0]) k = len(out1.splitlines()[1].split(',')[0])
print(f'k={k} streaming merged dump: {args.index}', file=sys.stderr) print(f'k={k} streaming merged dump: {args.index}', file=sys.stderr)
specimen_names, per_specimen = stream_merged_dump(args.obikmer, args.index) specimen_names, per_specimen = stream_merged_dump(args.obiskim, args.index)
print(f'{len(specimen_names)} specimen columns loaded', file=sys.stderr) print(f'{len(specimen_names)} specimen columns loaded', file=sys.stderr)
for name in specimen_names: for name in specimen_names:
+4 -4
View File
@@ -40,9 +40,9 @@ def decode_kmer(val: int, k: int) -> str:
# ── dump parsing ────────────────────────────────────────────────────────────── # ── dump parsing ──────────────────────────────────────────────────────────────
def load_index_kmers(obikmer_bin: str, index_dir: str) -> np.ndarray: def load_index_kmers(obiskim_bin: str, index_dir: str) -> np.ndarray:
"""Stream `obiskim dump` and return a sorted uint64 array of kmer integers.""" """Stream `obiskim dump` and return a sorted uint64 array of kmer integers."""
cmd = [obikmer_bin, 'dump', index_dir] cmd = [obiskim_bin, 'dump', index_dir]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True) text=True)
kmers = [] kmers = []
@@ -94,7 +94,7 @@ def main() -> None:
return return
# Detect k from the index (one cheap call before the full dump). # Detect k from the index (one cheap call before the full dump).
cmd1 = [args.obikmer, 'dump', '--head', '1', args.index] cmd1 = [args.obiskim, 'dump', '--head', '1', args.index]
out1 = subprocess.check_output(cmd1, stderr=subprocess.DEVNULL, text=True) out1 = subprocess.check_output(cmd1, stderr=subprocess.DEVNULL, text=True)
k = len(out1.splitlines()[1].split(',')[0]) k = len(out1.splitlines()[1].split(',')[0])
@@ -105,7 +105,7 @@ def main() -> None:
# Load index # Load index
print(f'Streaming dump (k={k}): {args.index}', file=sys.stderr) print(f'Streaming dump (k={k}): {args.index}', file=sys.stderr)
idx_kmers = load_index_kmers(args.obikmer, args.index) idx_kmers = load_index_kmers(args.obiskim, args.index)
print(f'k={k} ref={len(ref_kmers):,} idx={len(idx_kmers):,}', file=sys.stderr) print(f'k={k} ref={len(ref_kmers):,} idx={len(idx_kmers):,}', file=sys.stderr)
+1 -1
View File
@@ -1,4 +1,4 @@
site_name: obikmer site_name: obiskim
docs_dir: DevDocMD docs_dir: DevDocMD
site_dir: DevDoc site_dir: DevDoc
+5 -5
View File
@@ -1,6 +1,6 @@
# Prompt — refonte mmap de `obikmerge` (plans A puis C) # Prompt — refonte mmap de `obikmerge` (plans A puis C)
> À coller tel quel au début d'une nouvelle session Claude Code ouverte à la racine du dépôt obikmer. > À coller tel quel au début d'une nouvelle session Claude Code ouverte à la racine du dépôt obiskim.
> Conçu pour être suivi par **Sonnet** : toutes les décisions d'architecture sont fixées ci-dessous. Le plan B de l'audit (ouverture « slots only » dans `obikindex`) est **hors périmètre** de cette session (voir étape 5). > Conçu pour être suivi par **Sonnet** : toutes les décisions d'architecture sont fixées ci-dessous. Le plan B de l'audit (ouverture « slots only » dans `obikindex`) est **hors périmètre** de cette session (voir étape 5).
--- ---
@@ -30,14 +30,14 @@ Objectif : le nombre de mappings vivants par partition ne doit plus dépendre du
### 1a. Oracle synthétique (rapide, couvre comptage et merge en deux temps) ### 1a. Oracle synthétique (rapide, couvre comptage et merge en deux temps)
1. Lis `scripts/smoke_test_index.sh` (modèle de style, options de `obikmer index`) et les `--help` de `obikmer index`, `merge` et `dump`. 1. Lis `scripts/smoke_test_index.sh` (modèle de style, options de `obiskim index`) et les `--help` de `obiskim index`, `merge` et `dump`.
2. Écris `scripts/smoke_test_merge.sh`, sur le même modèle : 2. Écris `scripts/smoke_test_merge.sh`, sur le même modèle :
- génère 4 FASTA aléatoires déterministes A, B, C, D, petits, avec **des fragments partagés** entre eux. Le merge doit à la fois retrouver des k-mers déjà présents dans la destination (chemin « couche existante ») et en créer de nouveaux (chemin « nouvelle couche ») ; - génère 4 FASTA aléatoires déterministes A, B, C, D, petits, avec **des fragments partagés** entre eux. Le merge doit à la fois retrouver des k-mers déjà présents dans la destination (chemin « couche existante ») et en créer de nouveaux (chemin « nouvelle couche ») ;
- indexe chacun deux fois : présence (défaut) et comptage (`--with-counts`). Plusieurs partitions (`-p 4`) ; - indexe chacun deux fois : présence (défaut) et comptage (`--with-counts`). Plusieurs partitions (`-p 4`) ;
- scénario 1 : `merge A B C D` (présence), puis la même chose en comptage ; - scénario 1 : `merge A B C D` (présence), puis la même chose en comptage ;
- scénario 2 : `merge A B` → AB, puis `merge AB C D`. Ce scénario couvre une source multi-génome et une destination à plusieurs couches ; - scénario 2 : `merge A B` → AB, puis `merge AB C D`. Ce scénario couvre une source multi-génome et une destination à plusieurs couches ;
- scénario 3 : comme le scénario 1, avec `--dense` ; - scénario 3 : comme le scénario 1, avec `--dense` ;
- pour chaque sortie : `obikmer dump` → `sort` → un fichier texte ; - pour chaque sortie : `obiskim dump` → `sort` → un fichier texte ;
- deux modes : `--record DIR` écrit les sorties triées dans `DIR`, `--check DIR` les régénère et fait un `diff` avec `DIR`. Affiche PASS/FAIL clairement, avec un code de sortie cohérent. - deux modes : `--record DIR` écrit les sorties triées dans `DIR`, `--check DIR` les régénère et fait un `diff` avec `DIR`. Affiche PASS/FAIL clairement, avec un code de sortie cohérent.
3. Lance `--record benchmark/run/merge_oracle/synthetic` **avec le code actuel, non modifié**. Vérifie que les fichiers ne sont pas vides et que les colonnes de génomes ont du sens. 3. Lance `--record benchmark/run/merge_oracle/synthetic` **avec le code actuel, non modifié**. Vérifie que les fichiers ne sont pas vides et que les colonnes de génomes ont du sens.
4. Lance aussitôt `--check` sur le même code pour vérifier que le script est déterministe. 4. Lance aussitôt `--check` sur le même code pour vérifier que le script est déterministe.
@@ -54,7 +54,7 @@ Objectif : le nombre de mappings vivants par partition ne doit plus dépendre du
Procédure : Procédure :
1. Recompile le binaire release à partir du **code actuel non modifié** (`cargo build --release` dans `src/`). Ne touche pas aux artefacts existants de `benchmark/run/`. 1. Recompile le binaire release à partir du **code actuel non modifié** (`cargo build --release` dans `src/`). Ne touche pas aux artefacts existants de `benchmark/run/`.
2. Lance le merge des 20 index avec les mêmes options que `merge_presence.sh`, mais vers un répertoire **dédié**, par exemple `benchmark/run/merge_oracle/bench/merged`, jamais `benchmark/run/global_index_presence`. Garde le log stderr : le rapport de stages (wall et RSS de `merge_partitions`) sert de référence de performance. 2. Lance le merge des 20 index avec les mêmes options que `merge_presence.sh`, mais vers un répertoire **dédié**, par exemple `benchmark/run/merge_oracle/bench/merged`, jamais `benchmark/run/global_index_presence`. Garde le log stderr : le rapport de stages (wall et RSS de `merge_partitions`) sert de référence de performance.
3. `obikmer dump` du résultat → `sort` → compresse (`zstd`) + `sha256sum`, dans `benchmark/run/merge_oracle/bench/`. La sortie peut être volumineuse : compare d'abord les hash, et ne fais un `diff` que s'ils diffèrent. 3. `obiskim dump` du résultat → `sort` → compresse (`zstd`) + `sha256sum`, dans `benchmark/run/merge_oracle/bench/`. La sortie peut être volumineuse : compare d'abord les hash, et ne fais un `diff` que s'ils diffèrent.
4. Contrôle croisé informatif : fais la même chose (dump trié + hash) sur `benchmark/run/global_index_presence`. Si les hash diffèrent, **signale-le sans conclure** : l'écart peut venir d'évolutions légitimes du code depuis octobre. 4. Contrôle croisé informatif : fais la même chose (dump trié + hash) sur `benchmark/run/global_index_presence`. Si les hash diffèrent, **signale-le sans conclure** : l'écart peut venir d'évolutions légitimes du code depuis octobre.
5. Écris ces étapes dans un script `scripts/bench_merge_oracle.sh` avec deux modes : `--record DIR` et `--check DIR`. En mode `--check`, il affiche aussi le temps de `merge_partitions` avant/après. 5. Écris ces étapes dans un script `scripts/bench_merge_oracle.sh` avec deux modes : `--record DIR` et `--check DIR`. En mode `--check`, il affiche aussi le temps de `merge_partitions` avant/après.
@@ -143,7 +143,7 @@ Les couches sources de la passe 2 continuent donc d'être ouvertes par `partitio
5. Rapport final : liste des fichiers modifiés, résultats de tests, et estimation du nombre de mmaps par partition avant/après (calculée, marquée comme estimée). Termine par la commande de mesure à lancer en production, qui ne demande pas root : 5. Rapport final : liste des fichiers modifiés, résultats de tests, et estimation du nombre de mmaps par partition avant/après (calculée, marquée comme estimée). Termine par la commande de mesure à lancer en production, qui ne demande pas root :
```bash ```bash
PID=$(pgrep -f 'obikmer merge'); while sleep 60; do PID=$(pgrep -f 'obiskim merge'); while sleep 60; do
echo "$(date +%T) maps=$(wc -l < /proc/$PID/maps) threads=$(ls /proc/$PID/task | wc -l)"; done echo "$(date +%T) maps=$(wc -l < /proc/$PID/maps) threads=$(ls /proc/$PID/task | wc -l)"; done
``` ```
+7 -7
View File
@@ -1,4 +1,4 @@
Contexte : projet obikmer (workspace Rust de 26 crates, dépôt jj+git). Dans la session précédente Contexte : projet obiskim (workspace Rust de 26 crates, dépôt jj+git). Dans la session précédente
(lecture seule) nous avons étudié l'adoption par crate-kit (lecture seule) nous avons étudié l'adoption par crate-kit
(https://gargoton.petite-maison-orange.fr/LLM/crate-kit, clone local attendu à côté : ../crate-kit) (https://gargoton.petite-maison-orange.fr/LLM/crate-kit, clone local attendu à côté : ../crate-kit)
sur le modèle de pmo-kit (/Users/coissac/Sync/maison/Petite_maisons/src/pmo/pmo-kit/, sur le modèle de pmo-kit (/Users/coissac/Sync/maison/Petite_maisons/src/pmo/pmo-kit/,
@@ -6,19 +6,19 @@ cluster /Users/coissac/Sync/maison/Petite_maisons/src/pmo/).
État supposé au début de cette session (à vérifier avant tout) : État supposé au début de cette session (à vérifier avant tout) :
- J'ai déplacé le dépôt dans l'organisation « obi » de forge.metabarcoding.org (Gitea) et - J'ai déplacé le dépôt dans l'organisation « obi » de forge.metabarcoding.org (Gitea) et
le répertoire local obikmer dans un dossier local `obi/` (cluster, comme `pmo/`). le répertoire local obiskim dans un dossier local `obi/` (cluster, comme `pmo/`).
- L'ancienne origine était git@forge.metabarcoding.org:OBIKmers/obikmer.git. - L'ancienne origine était git@forge.metabarcoding.org:OBIKmers/obiskim.git.
- Le registre Cargo privé s'appelle `obi` (https://forge.metabarcoding.org/api/packages/obi/cargo/). - Le registre Cargo privé s'appelle `obi` (https://forge.metabarcoding.org/api/packages/obi/cargo/).
- Langue du projet et des documents générés : anglais (KIT_LANG ?= en). Licence : CeCILL-2.1. - Langue du projet et des documents générés : anglais (KIT_LANG ?= en). Licence : CeCILL-2.1.
Décisions déjà prises : Décisions déjà prises :
- obikmer reste un workspace d'APPLICATION (Makefile non-crate incluant dev-patch.mk, comme pmomusic). - obiskim reste un workspace d'APPLICATION (Makefile non-crate incluant dev-patch.mk, comme pmomusic).
Certaines crates génériques seront extraites plus tard en crates autonomes (sans `workspace = true`), Certaines crates génériques seront extraites plus tard en crates autonomes (sans `workspace = true`),
publiées sur le registre `obi`. Candidates : obipipeline, obikrope, obicompactvec, obiread, publiées sur le registre `obi`. Candidates : obipipeline, obikrope, obicompactvec, obiread,
obifastwrite, obitaxonomy (feuilles d'abord), puis obisys, obikseq ; obikentropy/obikalgorithm/obidebruinj à examiner. obifastwrite, obitaxonomy (feuilles d'abord), puis obisys, obikseq ; obikentropy/obikalgorithm/obidebruinj à examiner.
NE PAS extraire de crate dans cette session. NE PAS extraire de crate dans cette session.
- Les crates obikindex*, obikphylo, obikfilter, obikmerge, obikrebuild, obikquery, obikdump, obikselect, - Les crates obikindex*, obikphylo, obikfilter, obikmerge, obikrebuild, obikquery, obikdump, obikselect,
obikstats, obikidxcache, obiksession et le binaire obikmer restent dans le workspace d'application. obikstats, obikidxcache, obiksession et le binaire obiskim restent dans le workspace d'application.
- La CI de release actuelle (.gitea/workflows/release.yml : builds croisés macOS, images Docker) est conservée telle quelle. - La CI de release actuelle (.gitea/workflows/release.yml : builds croisés macOS, images Docker) est conservée telle quelle.
À faire dans cette session (annoncer chaque étape avant de l'exécuter ; jamais de push, je pousse moi-même ; À faire dans cette session (annoncer chaque étape avant de l'exécuter ; jamais de push, je pousse moi-même ;
@@ -35,7 +35,7 @@ aucune commande VCS mutante sans demande explicite dans le tour, `cd` toujours e
KIT_LANG ?= en), Makefile délégant à crate-kit, tools/kit-assemble.sh et kit-copy.sh, KIT_LANG ?= en), Makefile délégant à crate-kit, tools/kit-assemble.sh et kit-copy.sh,
overlay/templates, README en anglais, .gitignore, LICENSE CeCILL-2.1. Pas de « kind » plugin ni de catalogue. overlay/templates, README en anglais, .gitignore, LICENSE CeCILL-2.1. Pas de « kind » plugin ni de catalogue.
Ne pas copier ce qui est propre à PMO. Ne pas copier ce qui est propre à PMO.
4. Installer crate-kit dans le workspace d'application obikmer au niveau Makefile (inclusion de 4. Installer crate-kit dans le workspace d'application obiskim au niveau Makefile (inclusion de
dev-patch.mk, KIT_SRC ?= ../obi-kit), sans adopter les 26 crates ; ajouter `license = "CECILL-2.1"` dev-patch.mk, KIT_SRC ?= ../obi-kit), sans adopter les 26 crates ; ajouter `license = "CECILL-2.1"`
et `repository` dans les Cargo.toml de l'application (absents aujourd'hui) ; LICENSE/LICENSE.en à la racine. et `repository` dans les Cargo.toml de l'application (absents aujourd'hui) ; LICENSE/LICENSE.en à la racine.
5. Écrire la liste des risques Gitea à tester sur une crate jetable : version de Gitea et registre Cargo sparse, 5. Écrire la liste des risques Gitea à tester sur une crate jetable : version de Gitea et registre Cargo sparse,
@@ -43,5 +43,5 @@ aucune commande VCS mutante sans demande explicite dans le tour, `cd` toujours e
6. Terminer par un rapport : fichiers créés/modifiés, ce qui reste à faire (création des dépôts obi-kit/crate-kit 6. Terminer par un rapport : fichiers créés/modifiés, ce qui reste à faire (création des dépôts obi-kit/crate-kit
sur la forge, tests du pilote, premières extractions). sur la forge, tests du pilote, premières extractions).
Règles du projet à respecter : CLAUDE.md d'obikmer et ~/.claude/CLAUDE.md (code existant = hypothèse, pas de Règles du projet à respecter : CLAUDE.md d'obiskim et ~/.claude/CLAUDE.md (code existant = hypothèse, pas de
substitution de dépendance, serena/rust-analyzer-mcp pour le code), documentation de DevDocMD en anglais. substitution de dépendance, serena/rust-analyzer-mcp pour le code), documentation de DevDocMD en anglais.
+2 -2
View File
@@ -1,13 +1,13 @@
# Prompt — où optimiser l'étape `pack` du merge (diagnostic d'abord) # Prompt — où optimiser l'étape `pack` du merge (diagnostic d'abord)
> À coller tel quel au début d'une nouvelle session Claude Code ouverte à la racine du dépôt obikmer. > À coller tel quel au début d'une nouvelle session Claude Code ouverte à la racine du dépôt obiskim.
> Cette session est un **diagnostic** : elle produit une analyse chiffrée et des pistes classées, pas du code. Toute modification du code attend mon feu vert explicite, piste par piste. > Cette session est un **diagnostic** : elle produit une analyse chiffrée et des pistes classées, pas du code. Toute modification du code attend mon feu vert explicite, piste par piste.
--- ---
## Contexte ## Contexte
`obikmer merge` se termine par une étape `finalize`, dont l'essentiel est `pack` : les matrices de présence/comptage, écrites en colonnes pendant le merge (`MatrixBuilder`), sont transposées en un format compact par partition (sparse par défaut). Le point d'entrée est `KmerIndex::finalize_indexed` (`src/obikindex/src/index/builder.rs`, étape « pack » vers la ligne 109), qui appelle `KmerIndex::pack_matrices(sparse)` (`src/obikindex/src/index/kmer_index.rs`). Les primitives sont dans `src/obicompactvec/src/` : `pack_bit_matrix` (`bitmatrix/packed.rs`), `pack_compact_int_matrix` (`intmatrix.rs`), `pack_sparse_compact_int_matrix` (`sparse_intmatrix.rs`), et le côté sparse des bits dans `bitmatrix/`. `obiskim merge` se termine par une étape `finalize`, dont l'essentiel est `pack` : les matrices de présence/comptage, écrites en colonnes pendant le merge (`MatrixBuilder`), sont transposées en un format compact par partition (sparse par défaut). Le point d'entrée est `KmerIndex::finalize_indexed` (`src/obikindex/src/index/builder.rs`, étape « pack » vers la ligne 109), qui appelle `KmerIndex::pack_matrices(sparse)` (`src/obikindex/src/index/kmer_index.rs`). Les primitives sont dans `src/obicompactvec/src/` : `pack_bit_matrix` (`bitmatrix/packed.rs`), `pack_compact_int_matrix` (`intmatrix.rs`), `pack_sparse_compact_int_matrix` (`sparse_intmatrix.rs`), et le côté sparse des bits dans `bitmatrix/`.
Lis d'abord `DevDocMD/implementation/merge_scaling.md` (état du pack sparse : passage par une matrice dense séquentielle puis sparse, un seul mapping par partition) et `DevDocMD/implementation/merge_mmap_audit.md`. Lis d'abord `DevDocMD/implementation/merge_scaling.md` (état du pack sparse : passage par une matrice dense séquentielle puis sparse, un seul mapping par partition) et `DevDocMD/implementation/merge_mmap_audit.md`.
+2 -2
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Parse obikmer merge debug log → Markdown performance report.""" """Parse obiskim merge debug log → Markdown performance report."""
import re import re
import sys import sys
@@ -237,7 +237,7 @@ def rate_stats(n_key, t_key):
out = [] out = []
w = out.append w = out.append
w("# obikmer merge — performance report\n") w("# obiskim merge — performance report\n")
# Run info # Run info
n_parts = len([r for r in phases.values() if r['n_kmers'] > 0]) n_parts = len([r for r in phases.values() if r['n_kmers'] > 0])
+1 -1
View File
@@ -7,7 +7,7 @@ when its character is not an absence symbol (default '-' and '?').
Outputs (prefix given by -o): Outputs (prefix given by -o):
<prefix>_family_overlap.csv genome x genome matrix: number of columns where <prefix>_family_overlap.csv genome x genome matrix: number of columns where
both genomes carry a call (diagonal = 0, same both genomes carry a call (diagonal = 0, same
convention as `obikmer phylo --family-overlap`) convention as `obiskim phylo --family-overlap`)
<prefix>_nesting.csv per clade-size stratum: how closed the families <prefix>_nesting.csv per clade-size stratum: how closed the families
are under the tree are under the tree
+1 -1
View File
@@ -43,7 +43,7 @@ while [ $# -gt 0 ]; do
done done
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORK="$(mktemp -d -t obikmer_smoke.XXXXXX)" WORK="$(mktemp -d -t obiskim_smoke.XXXXXX)"
cleanup() { cleanup() {
if [ "$KEEP" -eq 1 ]; then if [ "$KEEP" -eq 1 ]; then
+1 -1
View File
@@ -57,7 +57,7 @@ done
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
case "$DIR" in /*) ;; *) DIR="$PWD/$DIR" ;; esac case "$DIR" in /*) ;; *) DIR="$PWD/$DIR" ;; esac
WORK="$(mktemp -d -t obikmer_merge_smoke.XXXXXX)" WORK="$(mktemp -d -t obiskim_merge_smoke.XXXXXX)"
cleanup() { cleanup() {
if [ "$KEEP" -eq 1 ]; then echo "kept: $WORK"; else rm -rf "$WORK"; fi if [ "$KEEP" -eq 1 ]; then echo "kept: $WORK"; else rm -rf "$WORK"; fi
@@ -1,6 +1,6 @@
//! VCF rendering of a [`SnpAlignment`]. //! VCF rendering of a [`SnpAlignment`].
//! //!
//! One contig per `(partition, layer)` (`obikmer_<partition>_<layer>`), `POS` //! One contig per `(partition, layer)` (`obiskim_<partition>_<layer>`), `POS`
//! = the family's `family_idx + 1` inside it: for a given index and sibling //! = the family's `family_idx + 1` inside it: for a given index and sibling
//! annex the same family always gets the same virtual coordinates, and //! annex the same family always gets the same virtual coordinates, and
//! sorting by `(partition, layer, family_idx)` is what makes the file a //! sorting by `(partition, layer, family_idx)` is what makes the file a
@@ -103,12 +103,12 @@ impl SnpAlignment {
}); });
writeln!(out, "##fileformat=VCFv4.5")?; writeln!(out, "##fileformat=VCFv4.5")?;
writeln!(out, "##source=obikmer")?; writeln!(out, "##source=obiskim")?;
let mut last = None; let mut last = None;
for &j in &order { for &j in &order {
let s = &self.sites[j]; let s = &self.sites[j];
if last != Some((s.partition, s.layer)) { if last != Some((s.partition, s.layer)) {
writeln!(out, "##contig=<ID=obikmer_{}_{}>", s.partition, s.layer)?; writeln!(out, "##contig=<ID=obiskim_{}_{}>", s.partition, s.layer)?;
last = Some((s.partition, s.layer)); last = Some((s.partition, s.layer));
} }
} }
@@ -166,7 +166,7 @@ impl SnpAlignment {
CanonicalKmer::from_raw_unchecked(s.family_id).write_family_id_ascii(&mut locus)?; CanonicalKmer::from_raw_unchecked(s.family_id).write_family_id_ascii(&mut locus)?;
write!( write!(
out, out,
"obikmer_{}_{}\t{}\t", "obiskim_{}_{}\t{}\t",
s.partition, s.partition,
s.layer, s.layer,
s.family_idx + 1 s.family_idx + 1
@@ -258,7 +258,7 @@ mod tests {
vec![site(0, 0, 4), site(0, 0, 9)], vec![site(0, 0, 4), site(0, 0, 9)],
); );
let f = first_record(&a); let f = first_record(&a);
assert_eq!(&f[..2], ["obikmer_0_0", "5"]); assert_eq!(&f[..2], ["obiskim_0_0", "5"]);
assert_eq!(&f[3..5], ["G", "A"]); assert_eq!(&f[3..5], ["G", "A"]);
assert_eq!(&f[9..], ["1", "0", "0", ".", "."]); assert_eq!(&f[9..], ["1", "0", "0", ".", "."]);
} }
@@ -309,7 +309,7 @@ mod tests {
a.write_vcf(&labels, false, &mut out).unwrap(); a.write_vcf(&labels, false, &mut out).unwrap();
let text = String::from_utf8(out).unwrap(); let text = String::from_utf8(out).unwrap();
let body: Vec<&str> = text.lines().filter(|l| !l.starts_with('#')).collect(); let body: Vec<&str> = text.lines().filter(|l| !l.starts_with('#')).collect();
assert!(body[0].starts_with("obikmer_0_2\t8\t")); assert!(body[0].starts_with("obiskim_0_2\t8\t"));
assert!(body[1].starts_with("obikmer_1_0\t1\t")); assert!(body[1].starts_with("obiskim_1_0\t1\t"));
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "obiskim" name = "obiskim"
version = "1.4.8" version = "1.4.9"
edition = "2024" edition = "2024"
license = "CECILL-2.1" license = "CECILL-2.1"
repository = "https://forge.metabarcoding.org/obi/obiskim" repository = "https://forge.metabarcoding.org/obi/obiskim"
+1 -1
View File
@@ -30,7 +30,7 @@ pub struct AlignArgs {
/// Write the pseudo-alignment in VCF format /// Write the pseudo-alignment in VCF format
/// ///
/// Writes `PREFIX_alignment.vcf`. Each scanned index layer is a contig /// Writes `PREFIX_alignment.vcf`. Each scanned index layer is a contig
/// named `obikmer_<partition>_<layer>`; `POS` is the position of the /// named `obiskim_<partition>_<layer>`; `POS` is the position of the
/// family within the layer and `ID` is the masked canonical k-mer of the /// family within the layer and `ID` is the masked canonical k-mer of the
/// family. Implies --pseudo-alignment; can be combined with --fasta to /// family. Implies --pseudo-alignment; can be combined with --fasta to
/// get both formats. /// get both formats.
+6 -6
View File
@@ -25,10 +25,10 @@ use tracing::info;
/// # How it is built /// # How it is built
/// ///
/// Each mode is one OS advisory file lock (`flock` on Unix, `LockFileEx` on /// Each mode is one OS advisory file lock (`flock` on Unix, `LockFileEx` on
/// Windows) on `.obikmer.lock`, so a crash releases it with no stale-lock /// Windows) on `.obiskim.lock`, so a crash releases it with no stale-lock
/// cleanup. On top of that, **every transition** (acquire, release into /// cleanup. On top of that, **every transition** (acquire, release into
/// another mode, promote, demote) happens while holding a *gate* — a second /// another mode, promote, demote) happens while holding a *gate* — a second
/// lock file, `.obikmer.gate`, taken for the length of one non-blocking /// lock file, `.obiskim.gate`, taken for the length of one non-blocking
/// attempt and never while waiting. A blocked request therefore releases the /// attempt and never while waiting. A blocked request therefore releases the
/// gate, sleeps, and tries again (polling, 20 ms growing to 500 ms), instead /// gate, sleeps, and tries again (polling, 20 ms growing to 500 ms), instead
/// of sleeping in the kernel while holding it. Because nobody else can touch /// of sleeping in the kernel while holding it. Because nobody else can touch
@@ -51,9 +51,9 @@ pub enum LockMode {
Exclusive, Exclusive,
} }
const LOCK_FILE: &str = ".obikmer.lock"; const LOCK_FILE: &str = ".obiskim.lock";
const GATE_FILE: &str = ".obikmer.gate"; const GATE_FILE: &str = ".obiskim.gate";
const CLAIM_FILE: &str = ".obikmer.promote"; const CLAIM_FILE: &str = ".obiskim.promote";
const POLL_MIN: Duration = Duration::from_millis(20); const POLL_MIN: Duration = Duration::from_millis(20);
const POLL_MAX: Duration = Duration::from_millis(500); const POLL_MAX: Duration = Duration::from_millis(500);
@@ -172,7 +172,7 @@ impl DirLock {
/// run in between and the caller must re-check what it relied on. /// run in between and the caller must re-check what it relied on.
/// ///
/// Gapless promotion is available to one promoter at a time (it holds /// Gapless promotion is available to one promoter at a time (it holds
/// `.obikmer.promote` while it waits for the other readers to leave). /// `.obiskim.promote` while it waits for the other readers to leave).
/// A second concurrent promoter releases its shared lock instead — two /// A second concurrent promoter releases its shared lock instead — two
/// promoters each keeping theirs while waiting for the other's would /// promoters each keeping theirs while waiting for the other's would
/// wait for ever. An exclusive lock is returned unchanged. /// wait for ever. An exclusive lock is returned unchanged.