Compare commits

...
29 Commits
Author SHA1 Message Date
Eric Coissac 917cb26186 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 12s
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.
2026-12-01 18:17:47 +01:00
Eric Coissac 42d5b881ec refactor: rename obikmer to obiskim
Rename the `obikmer` binary, crate, and documentation to `obiskim`. This change updates all references in source code, build scripts, CI workflows, and user documentation to reflect the new tool name.

- Move `src/obikmer` to `src/obiskim`, renaming the package and binary in `Cargo.toml` and updating `main.rs` and `cli.rs` to use the new name.
- Update `src/Cargo.toml` and `src/Cargo.lock` to replace the `obikmer` workspace member with `obiskim`.
- Update `Makefile` targets (`build`, `release`, `debug`, `profile-build`) and variables (`CARGO_TOML`, `bump-version`) to build and manage `obiskim`.
- Update `.gitea/workflows/release.yml` to build and upload `obiskim` artifacts for Linux and macOS.
- Rename all files in `src/obiskim/src/cmd/` from `obikmer` to `obiskim` paths, updating error messages and help text in `index/mod.rs`, `phylo/args/mod.rs`, and `phylo/tnt.rs`.
- Update documentation in `UserDocMD/` (including `index.md`, `installation.md`, `architecture.md`, and usage guides) to reference `obiskim` commands and behavior.
- Update `benchmark/` scripts and Python verification tools to use `obiskim` binary paths and arguments.
- Update `scripts/` (including `smoke_test_*.sh`, `bench_merge_oracle.sh`, and Docker debug scripts) to test and build `obiskim`.
- Update comments and error messages in library crates (`obicompactvec`, `obifastwrite`, `obikentropy`, `obikfilter`, `obikindex`, `obikindexer`, `obikphylo`, `obikselect`, `obikseq`, `obiread`, `obisys`) to reference `obiskim`.
2026-12-01 18:15:13 +01:00
Eric Coissac a71e59d6f0 refactor: modernize iteration patterns and add sparse matrix support
Update bitvector and matrix operations to use iterator-based loops, `as_chunks`, and direct references instead of index-based access. Introduce `Sparse` variants for persistent bit and integer matrices, including logic to detect and migrate stale columnar formats. Add `is_empty` methods to various data structures and implement `Default` for `PartitionRunner`.

- Add `Sparse` variants to `PersistentBitMatrix` and `PersistentIntMatrix` enums, with auto-detection logic to migrate stale columnar files (`matrix.pbmx`, `matrix.pcmx`) to the new sparse format by rebuilding from columnar data.
- Refactor bit manipulation functions (`or_where`, `and_where`, `xor_where`) in `bitvec.rs` to use direct references (`*word`) instead of indexed access (`words[wi]`), and update remainder handling in `set_last_word`.
- Update `read_int_window` and `read_bit_window` in sparse matrix modules to use `as_chunks::<8>()` for efficient byte-to-u64 conversion, replacing `chunks_exact` and `try_into`.
- Modify `inc_predicate_fast` in `builder.rs` to iterate over `primary.iter_mut().zip(col.primary_bytes())` for incrementing values, avoiding index-based access.
- Add `is_empty` methods to `Evidence`, `FamilyScalarAnnex`, and `RopeCursor` to check for zero-length or empty states.
- Implement `Default` for `PartitionRunner` in `obisys`, delegating to `Self::new()`.
- Refactor multiple test functions across `obicompactvec`, `obikmer`, `obikphylo`, `obikquery`, and `obiskio` to use `enumerate()`, `iter()`, and `take()` instead of index-based loops, improving idiomatic Rust patterns.
- Update `merge_partition` in `obikmerge` to use `clamp(4, 16)` for worker count calculation instead of chained `min`/`max` calls.
- Add `#[allow(clippy::large_enum_variant)]` to `KmerLayer` and `#[allow(clippy::too_many_arguments)]` to subsample functions, with updated documentation clarifying layer types and argument independence.
- Refactor `write_sankoff_phyg` and `write_sample_stats` in `obikmer` to use iterator methods (`take`, `copied`, `enumerate`) for processing matrices and labels.
- Update `build_emax` and `build_log_nwords` in `obikentropy` to use `enumerate` and direct cell references, and add `WS_MAX` constant and comments in `table.rs`.
- Modify `push_warmup_increments` in `obikentropy` to accept a fixed-size array `[u64; 6]` instead of individual arguments, updating `push` accordingly.
- Refactor `resolve_partition_batch` and `query_partition_with` in `obikphylo` and `obikquery` to iterate over `by_layer.iter_mut().enumerate().take(n_layer)`, using direct bucket references.
- Update `ascii_histogram` in `obikmer` to use `checked_div` and `unwrap_or(0)` for bar length calculation, replacing conditional checks.
- Refactor `from_ascii` in `obikseq` to iterate over references `&base in &ascii[..k]` instead of indices, and update related tests to use `#[test]` attributes and new type aliases.
2026-12-01 17:43:44 +01:00
Eric Coissac f022d83394 refactor: modernize arithmetic, control flow, and error handling
Replace manual ceiling division with `div_ceil`, update `map_or` patterns to `is_some_and`/`is_ok_and`, and simplify error handling across the codebase. Move the `default` function for `GraphDeBruijn` from the index layer module to the De Bruijn graph module.

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

- `src/obicompactvec`: Add support for sparse bit matrices and overflow handling in compact vectors; update distance metrics (Jaccard, Bray, Euclidean) to accept explicit sums and thresholds; add `transpose` module and refine `PersistentBitMatrix`/`PersistentSparseBitMatrix` APIs.
- `src/obicompactvec/src/bitmatrix`: Implement `PersistentSparseBitMatrix` and `PersistentSparseBitMatrixBuilder`; update pairwise distance calculations to handle implicit and sparse types; add `partial_group_presence_count` for group operations.
- `src/obicompactvec/src/tests`: Update tests to use new sparse matrix APIs, explicit `.close().unwrap()` chains, and refined assertions for distance symmetry and diagonal checks.
- `src/obidebruinj`: Refactor De Bruijn graph traversal to use atomic fetch-or for visited masks and explicit direction checks in `unitig_nucleotides` and `for_each_unitig`.
- `src/obifastwrite`: Update `annotation` to accept slice of tuples; refine `write_scatter` and `write_count` output structures; improve ID extraction in `different_sequences_different_id`.
- `src/obikdump`: Refactor `dump` and `write_unitigs` to use parallel iterators (`rayon::into_par_iter`) and updated `IndexCache` imports for kmer partitioning.
- `src/obikentropy`: Update `emit_f64_2d` formatting; refine entropy tests to use `Kmer::from_ascii` directly and multi-line assertions for range checks.
- `src/obikfilter`: Add `MinComplexity` filter; update `passes` logic for ingroup/outgroup counts with explicit threshold checks; refactor `filter_partition` to use closures for kmer insertion.
- `src/obikidxcache`: Update `iter_partition` and `iter_indexed` to handle explicit partition arguments and collect layer cache keys before iteration.
- `src/obikindex`: Refactor `IndexBuilder` and `KmerIndex` to explicitly initialize `meta` and `lock`; update `OKIError` to include static context and string details; add `TypedLayer` row presence histogram support.
- `src/obikindexer`: Update `build_index_layer` to handle zero layers and flatten `mphf1.bin` loading; refactor `graph_pipeline` to explicitly define transformations and sinks for `KmerGraphData`.
- `src/obikmer`: Refactor CLI commands (`annotate`, `convert`, `dump`, `filter`, `pack`, `select`, `unitig`) to use explicit error handling with `unwrap_or_else` and updated metadata access; add `query` and `select` modules.
- `src/obikmer/src/cmd/phylo`: Update phylogenetic output writers (`iqtree`, `phyg`, `phylip`, `sankoff`, `tnt`) to handle explicit genome indices, sites, and alignment structures; add `shared` module for shared kmer writing.
- `src/obikmerge`: Refactor `merge` to validate source compatibility with specific error messages; update pass 2 logic to stream layer unitigs to column builders.
- `src/obikphylo`: Overhaul distance metrics to support ambiguity policies and quartet conventions; update `SnpAlignment` to include sites; refactor sibling algorithms to handle masking, entropy, and pair weights explicitly.
- `src/obikphylo/src/siblings`: Update `alignment`, `cardcomp`, `entropy`, `masking`, and `pairwise` algorithms to use explicit policy arguments and refined assertions; add `sample_stats` and `subsample` modules.
- `src/obikphylo/src/tree`: Refactor `neighbor_joining` and `upgma` to explicitly handle node creation, edge finding, and label cloning.
- `src/obikquery`: Add `partition_kmers`, `query_layer`, and `smer_index` modules; update `process_chunk` to use explicit iterator chaining for statistics; refine `from_records` to push kmer descriptions.
- `src/obikrebuild`: Refactor `compact_partition` and `reindex` to use explicit block structures and updated error mapping for metadata evidence.
- `src/obikselect`: Update `build_output_cols` to handle group operations and default aggregation; refine `select_partition` to explicitly pass thresholds and presence flags.
- `src/obikseq`: Update `Kmer` push methods to use bitwise operations with `PhantomData`; refine `PackedSeq` initialization and error handling; add `RoutableSuperKmer` to public API.
- `src/obiksession`: Update `Session` to accept `force` parameter for opening; refine `Memoize` to use `get_or_compute_with_key` and explicit byte conversion.
- `src/obikstats`: Refactor `SharingNullModel` to directly construct probability vectors; update tests to use fixed `SharingSpectrum` definitions.
- `src/obipipeline`: Refactor scheduler macros to wrap transformations in `Box<dyn Fn>` with `Send + Sync`; update `Pipe` and `Pool` to handle explicit error signaling and stage indexing.
- `src/obiread`: Add `text/gbff` MIME type; update `read_sequence_chunks_sized` to use explicit `SeqChunkIter` constructors; refine `SeqRecord` initialization.
- `src/obiskbuilder`: Add `stream_iter` module for streaming superkmer iteration; update benchmarks to use direct `.count()` calls.
- `src/obiskio`: Refactor `SKError` to include static context and string details; update `UnitigFileReader`/`Writer` to use explicit error mapping and block offset handling.
- `src/obisys`: Refactor `DirLock` to use explicit `acquire_mode` and `promote`/`demote` logic; update `LockSlot` to handle exclusive/shared states with mutexes; refine `NodeConfig` and `effective_parallelism` tracing.
- `src/obitaxonomy`: Refactor `TaxPath` and `TaxPattern` parsing to handle segments and ranks explicitly; update error messages to include segment information; add `segment` and `segment_pattern` modules.
2026-12-01 17:34:15 +01:00
Eric Coissac 8159137f8b chore: add crate-kit build system and CeCILL license
Introduce the `.crate-kit` infrastructure to standardize build, testing,
and release workflows using Jujutsu and Cargo. Add CeCILL-2.1 license
files and update all workspace crate manifests with license and repository
metadata.

- Add `.crate-kit/` directory with `VERSION`, `crate.mk`, `dev-patch.mk`,
  `jj.mk`, and `org.mk` to define build targets, Jujutsu helpers, and
  registry configuration for the workspace.
- Add 21 shell scripts in `.crate-kit/scripts/` for API tracking,
  dependency checking, version bumping, publishing, tagging, and wiki
  generation, including `common.sh` with shared utility functions.
- Add `scripts/jj-tag.sh` to support tagging commits with version strings
  derived from the current crate version.
- Add `LICENSE` and `LICENSE.en` files containing the CeCILL-2.1 free
  software license agreement in French and English.
- Update `Makefile` with new targets for building, testing, formatting,
  CI, and releasing, integrating with `.crate-kit` scripts and updating
  the wiki directory path to `obiskim`.
- Update `.gitignore` to ignore `.cargo/config.toml` files generated by
  the development patch system.
- Add `license = "CECILL-2.1"` and
  `repository = "https://forge.metabarcoding.org/obi/obiskim"` to all
  `Cargo.toml` files in the workspace, including `obicompactvec`,
  `obidebruinj`, `obifastwrite`, `obikalgorithm`, `obikdump`,
  `obikentropy`, `obikfilter`, `obikidxcache`, `obikindex`,
  `obikindexer`, `obikmer`, `obikmerge`, `obikphylo`, `obikquery`,
  `obikrebuild`, `obikrope`, `obikselect`, `obikseq`, `obiksession`,
  `obikstats`, `obipipeline`, `obiread`, `obiskbuilder`, `obiskio`,
  `obisys`, and `obitaxonomy`.
- Update `src/obikrope/Cargo.toml` to use `criterion2` version 3 with
  the `cargo_bench_support` feature.
- Update `src/obikseq/Cargo.toml` to replace the "OnceLock-based params"
  feature with a new feature description involving thread-local storage.
- Update `src/Cargo.lock` to reflect the version bump of `obikmer` from
  1.4.7 to 1.4.8.
2026-12-01 17:18:34 +01:00
coissac 58e57ceae5 Merge pull request 'refactor: remove migrate-mphf tool and update sibling annex handling' (#84) from push-rstmlzzlxuzq into main
Reviewed-on: OBIKmers/obikmer#84
2026-12-01 09:36:34 +00:00
Eric Coissac b95348b226 refactor: remove migrate-mphf tool and update sibling annex handling
ci.yml / build (pull_request) Successful in 4m10s
Release / create-release (push) Successful in 26s
Release / build-linux-x86_64 (push) Successful in 6m22s
Release / build-macos-arm64 (push) Successful in 2m23s
Remove the `migrate-mphf` tool entirely, as its functionality is no longer needed or has been superseded. Update the `phylo` sibling annex logic to build missing annexes on demand under an exclusive lock, ensuring safe concurrent access. Adjust documentation and CI workflows to reflect the removal of the migration tool and clarify sibling annex behavior.

- Delete the entire `tools/migrate-mphf` directory, including `Cargo.toml`, `Cargo.lock`, and source files (`main.rs`, `layer.rs`, `plan.rs`, `data.rs`, `commit.rs`, `old.rs`, `verify.rs`, `util.rs`), removing functions such as `convert`, `build`, `permute_all`, `finish`, and `check`.
- Update `.gitignore` to remove patterns for `tools/migrate-mphf/target`, `data-stress`, `*.fasta`, and `*.fasta.gz`.
- Modify `Makefile` to remove the `migrate-mphf` and `clean-migrate-mphf` phony targets and associated build commands.
- Update `.gitea/workflows/release.yml` to remove the "Build migrate-mph (static)" job and the artifact upload step, and adjust the `linux-musl-cargo` job key to hash only `src/Cargo.lock`.
- Refactor `src/obikphylo/src/siblings/extensions/sibling_builder.rs` to update `build_family_annexes` documentation, noting that it builds the sibling annex from `siblings.psib` if missing and runs under the index's exclusive lock.
- Update `src/obikphylo/src/siblings/siblingannex.rs` documentation to clarify that `open` reports absent files differently when annexes were set aside by `migrate-mphf` or never built.
- Update `UserDocMD/usage/phylo.md` to clarify that `--sibling-annex` prepares the quartet annex on demand under an exclusive lock, and update descriptions for `--sibling-stats` and `--sibling-hist` to specify output file formats and contents.
- Update `DevDocMD/implementation/mphf_batch_queries.md` to reflect changes in batched query logic, `ptr_hash` versioning, and benchmark descriptions, noting that stale indexes with `ptr_hash` 1.x MPHFs fail on current binaries.
- Add `prompts/obi-migration.md` to document the context, decisions, and required actions for the `obikmer` project migration.
- Bump `obikmer` package version from 1.4.7 to 1.4.8 in `src/obikmer/Cargo.toml` and update `src/Cargo.lock` accordingly.
2026-12-01 10:31:25 +01:00
coissac d7ea6973e3 Merge pull request 'Push punmmmpkuymy' (#83) from push-punmmmpkuymy into main
Reviewed-on: OBIKmers/obikmer#83
2026-11-20 13:24:06 +00:00
Eric Coissac 1119af85ba feat: update indexing pipeline and bump obikmer version to 1.4.7
Release / create-release (push) Successful in 1m15s
Release / build-linux-x86_64 (push) Successful in 6m43s
Release / build-macos-arm64 (push) Successful in 1m57s
ci.yml / build (pull_request) Successful in 3m42s
Refactor the indexing process to support parallel phases, resumable builds, and three verification modes (Exact, Approximate, Hybrid). Update the on-disk layout to manage evidence-specific files and state in `index.meta`, and refine layer merging logic. Bump the obikmer package version from 1.4.6 to 1.4.7.

- Modify indexing routing to use low bits of hash and enable parallel, independent phases for resumable builds
- Update counting phase to build provisional MPHF and temporary counts, deleted unless `--keep-intermediate` is set
- Combine quorum filtering with local assembly by filtering kmers during de Bruijn graph construction before unitig assembly
- Expand verification modes to Exact, Approximate, and Hybrid, allowing post-build conversion between them
- Update on-disk layout to include specific files for each evidence type and manage build state in `index.meta`
- Refine layer merging to create new layers only for genuinely new kmer content and determine destination evidence mode from sources
- Add `--sparse` option to packing logic for sparse representation support
- Bump obikmer package version from 1.4.6 to 1.4.7 in Cargo.toml
2026-11-20 14:21:01 +01:00
Eric Coissac 36c7247acb feat: add k-mer sharing estimation and Poisson-binomial null model
Add a new `estimate --index` command to compare observed k-mer sharing against
a random-sequence model using a Poisson-binomial distribution. Introduce the
`row_presence_histogram` API to support this analysis across various matrix
types. Update documentation and dependencies accordingly.

- Add `src/obikstats/src/null_model.rs` implementing `SharingNullModel` and
  `SharingRow` for computing cumulative probabilities and false discovery rates
  based on a Poisson-binomial distribution.
- Add `src/obikstats/src/sharing.rs` defining `GenomeSharing` and `SharingSpectrum`
  to compute k-mer sharing spectra using parallel map-reduce.
- Add `src/obikmer/src/cmd/estimate/sharing.rs` with `run` and `write_csv` to
  execute sharing estimation and output CSV results containing observed, expected,
  and deviation metrics.
- Modify `src/obikmer/src/cmd/estimate/mod.rs` to support the new `--index`
  subcommand, adding `EstimateArgs` fields for index path, presence threshold,
  and output file.
- Add `src/obicompactvec/src/row_histogram.rs` implementing `row_presence_histogram`
  for `PersistentIntMatrix`, `PersistentBitMatrix`, and sparse matrices to count
  rows present in exactly $j$ columns.
- Update `src/obikindex/src/layer/content_layer.rs` and `src/obikindex/src/layer/typed_layer.rs`
  to expose the new `row_presence_histogram` method, dispatching based on layer type.
- Add tests in `src/obicompactvec/src/tests/bitmatrix.rs`, `intmatrix.rs`, and
  `sparse.rs` to verify `count_geq` and `row_presence_histogram` against naive
  implementations for various matrix structures.
- Update `UserDocMD/theory/kmer_indexing/kmers.md` to document the Poisson-binomial
  approach, $D_r$ bounds, and FDR calculations, replacing previous binomial approximations.
- Update `UserDocMD/usage/estimate.md` to describe the two uses of `estimate`:
  parameter estimation and index comparison via `--index`.
- Add `wiki` target to `Makefile` for regenerating documentation from user docs.
- Bump `obikmer` package version from 1.4.5 to 1.4.6 in `Cargo.toml` and `Cargo.lock`.
2026-11-19 17:50:29 +01:00
Eric Coissac 6d6d5e5e53 feat: add count_geq method to calculate column counts above a threshold
Introduce `count_geq` across the codebase to return the number of k-mers present in columns with counts greater than or equal to a specified threshold. This unifies the interface for counting distinct k-mers and updates `partial_kmer_counts` to rely on `count_geq(1)`.

- Add `count_geq` method to `PersistentBitMatrix` in `src/obicompactvec/src/bitmatrix/persistent.rs`, delegating to `count_ones`.
- Implement `ColumnWeights` trait for `PersistentBitMatrix` and add `count_geq` to `PersistentSparseBitMatrix` in `src/obicompactvec/src/bitmatrix/sparse.rs`.
- Add `count_geq` methods to `IntMatrix` variants (`Columnar`, `Packed`, `Sparse`) and `PersistentIntMatrix` in `src/obicompactvec/src/intmatrix.rs`, removing `partial_kmer_counts`.
- Implement `count_geq` for `SparseCompactIntMatrix` in `src/obicompactvec/src/sparse_intmatrix.rs`, handling threshold 0 explicitly, and remove `partial_kmer_counts`.
- Add `count_geq` method to `Reader` struct in `src/obicompactvec/src/reader.rs` with documentation.
- Update `ColumnWeights` trait in `src/obicompactvec/src/traits.rs` to include `count_geq` and redefine `partial_kmer_counts` as `count_geq(1)`.
- Add `count_geq` method to `Views` struct in `src/obicompactvec/src/views.rs` for distance calculations.
- Add `count_geq` tests in `src/obicompactvec/src/tests/sparse_intmatrix.rs` verifying behavior against naive implementations.
- Add `count_geq` to `ContentLayer` in `src/obikindex/src/layer/content_layer.rs`, delegating based on layer type.
- Add `count_geq` to `TypedLayer` in `src/obikindex/src/layer/typed_layer.rs`, delegating to `obicompactvec::ColumnWeights`.
- Add `count_geq` method to distance struct in `src/obikphylo/src/distance.rs` using `self.reduce`.
2026-11-19 17:49:19 +01:00
Eric Coissac 33d7a59dd9 docs: restructure documentation for kmer indexing and phylogeny theory
Reorganize the documentation structure to better separate kmer indexing logic from phylogenetic analysis methods. This involves moving several existing pages into new directories under `theory/kmer_indexing` and `theory/phylogeny`, updating navigation links across the site, and adding new content for VCF pseudo-alignment and specific phylogenetic models.

- Move `doc/index.html` to `doc/theory/kmer_indexing/minimizer_selection/index.html` to document minimizer selection logic.
- Move `doc/installation/index.html` to `doc/theory/phylogeny/kmer_based/kmer_set_distances/index.html` for whole k-mer set distance documentation.
- Move `doc/usage/dump/index.html` to `doc/theory/kmer_indexing/superkmers/index.html` to cover canonical super-kmers.
- Move `doc/usage/query/index.html` to `doc/theory/kmer_indexing/entropy_filter/index.html` for low-complexity kmer filtering details.
- Move `doc/theory/encoding/index.html` to `doc/theory/kmer_indexing/encoding/index.html` for DNA and kmer encoding specifics.
- Move `doc/theory/indexing_architecture/index.html` to `doc/theory/kmer_indexing/indexing_architecture/index.html` for partitioning and routing architecture.
- Move `doc/usage/query/index.html` (duplicate move noted in facts, likely referring to the query command usage or similar) to `doc/theory/phylogeny/snp_based/sankoff_model/index.html` for the 16-state Sankoff model.
- Move `doc/theory/minimizer_selection/index.html` to `doc/theory/phylogeny/snp_based/central_snp_model/index.html` for central-position SNP models and substitution corrections.
- Move `doc/theory/indexing_architecture/index.html` (duplicate move noted) to `doc/theory/phylogeny/snp_based/gamma_rate_heterogeneity/index.html` for gamma rate heterogeneity and automatic alpha estimation.
- Move `doc/theory/entropy_filter/index.html` to `doc/theory/phylogeny/snp_based/sampling_design/index.html` for entropy-biased sampling design.
- Move `doc/formats/index_layout/index.html` to `doc/formats/vcf/index.html` to document VCF pseudo-alignment output and structure.
- Add `doc/molecular-ecology-modified.csl` with a new XML style definition for Molecular Ecology Modified citations.
- Update `UserDocMD/formats/vcf.md` to clarify that `--vcf` implies `--pseudo-alignment`, requires `--n-sites`, and generates files alongside `--fasta`.
- Add three new BibTeX entries in `UserDocMD/references.bib` for Karlin (1997, 1995) and Bennett & Moran (2013).
- Update `UserDocMD/theory/kmer_indexing/kmers.md` to use binomial distribution for probability calculations and define k-mer sharing deviation.
- Clarify in `UserDocMD/theory/phylogeny/kmer_based/kmer_set_distances.md` that counts are used instead of presence/absence for $L^1$ distance.
- Update `UserDocMD/theory/phylogeny/snp_based/gamma_rate_heterogeneity.md` to attribute method-of-moments $\alpha$ estimation to obikmer, not Jin & Nei (1990).
- Update `UserDocMD/theory/phylogeny/snp_based/sampling_design.md` to redirect entropy sampling references to the correct phylo section.
- Add new options `--cpu-max`, `--output`, `--pair-balance`, `--sibling-stats`, `--family-overlap`, and `--shannon` to `UserDocMD/usage/phylo.md`.
- Mark SNP-based distance saving and session reuse as unavailable in `src/obikmer/src/cmd/phylo/args/distance.rs`.
2026-11-19 17:47:59 +01:00
coissac d78a6b4501 Merge pull request 'Push vpnykuuvnrnx' (#82) from push-vpnykuuvnrnx into main
Reviewed-on: OBIKmers/obikmer#82
2026-11-19 06:17:43 +00:00
Eric Coissac 5db7b440da refactor: treat absence as state unless --free-loss and update quartet annexes
ci.yml / build (pull_request) Successful in 4m33s
Release / create-release (push) Successful in 1m56s
Release / build-linux-x86_64 (push) Successful in 11m18s
Release / build-macos-arm64 (push) Successful in 2m27s
Refactor the handling of genome absence to be a distinct state unless `--free-loss` is specified. This change introduces `QuartetConvention` to pair ambiguity policies with the free-loss flag, updating file naming conventions and logic across sampling, masking, and stats modules.

- Update `--exclude-genome` description in `pair_coverage_sampling.md` to clarify absence as a state unless `--free-loss` is specified.
- Move multi-member genome handling convention from `pair_coverage_sampling.md` to file name conventions.
- Clarify persisted annex structure in `pair_coverage_sampling.md` as `PersistentBitVec` per non-monomorphic family with counting convention carried by file name.
- Fix initial version's absence handling in `has_bipartition`, the annex, and `--sample-stats` to correctly count index 0 when absence is a state.
- Replace entropy-only builder with `AnnexRequest` and `ensure_layer_family_annexes`.
- Consolidate sampling parameters into a single `SamplingSpec`.
- Update family constraint description in `sampling_design.md`.
- Modify uniform draws and `--quartet` removal text in `sampling_design.md`.
- Clarify state counting in tests for `--free-loss` option in `sampling_design.md`.
- State that absence forms a pair without `--free-loss` but never with it in `sampling_design.md`.
- Update `--quartet` option to require at least two distinct states, each carried by at least two genomes.
- Define absence as a state unless `--free-loss` is given for family carrier definition.
- Clarify `--pair-balance` favors families covering pairs with fewest shared families.
- Modify logic for families fitting every tree topology equally well in `phylo.md`.
- Change `--quartet` restriction logic to apply after pre-checks involving `--no-ambiguity` and `--exclude-genome`.
- Update `obikmer` dependency version from 1.4.4 to 1.4.5 in `Cargo.lock` and `Cargo.toml`.
- Modify `annex_selection` in `args/mod.rs` to derive `free_loss`, `entropy`, `quartet`, and `overlap` from `SamplingSpec`.
- Update `SamplingArgs::quartet` documentation in `sampling.rs` to describe state determination based on `--free-loss`.
- Add `free_loss` field to `AnnexSelection` struct in `family_annexes.rs`.
- Change `AnnexRequest` to use `Vec<QuartetConvention>` instead of `Vec<AmbiguityPolicy>`.
- Update `request` logic in `family_annexes.rs` to conditionally create `QuartetConvention` based on `self.quartet`.
- Modify `dedup` signature in `family_annexes.rs` to accept iterator of type `T: Ord`.
- Update `ensure_layer_family_annexes` in `family_annexes.rs` to use `missing_files` and `QuartetConvention`.
- Add `missing_files` definition to `family_annexes.rs`.
- Change `has_bipartition` in `masking.rs` to filter counts where count is `>= 2`.
- Update `is_quartet_informative` in `masking.rs` to accept `free_loss` boolean parameter.
- Modify `two_pairs_of_distinct_states_is_informative` and `singleton_variant_is_not_informative` in `masking.rs` to test both `free_loss` policies.
- Add `under_free_loss_absence_is_missing_and_forms_no_pair` and `without_free_loss_absence_is_a_state_that_can_form_a_pair` definitions to `masking.rs`.
- Update `no_ambiguity_drops_multi_member_genomes_from_the_count` in `masking.rs` to check `is_quartet_informative` under `free_loss=true`.
- Add `the_annex_rule_and_the_exact_check_agree_on_the_same_family` definition to `masking.rs`.
- Remove `absent_genomes_are_not_a_state` definition from `masking.rs`.
- Update `restrict_to_quartet` in `quartet.rs` to accept `QuartetConvention` instead of `AmbiquityPolicy`.
- Modify `add_site` in `sample_stats.rs` to handle state 0 as a state participating in bipartition.
- Add `absence_as_a_state_makes_a_site_informative` definition to `sample_stats.rs`.
- Add `quartet_convention` function to `SamplingSpec` in `subsample.rs`.
- Update `sample_index` in `subsample.rs` to use `spec.quartet_convention()` for `AnnexRequest`.
- Update `restrict_to_quartet` call in `subsample.rs` to use `spec.quartet_convention()`.
- Add comment regarding `--no-ambiguity` counting convention in `helpers.rs`.
- Import `QUARTET_ANNEX_FILE_NAMES` and `QuartetConvention` from `quartet_annex` in `mod.rs`.
- Add `QuartetConvention` struct with `policy` and `free_loss` fields to `quartet_annex.rs`.
- Modify `quartet_annex_file_name` in `quartet_annex.rs` to take `QuartetConvention`.
- Add `the_conventions_never_share_a_file` function to `quartet_annex.rs`.
- Remove `the_policies_never_share_a_file` definition from `quartet_annex.rs`.
2026-11-19 07:12:36 +01:00
Eric Coissac c93616b432 feat: add threshold-based Hamming distance and refine phylo documentation
Add `threshold_hamming_dist_matrix` to calculate k-mers present in exactly one genome using union minus intersection. Update `DistanceArgs` and `distance.rs` to support this metric on count indexes via `--presence-threshold`, removing the previous restriction that hamming was only for presence/absence indexes.

- Add `threshold_hamming_dist_matrix` method to `CountPartials` in `src/obikmer/src/traits.rs`
- Implement new test `threshold_hamming_counts_kmers_present_in_one_genome_only` in `src/obicompactvec/src/tests/intmatrix.rs`
- Update `DistanceArgs` in `src/obikmer/src/cmd/phylo/args/distance.rs` to clarify threshold effects on Jaccard/Mash/Hamming
- Modify `distance` function in `src/obikphylo/src/distance.rs` to support Hamming on count indexes and use pre-computed bit structures
- Update `obicompactvec.md` documentation with new function details and partial result explanations
- Refine `index.md` descriptions for `phylo`, `unitig`, and `select` options
2026-11-19 07:11:57 +01:00
Eric Coissac c4eacb3f72 feat(phylo): expand genome distance metrics and refactor CLI arguments
Refactor the `phylo` command to support explicit distance metrics (Jaccard, Hamming) and SNP-based pseudo-alignments. Replace implicit metric selection with explicit requirements, such as requiring `--n-sites` for SNP analysis. Add a new `shared-kmers` output option and update documentation for performance characteristics of sparse vs dense formats.

- Update `phylo` CLI to support genome-vs-genome distances using k-mer content or SNPs, including options for NJ/UPGMA tree building and data export
- Replace `reindex` command with `convert` for in-place index evidence conversion (exact/approx/hybrid) and add `--upgrade-index` to `utils` for missing layer metadata
- Refactor `distance_to_compute` logic to remove implicit Jaccard implications for `--nj`/`--upgma` unless `--distance` is specified, and enforce `--n-sites` for `--pseudo-alignment`/`--sankoff`
- Add `shared_kmers` method to `Metrics` trait in `src/obikphylo/src/distance.rs` and new `write_shared_kmers` function in `src/obikmer/src/cmd/phylo/shared.rs` for CSV export
- Update `PackArgs::dense` documentation to clarify that dense format is faster for column-oriented distance matrices while sparse is better for single-row access
- Remove `requires_counts` definition and update assertions in `values.rs` to reflect new distance computation signatures and metric requirements
2026-11-19 07:11:44 +01:00
Eric Coissac 14433e80a5 refactor: restructure phylo CLI arguments into submodules
Refactor the `phylo` command's argument handling by splitting the monolithic
`args.rs` file into specialized submodules (`distance`, `outputs`, `sampling`,
`select`) and a central `mod.rs`. This improves modularity and separates
concerns for distance metrics, sampling options, and output configurations.

- Move `alignment_output`, `ambiguity`, and `annex_selection` from `args.rs` to
  `args/mod.rs` in the `PhyloArgs` struct.
- Relocate distance parsing logic (`parse_gamma_shape`, `parse_n_sites`, `target`)
  and helper functions (`distance_to_compute`, `as_classic`, `as_snp`, etc.) from
  `args.rs` to `values.rs`.
- Add new submodule files: `args/distance.rs` for `DistanceArgs`, `args/outputs.rs`
  for `AlignArgs` and `CostsArgs`, `args/sampling.rs` for `SamplingArgs`, and
  `args/select.rs` for `SelectArgs` and `AnnexArgs`.
- Update `main.rs` to register the new `Phylo` command using `cmd::phylo::PhyloArgs`.
- Refactor `mod.rs` (`run`) to use nested argument structures (e.g., `args.dist`,
  `args.sample`) instead of flat fields.
- Update `alignment_out.rs` to reference the new nested paths (`args.align.fasta`,
  `args.sample.no_ambiguity`).
2026-11-19 07:11:26 +01:00
Eric Coissac 7f829ea557 docs: clarify merge re-merge behavior and input file handling
Update documentation to explain that merged indices can serve as sources if at least one source is unmerged, and that the resulting column order follows the base index first. Clarify that explicitly named files are always read regardless of extension, with format detection based on content.

- refactor: prevent I/O errors when re-merging packed outputs by restricting `choose_base` to valid destinations via new `can_be_destination` check
- fix: handle zero-layer partitions in `build_index_layer` and `remove_build_artifacts` to skip unnecessary operations
- feat: allow `PathIter` to treat unrecognized extensions as explicit files, ensuring they are not silently dropped during directory expansion
- test: add comprehensive tests for `PathIter` including extension recognition, explicit file handling, and stdin sentinel behavior
- test: update smoke tests to verify empty partitions, `.fna.gz` indexing, and refusal of merging only packed indexes
- chore: remove obsolete cargo build environment variables from `run.sh` script
2026-11-19 07:10:58 +01:00
Eric Coissac 07c0a54e04 feat: add compatibility testing scripts and update dependencies
Add `compat_ptrhash.sh` and `compat_ptrhash2.sh` to facilitate determinism control and incremental merge testing between obikmer binaries. Update `tikv-jemallocator` dependency version in `Cargo.toml` and refresh `Cargo.lock` with new crates and checksums.

- Add scripts/docker_debug/compat_ptrhash.sh for compatibility tests (T0-T4) comparing ptr_hash versions using Docker and md5sum
- Add scripts/docker_debug/compat_ptrhash2.sh for determinism control and incremental merge operations between binaries A and B
- Update src/obikmer/Cargo.toml to change tikv-jemallocator version from 0.7.0 to 0.5.4 under musl target cfg
- Update src/Cargo.lock by adding new crates (anes, block-pseudorand, criterion, plotters, etc.) and updating existing package versions/checksums
2026-11-19 07:10:37 +01:00
Eric Coissac af525cd268 feat: switch musl builds to jemalloc allocator for stability
Update Cargo.lock to remove unused dependencies and update tikv-jemallocator. Configure src/obikmer/Cargo.toml to use jemalloc for static musl builds, addressing fragmentation issues with the default multi-threaded allocator. Update main.rs to conditionally set Jemalloc as the global allocator when targeting musl.

- Remove unused dependencies from Cargo.lock: anes, block-pseudorand, chiapos-chacha8, criterion, criterion-plot, itertools (and its either dep), nanorand, hermit-abi, is-terminal, plotters ecosystem, tinytemplate deps, voracious_radix_sort rayon dep, and web-sys deps.
- Update tikv-jemallocator version from 0.5.4 to 0.7.0 in Cargo.lock.
- Add tikv-jemallocator = "0.7.0" to musl-specific dependencies in src/obikmer/Cargo.toml.
- Set Jemalloc as the global allocator in main.rs for static musl builds.
2026-11-19 07:10:20 +01:00
Eric Coissac d0668eb167 feat: add columnar sparse matrix support and windowed transposition
Introduce `sparse_columnar` and `sparse_intmatrix_columnar` modules to enable
building sparse matrices directly from columnar data without dense intermediates.
Add a `transpose` module with `RowBatch` and `transpose_windows` for efficient
windowed column-to-row transposition based on density checks.

- Add `src/obicompactvec/src/bitmatrix/sparse_columnar.rs` with `build_from_columnar`,
  `build_from_columnar_with`, and `read_bit_window` to build sparse bit matrices
  from columnar files using windowed reads.
- Add `src/obicompactvec/src/sparse_intmatrix_columnar.rs` with `build_from_columnar`,
  `build_from_columnar_with`, `invalid`, and `read_int_window` for integer matrix
  construction from PCIV columns, handling sentinel values and overflow.
- Add `src/obicompactvec/src/transpose.rs` containing `RowBatch<V>` struct and
  `transpose_windows` function for dynamic window sizing and memory-bounded
  column-to-row transposition.
- Update `src/obicompactvec/src/bitmatrix/sparse.rs` to use `packed_bit_matrix_n_cols`
  and `MatrixMeta` for validation, ensuring stale columnar data is transposed directly
  into a single `matrix.pbmx` file while removing old column files.
- Update `src/obicompactvec/src/sparse_intmatrix.rs` to use `packed_int_matrix_n_cols`
  for column count validation, making `pack_sparse_compact_int_matrix` idempotent and
  avoiding dense intermediates by transposing columnar data directly.
- Expose `packed_bit_matrix_n_cols` in `src/obicompactvec/src/bitmatrix/packed.rs` and
  make `packed_int_matrix_n_cols` public in `src/obicompactvec/src/intmatrix.rs`.
- Add `sparse_columnar` module to `src/obicompactvec/src/bitmatrix/mod.rs` and export
  `PersistentBitMatrixBuilder` and `batch_presence_counts`.
- Add `sparse_intmatrix_columnar` and `transpose` modules to `src/obicompactvec/src/lib.rs`.
- Add `transpose_columnar` test module in `src/obicompactvec/src/tests/mod.rs` with
  tests verifying columnar transpose matches dense route output.
2026-11-19 07:08:41 +01:00
Eric Coissac 4e98de4b77 feat: add BitSliceView::for_each_set_in and optimize build_from_dense
Introduce a new `views_scan` module containing `BitSliceView::for_each_set_in`, which iterates over set bits in a specified range using optimized word traversal. Update `build_from_dense` to use this method for batched, ordered column access, ensuring sorted row output. Add comprehensive tests for the new iteration logic and boundary handling.

- Add `src/obicompactvec/src/views_scan.rs` with `BitSliceView::for_each_set_in`, which iterates over a `Range<usize>` calling a closure for each set bit while optimizing sparse traversal via `word.trailing_zeros()`.
- Add `src/obicompactvec/src/tests/views_scan.rs` with tests `words`, `naive`, `scanned`, and helpers verifying that `for_each_set_in` matches naive iteration, handles empty/reversed ranges correctly, and rejects out-of-bounds ranges.
- Modify `build_from_dense` in `src/obicompactvec/src/bitmatrix/sparse.rs` to replace `nonzero_triples` with `dense.col_view(c).for_each_set_in`, ensuring column visits are batched and ordered for sorted row processing.
- Update module structure in `src/obicompactvec/src/lib.rs` and `src/obicompactvec/src/tests/mod.rs` to include the new `views_scan` module.
2026-11-19 07:08:07 +01:00
Eric Coissac 03eaa4544a feat: add pack optimization prompt, debug infrastructure, and monitoring scripts
Add a prompt template for optimizing the `pack` step and a suite of Docker-based
debug tools including build, run, and monitoring scripts. Enhance `pack_matrices`
with LFD partition sizing and detailed timing reports, and update `stop` with
additional system statistics.

- Add `prompts/pack_optimization.md` to guide optimization of the `pack` step,
  specifying context, performance measurements, and deliverable structures.
- Add `scripts/docker_debug/` infrastructure: Dockerfile for musl targets,
  `build.sh` for image creation, `run.sh` for parallel indexing and merging,
  `monitor.sh` for PID tracking, `gen_fasta.py` for synthetic genomes, and
  `gen_fasta_real.py` for real genome generation with `read_fna`.
- Add `scripts/monitor_pack.sh` as a 1 Hz sampler for I/O and memory metrics,
  writing samples to CSV and summary reports.
- Add `scripts/watch_merge.sh` to monitor process resource usage, enforcing
  memory limits via SIGTERM/SIGKILL guards based on VmRSS and VmSize.
- Modify `src/obikindex/src/index/kmer_index.rs`: add `pending_matrix_bytes` and
  `report_pack_timings`; update `pack_matrices` to use LFD strategy for partition
  sizing and clarify documentation regarding `stat()` proxy bytes.
- Modify `src/obisys/src/stage.rs`: update `stop` definition to include new
  variables (`user_secs`, `sys_secs`, faults, context switches, I/O blocks) and
  logic checking for swap usage.
2026-11-19 07:07:50 +01:00
Eric Coissac 24291a4484 refactor: remove unused dependencies and simplify logic
Remove obsolete dependencies across multiple crates to clean up the build graph and update `obikdump` to use `try_update`. Add dev-dependencies for tracing in `obiread` and clarify memoization logic in `obiksession`.

- Remove `obifastwrite`, `tracing`, `obidebruinj`, `obikentropy`, `obipipeline`, `obidex`, and `obiskbuilder` from `Cargo.lock`.
- Remove `obifastwrite` and `tracing` dependencies from `src/obidebruinj/Cargo.toml`.
- Update `dump` function in `src/obikdump/src/dump.rs` to use `try_update` instead of `fetch_update` for updating remaining counts.
- Remove `obitaxonomy`, `obidebruinj`, `obipipeline`, and `obikentropy` dependencies from `src/obikindex/Cargo.toml`.
- Remove `obiksession` dependency from `src/obikmer/Cargo.toml`.
- Remove `obiskbuilder` dependency from `src/obikphylo/Cargo.toml` and update `kodama` version to "0.3.0".
- Remove `bytes` dependency from `src/obikrope/Cargo.toml` and set `criterion2` version to "3" with `cargo_bench_support`.
- Add `tracing` and `tracing-subscriber` as dev-dependencies in `src/obiread/Cargo.toml`.
- Remove `lazy_static` dependency from `src/obiskbuilder/Cargo.toml` and add `obikseq` as a test-utils dev-dependency.
- Clarify `memo_key_from_debug` in `src/obiksession/src/memoize.rs` with comments explaining Debug-derived field usage.
2026-11-19 07:07:16 +01:00
coissac cbc344e4b4 Merge pull request 'Push txuyrtlmyoyl' (#81) from push-txuyrtlmyoyl into main
Reviewed-on: OBIKmers/obikmer#81
2026-11-17 14:38:33 +00:00
Eric Coissac 07bc5fc634 docs: update sparse packing strategy and benchmark scripts
ci.yml / build (pull_request) Successful in 4m53s
Release / create-release (push) Successful in 28s
Release / build-linux-x86_64 (push) Successful in 6m46s
Release / build-macos-arm64 (push) Successful in 4m8s
Update documentation to reflect that sparse packing now maps all columns of a layer at once and packs layers sequentially, reversing the previous choice to avoid materializing a packed copy. This change introduces an extra write/read cycle for the dense matrix, increasing pack benchmark time from 1.11s to 1.60s.

- Modify `pack_sparse_bit_matrix` in `src/obicompactvec/src/bitmatrix/sparse.rs` to always convert via the dense packed format, simplifying logic by removing conditional handling of existing files and ensuring a single mapping.
- Update `pack_sparse_compact_int_matrix` in `src/obicompactvec/src/sparse_intmatrix.rs` to exclusively handle conversion from the dense packed format (`matrix.pcmx`) to sparse, removing columnar format handling and simplifying file cleanup.
- Adjust `scripts/bench_merge_oracle.sh` to extract `PACK_WALL` metrics via `stage_field` for merge operations, updating grep patterns and output messages to report pack wall time.
- Revise `DevDocMD/implementation/merge_mmap_audit.md` and `merge_scaling.md` to document the new sequential packing strategy, noting that `N_part` scaling applies only to incremental merges and that `obisys::MemoryBudget` is no longer used by merge.
- Bump package version in `src/obikmer/Cargo.toml` from 1.4.3 to 1.4.4.
2026-11-17 15:35:41 +01:00
Eric Coissac 1f199c69db feat: implement in-memory column builders and refactor merge partitioning
Introduce `MemBitVecBuilder` and `MemCompactIntVecBuilder` to construct columns in RAM before writing, reducing the number of open file descriptors during merge operations. Refactor `partition_merge.rs` to use these new builders via `add_mem_col`, decoupling live memory mappings from source counts to prevent `SIGBUS` errors.

- Add `mem_builder` module with `MemBitVecBuilder` and `MemCompactIntVecBuilder` structs for in-memory column construction and PCIV file writing.
- Extend `MatrixBuilder` with `add_mem_col` and `n_cols` methods, updating `ColBuilder` enum to support `MemBit` and `MemInt` variants.
- Refactor `partition_merge.rs` to use `add_mem_col` instead of `add_col`, introducing `run_pass2` for batch processing and optimizing destination layer handling.
- Update `format.rs` with `pciv_index_layout`, `write_pciv_header`, and `write_pciv_tail` functions to manage PCIV index layout and header/tail sections.
- Modify `mmap_file.rs` to use `write_std_header` and introduce `write_built` for standardized file writing and flushing logic.
- Make `MAGIC` constant public in `bitvec.rs` and update documentation for memory mapping alignment and structure.
- Add test modules `tests/matrix_builder.rs` and `tests/mem_builder.rs` to verify column counts and byte-identical output of new builders against persistent versions.
- Update `mkdocs.yml` navigation to include "Merge mmap audit (2026-11)" documentation entry.
- Add implementation audit documentation in `DevDocMD/implementation/merge_mmap_audit.md` detailing memory mapping failures and refactoring plans.
- Add merge testing scripts `scripts/smoke_test_merge.sh` and `scripts/bench_merge_oracle.sh` for validation and benchmarking.
- Bump `obikmer` package version from 1.4.2 to 1.4.3 in `Cargo.toml`.
2026-11-17 15:16:41 +01:00
coissac b35127e4e3 Merge pull request 'Push smsmsoyssmnr' (#80) from push-smsmsoyssmnr into main
Reviewed-on: OBIKmers/obikmer#80
2026-11-09 10:01:21 +00:00
453 changed files with 39790 additions and 9688 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
0.3.4+0.1.1
+240
View File
@@ -0,0 +1,240 @@
# crate-kit: common targets for the crates of a multi-crate Rust project.
#
# This directory (.crate-kit/) is a COPY of the kit/ folder of the crate-kit repository: do not
# modify it here, fix it in crate-kit then run `make kit-update`.
#
# Usage, in the crate's Makefile:
# RELEASE_PROJECT_DESC = acmexxx (short description) # optional
# include .crate-kit/crate.mk
#
# Adjustable variables (before the include or on the command line):
# CARGO, CARGO_TOML, FEATURES, API_DIR, RELEASE_NOTES_DIR, REGISTRY, KIT_SRC
# KIT_LANG language of LLM-generated documents (default en; any language name or ISO code)
# RELEASE=x.y.z forces the version of bump-version / jjrelease
# DRY_RUN=1 publish: checks the package without sending it
#
# Crate kind: CRATE_KIND (default "crate"). kinds/<kind>.mk sets, before the targets, the generic variables
# that the kit reads: BUILD_TARGET (--target of the builds), EXTRA_TARGETS (targets that check and clippy
# go through in addition to the host), PUBLISH, API_TRACKED, WIKI (yes|no: publication to the registry,
# API snapshot and version verdict, wiki), AFTER_RELEASE (command run after the tag). A kind
# can also add its own targets. Kinds specific to an organization come from its overlay (org.mk
# sets REGISTRY and REGISTRY_INDEX); see tools/kit-assemble.sh.
KIT_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
KIT_SRC ?= ../crate-kit
CARGO ?= cargo
CARGO_TOML ?= Cargo.toml
FEATURES ?=
API_DIR ?= api
RELEASE_NOTES_DIR ?= ReleaseNotes
CRATE_KIND ?= crate
BUILD_TARGET ?=
PUBLISH ?= yes
API_TRACKED ?= yes
WIKI ?= yes
AFTER_RELEASE ?=
# Additional targets that check and clippy go through (e.g. EXTRA_TARGETS = wasm32-unknown-unknown).
EXTRA_TARGETS ?=
RELEASE_PROJECT_DESC ?= $(shell sed -n 's/^name = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1)
GREEN = \033[0;32m
YELLOW = \033[1;33m
BLUE = \033[1;34m
NC = \033[0m
include $(KIT_DIR)/dev-patch.mk
include $(KIT_DIR)/jj.mk
# Language of the documents an LLM generates (release notes). Default English; an extension kit
# overrides it in its org.mk (KIT_LANG ?= fr), included above, or the user on the command line.
KIT_LANG ?= en
# Language of the commit messages written by `jj auto-doc` (pmojj reads PMOJJ_LANG).
export PMOJJ_LANG = $(KIT_LANG)
ifeq ($(wildcard $(KIT_DIR)/kinds/$(CRATE_KIND).mk),)
$(error unknown crate kind: CRATE_KIND = $(CRATE_KIND) (kinds: $(patsubst $(KIT_DIR)/kinds/%.mk,%,$(wildcard $(KIT_DIR)/kinds/*.mk))))
endif
include $(KIT_DIR)/kinds/$(CRATE_KIND).mk
export KIT_LANG CARGO CARGO_TOML API_DIR RELEASE_NOTES_DIR REGISTRY RELEASE_PROJECT_DESC KIT_SRC CRATE_KIND PUBLISH API_TRACKED WIKI
.DEFAULT_GOAL := build
.PHONY: help build release debug test test-doc doc doc-build clean check fmt fmt-check clippy \
watch ci deps update bench coverage bump-version api-level api-snapshot publish wiki \
jjnew jjpush jjfetch jjrelease bookmark-check kit-check needs-commit kit-update kit-version
help:
@echo "$(GREEN)Available commands:$(NC)"
@sed -n "s/^## *\([^:]*\): */\1$$(printf '\t')/p" $(MAKEFILE_LIST) | column -t -s "$$(printf '\t')" | sed -e 's/^/ /'
## build: Release build (alias of release)
build: release
## release: Release build (the kind's BUILD_TARGET, if it sets one)
release:
@echo "$(YELLOW)→ Building (release)...$(NC)"
$(CARGO) build --release $(if $(BUILD_TARGET),--target $(BUILD_TARGET)) $(FEATURES)
@echo "$(GREEN)✓ Build finished$(NC)"
## debug: Debug build (the kind's BUILD_TARGET, if it sets one)
debug:
@echo "$(YELLOW)→ Building (debug)...$(NC)"
$(CARGO) build $(if $(BUILD_TARGET),--target $(BUILD_TARGET)) $(FEATURES)
@echo "$(GREEN)✓ Build finished$(NC)"
## test: All tests
test:
@echo "$(YELLOW)→ Running the tests...$(NC)"
$(CARGO) test --all --all-features
@echo "$(GREEN)✓ Tests finished$(NC)"
## test-doc: Documentation example tests
test-doc:
@echo "$(YELLOW)→ Testing the documentation examples...$(NC)"
$(CARGO) test --doc --all-features
@echo "$(GREEN)✓ Documentation tests finished$(NC)"
## doc: Generates the documentation and opens it
doc:
@echo "$(YELLOW)→ Generating the documentation...$(NC)"
$(CARGO) doc --no-deps --document-private-items --all-features --open
## doc-build: Generates the documentation without opening it
doc-build:
@echo "$(YELLOW)→ Generating the documentation...$(NC)"
$(CARGO) doc --no-deps --document-private-items --all-features
## clean: Cleanup
clean:
@echo "$(YELLOW)→ Cleaning...$(NC)"
$(CARGO) clean
## check: Code check (host, then EXTRA_TARGETS)
check:
@$(KIT_DIR)/scripts/publish-guard.sh
@echo "$(YELLOW)→ Checking the code...$(NC)"
$(CARGO) check --all
@for t in $(EXTRA_TARGETS); do $(CARGO) check --all --target $$t || exit 1; done
@echo "$(GREEN)✓ Code valid$(NC)"
## fmt: Code formatting
fmt:
$(CARGO) fmt --all
## fmt-check: Formatting check
fmt-check:
$(CARGO) fmt --all -- --check
## clippy: Static analysis on the host then EXTRA_TARGETS (warnings = errors)
clippy:
@echo "$(YELLOW)→ Analysing with clippy...$(NC)"
$(CARGO) clippy --all-targets --all-features -- -D warnings
@for t in $(EXTRA_TARGETS); do $(CARGO) clippy --lib --all-features --target $$t -- -D warnings || exit 1; done
@echo "$(GREEN)✓ Clippy analysis finished$(NC)"
## watch: Continuous check
watch:
$(CARGO) watch -x check
## ci: Verification pipeline (deps-check fmt-check clippy test doc-build)
ci: deps-check fmt-check clippy test doc-build
@echo "$(GREEN)✓ All CI checks passed$(NC)"
## deps: Outdated dependencies
deps:
$(CARGO) outdated
## update: Updates the dependencies
update:
$(CARGO) update
## bench: Benchmarks
bench:
$(CARGO) bench
## coverage: Coverage report (cargo-llvm-cov)
coverage:
@echo "$(YELLOW)→ Generating the coverage report...$(NC)"
@mkdir -p target/coverage
$(CARGO) llvm-cov --json --output-path target/coverage/llvm-cov-report.json
$(CARGO) llvm-cov report
@echo "$(GREEN)✓ Report: target/coverage/llvm-cov-report.json$(NC)"
## api-level: Compares the public API to the last snapshot (initial, unchanged, additive or breaking)
api-level:
@$(KIT_DIR)/scripts/api-level.sh
## api-snapshot: Records the public API of the current version (api/<version>.txt and .json.gz)
api-snapshot:
@$(KIT_DIR)/scripts/api-snapshot.sh
## bump-version: Next version according to the API (breaking: x.y+1.0 in 0.x), or fixed RELEASE=x.y.z
bump-version:
@$(KIT_DIR)/scripts/bump-version.sh
## publish: Publishes to the $(REGISTRY) registry (done by the CI after the tag; manual troubleshooting, DRY_RUN=1: without sending)
publish:
@$(KIT_DIR)/scripts/publish.sh
## wiki: Publishes the API doc to the wiki (done by the CI after the tag; manual troubleshooting, DRY_RUN=1: without push)
wiki:
@$(KIT_DIR)/scripts/wiki.sh
## jjpush: Version bump, API snapshot, documentation, then main advances to the commit and is pushed
jjpush: bookmark-check deps-check bump-version api-snapshot
@echo "$(YELLOW)→ Pushing the commit to main...$(NC)"
@jj auto-doc
@$(KIT_DIR)/scripts/push-main.sh
@$(KIT_DIR)/scripts/new-commit.sh
@echo "$(GREEN)✓ main pushed; new working commit created on top of it$(NC)"
## jjrelease: Release (ci, version according to the API, snapshot, notes, push of main, tag; the CI then publishes)
jjrelease: bookmark-check kit-check ci bump-version api-snapshot
@echo "$(BLUE)→ Documenting the undocumented commits...$(NC)"
@jj auto-doc
@echo "$(BLUE)→ Synchronizing the tags with the remote repository...$(NC)"
@jj git fetch
@$(KIT_DIR)/scripts/release-notes.sh
@echo "$(BLUE)→ Documenting the current commit...$(NC)"
@jj auto-doc
@echo "$(BLUE)→ Pushing main...$(NC)"
@$(KIT_DIR)/scripts/push-main.sh
@$(KIT_DIR)/scripts/tag.sh
@$(KIT_DIR)/scripts/new-commit.sh
@echo "$(GREEN)✓ Tag pushed: the CI (Release workflow) publishes the crate, updates the wiki and creates the release$(NC)"
ifneq ($(strip $(AFTER_RELEASE)),)
@echo "$(BLUE)→ After the release: $(AFTER_RELEASE)$(NC)"
@$(AFTER_RELEASE)
endif
@name=$$(sed -n 's/^name = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1); \
v=$$(sed -n 's/^version = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1); \
case "$$v" in 0.*) req=$$(echo "$$v" | cut -d. -f1,2);; *) req=$$(echo "$$v" | cut -d. -f1);; esac; \
echo "$(YELLOW)⚠ Dependent projects: the requirement must accept $$v. If it does not, the local [patch] is ignored: raise it in their Cargo.toml $$name = { version = \"$$req\", registry = \"$(REGISTRY)\" } then cargo update -p $$name$(NC)"
## bookmark-check: Does main track main@origin? Otherwise the push of main would fail at the end of the release (read-only)
bookmark-check:
@$(KIT_DIR)/scripts/bookmark-check.sh
## kit-check: Is this crate's kit and release workflow identical to crate-kit's? (read-only)
kit-check:
@$(KIT_DIR)/scripts/kit-check.sh
## needs-commit: Are there changes other than the kit's to commit? (read-only, code 1 if not)
needs-commit:
@$(KIT_DIR)/scripts/needs-commit.sh
## kit-update: Updates .crate-kit/ from the extension kit (KIT_SRC)
kit-update:
@test -x "$(KIT_SRC)/tools/kit-copy.sh" || { echo "crate-kit not found: $(KIT_SRC) (set KIT_SRC=...)"; exit 1; }
@"$(KIT_SRC)/tools/kit-copy.sh" $(KIT_DIR)
@echo "$(GREEN)✓ .crate-kit/ up to date: crate-kit $$(cat $(KIT_DIR)/VERSION)$(NC)"
## print-%: Value of a make variable (e.g. make print-PUBLISH); for the tools
print-%:
@echo '$($*)'
## kit-version: Kit version installed in this crate
kit-version:
@cat $(KIT_DIR)/VERSION
+42
View File
@@ -0,0 +1,42 @@
# Private registry and local Cargo configuration (joint development).
# Fragment included by crate.mk and by the Makefiles that are not crates (workspace):
# include .crate-kit/dev-patch.mk
DEVPATCH_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
CARGO_TOML ?= Cargo.toml
# Values specific to the organization (REGISTRY, REGISTRY_INDEX, FORGE_URL…): org.mk, provided by the
# extension that the crate declares (KIT_OVERLAY, tools/kit-assemble.sh). REGISTRY = crates-io: crates.io, without
# index or [patch]. Without org.mk, no registry: publish and deps-check fail saying so.
-include $(DEVPATCH_DIR)/org.mk
REGISTRY ?=
REGISTRY_INDEX ?=
export CARGO_TOML REGISTRY REGISTRY_INDEX FORGE_TOKEN_FILE
# Private registry: the index comes from the environment, never from a file tracked by the repository (CI,
# Docker and a repository cloned alone therefore work without configuration).
ifneq ($(filter-out crates-io,$(strip $(REGISTRY))),)
REGISTRY_UP := $(shell echo '$(REGISTRY)' | tr 'a-z-' 'A-Z_')
CARGO_REGISTRIES_$(REGISTRY_UP)_INDEX := $(REGISTRY_INDEX)
export CARGO_REGISTRIES_$(REGISTRY_UP)_INDEX
endif
# Joint development: .cargo/config.toml (local, ignored) is regenerated at EVERY invocation of
# make, whatever the target, from the project's actual dependencies. Nothing to remember.
DEV_PATCH_RUN := $(shell CARGO_TOML='$(CARGO_TOML)' REGISTRY='$(REGISTRY)' REGISTRY_INDEX='$(REGISTRY_INDEX)' $(DEVPATCH_DIR)/scripts/dev-patch.sh)
.PHONY: dev-patch
## dev-patch: Regenerates .cargo/config.toml (registry + local patches); already done at every make
dev-patch:
@$(DEVPATCH_DIR)/scripts/dev-patch.sh
@echo "ok: .cargo/config.toml up to date"
.PHONY: deps-check deps-bump
## deps-check: Dependencies up to date? from the private registry (requirement, lock, neighbour, duplicates) and external (requirement, minor, lock)
deps-check:
@rc=0; $(DEVPATCH_DIR)/scripts/deps-check.sh || rc=1; $(DEVPATCH_DIR)/scripts/deps-check-external.sh || rc=1; exit $$rc
## deps-bump: Raises the outdated requirements (private registry and external) to the latest version, then cargo update -p
deps-bump:
@$(DEVPATCH_DIR)/scripts/deps-check.sh bump
@$(DEVPATCH_DIR)/scripts/deps-check-external.sh bump
+22
View File
@@ -0,0 +1,22 @@
# Jujutsu targets common to all the crates and to crate-kit itself.
# Included by crate.mk; a repository that is not a crate includes it directly.
JJ_KIT_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
GREEN ?= \033[0;32m
YELLOW ?= \033[1;33m
BLUE ?= \033[1;34m
NC ?= \033[0m
## jjnew: Documents the current commit then creates a new one
jjnew:
@echo "$(YELLOW)→ Creating a new commit...$(NC)"
@jj auto-doc
@$(JJ_KIT_DIR)/scripts/new-commit.sh
@echo "$(GREEN)✓ Done$(NC)"
## jjfetch: Fetches the origin and rebases the local work on top of main@origin (nothing is lost)
jjfetch:
@$(JJ_KIT_DIR)/scripts/jjfetch.sh
@# Reruns make to resynchronize .crate-kit/: the Makefile does it at startup, before the rebase, and
@# the rebase may have left conflict markers there (kit copy newer than the origin's).
@$(MAKE) --no-print-directory -s help >/dev/null
+3
View File
@@ -0,0 +1,3 @@
# "crate" kind (default): ordinary Rust crate, published to the private registry, API tracked, wiki.
# The default values of BUILD_TARGET, EXTRA_TARGETS, PUBLISH, API_TRACKED, WIKI and AFTER_RELEASE
# (crate.mk) describe this kind: nothing to set here.
+9
View File
@@ -0,0 +1,9 @@
# Values specific to obi, read by dev-patch.mk (hence by every Makefile of the cluster) and by crate-kit.
# The cargo registry to publish to (a private name, or crates-io) and the forge hosting it.
REGISTRY ?= obi
FORGE_URL ?= https://forge.metabarcoding.org
REGISTRY_INDEX ?= sparse+$(FORGE_URL)/api/packages/$(REGISTRY)/cargo/
# No token here: the forge tokens of a workstation are files of the cluster, in secrets/ next to the
# repositories (secrets/forge.metabarcoding.org.token, ...), outside every repository. FORGETOKEN (CI) overrides them.
# Language of the documents an LLM generates (release notes, commit messages, Claude agents' notes).
KIT_LANG ?= en
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env bash
# Compares the current public API to the last snapshot and prints on standard output:
# initial no snapshot: first tracked version
# unchanged no change in the public API
# additive additions only (nothing removed or modified)
# breaking break: element removed/modified, or break seen by cargo-semver-checks
# All the detail goes to standard error.
#
# Two combined checks: cargo-semver-checks is the reference for breaks, but it does not
# report plain additions; the text diff of cargo public-api acts as a safety net (any removed
# or modified line = break) and provides the count of additions.
set -euo pipefail
. "$(dirname "$0")/common.sh"
if [ "${API_TRACKED:-yes}" = no ]; then
echo unchanged # no tracked Rust API: the version advances by patch (or RELEASE=x.y.z)
exit 0
fi
require_cargo_tool public-api cargo-public-api
require_cargo_tool semver-checks cargo-semver-checks
# A proc-macro crate has no library target: cargo-semver-checks cannot analyse it.
# Its API (the exported macros) is still tracked by the text diff of cargo public-api; this diff does
# not see a change in the macro's behaviour (rejected inputs, generated code): to be judged by hand.
is_proc_macro() {
"$CARGO" metadata --format-version 1 --no-deps | grep -q '"kind":\["proc-macro"\]'
}
last=$(latest_snapshot)
if [ -z "$last" ]; then
info " No snapshot in $API_DIR/: first tracked version"
echo initial
exit 0
fi
# A snapshot written with other tools (rustc, cargo-public-api) than today's is no longer
# comparable: cargo-semver-checks crashes on another rustdoc format, and the text diff sees
# breaks where only the rendering changed. It is regenerated from the tag of its version (no stamp =
# written before stamps existed, hence unknown).
if [ "$(cat "$API_DIR/$last.stamp" 2>/dev/null || true)" != "$(toolchain_stamp)" ]; then
info " Snapshot $last written with other tools: regenerating from tag version-$last"
regenerate_snapshot "$last" || {
err "✗ cannot regenerate snapshot $last: the comparison would be wrong"
exit 1
}
fi
tmp=$(mktemp -d)
trap 'rm -r "$tmp"' EXIT
info " Reference: API published in version $last"
"$CARGO" public-api -s >"$tmp/current.txt" 2>/dev/null || {
err "✗ cargo public-api failed"
exit 1
}
# `filter_unstable` (common.sh) removes from the cargo public-api text whatever is not the crate's API.
diff_out=$(diff <(filter_unstable "$API_DIR/$last.txt") <(filter_unstable "$tmp/current.txt") || true)
removed=$(printf '%s\n' "$diff_out" | grep -c '^<' || true)
added=$(printf '%s\n' "$diff_out" | grep -c '^>' || true)
# Code 100 = break; 0 = nothing to report; other = tool failure.
set +e
if is_proc_macro; then
info " proc-macro crate: cargo-semver-checks not applicable, text diff only"
rc=0
else
gzip -d -c "$API_DIR/$last.json.gz" >"$tmp/baseline.json"
"$CARGO" semver-checks --baseline-rustdoc "$tmp/baseline.json" --release-type minor >"$tmp/semver.log" 2>&1
rc=$?
fi
set -e
level=unchanged
if [ "$rc" -eq 100 ]; then
level=breaking
warn " Break detected by cargo-semver-checks:"
grep -E '^ +[A-Za-z0-9_]+::|^--- failure' "$tmp/semver.log" >&2 || true
elif [ "$rc" -ne 0 ]; then
err "✗ cargo-semver-checks failed (code $rc):"
tail -n 15 "$tmp/semver.log" >&2
exit 1
fi
if [ "$removed" -gt 0 ]; then
level=breaking
warn " $removed API line(s) removed or modified compared to $last:"
printf '%s\n' "$diff_out" | grep '^<' >&2
fi
if [ "$level" = unchanged ] && [ "$added" -gt 0 ]; then
level=additive
fi
info " API: +$added / -$removed lines; verdict: $level"
echo "$level"
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Records the public API of the current version:
# $API_DIR/<version>.txt readable, diffable list (cargo public-api)
# $API_DIR/<version>.json.gz compressed rustdoc JSON, reference of cargo-semver-checks
# $API_DIR/<version>.stamp rustc and cargo-public-api used (api-level regenerates if they change)
set -euo pipefail
. "$(dirname "$0")/common.sh"
if [ "${API_TRACKED:-yes}" = no ]; then
info " (kind ${CRATE_KIND:-crate}: no Rust API to record)"
exit 0
fi
require_cargo_tool public-api cargo-public-api
version=$(current_version)
name=$(crate_name)
warn "→ Public API snapshot of $name $version..."
emit_snapshot "$version" "$API_DIR"
ok "✓ $API_DIR/$version.txt and $API_DIR/$version.json.gz written"
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Checks that the local `main` bookmark tracks `main@origin` (read-only). Without this tracking, jj refuses
# to push main ("Non-tracking remote bookmark"), and jjrelease would fail at the very end,
# after the tests and the version bump: this check detects it beforehand.
# Without a jj repository, without a `main` bookmark or without `main@origin`, there is nothing to check: success.
set -euo pipefail
. "$(dirname "$0")/common.sh"
rows=$(jj bookmark list main --all-remotes -T 'remote ++ "|" ++ tracked ++ "\n"' 2>/dev/null) || exit 0
if printf '%s\n' "$rows" | grep -qx 'origin|false'; then
err "✗ main@origin exists but the local main bookmark does not track it: the push of main would be refused"
info " Fix once and for all: jj bookmark track main@origin"
exit 1
fi
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
# Computes and applies the next version according to the public API (see api-level.sh):
# break -> x.y+1.0 while x = 0, otherwise x+1.0.0
# additions -> x.y+1.0 once x >= 1 (SemVer: new feature), x.y.z+1 while x = 0
# otherwise -> x.y.z+1
# RELEASE=x.y.z forces the version. Updates Cargo.toml, version.txt and the
# dependency line `<crate> = "x.y"` of README.md when they exist.
set -euo pipefail
. "$(dirname "$0")/common.sh"
warn "→ Computing the next version..."
current=$(current_version)
name=$(crate_name)
info " Current version: $current"
IFS=. read -r major minor patch <<<"$current"
if [ -n "${RELEASE:-}" ]; then
new_version="$RELEASE"
else
level=$("$(dirname "$0")/api-level.sh")
case "$level" in
breaking)
if [ "$major" = "0" ]; then
new_version="0.$((minor + 1)).0"
else
new_version="$((major + 1)).0.0"
fi
;;
additive)
if [ "$major" = "0" ]; then
new_version="0.$minor.$((patch + 1))"
else
new_version="$major.$((minor + 1)).0"
fi
;;
initial | unchanged)
new_version="$major.$minor.$((patch + 1))"
;;
*)
err "✗ unexpected API verdict: '$level'"
exit 1
;;
esac
fi
# No silent jump to another version: a break must never be downgraded.
rc=0
"$(dirname "$0")/tag-exists.sh" "$new_version" || rc=$?
case "$rc" in
0)
err "✗ The release version-$new_version already exists (locally or on the server)"
info " Use RELEASE=x.y.z to force another version"
exit 1
;;
1) ;;
*) warn " (remote tags not checked: no jj repository or origin unreachable)" ;;
esac
info " New version: $new_version"
sed -i.bak "s/^version = \"$current\"/version = \"$new_version\"/" "$CARGO_TOML"
rm "$CARGO_TOML.bak"
[ -f version.txt ] && echo "$new_version" >version.txt
if [ -f README.md ]; then
sed -i.bak "s/^$name = \"[0-9][0-9.]*\"/$name = \"$(echo "$new_version" | cut -d. -f1,2)\"/" README.md
rm README.md.bak
fi
ok "✓ Version $new_version written to $CARGO_TOML (and version.txt, README.md if they exist)"
+266
View File
@@ -0,0 +1,266 @@
#!/usr/bin/env bash
# Functions shared by the kit scripts. To be sourced: `. "$(dirname "$0")/common.sh"`.
#
# Parameters read from the environment (default values below); crate.mk exports
# them, the scripts also remain usable on their own from the root of a crate.
CARGO="${CARGO:-cargo}"
CARGO_TOML="${CARGO_TOML:-Cargo.toml}"
API_DIR="${API_DIR:-api}"
RELEASE_NOTES_DIR="${RELEASE_NOTES_DIR:-ReleaseNotes}"
# Private cargo registry and its sparse index: provided by the organisation overlay (org.mk), empty otherwise.
REGISTRY="${REGISTRY:-}"
REGISTRY_INDEX="${REGISTRY_INDEX:-}"
info() { printf '\033[1;34m%s\033[0m\n' "$*" >&2; }
warn() { printf '\033[1;33m%s\033[0m\n' "$*" >&2; }
ok() { printf '\033[0;32m%s\033[0m\n' "$*" >&2; }
err() { printf '\033[0;31m%s\033[0m\n' "$*" >&2; }
# API call: `forge_call <operation> <curl args…>`. Returns the response body on standard output;
# on an HTTP response ≥ 400 (or a transport failure), states the operation, the code and the body on standard
# error and returns 1. Replaces `curl -sf`, which fails silently (code 22).
forge_call() {
local operation="$1" body code
shift
body=$(mktemp)
code=$(curl -s -o "$body" -w '%{http_code}' "$@") || code="000"
if [ "$code" -ge 400 ] || [ "$code" = "000" ]; then
err "✗ $operation : HTTP $code : $(head -c 500 "$body")"
rm -f "$body"
return 1
fi
cat "$body"
rm -f "$body"
}
# Directory of the forge tokens of a workstation: `secrets/` of the cluster, i.e. next to the repositories
# (the parent of the current repository), outside every repository. FORGE_SECRETS_DIR overrides it.
forge_secrets_dir() {
if [ -n "${FORGE_SECRETS_DIR:-}" ]; then
printf '%s' "$FORGE_SECRETS_DIR"
return 0
fi
local root
root=$(jj root 2>/dev/null) || root=$(pwd)
printf '%s/secrets' "$(dirname "$root")"
}
# "host owner repo" of a git or registry URL: ssh://git@host[:port]/owner/repo.git, git@host:owner/repo.git,
# https://host/owner/repo, sparse+https://host/api/packages/owner/cargo/ (owner of the registry, no repo).
# Fails if the URL has no known form. Fields are empty when absent.
forge_parse_url() {
local u="${1#sparse+}" host path owner repo
case "$u" in
*://*) u="${u#*://}"; u="${u#*@}"; host="${u%%/*}"; path="${u#*/}" ;;
*@*:*) u="${u#*@}"; host="${u%%:*}"; path="${u#*:}" ;;
*) return 1 ;;
esac
[ "$path" = "$u" ] && path=""
host="${host%%:*}"
path="${path%/}"; path="${path%.git}"
case "$path" in
api/packages/*) owner="${path#api/packages/}"; owner="${owner%%/*}"; repo="" ;;
*) owner="${path%%/*}"; repo="${path#*/}"; [ "$repo" = "$path" ] && repo="" ;;
esac
[ -n "$host" ] || return 1
printf '%s %s %s\n' "$host" "$owner" "$repo"
}
# Forge token. `forge_token [url]`: the forge is that of the URL (registry index, repository), by default that of
# the `origin` remote. Order, the first that exists wins:
# 1. $FORGETOKEN: the CI, where each forge provides its own secret to its own jobs;
# 2. the token files of the cluster, most specific first (one line, mode 0600; see forge_secrets_dir):
# <secrets>/<host>/<owner>/<repo>.token, <secrets>/<host>/<owner>.token, <secrets>/<host>.token;
# 3. the file $FORGE_TOKEN_FILE (former single-token layout).
# Nothing on standard output if there is none; the caller then says where to put it. Never displayed.
forge_token() {
if [ -n "${FORGETOKEN:-}" ]; then
printf '%s' "$FORGETOKEN"
return 0
fi
local url="${1:-}" host owner repo dir f
[ -n "$url" ] || url=$(jj git remote list 2>/dev/null | awk '$1=="origin"{print $2; exit}')
if [ -n "$url" ] && read -r host owner repo < <(forge_parse_url "$url"); then
dir=$(forge_secrets_dir)
for f in ${repo:+"$dir/$host/$owner/$repo.token"} ${owner:+"$dir/$host/$owner.token"} "$dir/$host.token"; do
if [ -f "$f" ]; then
head -n 1 "$f" | tr -d '[:space:]'
return 0
fi
done
fi
if [ -n "${FORGE_TOKEN_FILE:-}" ] && [ -f "$FORGE_TOKEN_FILE" ]; then
head -n 1 "$FORGE_TOKEN_FILE" | tr -d '[:space:]'
fi
return 0
}
# cargo authentication against the private registry: CARGO_REGISTRIES_<REGISTRY>_TOKEN ("Bearer <token>"),
# built from the forge token if not already defined. Needed by any cargo call that
# resolves registry dependencies (publish, wiki doc). For crates.io (REGISTRY = crates-io) nothing
# is built: the crates.io token is CARGO_REGISTRY_TOKEN, supplied by the user.
if [ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ]; then
reg_var="CARGO_REGISTRIES_$(printf '%s' "$REGISTRY" | tr 'a-z-' 'A-Z_')_TOKEN"
if [ -z "${!reg_var:-}" ] && [ -n "$(forge_token "$REGISTRY_INDEX")" ]; then
export "$reg_var=Bearer $(forge_token "$REGISTRY_INDEX")"
fi
fi
# Version: content of $VERSION_FILE if set (repositories that are not crates, like
# crate-kit itself), otherwise first occurrence in the crate's Cargo.toml.
current_version() {
# Source of the version: VERSION_FILE (exported by the Makefiles of the kits), else the Cargo.toml of a crate.
# Without either (script run by hand at the root of a kit, not through make): kit/VERSION (crate-kit) or
# overlay/kit/VERSION (extension kit), if present.
local file="${VERSION_FILE:-}" candidate
if [ -z "$file" ] && [ ! -f "$CARGO_TOML" ]; then
for candidate in kit/VERSION overlay/kit/VERSION; do
[ -f "$candidate" ] && { file="$candidate"; break; }
done
fi
if [ -n "$file" ]; then
head -n 1 "$file"
elif [ -f "$CARGO_TOML" ]; then
sed -n 's/^version = "\(.*\)"/\1/p' "$CARGO_TOML" | head -n 1
else
err "✗ no source for the version: no VERSION_FILE, no $CARGO_TOML, no kit/VERSION nor overlay/kit/VERSION here"
return 1
fi
}
# Package name: first occurrence in the crate's Cargo.toml.
# Abandons the empty commits without a description between trunk() and @ (excluding @ itself): jj refuses to
# push a commit without a description, and these carry nothing (leftovers of `jj new`). Descendants
# are rebased automatically; neither work nor an already pushed (immutable) commit is touched.
abandon_blank_commits() {
jj abandon 'trunk()..@ & mutable() & empty() & description(exact:"") ~ @' >/dev/null 2>&1 || true
}
# The commit to publish: @, unless it is empty and without a description (the working commit that `jj new`
# leaves after a release or a push); we then go up to the first ancestor that carries work.
# Such a commit is not pushed (jj refuses a commit without a description) and deserves neither tag nor main.
release_rev() {
local rev='@' blank
while :; do
blank=$(jj log -r "$rev" --no-graph -T 'if(empty && description == "", "1", "0")')
[ "$blank" = 1 ] || break
rev="$rev-"
done
echo "$rev"
}
crate_name() { sed -n 's/^name = "\(.*\)"/\1/p' "$CARGO_TOML" | head -n 1; }
# Last version having an API snapshot (sorted by version number), empty if there is none.
latest_snapshot() {
ls "$API_DIR"/*.json.gz 2>/dev/null | sed 's|.*/||; s|\.json\.gz$||' | sort -V | tail -n 1 || true
}
# Fingerprint of the tools that produce a snapshot. The rustdoc JSON (format number) and the text
# rendering of cargo public-api change with rustc and cargo-public-api: a snapshot written with other
# tools than today's is no longer comparable (cargo-semver-checks crashes, or the text diff
# announces a break where only the rendering changed).
toolchain_stamp() {
printf '%s | %s\n' "$(rustc -V)" "$("$CARGO" public-api --version)"
}
# Writes the snapshot of version <version> of the code in the current directory (root of a
# crate), into <api_dir>: <version>.txt, <version>.json.gz and <version>.stamp (toolchain_stamp).
# Parameters: version, snapshot directory (absolute if the current directory is not the crate).
emit_snapshot() {
local version="$1" api_dir="$2" name target_dir
name=$(crate_name)
mkdir -p "$api_dir"
# -s: without the blanket implementations (`impl<T> Into<U> for Type`…), added by rustc to
# every public type and unrelated to its API (they made up half of the file).
"$CARGO" public-api -s >"$api_dir/$version.txt"
# The rustdoc JSON is unstable; RUSTC_BOOTSTRAP makes it possible to produce it with the stable toolchain,
# the same one cargo-semver-checks uses to build the current state.
# --document-private-items: cargo-semver-checks builds the current state with private items
# (private fields included); a reference without them makes a struct with a private field look like
# it "gains a private field" and gives a break wrongly.
RUSTC_BOOTSTRAP=1 "$CARGO" rustdoc --lib -q -- -Zunstable-options --output-format json --document-private-items
target_dir=$("$CARGO" metadata --format-version 1 --no-deps |
sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p')
# Compressed (gzip -n: reproducible output): the JSON exceeds 1 MB, jj's limit for a new file.
gzip -9 -n -c "$target_dir/doc/${name//-/_}.json" >"$api_dir/$version.json.gz"
toolchain_stamp >"$api_dir/$version.stamp"
}
# Regenerates the snapshot of the published version <version> with the current tools, from the code of
# its tag `version-<version>` (read-only: `jj file list/show`, no modification of the repository).
# The tag is exported into a sibling folder of the crate (`<crate>.baseline.tmp`): the relative paths
# of `.cargo/config.toml` (`[patch.<registry>]` towards the neighbours) remain valid there. Only `.cargo/` (ignored
# by the repository, generated by `make`) is copied in addition.
regenerate_snapshot() {
local version="$1" api_dir root tmp rev="version-$1" f
api_dir="$(pwd)/$API_DIR"
root="$(pwd)"
tmp="$root.baseline.tmp"
if ! jj file list -r "$rev" >/dev/null 2>&1; then
err "✗ tag $rev not found: cannot regenerate the snapshot of $version"
return 1
fi
rm -rf "$tmp"
mkdir -p "$tmp"
while IFS= read -r f; do
mkdir -p "$tmp/$(dirname "$f")"
jj file show -r "$rev" "$f" >"$tmp/$f"
done < <(jj file list -r "$rev")
[ -d "$root/.cargo" ] && cp -R "$root/.cargo" "$tmp/.cargo"
(
cd "$tmp"
CARGO_TARGET_DIR="$tmp/target" emit_snapshot "$version" "$api_dir"
) || { rm -rf "$tmp"; return 1; }
rm -rf "$tmp"
}
# Fails with an installation message if a cargo tool is missing.
require_cargo_tool() {
local sub="$1" crate="$2"
if ! command -v "cargo-$sub" >/dev/null 2>&1; then
err "✗ cargo-$sub is required: cargo install $crate --locked"
exit 1
fi
}
# Lines that are not the crate's API and that the text diff must not see:
# - `impl core::marker::Freeze`: unstable auto trait, invisible on stable; it appears or
# disappears as soon as a field goes under `Mutex`/`Atomic*`, with no effect for a caller;
# - the blanket implementations (`impl<T> other_crate::Trait for Type`) of traits of OTHER crates
# and their associated items: rustdoc lists them for every trait of the dependency graph, so
# they appear or disappear when a dependency changes (e.g. `crossbeam_epoch::Pointable`,
# `either::IntoEither`), without the crate's API having moved. Those of `core`,
# `alloc`, `std` and of the crate itself are kept.
filter_unstable() {
grep -v '^impl core::marker::Freeze for ' "$1" | awk -v crate="$(crate_name)" '
/^impl</ {
skip = 0
rest = $0
sub(/^impl<[^>]*> /, "", rest)
split(rest, parts, " ")
trait = parts[1]
if (trait !~ /^(core|alloc|std)::/ && index(trait, crate "::") != 1 && match($0, / for [^ ]+/)) {
self = substr($0, RSTART + 5, RLENGTH - 5)
skip = 1
next
}
print
next
}
skip && (index($0, "pub fn " self "::") == 1 || index($0, "pub unsafe fn " self "::") == 1 ||
index($0, "pub type " self "::") == 1 || index($0, "pub const " self "::") == 1) { next }
{ skip = 0; print }
' || true
}
# API text for the release notes: `filter_unstable`, then without the auto traits
# (`Send`, `Sync`, `Unpin`, `UnwindSafe`, `RefUnwindSafe`, `Freeze`, `Forget`, `Move`, `UnsafeUnpin`,
# `StructuralPartialEq`) that cargo public-api lists for every type: a new type adds nine
# lines that drown the API. They remain in the snapshot, hence in the verdict of `make api-level`
# (losing `Send` is a break); only the readable notes omit them.
filter_notes() {
filter_unstable "$1" | grep -v -E '^impl core::(marker::(Forget|Freeze|Move|Send|Sync|Unpin|UnsafeUnpin|StructuralPartialEq)|panic::unwind_safe::(RefUnwindSafe|UnwindSafe)) for ' || true
}
+193
View File
@@ -0,0 +1,193 @@
#!/usr/bin/env bash
# Freshness of the EXTERNAL dependencies (crates.io) declared by the project. `cargo outdated` compares the
# Cargo.lock version to the latest published one, but not the requirement written in Cargo.toml: a
# requirement `os_info = "3.8"` with a lock up to date at 3.15 goes unnoticed, and a consumer of the
# crate may end up with a version seven minor versions old.
#
# For each direct dependency `name = "x.y"` or `name = { version = "x.y", … }` (excluding `path`, `git`,
# `registry`, `workspace`), in [dependencies], [dev-dependencies], [build-dependencies], their
# `target.*` variants and [workspace.dependencies], it checks:
# 1. the requirement accepts the latest published version (for a 0.x, `0.5` does not accept 0.6);
# 2. for a version ≥ 1, the required minor version is not behind the latest
# (`tokio = "1.35"` while 1.52 exists). A 0.x is not checked at this level: its
# patch number does not count;
# 3. Cargo.lock is on the latest version that the requirement accepts.
# Requirements that are not written `x`, `x.y` or `x.y.z` (`=1.2.3`, `~1.2`, `>=1`, ranges) are
# explicit choices: ignored.
#
# deps-check-external.sh check (read-only, except for the network)
# deps-check-external.sh bump raises the outdated requirements then `cargo update -p`
#
# Variables: DEPS_CHECK_EXTERNAL=0 disables the check (workspace too large to be kept up
# to date all at once); DEPS_CHECK_EXTERNAL_IGNORE="crate1 crate2" sets crates aside (to be justified in
# the Makefile: for example a public dependency that must move up with the neighbouring crates); CRATES_IO_INDEX (default https://index.crates.io); DEPS_CHECK_OFFLINE=1 ignores
# the absence of network (warning).
# shellcheck disable=SC2154 # manifests comes from deps-lib.sh
set -euo pipefail
. "$(dirname "$0")/common.sh"
. "$(dirname "$0")/deps-lib.sh"
mode="${1:-check}"
case "$mode" in check | bump) ;; *)
err "usage: deps-check-external.sh [check|bump]"
exit 2
;;
esac
if [ "${DEPS_CHECK_EXTERNAL:-1}" = 0 ]; then
info " (external dependencies: check disabled by DEPS_CHECK_EXTERNAL=0)"
exit 0
fi
[ -f "$CARGO_TOML" ] || exit 0
crates_index="${CRATES_IO_INDEX:-https://index.crates.io}"
crates_index="${crates_index%/}"
fail=0
bad() {
err " ✗ $*"
fail=1
}
# External declarations of a manifest: "key<TAB>crate<TAB>requirement" (the crate differs from the key
# when the dependency is renamed by `package = "…"`).
declarations() {
awk '
/^\[/ { dep = ($0 ~ /^\[(workspace\.|target\..*\.)?(dev-|build-)?dependencies\]$/); next }
!dep { next }
/^[ \t]*#/ { next }
{
if (match($0, /^[A-Za-z0-9_-]+[ \t]*=/) == 0) next
key = $0; sub(/[ \t]*=.*/, "", key)
rest = $0; sub(/^[A-Za-z0-9_-]+[ \t]*=[ \t]*/, "", rest)
crate = key
if (rest ~ /^"/) {
req = rest; sub(/^"/, "", req); sub(/".*/, "", req)
} else if (rest ~ /^\{/) {
if (rest ~ /(path|git|registry|workspace)[ \t]*=/) next
if (match(rest, /version[ \t]*=[ \t]*"[^"]*"/) == 0) next
req = substr(rest, RSTART, RLENGTH)
sub(/^version[ \t]*=[ \t]*"/, "", req); sub(/"$/, "", req)
if (match(rest, /package[ \t]*=[ \t]*"[^"]*"/)) {
crate = substr(rest, RSTART, RLENGTH)
sub(/^package[ \t]*=[ \t]*"/, "", crate); sub(/"$/, "", crate)
}
} else next
print key "\t" crate "\t" req
}
' "$1"
}
# Replaces the requirement of the dependency `key` (in a dependencies section) of manifest $1 with $3.
rewrite_req() {
awk -v n="$2" -v r="$3" '
/^\[/ { dep = ($0 ~ /dependencies\]$/) }
dep && $0 ~ "^" n "[ \t]*=" {
if ($0 ~ /\{/) sub(/version[ \t]*=[ \t]*"[^"]*"/, "version = \"" r "\"")
else sub(/"[^"]*"/, "\"" r "\"")
}
{ print }
' "$1" >"$1.tmp" && mv "$1.tmp" "$1"
}
# Requirement to write for version $1: x.y (≥ 1) or 0.y.
floor_for() { echo "$1" | cut -d. -f1,2; }
tmp=$(mktemp -d)
trap 'rm -r "$tmp"' EXIT
info "→ Freshness of the external dependencies (crates.io)..."
count=0
offline=0
updates=""
for manifest in "${manifests[@]}"; do
while IFS=$'\t' read -r key crate req; do
[ -n "$crate" ] || continue
# Dependency deliberately set aside (DEPS_CHECK_EXTERNAL_IGNORE, with its reason in the Makefile).
case " ${DEPS_CHECK_EXTERNAL_IGNORE:-} " in *" $crate "*) continue ;; esac
# Explicit requirement (=, ~, >=, range): a choice, not checked (and no network request).
case "${req#^}" in '' | *[!0-9.]*) continue ;; esac
count=$((count + 1))
if [ ! -f "$tmp/$crate" ]; then
rc=0
found=$(latest_published "$crate" "$crates_index") || rc=$?
printf '%s %s\n' "$rc" "$found" >"$tmp/$crate"
fi
read -r rc latest <"$tmp/$crate"
if [ "$rc" -eq 2 ]; then
offline=1
continue
fi
if [ "$rc" -eq 1 ] || [ -z "$latest" ]; then
warn " ⚠ $crate ($manifest): not found on crates.io, not checked"
continue
fi
acc=0
req_accepts "$req" "$latest" || acc=$?
if [ "$acc" -eq 1 ]; then
# Newer than the latest published (pre-release, yank): nothing to raise.
[ "$(printf '%s\n%s\n' "$req" "$latest" | sort -V | tail -n 1)" = "$latest" ] || continue
if [ "$mode" = bump ]; then
new=$(floor_for "$latest")
rewrite_req "$manifest" "$key" "$new"
info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)"
updates+="$crate "
else
bad "$crate ($manifest): the requirement \"$req\" does not accept the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)"
fi
continue
fi
# The requirement accepts the latest version: is the required minor (≥ 1.0) behind?
IFS=. read -r rmaj rmin _ <<<"${req#^}"
IFS=. read -r _ lmin _ <<<"$latest"
if [ "$rmaj" != 0 ] && [ -n "$rmin" ] && [ "$rmin" -lt "$lmin" ]; then
if [ "$mode" = bump ]; then
new=$(floor_for "$latest")
rewrite_req "$manifest" "$key" "$new"
info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)"
updates+="$crate "
else
bad "$crate ($manifest): the requirement \"$req\" is behind the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)"
fi
fi
# Cargo.lock: on the latest version that the requirement accepts.
if [ -f Cargo.lock ]; then
locked=$(lock_entries | awk -v n="$crate" '$1 == n && index($3, "crates.io-index") { print $2 }' | sort -V | tail -n 1)
if [ -n "$locked" ] && [ "$locked" != "$latest" ] &&
[ "$(printf '%s\n%s\n' "$locked" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
if [ "$mode" = bump ]; then
updates+="$crate "
else
bad "$crate: Cargo.lock is on $locked, the latest version is $latest → cargo update -p $crate (make deps-bump)"
fi
fi
fi
done < <(declarations "$manifest")
done
if [ "$offline" -eq 1 ]; then
if [ "${DEPS_CHECK_OFFLINE:-}" = 1 ]; then
warn " ⚠ crates.io unreachable: freshness of the external dependencies not verified (DEPS_CHECK_OFFLINE=1)"
else
bad "crates.io unreachable ($crates_index): freshness cannot be verified (DEPS_CHECK_OFFLINE=1 to ignore)"
fi
fi
if [ "$mode" = bump ] && [ -n "$updates" ]; then
for n in $(printf '%s\n' $updates | sort -u); do
info " cargo update -p $n"
"$CARGO" update -p "$n" >/dev/null
done
fi
if [ "$fail" -ne 0 ]; then
err "✗ External dependencies out of date (see above)"
exit 1
fi
ok "✓ External dependencies up to date ($count checked)"
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env bash
# Freshness of the dependencies between crates of the private registry: we must never keep running with an
# old version of a registry crate when a new one is published. Fails (code 1) at the slightest discrepancy.
#
# For each dependency `name = { version = "x.y", registry = "<registry>" }` declared by the project
# (same reading as dev-patch.sh), it checks:
# 1. the requirement accepts the latest version published on the registry (for a 0.x, `0.1` never
# accepts 0.2: Cargo says nothing);
# 2. Cargo.lock is on that latest version (if it points to the registry);
# 3. the neighbouring folder ../<name>, which replaces the dependency in joint development, is not
# behind the registry (otherwise we build against stale code);
# 4. Cargo.lock contains no [[patch.unused]] (ignored local patch: requirement too low);
# 5. no registry crate appears in several versions in Cargo.lock (two copies in the build).
# A neighbour newer than the registry (pending publication) is reported without failing.
#
# deps-check.sh check (read-only, except for the network)
# deps-check.sh bump fixes the outdated requirements (rewrites the Cargo.toml) then `cargo update -p`
#
# Network: the sparse index of the registry ($REGISTRY_INDEX), public. Without network, the check
# fails; DEPS_CHECK_OFFLINE=1 explicitly ignores it (warning).
# shellcheck disable=SC2154 # index_url and manifests come from deps-lib.sh
set -euo pipefail
. "$(dirname "$0")/common.sh"
[ -n "$REGISTRY" ] || { err "✗ no registry: declare the kit extension (KIT_OVERLAY in the Makefile, org.mk) or set REGISTRY = crates-io"; exit 1; }
[ "$REGISTRY" != crates-io ] || { info " (crates.io registry: dependencies checked by deps-check-external)"; exit 0; }
mode="${1:-check}"
case "$mode" in check | bump) ;; *)
err "usage: deps-check.sh [check|bump]"
exit 2
;;
esac
[ -f "$CARGO_TOML" ] || exit 0
fail=0
bad() {
err " ✗ $*"
fail=1
}
. "$(dirname "$0")/deps-lib.sh"
decl=""
for m in "${manifests[@]}"; do
lines=$(grep -E "^[A-Za-z0-9_-]+[[:space:]]*=[[:space:]]*\{[^}]*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\"" "$m" || true)
[ -n "$lines" ] && decl+="$(printf '%s\n' "$lines" | sed "s|^|$m |")"$'\n'
done
if [ -z "$decl" ]; then
ok "✓ No dependency on registry $REGISTRY to check"
exit 0
fi
info "→ Freshness of the registry dependencies (registry $REGISTRY)..."
count=0
updates=""
offline=0
while IFS=$'\t' read -r manifest line; do
[ -n "$manifest" ] || continue
name=${line%%[[:space:]=]*}
req=$(printf '%s' "$line" | sed -nE 's/.*version[[:space:]]*=[[:space:]]*"([^"]*)".*/\1/p')
count=$((count + 1))
if [ -z "$req" ]; then
bad "$name ($manifest): no \"version\" in the declaration"
continue
fi
rc=0
latest=$(latest_published "$name") || rc=$?
if [ "$rc" -eq 2 ]; then
offline=1
continue
fi
if [ "$rc" -eq 1 ] || [ -z "$latest" ]; then
bad "$name ($manifest): no version published on registry $REGISTRY"
continue
fi
acc=0
req_accepts "$req" "$latest" || acc=$?
case "$acc" in
2) bad "$name ($manifest): requirement \"$req\" cannot be parsed (write x.y, or x for a version ≥ 1)" ;;
1)
if [ "$(printf '%s\n%s\n' "$req" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
if [ "$mode" = bump ]; then
new=$(req_for "$latest")
sed -E "/^${name}[[:space:]]*=.*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\"/ s/(version[[:space:]]*=[[:space:]]*\")[^\"]*/\1$new/" "$manifest" >"$manifest.tmp" &&
mv "$manifest.tmp" "$manifest"
info " $name ($manifest): \"$req\" → \"$new\" (latest published version: $latest)"
updates+="$name "
else
bad "$name ($manifest): the requirement \"$req\" does not accept the latest published version $latest → $name = { version = \"$(req_for "$latest")\", registry = \"$REGISTRY\" } (make deps-bump)"
fi
else
bad "$name ($manifest): the requirement \"$req\" is newer than the latest published version $latest (publication pending?)"
fi
;;
esac
# Cargo.lock: on the latest version if the dependency comes from the registry.
if [ -f Cargo.lock ]; then
locked=$(lock_entries | awk -v n="$name" -v r="/api/packages/$REGISTRY/" '$1 == n && index($3, r) { print $2 }' | sort -V | tail -n 1)
if [ -n "$locked" ] && [ "$locked" != "$latest" ] && [ "$acc" -eq 0 ]; then
if [ "$mode" = bump ]; then
updates+="$name "
else
bad "$name: Cargo.lock is on $locked, the latest published version is $latest → cargo update -p $name (make deps-bump)"
fi
fi
fi
# Neighbouring folder: replaces the dependency in joint development.
if [ -f "../$name/Cargo.toml" ]; then
neighbor=$(sed -n 's/^version = "\(.*\)"/\1/p' "../$name/Cargo.toml" | head -n 1)
if [ -n "$neighbor" ] && [ "$neighbor" != "$latest" ]; then
if [ "$(printf '%s\n%s\n' "$neighbor" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
bad "$name: the neighbouring folder ../$name is at $neighbor, the registry at $latest → update the neighbour (jj git fetch)"
else
warn " ⚠ $name: the neighbouring folder ../$name ($neighbor) is newer than the published version ($latest): publication pending"
fi
fi
fi
done <<<"$decl"
if [ "$offline" -eq 1 ]; then
if [ "${DEPS_CHECK_OFFLINE:-}" = 1 ]; then
warn " ⚠ registry unreachable: freshness of the dependencies not verified (DEPS_CHECK_OFFLINE=1)"
else
bad "registry $REGISTRY unreachable ($index_url): freshness cannot be verified (DEPS_CHECK_OFFLINE=1 to ignore)"
fi
fi
# Cargo.lock: ignored patch and duplicates.
if [ -f Cargo.lock ]; then
unused=$(awk '
/^\[\[patch.unused\]\]/ { u = 1; next }
/^\[/ { u = 0 }
u && /^name = / { gsub(/"/, "", $3); print $3 }
' Cargo.lock | sort -u | paste -sd' ' -)
if [ -n "$unused" ] && [ "$mode" = check ]; then
bad "Cargo.lock: local patch ignored for $unused — the project's requirement does not accept the version of the neighbouring folder"
fi
dups=$(lock_entries | awk -v r="/api/packages/$REGISTRY/" '
{ c[$1]++; vs[$1] = vs[$1] " " $2; if ($3 == "-" || index($3, r)) p[$1] = 1 }
END { for (n in c) if (c[n] > 1 && p[n]) print n ":" vs[n] }
')
if [ -n "$dups" ]; then
while IFS= read -r d; do
bad "Cargo.lock: several versions of ${d%%:*} in the build (${d#*: }) — align the requirements of the crates that depend on it"
done <<<"$dups"
fi
fi
if [ "$mode" = bump ] && [ -n "$updates" ]; then
for n in $(printf '%s\n' $updates | sort -u); do
info " cargo update -p $n"
"$CARGO" update -p "$n" >/dev/null
done
fi
if [ "$fail" -ne 0 ]; then
err "✗ Registry dependencies stale or inconsistent (see above)"
exit 1
fi
ok "✓ Registry dependencies up to date ($count checked)"
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# Functions shared by the dependency checks (deps-check.sh, deps-check-external.sh).
# To be sourced after common.sh. Nothing here writes a file.
index_url="${REGISTRY_INDEX#sparse+}"
index_url="${index_url%/}"
# Path of a crate in a sparse index (1, 2, 3 characters, then two pairs).
index_path() {
local n
n=$(printf '%s' "$1" | tr 'A-Z' 'a-z')
case ${#n} in
1) echo "1/$n" ;;
2) echo "2/$n" ;;
3) echo "3/${n:0:1}/$n" ;;
*) echo "${n:0:2}/${n:2:2}/$n" ;;
esac
}
# Latest published version (not yanked, excluding pre-releases) of $1 in the sparse index $2 (default:
# the private registry); empty if not found.
# Code: 0 found, 1 absent from the index, 2 index unreachable.
latest_published() {
local body rc=0 base="${2:-$index_url}"
body=$(curl -sS -f -m 20 "$base/$(index_path "$1")" 2>/dev/null) || rc=$?
if [ "$rc" -ne 0 ]; then
case "$rc" in 22 | 37) return 1 ;; *) return 2 ;; esac
fi
printf '%s\n' "$body" |
sed -n 's/.*"vers":"\([^"]*\)".*"yanked":false.*/\1/p' |
grep -v -- '-' | sort -V | tail -n 1
}
# Does the requirement $1 (x, x.y or x.y.z, with optional ^) accept version $2?
# Code: 0 yes, 1 no, 2 unsupported form.
req_accepts() {
local r="${1#^}" v="$2" rmaj rmin rest vmaj vmin
case "$r" in '' | *[!0-9.]*) return 2 ;; esac
IFS=. read -r rmaj rmin rest <<<"$r"
IFS=. read -r vmaj vmin rest <<<"$v"
[ "$rmaj" = "$vmaj" ] || return 1
if [ "$rmaj" = 0 ] && [ -n "$rmin" ]; then
[ "$rmin" = "$vmin" ] || return 1
fi
return 0
}
# Minimal requirement that accepts version $1: x.y for a 0.x, x otherwise.
req_for() {
case "$1" in
0.*) echo "$1" | cut -d. -f1,2 ;;
*) echo "$1" | cut -d. -f1 ;;
esac
}
# Packages of Cargo.lock, one per line: "name version source" ("-" without source). The
# [[patch.unused]] blocks are excluded.
lock_entries() {
awk '
function flush() { if (n != "") print n, v, (s == "" ? "-" : s); n = v = s = "" }
/^\[\[package\]\]/ { flush(); inpkg = 1; next }
/^\[/ { flush(); inpkg = 0; next }
inpkg && /^name = / { gsub(/"/, "", $3); n = $3 }
inpkg && /^version = / { gsub(/"/, "", $3); v = $3 }
inpkg && /^source = / { gsub(/"/, "", $3); s = $3 }
END { flush() }
' Cargo.lock
}
manifests=("$CARGO_TOML")
# Root of a workspace whose member CARGO_TOML designates (workspace): shared dependencies.
[ "$CARGO_TOML" != Cargo.toml ] && [ -f Cargo.toml ] && manifests+=(Cargo.toml)
for m in */Cargo.toml; do
if [ -f "$m" ]; then manifests+=("$m"); fi
done
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# Generates .cargo/config.toml (local, ignored by jj) for joint development:
# - the definition of the private registry;
# - a [patch.<registry>] for each registry dependency that has a neighbouring folder
# (../<name>/Cargo.toml), so that the project builds against the neighbouring code without publishing.
# Only the dependencies actually declared by this project are patched: no unused patch
# (Cargo complains about it), whatever the number of crates coming out of a workspace.
#
# Run by crate.mk on every make invocation. The file is rewritten only if it changes.
# Reads the root Cargo.toml and those of the direct subfolders (workspace members);
# only the dependencies on one line `name = { …, registry = "<registry>" }` are seen.
# A .cargo/config.toml that was not generated by this script is never overwritten (warning).
set -euo pipefail
. "$(dirname "$0")/common.sh"
[ -f "$CARGO_TOML" ] || exit 0
# Nothing to generate without a registry (no extension) nor for crates.io (cargo's default index and token).
[ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ] || exit 0
marker="# Generated by .crate-kit/scripts/dev-patch.sh"
config=".cargo/config.toml"
if [ -f "$config" ] && ! grep -q "^$marker" "$config"; then
warn "⚠ $config was not generated by the kit: left as is. If it is tracked by the repository,"
warn " delete it and add /.cargo/config.toml to .gitignore (the CI uses an environment variable)."
exit 0
fi
self=$(crate_name)
manifests=("$CARGO_TOML")
# Root of a workspace whose member CARGO_TOML designates (workspace): this is where the shared
# dependencies ([workspace.dependencies]) are declared.
[ "$CARGO_TOML" != Cargo.toml ] && [ -f Cargo.toml ] && manifests+=(Cargo.toml)
for m in */Cargo.toml; do [ -f "$m" ] && manifests+=("$m"); done
registry_deps() {
sed -nE "s/^([A-Za-z0-9_-]+)[[:space:]]*=[[:space:]]*\{[^}]*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\".*/\1/p" "$@"
}
names=$(registry_deps "${manifests[@]}" | sort -u)
# Transitive closure through the neighbours: a dependency of a patched neighbour (a -> a-macros)
# must be patched too, otherwise the project builds the neighbour against the published version of its own
# dependency and not against the neighbouring code.
while :; do
more=$(for n in $names; do [ -f "../$n/Cargo.toml" ] && registry_deps "../$n/Cargo.toml"; done | sort -u)
merged=$(printf '%s\n%s\n' "$names" "$more" | sed '/^$/d' | sort -u)
[ "$merged" = "$names" ] && break
names=$merged
done
patches=""
for n in $names; do
[ "$n" = "$self" ] && continue
[ -f "../$n/Cargo.toml" ] && patches+="$n = { path = \"../$n\" }"$'\n'
done
new="$marker on every \`make\`: do not edit, do not commit (ignored by the repository).
# Private registry and, for joint development, dependencies resolved to the neighbouring folders.
[registries.$REGISTRY]
index = \"$REGISTRY_INDEX\"
"
[ -n "$patches" ] && new+="
[patch.$REGISTRY]
$patches"
if [ ! -f "$config" ] || [ "$(cat "$config")" != "${new%$'\n'}" ]; then
mkdir -p .cargo
printf '%s' "$new" >"$config"
list=$(printf '%s' "$patches" | sed 's/ = .*//' | paste -sd' ' -)
info " $config updated (local patches: ${list:-none})"
fi
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Creates the Forgejo release associated with the tag version-x.y.z. Description: the message of the tag if it is
# annotated, otherwise (lightweight tag created by tag.sh) the file $RELEASE_NOTES_DIR/version-x.y.z.md of the
# working directory, which must be the checkout of the tag. Meant for the CI; idempotent: an already existing release is
# reused, and an attached file that is already present is not sent again.
#
# Variables (provided by the workflow):
# FORGETOKEN Forgejo API token (write access to releases)
# TAG tag to publish (e.g. version-0.1.4)
# SERVER Forgejo server URL (e.g. https://forge.example.org)
# REPO owner/repository (e.g. org/crate)
# ASSET optional: file to attach to the release (e.g. dist/crate-kit-0.1.4.tar.gz)
set -euo pipefail
. "$(dirname "$0")/common.sh"
: "${FORGETOKEN:?FORGETOKEN required}" "${TAG:?TAG required}" "${SERVER:?SERVER required}" "${REPO:?REPO required}"
command -v jq >/dev/null || { err "✗ jq is required"; exit 1; }
api="$SERVER/api/v1/repos/$REPO"
auth="Authorization: token $FORGETOKEN"
if release_json=$(curl -sf -H "$auth" "$api/releases/tags/$TAG"); then
warn " The release $TAG already exists: reused"
else
# Message of the annotated tag (object of type "tag"); empty for a lightweight tag.
ref_json=$(forge_call "reading tag $TAG" -H "$auth" "$api/git/refs/tags/$TAG") || exit 1
obj_sha=$(echo "$ref_json" | jq -r '.[0]?.object.sha // empty')
obj_type=$(echo "$ref_json" | jq -r '.[0]?.object.type // empty')
body=""
if [ "$obj_type" = "tag" ]; then
tag_json=$(forge_call "reading the message of tag $TAG" -H "$auth" "$api/git/tags/$obj_sha") || exit 1
body=$(echo "$tag_json" | jq -r '.message // empty')
fi
# Lightweight tag (tag.sh, jj only): the notes are the file committed in the tagged revision, read in the
# working directory (the workflow runs in the checkout of the tag).
if [ -z "$body" ] && [ -f "$RELEASE_NOTES_DIR/$TAG.md" ]; then
body=$(cat "$RELEASE_NOTES_DIR/$TAG.md")
fi
release_json=$(forge_call "creating release $TAG" -X POST "$api/releases" -H "$auth" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg tag "$TAG" --arg body "$body" '{tag_name: $tag, name: $tag, body: $body}')") || exit 1
ok "✓ Release $TAG created"
fi
if [ -n "${ASSET:-}" ]; then
[ -f "$ASSET" ] || { err "✗ file to attach not found: $ASSET"; exit 1; }
release_id=$(echo "$release_json" | jq -r '.id')
name=$(basename "$ASSET")
if echo "$release_json" | jq -e --arg n "$name" '.assets[]? | select(.name == $n)' >/dev/null; then
warn " $name is already attached to the release: nothing to do"
else
forge_call "uploading $name to release $TAG" -X POST "$api/releases/$release_id/assets?name=$name" \
-H "$auth" -F "attachment=@$ASSET" >/dev/null || exit 1
ok "✓ $name attached to release $TAG"
fi
fi
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Fetches the latest commits from origin WITHOUT losing local work: the mutable revisions
# sitting on the old main are rebased on top of the fetched main@origin.
#
# - local work (mutable revisions between main@origin and @, including an empty working
# copy): rebased onto main@origin;
# - work sitting on a pushed revision not yet merged into main@origin (pending
# PR): left in place, with a warning (rebasing it would cut it off from that revision);
# - working copy already contained in main@origin: we start again from a new revision on top of it.
#
# JJ_BASE (default main@origin): the base to join.
set -euo pipefail
. "$(dirname "$0")/common.sh"
base="${JJ_BASE:-main@origin}"
info "→ Fetching the latest commits..."
jj git fetch
jj log -r "$base" --no-graph -T 'change_id' >/dev/null 2>&1 || {
err "✗ $base not found after the fetch"
exit 1
}
# Local work = mutable revisions between the base and @ that are NOT already published (reachable
# from a remote bookmark): we do not rewrite what origin knows. We only keep the roots
# whose parent is already in the base's history.
work="(mutable() & ($base..@)) ~ ::remote_bookmarks()"
# A local revision rewritten AFTER its push (describe, rebase…) then merged on the server side in its
# pushed version has a twin in $base: same change id, other commit, hence a divergent
# change. We never designate a revision by its change id (jj refuses a divergent
# identifier), and we do not rebase what is already merged:
# - same content as the merged twin: the local revision is abandoned (nothing is lost);
# - different content: we stop before rewriting anything, with the course of action to follow.
for c in $(jj log --no-graph -r "($work) & divergent()" -T 'commit_id ++ "\n"'); do
cid=$(jj log --no-graph -r "$c" -T 'change_id')
twin=$(jj log --no-graph -r "change_id($cid) & ::$base" -T 'commit_id ++ "\n"' | head -n 1)
[ -n "$twin" ] || continue
short=$(jj log --no-graph -r "$c" -T 'commit_id.short(12)')
if [ -z "$(jj interdiff --from "$twin" --to "$c" --summary)" ]; then
jj abandon "$c"
ok "✓ Revision $short already merged into $base (same content): abandoned"
else
err "✗ The local revision $short has already been merged into $base in another version"
err " (same change id, different content): nothing was rewritten."
err " See the difference: jj interdiff --from $twin --to $c"
err " Keep the merged version: jj abandon $c"
err " Keep the local version: jj metaedit --update-change-id $c, then rerun"
exit 1
fi
done
roots=$(jj log --no-graph -r "roots($work) & children(::$base)" -T 'commit_id ++ "\n"')
if [ -n "$roots" ]; then
args=()
for r in $roots; do args+=(-s "$r"); done
jj rebase "${args[@]}" -d "$base"
ok "✓ Local work rebased onto $base"
elif [ -n "$(jj log --no-graph -r "@ & ::$base" -T 'change_id')" ]; then
# The working copy is already part of the base: nothing to keep.
jj new "$base"
ok "✓ New revision on $base"
elif [ -n "$(jj log --no-graph -r "($base..@) & (::remote_bookmarks() | immutable())" -T 'change_id')" ]; then
warn "⚠ The work rests on pushed revisions not merged into $base (pending PR):"
warn " left in place. Merge the PR then rerun, if needed."
else
ok "✓ Already up to date on $base"
fi
if [ -n "$(jj log --no-graph -r 'conflicts() & ::@ & mutable()' -T 'change_id' 2>/dev/null)" ]; then
warn "⚠ Conflicts after the rebase: jj st, then jj resolve."
fi
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Checks that the crate is adopted: the CI release workflow is installed and up to date with the template of
# its kind (comments and step names ignored; opt out with a `# kit-workflow: custom` line), and the kit copy
# (.crate-kit/) is identical to the reference kit (crate-kit + overlay, assembled by $KIT_SRC/tools/kit-assemble.sh; default ../crate-kit). Read-only.
#
# Compares the CONTENT, not VERSION: a fix to the kit does not always change its number.
# `--fix`: instead of failing on an out-of-date workflow, replace it with the template of its kind.
# Without a crate-kit repository alongside (clone of the crate alone, CI), there is nothing to compare: success.
set -euo pipefail
. "$(dirname "$0")/common.sh"
fix=0
[ "${1:-}" = "--fix" ] && fix=1
kit_dir="$(cd "$(dirname "$0")/.." && pwd)"
crate_dir="$(dirname "$kit_dir")"
# Without this workflow, a version-* tag publishes nothing: the crate was not adopted all the way.
workflow=".gitea/workflows/release.yaml"
if [ ! -f "$crate_dir/$workflow" ]; then
err "✗ $workflow is missing in $crate_dir: the release CI will not trigger"
info " Complete the adoption: crate-kit/adopt.sh [--kind <kind>] $crate_dir"
exit 1
fi
kit_src="${KIT_SRC:-../crate-kit}"
# Workflow up to date with the template of the crate's kind (the same one adopt.sh lays down). Only the
# logic counts: comment lines and `- name:` labels are ignored, so a rewording is not a difference.
if [ -x "$kit_src/tools/kit-assemble.sh" ] && ! grep -q '^# kit-workflow: custom' "$crate_dir/$workflow"; then
kind="${CRATE_KIND:-}"
if [ -z "$kind" ] && [ -f "$crate_dir/Makefile" ]; then
kind=$(sed -n 's/^CRATE_KIND *[:?]*= *\([a-z]*\).*/\1/p' "$crate_dir/Makefile" | head -n 1)
fi
template="$("$kit_src/tools/kit-assemble.sh" --root)/template"
overlay=$("$kit_src/tools/kit-assemble.sh" --overlay 2>/dev/null || true)
[ -n "$kind" ] && [ -n "$overlay" ] && [ -d "$overlay/templates/$kind" ] && template="$overlay/templates/$kind"
norm() { grep -v '^ *#' "$1" | grep -v '^ *- name:' | sed 's/[[:space:]]*$//'; }
if [ -f "$template/$workflow" ] && ! diff <(norm "$crate_dir/$workflow") <(norm "$template/$workflow") >/dev/null; then
if [ "$fix" = 1 ]; then
cp "$template/$workflow" "$crate_dir/$workflow"
ok "→ $workflow replaced with the template of its kind"
else
err "✗ $workflow differs from the template of its kind: the release CI is out of date"
diff <(norm "$crate_dir/$workflow") <(norm "$template/$workflow") >&2 || true
info " Replace it: cp $template/$workflow $crate_dir/$workflow"
info " (keep a deliberate customization by adding the line \"# kit-workflow: custom\" to the workflow)"
exit 1
fi
fi
fi
if [ ! -x "$kit_src/tools/kit-assemble.sh" ]; then
info " (reference kit not found: $kit_src, check skipped)"
exit 0
fi
ref="$(mktemp -d "${TMPDIR:-/tmp}/kit-check.XXXXXX")"
trap 'rm -r "$ref"' EXIT
"$kit_src/tools/kit-assemble.sh" "$ref"
if diff -rq "$ref" "$kit_dir" >/dev/null 2>&1; then
ok "✓ Kit up to date (crate-kit $(cat "$ref/VERSION"))"
exit 0
fi
err "✗ This crate's kit is not the one from $kit_src:"
diff -rq "$ref" "$kit_dir" >&2 || true
info " Update: make kit-update"
exit 1
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
# Is there, in the crate's jj working copy (current directory), a change that justifies a
# commit, that is, something other than what the kit itself produces or modifies? Read-only.
#
# Do not count:
# - .crate-kit/ (kit copy) and .cargo/ (generated local configuration);
# - a template file (.gitea/workflows/release.yaml, LICENSE, .gitignore, Makefile…) identical to
# that of the kind's template (<extension>/templates/<kind>, otherwise crate-kit/template): adopt.sh laid it down as is;
# - Cargo.lock when only the `version` line of the crate itself changed (version bump);
# - the Makefile when only its kit bootstrap lines changed (KIT_SRC, copy or sync of
# .crate-kit/, comments that talk about the kit): the rest (description, PLUGIN_ID…) belongs to the crate.
# Without a crate-kit repository alongside ($KIT_SRC), the second filter cannot apply: these files
# then count as changes.
#
# Output: one file per line on standard output. Code 0 if there are any, 1 otherwise (nothing to commit).
set -euo pipefail
. "$(dirname "$0")/common.sh"
kit_src="${KIT_SRC:-../crate-kit}"
kind="${CRATE_KIND:-}"
if [ -z "$kind" ] && [ -f Makefile ]; then
kind=$(sed -n 's/^CRATE_KIND *[:?]*= *\([a-z]*\).*/\1/p' Makefile | head -n 1)
fi
template="$("$kit_src/tools/kit-assemble.sh" --root)/template"
overlay=$("$kit_src/tools/kit-assemble.sh" --overlay 2>/dev/null || true)
[ -n "$kind" ] && [ -n "$overlay" ] && [ -d "$overlay/templates/$kind" ] && template="$overlay/templates/$kind"
# Cargo.lock: did only the `version` line of the crate's package change?
lock_is_version_bump() {
local name
name=$(crate_name)
jj diff --git --context 1 Cargo.lock 2>/dev/null | awk -v name="$name" '
/^(\+\+\+|---)/ { next }
/^@@/ { prev = ""; next }
/^[-+]/ {
changed++
if ($0 !~ /^[-+]version = / || prev != " name = \"" name "\"") bad = 1
next
}
/^ / { prev = $0 }
END { exit (changed > 0 && !bad) ? 0 : 1 }'
}
# Makefile: did only the kit bootstrap lines change? Those that name KIT_SRC or
# `crate-kit` (variable, sync, copy of .crate-kit/) and the comments that talk about the kit; a
# modification of any other line (description, PLUGIN_ID, targets) is a real change of the crate.
makefile_is_kit_bootstrap() {
jj diff --git --context 1 Makefile 2>/dev/null | awk '
/^(\+\+\+|---)/ { next }
/^[-+]/ {
changed++
if ($0 !~ /KIT_SRC|crate-kit|kit-copy|^[-+]# .*[Kk]it/) bad = 1
}
END { exit (changed > 0 && !bad) ? 0 : 1 }'
}
found=0
while IFS= read -r line; do
# Format of `jj diff --summary`: "M path"; a rename "R {a => b}" remains a change.
path="${line#? }"
case "$path" in
.crate-kit/* | .cargo/*) continue ;;
Cargo.lock)
if lock_is_version_bump; then continue; fi
;;
Makefile)
if makefile_is_kit_bootstrap; then continue; fi
;;
esac
if [ "${line%% *}" = M ] && [ -f "$template/$path" ] && cmp -s "$template/$path" "$path"; then
continue
fi
echo "$path"
found=1
done < <(jj diff --summary)
[ "$found" -eq 1 ] || { info " nothing to commit outside the kit" ; exit 1; }
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Starts a new working commit (`jj new`), unless @ already is a blank one (empty, without a description).
# After a push of main, @ is usually already blank: when the pushed commit was @, it became immutable and jj
# itself created an empty working commit on top of it (operation "push bookmark main"). An unconditional
# `jj new` would then stack a second, useless empty commit.
set -euo pipefail
. "$(dirname "$0")/common.sh"
blank=$(jj log -r @ --no-graph -T 'if(empty && description == "", "1", "0")')
if [ "$blank" = 1 ]; then
info " (@ is already an empty working commit: no new commit)"
exit 0
fi
jj new
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# Safeguard: a crate published on a private registry declares `publish = ["<registry>"]` in its
# Cargo.toml, so that cargo itself refuses any publication elsewhere (crates.io for example).
# Not applicable: kind without publication (PUBLISH=no), registry absent or crates-io.
set -euo pipefail
. "$(dirname "$0")/common.sh"
[ "${PUBLISH:-yes}" = no ] && exit 0
{ [ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ]; } || exit 0
[ -f "$CARGO_TOML" ] || exit 0
grep -qE "^publish[[:space:]]*=[[:space:]]*\[[[:space:]]*\"$REGISTRY\"[[:space:]]*\]" "$CARGO_TOML" && exit 0
err "✗ $CARGO_TOML : publish = [\"$REGISTRY\"] missing in [package] (without it, cargo publish would accept crates.io)"
exit 1
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Publishes the current version on the $REGISTRY registry (private, or crates-io with CARGO_REGISTRY_TOKEN).
# DRY_RUN non-empty: assembles and builds the package without sending it.
#
# Idempotent: if the version is already published, it is a success (allows replaying the release
# workflow after a later failure). Authentication: variable CARGO_REGISTRIES_<REGISTRY>_TOKEN
# ("Bearer <token>"), otherwise built from the forge token (forge_token: FORGETOKEN in CI).
#
# --allow-dirty: in a colocated jj repository, git always sees the working copy as
# modified relative to its HEAD, even when the jj commit is already pushed.
set -euo pipefail
. "$(dirname "$0")/common.sh"
if [ "${PUBLISH:-yes}" = no ]; then
info " (kind ${CRATE_KIND:-crate}: nothing to publish on the registry)"
exit 0
fi
[ -n "$REGISTRY" ] || { err "✗ no registry: declare the kit extension (KIT_OVERLAY in the Makefile, org.mk) or set REGISTRY = crates-io"; exit 1; }
version=$(current_version)
name=$(crate_name)
if [ -n "${DRY_RUN:-}" ]; then
warn "→ Checking the publication of $name $version (without sending)..."
"$CARGO" publish --registry "$REGISTRY" --allow-dirty --dry-run
exit 0
fi
warn "→ Publishing $name $version on registry $REGISTRY..."
log=$(mktemp)
trap 'rm -f -- "$log"' EXIT
if "$CARGO" publish --registry "$REGISTRY" --allow-dirty 2>&1 | tee "$log" >&2; then
ok "✓ $name $version published"
elif grep -qiE 'already (exists|uploaded)|crate version .* is already' "$log"; then
warn " $name $version is already published on $REGISTRY: nothing to do"
else
err "✗ Publication of $name $version failed"
exit 1
fi
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Advances the main bookmark to the current commit (@, or its first non-empty ancestor if @ is an
# empty working commit without a description: release_rev) and pushes it: no PR branch, main receives
# the commit directly. Moving main must be a fast-forward (jj refuses otherwise): if
# main@origin has advanced, `make jjfetch` first rebases the local work onto it.
set -euo pipefail
. "$(dirname "$0")/common.sh"
abandon_blank_commits
rev=$(release_rev)
if ! jj bookmark set main -r "$rev" 2>/dev/null; then
err "✗ main cannot advance to $rev (main has diverged or $rev does not descend from it)"
info " Run make jjfetch to rebase the work onto main@origin, then start again."
exit 1
fi
jj git push --bookmark main
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Generates $RELEASE_NOTES_DIR/version-<version>.md: notes produced by `jj release-notes`
# (fallback to one line if they fail, e.g. before the first tag), then adds a
# "Public API" section with the snapshot diff since the previous version.
set -euo pipefail
. "$(dirname "$0")/common.sh"
version=$(current_version)
notes="$RELEASE_NOTES_DIR/version-$version.md"
info "→ Generating the release notes ($notes)..."
mkdir -p "$RELEASE_NOTES_DIR"
PMOJJ_RELEASE_LANG="${KIT_LANG:-en}" PMOJJ_RELEASE_PROJECT="${RELEASE_PROJECT_DESC:-$(crate_name)}" jj release-notes --release "$version" >"$notes" ||
echo "Release version-$version" >"$notes"
prev=$(ls "$API_DIR"/*.txt 2>/dev/null | sed 's|.*/||; s|\.txt$||' | sort -V |
grep -v -x "$version" | tail -n 1 || true)
if [ -n "$prev" ] && [ -f "$API_DIR/$version.txt" ]; then
api_diff=$(diff <(filter_notes "$API_DIR/$prev.txt") <(filter_notes "$API_DIR/$version.txt") | grep '^[<>]' || true)
if [ -n "$api_diff" ]; then
printf '\n## Public API (changes since %s)\n\n```diff\n%s\n```\n' \
"$prev" "$api_diff" >>"$notes"
fi
fi
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Does the release tag `version-<version>` already exist (locally or on origin)? jj only, no git command.
# Usage: tag-exists.sh <version>
# Exit: 0 = the tag exists, 1 = it does not, 2 = not checked (no jj repository, origin unreachable).
# jj has no equivalent of `ls-remote`: the tag alone is fetched (`jj git fetch --tag`), which imports it as a
# tracked remote tag if it exists on origin and changes nothing else, then `jj tag list` tells.
set -uo pipefail
version="${1:?usage: tag-exists.sh <version>}"
tag="version-$version"
jj root >/dev/null 2>&1 || exit 2
jj git fetch --tag "exact:$tag" >/dev/null 2>&1 || exit 2
if [ -n "$(jj tag list "exact:$tag" -T 'name ++ "\n"' 2>/dev/null)" ]; then
exit 0
fi
exit 1
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Creates and pushes the tag version-<version> on the published commit (release_rev: @, or its first
# non-empty ancestor), with jj only. The tag is lightweight (jj creates no annotated tag): the release notes
# are not its message but the file $RELEASE_NOTES_DIR/version-<version>.md committed in the tagged revision,
# which forgejo-release.sh reads in the CI as the body of the release.
set -euo pipefail
. "$(dirname "$0")/common.sh"
version=$(current_version)
tag="version-$version"
notes="$RELEASE_NOTES_DIR/$tag.md"
[ -f "$notes" ] || { err "✗ release notes missing: $notes (make release-notes)"; exit 1; }
if [ -n "$(jj tag list "exact:$tag" 2>/dev/null)" ]; then
err "✗ tag $tag already exists"
exit 1
fi
rev=$(release_rev)
jj tag set "$tag" -r "$rev"
jj git push --tag "exact:$tag"
ok "✓ Release $tag published"
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env bash
# Publishes the API documentation (rustdoc -> JSON -> Markdown) to the crate's Forgejo wiki.
#
# The Forgejo wiki is a second repository (<repository>.wiki.git). It is never kept: the script
# clones it into a temporary directory (git), replaces the generated pages, commits and pushes, then
# removes the clone. Works identically locally and in the CI (release workflow).
#
# Pages produced: Home.md (module index), _Sidebar.md, one page per module.
# The wiki content is ENTIRELY replaced: any page written by hand on the Forgejo side
# disappears at the next run.
#
# Variables:
# WIKI_URL wiki repository URL (default: `origin` URL with .git replaced by .wiki.git)
# WIKI_TOKEN access token (CI, https URL): sent in the header "Authorization: token …"
# GIT_USER_NAME / GIT_USER_EMAIL commit identity if git has none configured
# DRY_RUN non-empty: generates and commits in the temporary clone, shows the diff, does not push
#
# Prerequisites: cargo-doc-md (cargo install cargo-doc-md --locked); the wiki must exist on the
# Forgejo side (create a first page by hand once per crate, otherwise the repository is not found).
set -euo pipefail
. "$(dirname "$0")/common.sh"
if [ "${WIKI:-yes}" = no ]; then
info " (kind ${CRATE_KIND:-crate}: no API documentation for the wiki)"
exit 0
fi
require_cargo_tool doc-md cargo-doc-md
name=$(crate_name)
version=$(current_version)
# Wiki URL: that of origin, with .git replaced by .wiki.git.
if [ -z "${WIKI_URL:-}" ]; then
origin=$(git remote get-url origin 2>/dev/null || true)
[ -n "$origin" ] || { err "✗ remote origin not found: set WIKI_URL=..."; exit 1; }
WIKI_URL="${origin%.git}.wiki.git"
fi
# Common git options: token in a header (CI) and fallback identity.
git_opts=()
if [ -n "${WIKI_TOKEN:-}" ]; then
git_opts+=(-c "http.extraHeader=Authorization: token $WIKI_TOKEN")
fi
if [ -z "$(git config user.name 2>/dev/null || true)" ]; then
git_opts+=(-c "user.name=${GIT_USER_NAME:-crate-kit}")
fi
if [ -z "$(git config user.email 2>/dev/null || true)" ]; then
git_opts+=(-c "user.email=${GIT_USER_EMAIL:-crate-kit@localhost}")
fi
wgit() { git "${git_opts[@]}" "$@"; }
work=$(mktemp -d "${TMPDIR:-/tmp}/crate-kit-wiki.XXXXXX")
[ -n "$work" ] && [ -d "$work" ] || { err "✗ temporary directory not created"; exit 1; }
trap 'rm -rf -- "$work"' EXIT
# 1. Rustdoc -> Markdown (one file per module, in $work/md/<crate>/).
info "→ Generating the Markdown ($name $version)..."
"$CARGO" doc-md --no-deps -o "$work/md" >&2
src="$work/md/$name"
[ -f "$src/index.md" ] || {
# The folder name follows the library name (hyphens -> underscores).
src="$work/md/${name//-/_}"
[ -f "$src/index.md" ] || { err "✗ index.md not found in $work/md"; exit 1; }
}
# 2. Wiki pages: flat, links between pages without the .md extension (Forgejo wiki convention).
pages="$work/pages"
mkdir -p "$pages"
for f in "$src"/*.md; do
base=$(basename "$f")
[ "$base" = index.md ] && continue
cp "$f" "$pages/$base"
done
# Home = crate index as produced by cargo-doc-md (title, crate doc, modules);
# the version appears in the sidebar.
sed -E 's/\]\(([^)#]+)\.md\)/](\1)/g' "$src/index.md" >"$pages/Home.md"
{
printf '**[%s](Home)** %s\n\n' "$name" "$version"
sed -nE 's/^### \[`([^`]+)`\]\(([^)]+)\.md\).*/- [\1](\2)/p' "$src/index.md"
} >"$pages/_Sidebar.md"
# Rustdoc intra-doc links (``[`item`]``, ``[`module::item`]``): cargo-doc-md does not resolve them
# and leaves them in literal brackets. We resolve them here to the wiki page that defines
# the item (table built from the "Contents" of each module page); a module
# points to its own page. Names not found (std, other crates) lose their
# brackets and remain as code.
map="$work/map"
: >"$map"
for f in "$pages"/*.md; do
p=$(basename "$f" .md)
case "$p" in Home | _Sidebar) continue ;; esac
echo "$p $p" >>"$map"
done
for f in "$pages"/*.md; do
p=$(basename "$f" .md)
case "$p" in Home | _Sidebar) continue ;; esac
sed -nE 's/^- \[`([A-Za-z0-9_]+)`\]\(#.*/\1 '"$p"'/p' "$f" >>"$map"
done
resolve="$work/resolve.sed"
: >"$resolve"
while read -r item page; do
# First wins: the module pages (lines at the start) take precedence; an item already
# turned into a link is no longer a candidate (it is followed by "(").
printf 's/\\[`((([A-Za-z0-9_]+::)*)%s)`\\]([^(:[]|$)/[`\\1`](%s)\\4/g\n' "$item" "$page" >>"$resolve"
done <"$map"
for f in "$pages"/*.md; do
sed -E -f "$resolve" "$f" | sed -E 's/\[(`[^`]+`)\]([^(:[]|$)/\1\2/g' >"$f.tmp"
mv "$f.tmp" "$f"
done
# 3. Clone the wiki, replace the pages, commit, push.
info "→ Cloning the wiki ${WIKI_URL}..."
clone="$work/clone"
wgit clone --quiet "$WIKI_URL" "$clone" >&2 || {
err "✗ cannot clone: does the wiki exist? (create a first page on Forgejo)"
exit 1
}
cd "$clone"
# Default branch of the wiki (master or main depending on the instance): the one the clone checked out.
branch=$(git symbolic-ref --short HEAD)
# The generated files replace all the .md; the rest (images…) is kept.
find . -maxdepth 1 -name '*.md' -type f -delete
cp "$pages"/*.md .
git add -A
if [ -z "$(git status --porcelain)" ]; then
ok "✓ Wiki already up to date"
exit 0
fi
git diff --cached --stat >&2
wgit commit --quiet -m "API documentation: $name $version"
if [ -n "${DRY_RUN:-}" ]; then
warn "→ DRY_RUN: local commit in the temporary clone, nothing is pushed"
exit 0
fi
wgit push --quiet origin "$branch" >&2
ok "✓ Wiki of $name updated ($version)"
+6 -29
View File
@@ -62,8 +62,7 @@ jobs:
~/.cargo/registry
~/.cargo/git
src/target
tools/migrate-mphf/target
key: linux-musl-cargo-${{ hashFiles('src/Cargo.lock', 'tools/migrate-mphf/Cargo.lock') }}
key: linux-musl-cargo-${{ hashFiles('src/Cargo.lock') }}
restore-keys: linux-musl-cargo-
- name: Build static binary
@@ -77,34 +76,12 @@ jobs:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
run: |
mkdir -p /tmp/dist
cp target/x86_64-unknown-linux-musl/release/obikmer /tmp/dist/obikmer-linux-x86_64
strip /tmp/dist/obikmer-linux-x86_64
cp target/x86_64-unknown-linux-musl/release/obiskim /tmp/dist/obiskim-linux-x86_64
strip /tmp/dist/obiskim-linux-x86_64
curl -s -X POST \
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/$RELEASE_ID/assets" \
-H "Authorization: token $GITEA_TOKEN" \
-F "attachment=@/tmp/dist/obikmer-linux-x86_64"
# One-shot converter for indexes built with ptr_hash 1.x. A standalone
# crate (own Cargo.lock/target, outside src/'s workspace), built after
# obikmer's own asset is already uploaded: it never blocks that one.
- name: Build migrate-mphf (static)
working-directory: tools/migrate-mphf
env:
PKG_CONFIG_ALLOW_CROSS: "1"
run: cargo zigbuild --release --target x86_64-unknown-linux-musl
- name: Upload migrate-mphf artifact
working-directory: tools/migrate-mphf
env:
GITEA_TOKEN: ${{ secrets.GITEATOKEN }}
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
run: |
cp target/x86_64-unknown-linux-musl/release/migrate-mphf /tmp/dist/migrate-mphf-linux-x86_64
strip /tmp/dist/migrate-mphf-linux-x86_64
curl -s -X POST \
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/$RELEASE_ID/assets" \
-H "Authorization: token $GITEA_TOKEN" \
-F "attachment=@/tmp/dist/migrate-mphf-linux-x86_64"
-F "attachment=@/tmp/dist/obiskim-linux-x86_64"
build-macos-arm64:
needs: create-release
@@ -135,7 +112,7 @@ jobs:
docker start -a "$CID"
STATUS=$(docker wait "$CID")
mkdir -p /tmp/dist
docker cp "$CID:/src/src/target/aarch64-apple-darwin/release/obikmer" /tmp/dist/obikmer-macos-arm64
docker cp "$CID:/src/src/target/aarch64-apple-darwin/release/obiskim" /tmp/dist/obiskim-macos-arm64
docker rm "$CID" > /dev/null
[ "$STATUS" -eq 0 ]
@@ -147,4 +124,4 @@ jobs:
curl -s -X POST \
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/$RELEASE_ID/assets" \
-H "Authorization: token $GITEA_TOKEN" \
-F "attachment=@/tmp/dist/obikmer-macos-arm64"
-F "attachment=@/tmp/dist/obiskim-macos-arm64"
+3 -1
View File
@@ -9,7 +9,6 @@ CLAUDE.md
memory/
sandbox/
src/target
tools/migrate-mphf/target
data-stress
*.fasta
*.fasta.gz
@@ -46,3 +45,6 @@ biblio
*.ckp.gz
*.model
scripts/__pycache__/mk_wiki.cpython-314.pyc
# Generated by .crate-kit/dev-patch.mk at every make
/.cargo/config.toml
@@ -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.
**`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.
+14 -14
View File
@@ -203,7 +203,7 @@ Genome keys follow the iteration order of `meta.genomes`.
## CLI
```
obikmer query <index> [--detail] [--mismatch] [--count-missing]
obiskim query <index> [--detail] [--mismatch] [--count-missing]
[--force-presence] [--presence-threshold <n>]
[-z <z>] [-T <threads>] [--chunk-size <MiB>]
<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`.**
`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.
`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.
@@ -285,7 +285,7 @@ None of this is implemented yet — parked here as a coherent roadmap while the
## 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.
@@ -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.
**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.
@@ -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.
- `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 `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.
- **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.
@@ -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.
- `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`.
- 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).
@@ -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.
- `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
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).
- `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.
- **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`:
@@ -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.
- **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.
- **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
@@ -360,7 +360,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**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.
- `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.
**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.
- `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`).
- 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.
- 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).
- 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."
- **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.
- `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).
- **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.
- 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
- `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
- `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`,
`family_overlap`. The sampled SNP path (`sampled_scan`, `AlignmentReducer`,
`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
(`--pseudo-alignment`/Sankoff group/`snp-*` `--distance` can combine in one
call). A per-output trait method would have to either duplicate that
@@ -2,8 +2,8 @@
`benchmark/Makefile` exercises indexing, merge, and phylo distance
reconstruction against simulated bacterial genomes. It now also covers
`obikmer query` — the read-matching path — and the sparse packed
presence-matrix format (`obikmer pack --sparse`), previously untested by
`obiskim query` — the read-matching path — and the sparse packed
presence-matrix format (`obiskim pack --sparse`), previously untested by
this pipeline.
## Motivation
@@ -42,7 +42,7 @@ without duplicating the exhaustive per-specimen coverage
## Sparse global index
`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`,
`pack_matrices(false)`) keeps the per-genome column files on disk after
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_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
gzipped to `query_{dense,sparse}/SPECIMEN.fasta.gz`, Reporter wall/RSS
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/meta.rs` — EvidenceKind::Approx { b, z }, LayerMeta
- `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
- `obikmer/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/reindex.rs` — CLI reindex, options --approx, -z, --evidence-bits, --fp, --block-size
- `obiskim/src/cmd/index.rs` — resolve_approx_params(), options --approx, -z, --evidence-bits, --fp
- `obiskim/src/cmd/estimate.rs` — commande estimate (dry-run des paramètres)
## 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:
```sh
obikmer filter src --output dst \
obiskim filter src --output dst \
--ingroup "species=Betula_nana" \
--outgroup "*" \
--min-count 2 \
@@ -217,7 +217,7 @@ Keep k-mers found in at least 2 *Betula nana* genomes and absent from all
other *Betula*:
```sh
obikmer filter src --output dst \
obiskim filter src --output dst \
--ingroup "species=Betula_nana" \
--outgroup "genus=Betula" \
--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*:
```sh
obikmer filter src --output dst \
obiskim filter src --output dst \
--ingroup "taxon~/Betulaceae/Betula" \
--outgroup "taxon!~/Betulaceae" \
--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*:
```sh
obikmer filter src --output dst \
obiskim filter src --output dst \
--ingroup "genus=Betula" \
--outgroup "genus=Alnus" \
--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:
```sh
obikmer filter src --output dst \
obiskim filter src --output dst \
--ingroup "genus=Betula" \
--outgroup "*" \
--min-count -1 \
@@ -259,7 +259,7 @@ obikmer filter src --output dst \
To dump only k-mers specific to *Betula nana*:
```sh
obikmer dump myindex \
obiskim dump myindex \
--ingroup "species=Betula_nana" \
--outgroup "*" \
--min-count 1 \
@@ -269,7 +269,7 @@ obikmer dump myindex \
To enumerate unitigs of the *Betula*-specific subgraph:
```sh
obikmer unitig myindex \
obiskim unitig myindex \
--ingroup "genus=Betula" \
--outgroup "*" \
--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.
```sh
obikmer dump myindex --head 100
obikmer dump myindex --head 20 --ingroup "species=Betula_nana" --min-count 1
obiskim dump myindex --head 100
obiskim dump myindex --head 20 --ingroup "species=Betula_nana" --min-count 1
```
### `phylo --presence-threshold N`
@@ -296,7 +296,7 @@ This option is independent of the `--presence-threshold` used in filtering.
```sh
# 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.
@@ -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
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
`UnitigArgs`. `FilterArgs::build_filters()` returns a ready-to-use filter
list.
+20 -34
View File
@@ -2,7 +2,7 @@
## 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.
---
@@ -62,52 +62,38 @@ fn validate_evidence_compat(sources: &[&KmerIndex]) -> OKIResult<EvidenceKind>
Check all sources against the constraints above. Abort on any mismatch.
### 2. Bootstrap output from first source
### 2. Bootstrap output from the base source
Recursive file copy of `sources[0]` → `output`. 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.
- In `Presence` mode, any `counts/` directories inherited from source_0 are removed.
- `spectrums/` from source_0 is removed and rebuilt from scratch across all sources, applying the (possibly renamed) labels.
This establishes the partition layout, all existing MPHFs, unitigs, and evidence files. The first source's genomes occupy columns 0 … `n_dst_genomes - 1` in the destination.
This establishes the partition layout, all existing MPHFs, unitigs, and evidence files. The base source's genomes occupy columns 0 … `n_dst_genomes - 1` in the destination.
### 3. For each subsequent source (parallel across partitions)
`KmerPartition::merge_partition(i, sources, mode, n_dst_genomes, block_bits)` is called for each partition index `i`. `block_bits` is taken from `dst.meta.config.block_bits`.
`obikmerge::partition_merge::merge_partition(dst, i, sources, mode, n_dst_genomes, block_bits, evidence)` runs once per partition index `i` (scheduled largest first by `PartitionRunner`). Each entry of `sources` is `(&KmerIndex, n_genomes)`, where `n_genomes` is the number of columns that source contributes (> 1 for an already-merged source). Code: `partition_merge/mod.rs` (orchestration, pass 1) and `partition_merge/pass2.rs` (per-group fill pipeline).
Each entry in `sources` is `(&KmerPartition, n_genomes)` where `n_genomes` is the column count that source contributes (> 1 when the source is itself a merged index).
**First merge, Presence mode**: when `n_dst_genomes == 1`, `TypedLayer::<()>::init_presence_matrix` is called on every existing dst layer first. It materialises the implicit single-genome matrix (`presence/col_000000.pbiv`, all true) so that source columns can be appended to it.
**First merge, Presence mode**: when `n_dst_genomes == 1`, `Layer::<()>::init_presence_matrix` is called on every existing destination layer before any source column is appended. This creates `presence/col_000000.pbiv` set all-true (genome 0 is present in every slot).
The dst layers are opened once per partition and shared by both passes.
**Pass 1 — classify kmers**
**Pass 1 — new k-mers into a de Bruijn graph.** Only the sources' `unitigs.bin` *paths* are needed (`KmerLayer::new(..).unitigs_path()`); no source layer is opened. The files are streamed (at most `max_open = 2` open at once), and every k-mer absent from all dst layers is pushed into one `GraphDeBruijn`. All new k-mers of all sources go into a **single** new layer per merge, built by `materialize_layer` (unitigs + MPHF + evidence).
Iterate all kmers from all source partitions (via `UnitigFileReader` + canonical kmer iteration). For each kmer, probe the destination `LayeredMap<()>`:
**New-layer matrix.** If a new layer exists, its matrix is created with `n_dst_genomes` absent columns (all zero/false) and closed immediately. This keeps the column-count invariant, and every source group then appends to it like to the existing layers.
- **Hit**: kmer already in the destination; record for Pass 2.
- **Miss**: push kmer into a `GraphDeBruijn` accumulator.
**Pass 2 — by consecutive groups of `SRC_GROUP = 2` sources, in source order.** Per group:
**New layer construction**
1. open the group's source layers for this partition;
2. `MatrixBuilder::resume` every dst matrix (existing layers + new layer), check `n_cols == n_dst_genomes + col_base`, append the group's `group_n` columns;
3. run the pipeline: stream each source layer's k-mers, `hash_batch` + `fill_sub_matrix` on the source, locate each k-mer in the dst layers (`find_batch_grouped`) or else in the new layer's MPHF, and write the values column-major into the group's builders;
4. close the columns, then the matrices; drop the group's layers; `col_base += group_n`.
If the accumulator is non-empty, compute de Bruijn unitigs and call `Layer::<()>::build(&new_layer_dir, block_bits)`. All kmers absent from the destination — across **all** sources — accumulate into a **single** graph, producing one new layer per merge operation (not one per source).
Only one group's source layers and destination columns are alive at a time, so the number of live mappings per partition does not depend on the number of sources. Columns are appended in source order, so every genome lands in the same absolute column as in a single-session merge.
**Pass 2 — fill column builders**
For each source and each of its layers, re-iterate unitigs and look up stored values via `SrcLayerData::lookup(kmer, src_n)`:
- `SrcLayerData::SetMembership` — no data directory exists; every kmer returns `vec![1; n_genomes]`
- `SrcLayerData::Presence` — reads `PersistentBitMatrix` from `presence/`
- `SrcLayerData::Count` — reads `PersistentCompactIntMatrix` from `counts/`
Hits are routed to `exist_builders[dst_layer][src_col]`; misses are routed to `new_src_builders[src_col]`.
**Column prepending for new layers**
Before source columns are written to the new layer, `n_dst_genomes` absent columns (all-zero / all-false) are prepended — one per genome already in the index — so the column count invariant holds immediately after layer creation.
**Close and update metadata**
Close all builders; update `presence/meta.json` or `counts/meta.json` with `{"n": N, "n_cols": n_dst_genomes + n_src_total}`; increment `PartitionMeta::n_layers` if a new layer was added.
**In-memory columns.** The group's columns are built in RAM (`MatrixBuilder::add_mem_col` → `MemBitVecBuilder` / `MemCompactIntVecBuilder`) and written once, sequentially, at `close` (`.building` file, then `rename`). The files are byte-identical to the former mmap-backed builders' output. There is no sparse file and no `MmapMut` on this path, so a block the FS cannot allocate is an `io::Error` instead of a SIGBUS. Files are not `fsync`ed: one sync per column file made merge ~8× slower. RAM per partition is at most `SRC_GROUP × src_n × N_part × (1/8 | 1)` bytes (presence | counts). History and figures: `merge_mmap_audit.md`; scaling limits: `merge_scaling.md`.
### 4. Update index metadata
@@ -129,7 +115,7 @@ impl Layer<PersistentBitMatrix> {
}
```
Each appends one column file to the matrix subdirectory (`counts/` or `presence/`). In `merge_partition`, columns are written directly via `PersistentBitVecBuilder` / `PersistentCompactIntVecBuilder` rather than through these helpers, but the invariant they enforce is the same.
Each appends one column file to the matrix subdirectory (`counts/` or `presence/`). In `merge_partition`, columns are written through `MatrixBuilder::add_mem_col` (in-memory builders) rather than through these helpers, but the invariant they enforce is the same.
---
@@ -139,7 +125,7 @@ After any merge, **every layer in every partition has exactly `n_genomes` column
Maintained by three mechanisms:
1. **Existing layers**: `n_src_total` columns appended (one per source genome).
1. **Existing layers**: `n_src_total` columns appended (one per source genome), group by group.
2. **New layers created during merge**: `n_dst_genomes` absent columns prepended before source columns.
3. **First merge, Presence mode**: `init_presence_matrix` retroactively creates `presence/col_0` all-true for genome 0.
@@ -161,7 +147,7 @@ The invariant is a precondition of `LayeredStore` aggregation traits: `col_weigh
## On-disk impact
After merging `G` genomes (sources_0 contributes `G0`, subsequent sources the rest):
After merging `G` genomes (sources_0 contributes `G0`, subsequent sources the rest), *before* `finalize` packs each matrix (sparse by default, `matrix.pbmx` with `--dense`):
```
partitions/
@@ -199,7 +185,7 @@ index.meta ← complete genome list + evidence kind written at
## 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 caused by the hard-link change above**: verified via checksum that a normal (two distinct sources) merge leaves every source file byte-identical.
@@ -0,0 +1,96 @@
# Merge: mmap audit (2026-11-17)
Audit of the memory-mapping behaviour of `obikmerge::partition_merge::merge_partition`, triggered by two production failures on a 192-core NUMA server merging 186 freshly built mono-genome presence indexes (256 partitions, data on BeeGFS `/hoyt`). Status: **A + C implemented (2026-11-17)**, B deferred. See [Implementation](#implementation-2026-11-17). Implementation prompt: `prompts/merge_mmap_refactor.md` (repository root, outside the doc tree).
## Observed failures
| Run | Flags | Failure | When |
|---|---|---|---|
| 1 | none | `Bus error` (SIGBUS) | seconds after `merge_partitions` starts |
| 2 | `--cpu-max 32` | `memory allocation of 32768 bytes failed` → abort, many threads at once | after ~1 h, 128/256 partitions done |
Run 2 rules out "one partition too large for RAM": partitions are scheduled largest first (LFD, `merge.rs:289`), so at 50 % every remaining partition is smaller than one already merged. Small `malloc` failures on a 700 GB host are not RAM exhaustion either. Linux would OOM-kill (SIGKILL) instead. A NULL from `malloc` means `mmap`/`brk` returned `ENOMEM`: `vm.max_map_count` (default 65 530), `RLIMIT_AS`, or strict overcommit. Root access is not available on the compute server, so the fix must be in the code.
## Inventory: mappings held by one `merge_partition` call
Counts read from the code; totals assume 1 layer per source partition and 1 pre-existing dst layer (estimate, not measured).
| Resource | Where | Maps | Lifetime | Needed? |
|---|---|---|---|---|
| Source layers, fully opened | `partition_merge.rs:219-227` → `KmerLayer::open` → `MphfLayer::open` (`mphf_layer.rs:171`) | 4 per layer: MPHF (`MphfOnly`), `unitigs.bin` (direct access), `evidence.bin`, `unitigs.bin` again (`LayerEvidence::open`, `mphf_layer.rs:100`). ≈ **740** | whole partition | Only the MPHF. Pass 2 calls `hash_batch` (MPHF only, `mphf_layer.rs:258`) and `fill_sub_matrix` (matrix: `Implicit` for mono-genome, zero maps). Pass 1 only needs the `unitigs.bin` *path*. |
| Writable columns, created up front | `partition_merge.rs:327`, `:349` → `PersistentBitVecBuilder::new` / `PersistentCompactIntVecBuilder::new` | `set_len` (sparse) + `MmapMut`, `n_src_total × (L_dst + 1)` ≈ **370** | whole pass 2 | Only the columns of the ≤ 2 sources being streamed (`max_open = 2`). |
| dst layers, new-layer MPHF, sequential readers | various | ≈ 10 | variable | yes |
≈ **1 100 maps per partition**, > 95 % idle at any instant. × ~32 concurrent partitions (`--cpu-max 32`) ≈ 35 k, plus stacks and glibc arenas of several hundred pipeline threads. That is within reach of 65 530. Without a cap (192 cores) it is several times over. Consistent with run 2, **not measured**. Whether run 1's SIGBUS comes from the same exhaustion or from failure 4 below is **not established**.
## Weaknesses
1. **Source layers opened in full** although merge needs MPHF + matrix only. Evidence and both `unitigs.bin` maps are dead weight.
2. **All sources opened up front, for the whole partition.** This contradicts the point of partitioning, which is to work on a bounded sub-part of the index. The cost of one partition grows linearly with the number of sources, whatever the partition size.
3. **All destination columns created up front**, the same mismatch on the write side.
4. **Sparse files written through `MmapMut`.** A page whose block cannot be allocated (quota, full FS, BeeGFS) faults with SIGBUS. That cannot be caught and reports nothing.
5. **No bound on live mappings.** `obipipeline::throttle` only bounds open read streams.
6. *(minor)* `obicompactvec::mmap_file::open_mmap_file` validates magic and header length, not file length against `n`.
Side finding: `merge_parallelism.md` documents a `MemoryBudget` semaphore and `--budget-fraction`. `obisys::MemoryBudget` still exists but `merge.rs` no longer uses it (scheduling is `PartitionRunner`). That page is stale on this point.
## Plan
**A. Source-group streaming in pass 2** (`obikmerge`). Process sources in consecutive groups of `G` (G = 2, matching `max_open`). Per group: open its layers, resume each dst matrix (existing layers + new layer), append its `src_n` columns, fill them through the existing pipeline, close, drop. Pass 1 opens no source layer: it builds paths through `KmerLayer::new(..).unitigs_path()` (valid on `Empty`). Live maps per partition become independent of the source count. Column order is unchanged (sources visited in order, columns appended in order), so the on-disk result is identical. Fixes 2, 3, 5.
**C. In-memory column builders** (`obicompactvec`). Under A only `G × src_n × (L_dst+1)` columns are alive. Build them in RAM (bits: n/8 B; counts: n B + overflow map) and write once with `write_all` to the `.building` path, then publish. No sparse file and no `MmapMut` on the merge write path, so `ENOSPC`/quota becomes an `io::Error`. The on-disk format must be byte-identical to the current builders' output. Exposed through `MatrixBuilder`/`ColBuilder` so `obikselect`/`obikfilter` can adopt it later. Fixes 4.
**B. Slots-only layer opening** (`obikindex`, the authority crate). **Deferred to a separate work item** (decision 2026-11-17). Consumers whose kmers are members by construction need MPHF + matrix, never evidence. The same `hash_batch` + `fill_sub_matrix` pattern without `find` appears in three crates: `obikmerge` (`partition_merge.rs:489`), `obikfilter` (`partition_iter.rs:106`), `obikphylo` (`family_scan.rs:289`). `family_scan.rs:402` hashes `variants`; whether those are guaranteed members is unchecked. Fixes 1.
- **Rejected: lazy evidence inside `MphfLayer`.** `find`/`confirm` return `Option<usize>`, so an evidence open error at first use cannot be propagated (panic, or a signature change across the query path). It would also add an "initialised?" branch to the hottest path, and hide in runtime state a distinction that is structural: external query (`find`, needs evidence) vs in-layer iteration (`index`/`index_batch`, no evidence).
- **Rejected: a standalone parallel type** next to `KmerLayer`/`TypedLayer`. It would duplicate count/presence detection and matrix access, and two opening paths would drift.
- **Retained: composition.** A slots layer = `MphfOnly` + matrix, carrying `hash_batch`, `fill_sub_matrix`, `n_cols`. The full layer = slots layer + evidence, keeping `find`/`confirm`. `KmerLayer` exposes both openings (`open()` / e.g. `open_slots()`) over a single count/presence detection. Open point: `MphfLayer::n` currently comes from the evidence (`evidence.len()` / `fingerprint.n()`). A slots layer must take it from the matrix (`n_rows`; `layer_meta.json` for `Implicit`), so the two must be checked to always agree.
Why deferred: after A, B only takes merge from ~8 to ~2 maps per partition, which is negligible. It touches the `obikindex` query path and needs its own session with `query` performance checks.
Order: oracle first (end-to-end merge golden output), then A → C. A alone removes the scaling problem; C removes the SIGBUS class.
## Implementation (2026-11-17)
**A — source-group streaming** (`obikmerge/src/partition_merge/`, split into `mod.rs` + `pass2.rs`). As planned: pass 1 builds paths only; the new-layer matrix is created with its absent columns and closed; pass 2 iterates `sources.chunks(SRC_GROUP = 2)`, resuming each dst matrix, checking `n_cols == n_dst_genomes + col_base` (`InvalidData` otherwise), and appending the group's columns. Prerequisite: `MatrixBuilder::n_cols` (`obicompactvec`).
**C — in-memory columns** (`obicompactvec`). New `mem_builder.rs` (`MemBitVecBuilder`, `MemCompactIntVecBuilder`), `add_mem_col` on both matrix builders and on `MatrixBuilder`, and `ColBuilder::MemBit`/`MemInt`. Format writing is factored rather than duplicated: `format::write_pciv_header`/`write_pciv_tail` (also used by `finalize_pciv`), `mmap_file::write_std_header`/`write_built`. Byte identity with the mmap builders is unit-tested for n ∈ {0, 1, 63, 64, 65, 10 000}, with overwrites and > 2 048 overflow entries. Merge uses `add_mem_col` for source columns; `add_absent_col` is unchanged (never written through its mapping).
Deviations from the plan:
- **No `sync_all` in `close`.** With one forced sync per column file, `merge_partitions` went from 7.4 s to 63.6 s on the benchmark; without it, 7.0 s (measured, macOS). The mmap builders never synced either. The `rename` still prevents publishing a partial file. Caveat: on a write-back network FS an allocation error may only surface at `close(2)`, which `File`'s drop ignores.
- `add_mem_col` returns `ColBuilder`, not `io::Result<ColBuilder>`: it does no I/O.
- The mmap count builder (`PersistentCompactIntVecBuilder`) writes in place, without `.building`; the in-memory one goes through `.building` + `rename`. Same final bytes.
- `obikmerge`'s `matrix_builder_tests` were removed: they only exercised `obicompactvec::MatrixBuilder` and are covered by `obicompactvec/src/tests/{matrix_builder,mem_builder}.rs`. `tempfile` dev-dependency of `obikmerge` removed with them.
**Verification.** Two golden-output oracles, recorded on the unmodified code:
- `scripts/smoke_test_merge.sh`: synthetic, 4 genomes with shared fragments and counts ≥ 255, presence/count/`--dense`; frozen source indexes;
- `scripts/bench_merge_oracle.sh`: 20 real specimen presence indexes, sorted `dump --debug` hash, 85 681 700 k-mers.
Both pass after every step. The existing `global_index_presence` (October binary) gives the same hash.
`merge_partitions` wall time on the benchmark: 7.40 s (ref) → 7.91 s (A) → 7.07 s (A + C) → 8.05 s (after the module split, same code). Single runs; the spread is noise. RSS 243–256 MB throughout. The benchmark is too small to show either the mapping or the memory effect.
**Live mappings per partition (estimate, not measured).** Assumptions: 186 mono-genome sources, 1 layer each, 1 pre-existing dst layer.
| | Source layers | Dst columns | Other | Total |
|---|---|---|---|---|
| Before | 186 × 4 ≈ 744 | 186 × 2 ≈ 372 (`MmapMut`) | ≈ 10 | **≈ 1 100** |
| After A + C | 2 × 4 = 8 | 0 (in RAM) | ≈ 10 | **≈ 20**, independent of the source count |
B would take the 8 down to ~2.
**Follow-up — sparse pack (same day).** `pack_sparse_bit_matrix`/`pack_sparse_compact_int_matrix` used to open the columnar matrix directly, which maps every column file of a layer at once: `n_genomes` maps per partition, since layers are packed one after another. Both now call the dense pack first. It concatenates the column files one at a time without mapping them, so the sparse matrix is built from a single `matrix.pbmx`/`.pcmx` mapping. This deliberately reverses an earlier choice ("never materialise a packed copy just to read it back once"). It costs one extra write and read of the dense matrix: `pack` went from 1.11 s to 1.60 s on the benchmark (single run). As a side effect, a stale `matrix.pbmx` that predates newer columnar data is now re-packed instead of being used as is (`pack_bit_matrix` compares `n_cols`). Both oracles pass.
## Re-merging a merge output (resolved 2026-11-18)
Symptom: `I/O error: No such file or directory` in `merge_partitions` when a merge output was one of the sources. Cause (verified): `finalize_indexed` packs the output matrices (`sparse_meta.json` + dict/PFIV files, or `matrix.pbmx`), so `presence/`/`counts/` no longer holds `meta.json` + `col_*`. `choose_base` picks the largest source as destination, i.e. the merged one; bootstrap copies the packed layout and `MatrixBuilder::resume` → `MatrixMeta::load` finds no `meta.json`.
Fix: a packed index can only be a *source* (pass 2 reads it through `PersistentBitMatrix`/`PersistentIntMatrix::open`, which handle every layout). `choose_base` now filters candidates with `can_be_destination` (`obikmerge/src/merge.rs`): one layer is probed with `detect_storage`; `Columnar` qualifies, `Implicit` only for a single genome (materialized on the fly), `Packed`/`Sparse` never. With a single source there is nothing to append and the filter is skipped. When several sources are given and none qualifies, `run` returns an explicit error before any work. Consequence: the result's column order follows the chosen base first, so it can differ from the command-line order.
Not done: in-place unpack of a packed index to allow it as destination, or a destination-side append on the packed format — the sparse incremental strategy is tracked in `merge_scaling.md`.
Oracle: `scripts/smoke_test_merge.sh` scenario 2 (A B → AB, then AB C D) is compared against the flat merge by genome label (not against the golden dumps, whose layer placement differs), and merging only packed indexes is checked to be refused.
Residual risk, accepted: read-only maps still SIGBUS if a file is truncated by another process during a merge. That is inherent to `mmap`.
+2 -2
View File
@@ -2,7 +2,7 @@
## 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:
```
@@ -58,7 +58,7 @@ Plausible for the largest partition of 108 Salix/Betula sources (~450 Mbp each).
## 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).
Observed on a 9-genome pilot (256 partitions):
+41
View File
@@ -0,0 +1,41 @@
# Merge: scaling to thousands of genomes (open, 2026-11-17)
Open design question raised during the mmap refactor (`merge_mmap_audit.md`). Target: merges of ~6 000 genomes of a few Gb each. Nothing here is implemented or measured. Figures are estimates, labelled as such.
## What scales with what (after the mmap refactor)
| Cost | Depends on | Status |
|---|---|---|
| Live source layers + dst columns per partition (merge pass 2) | `SRC_GROUP × src_n`, not the source count | fixed by plan A |
| Pass-2 column RAM | `SRC_GROUP × src_n × N_part × (1/8 \| 1)` B | bounded, see below |
| Pass-1 de Bruijn graph | ≥ ~19 B per *new* k-mer (`HashMap<u64, AtomicU8>`, verified in `obidebruinj/src/debruijn/graph.rs`) | unchanged |
| Columnar intermediate files | `n_genomes × n_layers × n_partitions` (6 000 × 2 × 256 ≈ 3 M files, estimate) | **does not scale** |
| Sparse `pack` | used to map **all** columns of a layer at once (`ColumnarBitMatrix::open`); layers are packed one after another, so `n_genomes` maps per partition (186 × 192 concurrent ≈ 36 k, estimate) | **fixed 2026-11-17**: now goes columnar → dense `matrix.pbmx` (sequential concatenation, unmapped) → sparse, one mapping per partition |
`N_part`: k-mers of one dst partition over all layers. Pass-2 column RAM stays below pass-1 graph RAM for one-shot merges. It dominates only for **incremental** merges, where few genomes are added to a large index: the new layer is small, the existing layers are large. Example (estimate): `N_total = 1e12`, counts, 192 concurrent partitions → ~1.5 TB. A memory-budgeted concurrency cap is needed there whatever the column strategy. `obisys::MemoryBudget` exists but is no longer used by merge.
## Why a columnar intermediate at all
The sparse format (`bitmatrix/sparse.rs`) is row-major and deduplicated: per slot, either one genome (`singleton.pfiv`) or a `dict_id` (`multi.pfiv`) into a dictionary of distinct genome sets (`dict_offsets` + `dict_values.bin`). Its builder only offers `push_row(genomes)`, i.e. the **complete** genome set of a row, rows in **slot order**.
Merge discovers values **column by column** (source by source), in **random slot order** (MPHF order). The columnar files are a transposition buffer: they absorb random per-column writes, and `pack` transposes them row by row.
## Options to build the final format directly
1. **All sources at once.** That is exactly what plan A removed. No.
2. **Whole matrix in RAM.** `N_part × n_genomes / 8` B per partition: ~3 TB at 6 000 genomes and `N_part = 4e9` (estimate). No.
3. **External sort of `(slot, genome)` pairs.** Volume ∝ non-zeros ≈ Σ genome k-mers (~6 000 × 3e9). That is huge, while the final format is small precisely because genome sets repeat. No.
4. **Incremental sparse update per source group** (most promising). Per group:
- fill the group's columns in RAM (as now);
- stream the partition's existing sparse matrix **sequentially in slot order**;
- for each row: new set = old set ∪ group bits. Through the dictionary this is a transition `(old dict_id, group bit pattern) → new dict_id`, which can be memoised in a table;
- write the new sparse matrix sequentially, then publish.
No columnar files, no `pack`, no per-genome mapping, sequential I/O only. It also removes the re-merge bug: it starts from an existing sparse matrix instead of requiring a columnar one.
The cost is **one full pass over the partition's sparse matrix per group**. With `SRC_GROUP = 2` and 6 000 genomes that is 3 000 rewrites, far too many. Groups must therefore be large (64–256 sources), and group column RAM grows with them: `group × N_part / 8` B, e.g. 32 GB per partition for 64 sources at `N_part = 4e9` (estimate). One parameter trades passes against RAM, and it should be sized from a memory budget. The count matrix (`sparse_intmatrix.rs`) has its own format and needs the same analysis.
## 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 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.
+9 -10
View File
@@ -12,7 +12,7 @@ Investigation of 2026-10-14 (`ptr_hash` 2.1.2, `epserde` 0.13). Question: where
- `index_batch_exact` needs the nightly `unstable` feature; `index_batch_exact2` is `#[doc(hidden)]`. Neither is usable.
- Prefetch is `prefetch-index 0.2.1`: `_mm_prefetch(T0)` on x86_64, asm on aarch64, **no-op elsewhere**.
- **`SINGLE_PART`**: neither `index_stream` nor `index_batch` branches on it — both always run the multi-part `bucket()`/`slot()`. Only `index()` has the faster single-part path. So with batched queries the `SINGLE_PART = true` advantage disappears, and `false` (our choice) costs nothing while keeping parallel construction (`true` also panics with sharding).
- Old `ptr_hash` 1.1.0 (used by `tools/migrate-mphf`) has the same family with an extra `MINIMAL` const: `index_stream<B, MINIMAL, Q>`, `index_batch<K, MINIMAL, Q>`. No new dependency needed there.
- Old `ptr_hash` 1.1.0 has the same family with an extra `MINIMAL` const: `index_stream<B, MINIMAL, Q>`, `index_batch<K, MINIMAL, Q>`. No new dependency needed there.
```rust
// consuming index_stream: fold-based only
@@ -55,7 +55,6 @@ Layer sizes: `layer_0` MPHF 2–3 MB (cache-resident), `layer_1` ~40 MB (beyond
| `obikindexer/counter/count.rs:47` | `mphf.index` then `counts.get/set` | (b), hard (needs (kmer, count) pairs) |
| `obikindexer/extensions/private_builder.rs:177` | abundance filter | (b), conditional |
| `private_builder.rs:196`, `verify.rs`, `IndexCache::find_in_*` | per-kmer by nature / sampled | (c) |
| `tools/migrate-mphf/plan.rs:41-42` | `old.index` + `new.index` per kmer, random writes | (b) |
Dead or suspect code found along the way (candidates for removal, not removed):
@@ -82,7 +81,7 @@ Open one real partition's `layer_1` (~130 M keys) and `layer_0` (~8 M) with `Mph
## 7. Not verified
No measurement at prod scale; prod CPU architecture and cache sizes; evidence mode and `--block-size` used in prod; whether `migrate-mphf` already ran; share of total index/merge/query time spent in these loops; `count.rs` f0 per partition at prod scale; whether `merge_layer/` is dead (only the head of `lib.rs` read).
No measurement at prod scale; prod CPU architecture and cache sizes; evidence mode and `--block-size` used in prod; share of total index/merge/query time spent in these loops; `count.rs` f0 per partition at prod scale; whether `merge_layer/` is dead (only the head of `lib.rs` read).
## 8. First improvement and measurements (2026-10-15)
@@ -107,14 +106,14 @@ About −5 % wall and −5.5 % CPU, ranges non-overlapping **[measured]**. All o
**Noise caveat.** With a load average of 16–22 from unrelated processes, single-run walls of `index`, `merge` and `filter` moved ±10–40 % between identical binaries; only interleaved repeated A/B runs were trustworthy. The `index`/`merge`/`filter`/`convert`/`phylo` rows of the first comparison are noise, not effects (`index` pass 2 was not changed at all; a later interleaved `filter` A/B was inconclusive, 13.0 s vs 13.8 s medians with a 10–20 s spread).
**Stale benchmark indexes.** The indexes already under `benchmark/run/` (`specimen_index_*`, `global_index_*`, built 2026-08-28) carry `ptr_hash` 1.x MPHFs and fail with "Major version mismatch" on current binaries (`tools/migrate-mphf` converts them). `bench_mphf.sh` therefore builds its own copies under `run/bench_mphf/data/` on first use.
**Stale benchmark indexes.** The indexes already under `benchmark/run/` (`specimen_index_*`, `global_index_*`, built 2026-08-28) carry `ptr_hash` 1.x MPHFs and fail with "Major version mismatch" on current binaries. `bench_mphf.sh` therefore builds its own copies under `run/bench_mphf/data/` on first use.
## 9. Benchmark procedure
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>`.
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.
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/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`.
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`).
@@ -180,7 +179,7 @@ Total ≈ 354 M distinct kmers for one skim. `-p 4` is already in the 30–45 MB
## 13. Query on a real-scale index (2026-10-15)
**Index.** Working index `phyloskims_sal_vac_sav` (91 genomes of Salix/Vaccinium, 256 partitions × 2 layers, exact evidence, 180 GB, ptr_hash 1.x MPHFs). Converted with `tools/migrate-mphf` **on an APFS clone** (`cp -c`, 0.8 s, no space used until written; the tool works in place and sets the annexes aside, so the original was left untouched — verified by mtime): 512 layers in 10 min (1311 % CPU), ≈ 57 GB of new data. Clone at `/Users/coissac/travail/obiskim/data/phyloalps/bench_mphf/phyloskims_sal_vac_sav_v2`; its sibling annex is in `stale_annexes_pre_ptrhash2/` and would need rebuilding to be used. Per partition: `layer_1` ≈ 31 M keys / 9.3 MB MPHF, `layer_0` ≈ 5.6 M keys / 1.7 MB — larger than the 20-genome set (100 KB) but 4× smaller than the production layers (~130 M keys, ~40 MB).
**Index.** Working index `phyloskims_sal_vac_sav` (91 genomes of Salix/Vaccinium, 256 partitions × 2 layers, exact evidence, 180 GB, ptr_hash 1.x MPHFs). Converted to ptr_hash 2 **on an APFS clone** (`cp -c`, 0.8 s, no space used until written; the original was left untouched — verified by mtime): 512 layers in 10 min (1311 % CPU), ≈ 57 GB of new data. Clone at `/Users/coissac/travail/obiskim/data/phyloalps/bench_mphf/phyloskims_sal_vac_sav_v2`; its sibling annex is in `stale_annexes_pre_ptrhash2/` and would need rebuilding to be used. Per partition: `layer_1` ≈ 31 M keys / 9.3 MB MPHF, `layer_0` ≈ 5.6 M keys / 1.7 MB — larger than the 20-genome set (100 KB) but 4× smaller than the production layers (~130 M keys, ~40 MB).
**Query** (2 × 48 MB of *V. oxycoccos* reads, `--chunk-size 8`, AC power, 3 interleaved runs per binary, identical sorted output for all three):
@@ -215,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.
**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.
@@ -227,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)
`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).
@@ -366,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.
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
View File
@@ -509,6 +509,7 @@ Provided finalisations:
| `hellinger_dist_matrix()` | `√partial_hellinger[i,j] / √2` |
| `hellinger_euclidean_dist_matrix()` | `√partial_hellinger[i,j]` |
| `threshold_mash_dist_matrix(k, t)` | Mash distance, derived from `threshold_jaccard_dist_matrix(t)` — no separate partial |
| `threshold_hamming_dist_matrix(t)` | `union[i,j] − inter[i,j]` (k-mers present in exactly one genome) — no separate partial |
### BitPartials
+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
@@ -232,7 +232,7 @@ needed — `obikindex → obikpartitionner` stays the same direction as before.
conversation as a side effect of investigating the false "independent
lifecycle" claim.
- `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()`.
- A real bug caught by the test suite during this move:
`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.
`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
(file→pages→superkmers), throttling, per-file logging. What changed:
- 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
end-to-end (`obikphylo`'s test harness and `obikpartitionner`'s own
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
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
@@ -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
against real FASTA data (scatter → dereplicate → count → index-build →
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.
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
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
`pipeline_counts` test helper) all updated to `Counter::new(&idx).
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
beyond construction — see [[project_unitigs_always_kept]]),
`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).
### 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
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 —
it never could have, once privacy was real rather than aspirational. Each
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
they're no longer inherent — `merge.rs`, `select.rs`, `rebuild.rs`,
`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
site is unchanged (`KmerIndex::create_skeleton(...)`,
`self.state()`) — only trait-in-scope requirements are new, which is
@@ -1210,7 +1210,7 @@ itself.
Verification went one step further than (9): beyond
`cargo check --workspace --all-targets` + `cargo test --workspace` +
`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
`scripts/smoke_test_index.sh` itself never touches) — exit 0, `pack`
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
`self.meta().genomes.len()`-shaped reads, mechanically fixed to
`.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(...)`
instead of `meta_mut()`), `filter`/`pack`/`dump`/`unitig`/`merge`/`select`/
`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
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()`
on these algorithms, so the trait has to be reachable from outside
`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
separated `obikindex` (data model) from `obikindexer` (algorithms
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.
**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
scope); `obikindexer::algorithms::partitionner::tests` and `obikphylo::
siblings::tests` (both had direct `.run(None::<fn(Progress)>)`-shaped
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).
**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` |
| `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
with no cache at all. `obikphylo` built a cache first only because
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>>`.
4. Migrate `obikindex::query_layer::QueryLayer`/`query_partition_with` to
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).
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
- `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
`Mat::open` already reads the result back in the sibling-annex path.
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:
- **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.
- **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].
- **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 `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:
+7 -7
View File
@@ -22,7 +22,7 @@ are preserved unchanged; only the data matrices are rewritten.
## Synopsis
```sh
obikmer select <input-index>
obiskim select <input-index>
--output <dir>
[--group <name>:<pred> ...]
[--group-op <name>:<op> ...]
@@ -165,14 +165,14 @@ is > N.
### Aggregate by metadata group, default operators
```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
```
### Named groups with different operators
```sh
obikmer select myindex --output out \
obiskim select myindex --output out \
--group "pub:species=Betula_pubescens" \
--group "nan:species=Betula_nana" \
--group-op "pub:any" \
@@ -183,7 +183,7 @@ obikmer select myindex --output out \
### Mix aggregated group and individual genome
```sh
obikmer select myindex --output out \
obiskim select myindex --output out \
--group "A:group=A" \
--select "A,Betula_nana--IGA-24-39"
```
@@ -191,7 +191,7 @@ obikmer select myindex --output out \
### Pure column projection (no aggregation)
```sh
obikmer select myindex --output out \
obiskim select myindex --output out \
--select "Betula_nana--TROM-V-149986,Betula_nana--AG-P04-25-01"
```
@@ -199,11 +199,11 @@ obikmer select myindex --output out \
```sh
# Step 1: keep only B. nana-specific k-mers
obikmer filter myindex --output filtered \
obiskim filter myindex --output filtered \
--ingroup "species=Betula_nana" --outgroup "*"
# Step 2: aggregate genome columns by collection site
obikmer select filtered --output final --aggregate-by site
obiskim select filtered --output final --aggregate-by site
```
---
+4 -4
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
@@ -13,11 +13,11 @@
| `query` | Query an index with sequences and annotate matches |
| `dump` | Dump all indexed k-mers as CSV (kmer + per-genome counts or presence); supports the shared [kmer filtering](implementation/filtering.md) system; `--head N` limits output to the first N k-mers |
| `annotate` | Add or update genome metadata from a CSV file; or dump metadata as CSV |
| `phylo` | Compute pairwise evolutionary-distance proxies between genomes (`--metric jaccard\|mash\|hamming\|bray-curtis\|relfreq-bray-curtis\|euclidean\|relfreq-euclidean\|hellinger\|hellinger-euclidean`); optionally build NJ/UPGMA trees; `--presence-threshold N` sets the minimum count to consider a k-mer present when computing Jaccard/Mash on count indexes (default 1); optionally a central-position SNP/Sankoff calibration with exports for TNT/PhyG/IQ-TREE (see [evolutionary distances](theory/evolutionary_distances.md)) |
| `phylo` | Genome-vs-genome distances, trees and SNP-based pseudo-alignments. `--distance` selects either a whole-genome distance computed from k-mer content (`jaccard`, `mash`, `hamming`, `bray-curtis`, `relfreq-bray-curtis`, `euclidean`, `relfreq-euclidean`, `hellinger`, `hellinger-euclidean`; `--presence-threshold N` converts counts to presence for Jaccard/Mash/Hamming on count indexes) or a `snp-*` distance (`snp-raw`, `snp-jc`, `snp-k2p`, `snp-k81`, `snp-f81`, `snp-t92`, `snp-tn93`, `snp-tv`; optional `--gamma-shape`) computed from central-position SNPs of k-mer families. `--nj`/`--upgma` build trees (Jaccard if no `--distance`); `--shared-kmers` writes the shared-k-mer count matrix on its own. SNP analyses read the sibling annex, built on demand (`--sibling-annex` forces it), with site selection/sampling options (`--n-sites`, `--quartet`, `--pair-balance`, `--entropy`, `--free-loss`, `--no-ambiguity`/`--only-diploid`, `--session`), a pseudo-alignment export (`--pseudo-alignment`, `--fasta`, `--vcf`) and Sankoff cost calibration with TNT/PhyG/IQ-TREE exports. See [evolutionary distances](theory/evolutionary_distances.md) |
| `unitig` | Build a global de Bruijn graph across all partitions and enumerate its unitigs as FASTA; supports the shared [kmer filtering](implementation/filtering.md) system |
| `select` | Project and/or aggregate genome columns into a new or in-place index; the column-axis counterpart of `filter` (see [select](implementation/select.md)) |
| `estimate` | Estimate approximate-index parameters (z, evidence bits, FP rates) before indexing |
| `reindex` | Convert an index's evidence in-place: exact ↔ approx |
| `convert` | Convert an index's evidence representation (exact / approximate / hybrid), in place |
| `utils` | Miscellaneous index utilities: `--new-label NEW=OLD` renames a genome label; `--upgrade-index` adds missing `layer_meta.json` to old indexes |
| `pack` | Pack per-column matrix files into single-file format to reduce query I/O |
+2 -2
View File
@@ -3,8 +3,8 @@
## Code couvert
- `obikmer/src/main.rs` — point d'entrée CLI, contraintes globales
- `obikmer/src/cli.rs` — structure des arguments communs
- `obiskim/src/main.rs` — point d'entrée CLI, contraintes globales
- `obiskim/src/cli.rs` — structure des arguments communs
## Notes
+6 -6
View File
@@ -4,7 +4,7 @@
### 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
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
@@ -13,7 +13,7 @@ rustup update stable
### 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)
@@ -47,11 +47,11 @@ brew install automake libtool autoconf pkg-config
```bash
git clone <repository-url>
cd obikmer/src
cd obiskim/src
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)
@@ -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:
```bash
cp /scratch/$USER/cargo-target/release/obikmer ~/bin/
cp /scratch/$USER/cargo-target/release/obiskim ~/bin/
```
## NUMA support
@@ -80,5 +80,5 @@ NUMA-aware thread placement is active automatically on multi-socket Linux machin
## Verifying the installation
```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.
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
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
fed to `raxml-ng`. Two problems surfaced, both traced back to conflating
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
`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
`family_size() >= 2`). A small external Python script decodes IUPAC back to
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
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
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
@@ -630,7 +630,7 @@ it, no external script needed. `∅` is an ordinary 16th state throughout
(never `-`), specifically to avoid gap-semantics confusion in downstream
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
the wider IUPAC set otherwise), scales and rounds costs to integers
(`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
own frequency line unconditionally; omitting it and passing `+F` instead
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
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
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
`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).
**Resolution: subset + compact-renumber, not rely on all 16 appearing.**
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
16th (or any particular) state happens to occur:
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)
`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
`<prefix>_iqtree.model` (lower-triangular `R`, PAML order, then `π`) and
`<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
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
`RawSnpDistanceOutput` after `raw_snp_distance` runs (a pair with zero
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 —
matches the manual `+ASC` failures hit earlier in this same investigation,
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
now constant. Verified: 908,723 → 792,372 sites after excluding 2 taxa,
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,
evaluated once. Partition index is then
`(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.
### 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
calls — the same lazy-derived-cache pattern `PersistentBitMatrix` already
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
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
@@ -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,
mmap and reuse.
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
invalidate. `select --in-place` (`select_layer.rs:139-235`) mutates
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
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
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).
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.
2. `SnpTally` + finalisation math with a brute-force (non-swept) reference
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)
`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
default ordinary, costed 16th state — the resolution of the discussion
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
shared variable families (columns where neither genome is `∅`), diagonal
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
pattern exactly: Candidozyma shares **0** families with all 19 others (hence
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 <
(int)seq_names.size()' failed` in `Alignment::getSeqName` /
`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
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
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
`free_loss && b == b'-'` *before* recoding/counting, so the absent state
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
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
`compact_alphabet` call (post ascertainment-filtering), any state with
`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`
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
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
summary of rate heterogeneity than `α` alone whenever `θ` isn't negligible
— `α` 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
get α — again no closed form, numerical optimization. This is a real
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
own answer to this chicken-and-egg problem is an iterative
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`/
`--iqtree` (via `SiblingExt::sankoff_bundle`) and a `snp-*` `--distance`
(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
no way to give them different values in one run, see `cmd/phylo/args.rs`).
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
index) that persists the `snp-*` `--distance` sample — the
`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
(`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
(`--fasta`/`--vcf` choose the formats, FASTA is the default, both can be
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
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
@@ -2920,7 +2920,7 @@ Checked with `bcftools view`/`stats` and `tabix`: no warning, the sites with
majority base (alphabetical on ties).
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
whether several forms mean heterozygosity or paralogues. Compromise chosen:
`--no-ambiguity` => haploid (ambiguous cells are already `?`); otherwise
+1 -1
View File
@@ -9,4 +9,4 @@
## Notes
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`).
+3 -1
View File
@@ -226,7 +226,9 @@ Design decision (user): the way genomes are counted depends on `--no-ambiguity`,
## Implemented: `--quartet` (2026-10-13)
`--quartet` keeps only the families with at least two called states each carried by at least two genomes (`masking::is_quartet_informative` for the raw masks, `survives_quartet` for the exact check on masked states and `--exclude-genome`). Absence never counts as a state; with `--no-ambiguity`, multi-member genomes are left out of the count. The persisted annex is a plain `PersistentBitVec` (one bit per non-monomorphic family, compact ordinal) — no ad hoc format; the `--no-ambiguity` convention is carried by the file name (`quartet.pbiv`, `quartet.noamb.pbiv`) because that header has no room for a flag. It is a safe pre-filter: excluding genomes can only destroy a bipartition, never create one.
`--quartet` keeps only the families with at least two called states each carried by at least two genomes (`masking::is_quartet_informative` for the raw masks, `survives_quartet` for the exact check on masked states and `--exclude-genome`). Genomes are read through `masked_state`, exactly as in the alignment: absence is a state of its own unless `--free-loss` (then it is missing and counts for nothing), and with `--no-ambiguity` multi-member genomes are left out of the count. The persisted annex is a plain `PersistentBitVec` (one bit per non-monomorphic family, compact ordinal) — no ad hoc format; its counting convention (`QuartetConvention`: ambiguity policy × `--free-loss`) is carried by the file name (`quartet.pbiv`, `quartet.noamb.pbiv`, `quartet.diploid.pbiv` for `--free-loss`; `quartet.abs.*.pbiv` for absence-as-a-state) because that header has no room for a flag.
*Correction (2026-11-19).* The first version never counted absence, whatever `--free-loss` said, which contradicted the alignment: without `--free-loss` a genome lacking the family has the state `∅`, so `A A ∅ ∅` separates two pairs yet was rejected. Fixed in `has_bipartition` (index 0 is now counted, and is only ever populated when absence is a state), in the annex (one file per `QuartetConvention`) and in `--sample-stats` (informative sites follow the same rule). The old file names keep the `--free-loss` semantics, which is exactly the old rule, so annexes already built with `--free-loss` stay valid; the sampling measured below used `--free-loss` and is unaffected. It is a safe pre-filter: excluding genomes can only destroy a bipartition, never create one.
Plumbing: `AnnexRequest` (which annexes, per convention) and `ensure_layer_family_annexes` (one shared scan for entropy, quartet and overlap) replace the entropy-only builder; the sampling parameters travel as one `SamplingSpec { free_loss, no_ambiguity, quartet, entropy_bias }` instead of a growing positional list.
@@ -51,7 +51,7 @@ Structural tension: path coherence (long unitigs) needs a key shared by consecut
## 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).
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$.
+550
View File
@@ -0,0 +1,550 @@
CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL
Version 2.1 du 2013-06-21
Avertissement
Ce contrat est une licence de logiciel libre issue d'une concertation
entre ses auteurs afin que le respect de deux grands principes préside à
sa rédaction:
* d'une part, le respect des principes de diffusion des logiciels
libres: accès au code source, droits étendus conférés aux utilisateurs,
* d'autre part, la désignation d'un droit applicable, le droit
français, auquel elle est conforme, tant au regard du droit de la
responsabilité civile que du droit de la propriété intellectuelle et
de la protection qu'il offre aux auteurs et titulaires des droits
patrimoniaux sur un logiciel.
Les auteurs de la licence CeCILL (Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre])
sont:
Commissariat à l'énergie atomique et aux énergies alternatives - CEA,
établissement public de recherche à caractère scientifique, technique et
industriel, dont le siège est situé 25 rue Leblanc, immeuble Le Ponant
D, 75015 Paris.
Centre National de la Recherche Scientifique - CNRS, établissement
public à caractère scientifique et technologique, dont le siège est
situé 3 rue Michel-Ange, 75794 Paris cedex 16.
Institut National de Recherche en Informatique et en Automatique -
Inria, établissement public à caractère scientifique et technologique,
dont le siège est situé Domaine de Voluceau, Rocquencourt, BP 105, 78153
Le Chesnay cedex.
Préambule
Ce contrat est une licence de logiciel libre dont l'objectif est de
conférer aux utilisateurs la liberté de modification et de
redistribution du logiciel régi par cette licence dans le cadre d'un
modèle de diffusion en logiciel libre.
L'exercice de ces libertés est assorti de certains devoirs à la charge
des utilisateurs afin de préserver ce statut au cours des
redistributions ultérieures.
L'accessibilité au code source et les droits de copie, de modification
et de redistribution qui en découlent ont pour contrepartie de n'offrir
aux utilisateurs qu'une garantie limitée et de ne faire peser sur
l'auteur du logiciel, le titulaire des droits patrimoniaux et les
concédants successifs qu'une responsabilité restreinte.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs ou des
professionnels avertis possédant des connaissances informatiques
approfondies. Les utilisateurs sont donc invités à charger et tester
l'adéquation du logiciel à leurs besoins dans des conditions permettant
d'assurer la sécurité de leurs systèmes et/ou de leurs données et, plus
généralement, à l'utiliser et l'exploiter dans les mêmes conditions de
sécurité. Ce contrat peut être reproduit et diffusé librement, sous
réserve de le conserver en l'état, sans ajout ni suppression de clauses.
Ce contrat est susceptible de s'appliquer à tout logiciel dont le
titulaire des droits patrimoniaux décide de soumettre l'exploitation aux
dispositions qu'il contient.
Une liste de questions fréquemment posées se trouve sur le site web
officiel de la famille des licences CeCILL
(http://www.cecill.info/index.fr.html) pour toute clarification qui
serait nécessaire.
Article 1 - DEFINITIONS
Dans ce contrat, les termes suivants, lorsqu'ils seront écrits avec une
lettre capitale, auront la signification suivante:
Contrat: désigne le présent contrat de licence, ses éventuelles versions
postérieures et annexes.
Logiciel: désigne le logiciel sous sa forme de Code Objet et/ou de Code
Source et le cas échéant sa documentation, dans leur état au moment de
l'acceptation du Contrat par le Licencié.
Logiciel Initial: désigne le Logiciel sous sa forme de Code Source et
éventuellement de Code Objet et le cas échéant sa documentation, dans
leur état au moment de leur première diffusion sous les termes du Contrat.
Logiciel Modifié: désigne le Logiciel modifié par au moins une
Contribution.
Code Source: désigne l'ensemble des instructions et des lignes de
programme du Logiciel et auquel l'accès est nécessaire en vue de
modifier le Logiciel.
Code Objet: désigne les fichiers binaires issus de la compilation du
Code Source.
Titulaire: désigne le ou les détenteurs des droits patrimoniaux d'auteur
sur le Logiciel Initial.
Licencié: désigne le ou les utilisateurs du Logiciel ayant accepté le
Contrat.
Contributeur: désigne le Licencié auteur d'au moins une Contribution.
Concédant: désigne le Titulaire ou toute personne physique ou morale
distribuant le Logiciel sous le Contrat.
Contribution: désigne l'ensemble des modifications, corrections,
traductions, adaptations et/ou nouvelles fonctionnalités intégrées dans
le Logiciel par tout Contributeur, ainsi que tout Module Interne.
Module: désigne un ensemble de fichiers sources y compris leur
documentation qui permet de réaliser des fonctionnalités ou services
supplémentaires à ceux fournis par le Logiciel.
Module Externe: désigne tout Module, non dérivé du Logiciel, tel que ce
Module et le Logiciel s'exécutent dans des espaces d'adressage
différents, l'un appelant l'autre au moment de leur exécution.
Module Interne: désigne tout Module lié au Logiciel de telle sorte
qu'ils s'exécutent dans le même espace d'adressage.
GNU GPL: désigne la GNU General Public License dans sa version 2 ou
toute version ultérieure, telle que publiée par Free Software Foundation
Inc.
GNU Affero GPL: désigne la GNU Affero General Public License dans sa
version 3 ou toute version ultérieure, telle que publiée par Free
Software Foundation Inc.
EUPL: désigne la Licence Publique de l'Union européenne dans sa version
1.1 ou toute version ultérieure, telle que publiée par la Commission
Européenne.
Parties: désigne collectivement le Licencié et le Concédant.
Ces termes s'entendent au singulier comme au pluriel.
Article 2 - OBJET
Le Contrat a pour objet la concession par le Concédant au Licencié d'une
licence non exclusive, cessible et mondiale du Logiciel telle que
définie ci-après à l'article 5 <#etendue> pour toute la durée de
protection des droits portant sur ce Logiciel.
Article 3 - ACCEPTATION
3.1 L'acceptation par le Licencié des termes du Contrat est réputée
acquise du fait du premier des faits suivants:
* (i) le chargement du Logiciel par tout moyen notamment par
téléchargement à partir d'un serveur distant ou par chargement à
partir d'un support physique;
* (ii) le premier exercice par le Licencié de l'un quelconque des
droits concédés par le Contrat.
3.2 Un exemplaire du Contrat, contenant notamment un avertissement
relatif aux spécificités du Logiciel, à la restriction de garantie et à
la limitation à un usage par des utilisateurs expérimentés a été mis à
disposition du Licencié préalablement à son acceptation telle que
définie à l'article 3.1 <#acceptation-acquise> ci dessus et le Licencié
reconnaît en avoir pris connaissance.
Article 4 - ENTREE EN VIGUEUR ET DUREE
4.1 ENTREE EN VIGUEUR
Le Contrat entre en vigueur à la date de son acceptation par le Licencié
telle que définie en 3.1 <#acceptation-acquise>.
4.2 DUREE
Le Contrat produira ses effets pendant toute la durée légale de
protection des droits patrimoniaux portant sur le Logiciel.
Article 5 - ETENDUE DES DROITS CONCEDES
Le Concédant concède au Licencié, qui accepte, les droits suivants sur
le Logiciel pour toutes destinations et pour la durée du Contrat dans
les conditions ci-après détaillées.
Par ailleurs, si le Concédant détient ou venait à détenir un ou
plusieurs brevets d'invention protégeant tout ou partie des
fonctionnalités du Logiciel ou de ses composants, il s'engage à ne pas
opposer les éventuels droits conférés par ces brevets aux Licenciés
successifs qui utiliseraient, exploiteraient ou modifieraient le
Logiciel. En cas de cession de ces brevets, le Concédant s'engage à
faire reprendre les obligations du présent alinéa aux cessionnaires.
5.1 DROIT D'UTILISATION
Le Licencié est autorisé à utiliser le Logiciel, sans restriction quant
aux domaines d'application, étant ci-après précisé que cela comporte:
1.
la reproduction permanente ou provisoire du Logiciel en tout ou
partie par tout moyen et sous toute forme.
2.
le chargement, l'affichage, l'exécution, ou le stockage du Logiciel
sur tout support.
3.
la possibilité d'en observer, d'en étudier, ou d'en tester le
fonctionnement afin de déterminer les idées et principes qui sont à
la base de n'importe quel élément de ce Logiciel; et ceci, lorsque
le Licencié effectue toute opération de chargement, d'affichage,
d'exécution, de transmission ou de stockage du Logiciel qu'il est en
droit d'effectuer en vertu du Contrat.
5.2 DROIT D'APPORTER DES CONTRIBUTIONS
Le droit d'apporter des Contributions comporte le droit de traduire,
d'adapter, d'arranger ou d'apporter toute autre modification au Logiciel
et le droit de reproduire le logiciel en résultant.
Le Licencié est autorisé à apporter toute Contribution au Logiciel sous
réserve de mentionner, de façon explicite, son nom en tant qu'auteur de
cette Contribution et la date de création de celle-ci.
5.3 DROIT DE DISTRIBUTION
Le droit de distribution comporte notamment le droit de diffuser, de
transmettre et de communiquer le Logiciel au public sur tout support et
par tout moyen ainsi que le droit de mettre sur le marché à titre
onéreux ou gratuit, un ou des exemplaires du Logiciel par tout procédé.
Le Licencié est autorisé à distribuer des copies du Logiciel, modifié ou
non, à des tiers dans les conditions ci-après détaillées.
5.3.1 DISTRIBUTION DU LOGICIEL SANS MODIFICATION
Le Licencié est autorisé à distribuer des copies conformes du Logiciel,
sous forme de Code Source ou de Code Objet, à condition que cette
distribution respecte les dispositions du Contrat dans leur totalité et
soit accompagnée:
1.
d'un exemplaire du Contrat,
2.
d'un avertissement relatif à la restriction de garantie et de
responsabilité du Concédant telle que prévue aux articles 8
<#responsabilite> et 9 <#garantie>,
et que, dans le cas où seul le Code Objet du Logiciel est redistribué,
le Licencié permette un accès effectif au Code Source complet du
Logiciel pour une durée d'au moins 3 ans à compter de la distribution du
logiciel, étant entendu que le coût additionnel d'acquisition du Code
Source ne devra pas excéder le simple coût de transfert des données.
5.3.2 DISTRIBUTION DU LOGICIEL MODIFIE
Lorsque le Licencié apporte une Contribution au Logiciel, les conditions
de distribution du Logiciel Modifié en résultant sont alors soumises à
l'intégralité des dispositions du Contrat.
Le Licencié est autorisé à distribuer le Logiciel Modifié, sous forme de
code source ou de code objet, à condition que cette distribution
respecte les dispositions du Contrat dans leur totalité et soit
accompagnée:
1.
d'un exemplaire du Contrat,
2.
d'un avertissement relatif à la restriction de garantie et de
responsabilité du Concédant telle que prévue aux articles 8
<#responsabilite> et 9 <#garantie>,
et, dans le cas où seul le code objet du Logiciel Modifié est redistribué,
3.
d'une note précisant les conditions d'accès effectif au code source
complet du Logiciel Modifié, pendant une période d'au moins 3 ans à
compter de la distribution du Logiciel Modifié, étant entendu que le
coût additionnel d'acquisition du code source ne devra pas excéder
le simple coût de transfert des données.
5.3.3 DISTRIBUTION DES MODULES EXTERNES
Lorsque le Licencié a développé un Module Externe les conditions du
Contrat ne s'appliquent pas à ce Module Externe, qui peut être distribué
sous un contrat de licence différent.
5.3.4 COMPATIBILITE AVEC D'AUTRES LICENCES
Le Licencié peut inclure un code soumis aux dispositions d'une des
versions de la licence GNU GPL, GNU Affero GPL et/ou EUPL dans le
Logiciel modifié ou non et distribuer l'ensemble sous les conditions de
la même version de la licence GNU GPL, GNU Affero GPL et/ou EUPL.
Le Licencié peut inclure le Logiciel modifié ou non dans un code soumis
aux dispositions d'une des versions de la licence GNU GPL, GNU Affero
GPL et/ou EUPL et distribuer l'ensemble sous les conditions de la même
version de la licence GNU GPL, GNU Affero GPL et/ou EUPL.
Article 6 - PROPRIETE INTELLECTUELLE
6.1 SUR LE LOGICIEL INITIAL
Le Titulaire est détenteur des droits patrimoniaux sur le Logiciel
Initial. Toute utilisation du Logiciel Initial est soumise au respect
des conditions dans lesquelles le Titulaire a choisi de diffuser son
oeuvre et nul autre n'a la faculté de modifier les conditions de
diffusion de ce Logiciel Initial.
Le Titulaire s'engage à ce que le Logiciel Initial reste au moins régi
par le Contrat et ce, pour la durée visée à l'article 4.2 <#duree>.
6.2 SUR LES CONTRIBUTIONS
Le Licencié qui a développé une Contribution est titulaire sur celle-ci
des droits de propriété intellectuelle dans les conditions définies par
la législation applicable.
6.3 SUR LES MODULES EXTERNES
Le Licencié qui a développé un Module Externe est titulaire sur celui-ci
des droits de propriété intellectuelle dans les conditions définies par
la législation applicable et reste libre du choix du contrat régissant
sa diffusion.
6.4 DISPOSITIONS COMMUNES
Le Licencié s'engage expressément:
1.
à ne pas supprimer ou modifier de quelque manière que ce soit les
mentions de propriété intellectuelle apposées sur le Logiciel;
2.
à reproduire à l'identique lesdites mentions de propriété
intellectuelle sur les copies du Logiciel modifié ou non.
Le Licencié s'engage à ne pas porter atteinte, directement ou
indirectement, aux droits de propriété intellectuelle du Titulaire et/ou
des Contributeurs sur le Logiciel et à prendre, le cas échéant, à
l'égard de son personnel toutes les mesures nécessaires pour assurer le
respect des dits droits de propriété intellectuelle du Titulaire et/ou
des Contributeurs.
Article 7 - SERVICES ASSOCIES
7.1 Le Contrat n'oblige en aucun cas le Concédant à la réalisation de
prestations d'assistance technique ou de maintenance du Logiciel.
Cependant le Concédant reste libre de proposer ce type de services. Les
termes et conditions d'une telle assistance technique et/ou d'une telle
maintenance seront alors déterminés dans un acte séparé. Ces actes de
maintenance et/ou assistance technique n'engageront que la seule
responsabilité du Concédant qui les propose.
7.2 De même, tout Concédant est libre de proposer, sous sa seule
responsabilité, à ses licenciés une garantie, qui n'engagera que lui,
lors de la redistribution du Logiciel et/ou du Logiciel Modifié et ce,
dans les conditions qu'il souhaite. Cette garantie et les modalités
financières de son application feront l'objet d'un acte séparé entre le
Concédant et le Licencié.
Article 8 - RESPONSABILITE
8.1 Sous réserve des dispositions de l'article 8.2
<#limite-responsabilite>, le Licencié a la faculté, sous réserve de
prouver la faute du Concédant concerné, de solliciter la réparation du
préjudice direct qu'il subirait du fait du Logiciel et dont il apportera
la preuve.
8.2 La responsabilité du Concédant est limitée aux engagements pris en
application du Contrat et ne saurait être engagée en raison notamment:
(i) des dommages dus à l'inexécution, totale ou partielle, de ses
obligations par le Licencié, (ii) des dommages directs ou indirects
découlant de l'utilisation ou des performances du Logiciel subis par le
Licencié et (iii) plus généralement d'un quelconque dommage indirect. En
particulier, les Parties conviennent expressément que tout préjudice
financier ou commercial (par exemple perte de données, perte de
bénéfices, perte d'exploitation, perte de clientèle ou de commandes,
manque à gagner, trouble commercial quelconque) ou toute action dirigée
contre le Licencié par un tiers, constitue un dommage indirect et
n'ouvre pas droit à réparation par le Concédant.
Article 9 - GARANTIE
9.1 Le Licencié reconnaît que l'état actuel des connaissances
scientifiques et techniques au moment de la mise en circulation du
Logiciel ne permet pas d'en tester et d'en vérifier toutes les
utilisations ni de détecter l'existence d'éventuels défauts. L'attention
du Licencié a été attirée sur ce point sur les risques associés au
chargement, à l'utilisation, la modification et/ou au développement et à
la reproduction du Logiciel qui sont réservés à des utilisateurs avertis.
Il relève de la responsabilité du Licencié de contrôler, par tous
moyens, l'adéquation du produit à ses besoins, son bon fonctionnement et
de s'assurer qu'il ne causera pas de dommages aux personnes et aux biens.
9.2 Le Concédant déclare de bonne foi être en droit de concéder
l'ensemble des droits attachés au Logiciel (comprenant notamment les
droits visés à l'article 5 <#etendue>).
9.3 Le Licencié reconnaît que le Logiciel est fourni "en l'état" par le
Concédant sans autre garantie, expresse ou tacite, que celle prévue à
l'article 9.2 <#bonne-foi> et notamment sans aucune garantie sur sa
valeur commerciale, son caractère sécurisé, innovant ou pertinent.
En particulier, le Concédant ne garantit pas que le Logiciel est exempt
d'erreur, qu'il fonctionnera sans interruption, qu'il sera compatible
avec l'équipement du Licencié et sa configuration logicielle ni qu'il
remplira les besoins du Licencié.
9.4 Le Concédant ne garantit pas, de manière expresse ou tacite, que le
Logiciel ne porte pas atteinte à un quelconque droit de propriété
intellectuelle d'un tiers portant sur un brevet, un logiciel ou sur tout
autre droit de propriété. Ainsi, le Concédant exclut toute garantie au
profit du Licencié contre les actions en contrefaçon qui pourraient être
diligentées au titre de l'utilisation, de la modification, et de la
redistribution du Logiciel. Néanmoins, si de telles actions sont
exercées contre le Licencié, le Concédant lui apportera son expertise
technique et juridique pour sa défense. Cette expertise technique et
juridique est déterminée au cas par cas entre le Concédant concerné et
le Licencié dans le cadre d'un protocole d'accord. Le Concédant dégage
toute responsabilité quant à l'utilisation de la dénomination du
Logiciel par le Licencié. Aucune garantie n'est apportée quant à
l'existence de droits antérieurs sur le nom du Logiciel et sur
l'existence d'une marque.
Article 10 - RESILIATION
10.1 En cas de manquement par le Licencié aux obligations mises à sa
charge par le Contrat, le Concédant pourra résilier de plein droit le
Contrat trente (30) jours après notification adressée au Licencié et
restée sans effet.
10.2 Le Licencié dont le Contrat est résilié n'est plus autorisé à
utiliser, modifier ou distribuer le Logiciel. Cependant, toutes les
licences qu'il aura concédées antérieurement à la résiliation du Contrat
resteront valides sous réserve qu'elles aient été effectuées en
conformité avec le Contrat.
Article 11 - DISPOSITIONS DIVERSES
11.1 CAUSE EXTERIEURE
Aucune des Parties ne sera responsable d'un retard ou d'une défaillance
d'exécution du Contrat qui serait dû à un cas de force majeure, un cas
fortuit ou une cause extérieure, telle que, notamment, le mauvais
fonctionnement ou les interruptions du réseau électrique ou de
télécommunication, la paralysie du réseau liée à une attaque
informatique, l'intervention des autorités gouvernementales, les
catastrophes naturelles, les dégâts des eaux, les tremblements de terre,
le feu, les explosions, les grèves et les conflits sociaux, l'état de
guerre...
11.2 Le fait, par l'une ou l'autre des Parties, d'omettre en une ou
plusieurs occasions de se prévaloir d'une ou plusieurs dispositions du
Contrat, ne pourra en aucun cas impliquer renonciation par la Partie
intéressée à s'en prévaloir ultérieurement.
11.3 Le Contrat annule et remplace toute convention antérieure, écrite
ou orale, entre les Parties sur le même objet et constitue l'accord
entier entre les Parties sur cet objet. Aucune addition ou modification
aux termes du Contrat n'aura d'effet à l'égard des Parties à moins
d'être faite par écrit et signée par leurs représentants dûment habilités.
11.4 Dans l'hypothèse où une ou plusieurs des dispositions du Contrat
s'avèrerait contraire à une loi ou à un texte applicable, existants ou
futurs, cette loi ou ce texte prévaudrait, et les Parties feraient les
amendements nécessaires pour se conformer à cette loi ou à ce texte.
Toutes les autres dispositions resteront en vigueur. De même, la
nullité, pour quelque raison que ce soit, d'une des dispositions du
Contrat ne saurait entraîner la nullité de l'ensemble du Contrat.
11.5 LANGUE
Le Contrat est rédigé en langue française et en langue anglaise, ces
deux versions faisant également foi.
Article 12 - NOUVELLES VERSIONS DU CONTRAT
12.1 Toute personne est autorisée à copier et distribuer des copies de
ce Contrat.
12.2 Afin d'en préserver la cohérence, le texte du Contrat est protégé
et ne peut être modifié que par les auteurs de la licence, lesquels se
réservent le droit de publier périodiquement des mises à jour ou de
nouvelles versions du Contrat, qui posséderont chacune un numéro
distinct. Ces versions ultérieures seront susceptibles de prendre en
compte de nouvelles problématiques rencontrées par les logiciels libres.
12.3 Tout Logiciel diffusé sous une version donnée du Contrat ne pourra
faire l'objet d'une diffusion ultérieure que sous la même version du
Contrat ou une version postérieure, sous réserve des dispositions de
l'article 5.3.4 <#compatibilite>.
Article 13 - LOI APPLICABLE ET COMPETENCE TERRITORIALE
13.1 Le Contrat est régi par la loi française. Les Parties conviennent
de tenter de régler à l'amiable les différends ou litiges qui
viendraient à se produire par suite ou à l'occasion du Contrat.
13.2 A défaut d'accord amiable dans un délai de deux (2) mois à compter
de leur survenance et sauf situation relevant d'une procédure d'urgence,
les différends ou litiges seront portés par la Partie la plus diligente
devant les Tribunaux compétents de Paris.
+519
View File
@@ -0,0 +1,519 @@
CeCILL FREE SOFTWARE LICENSE AGREEMENT
Version 2.1 dated 2013-06-21
Notice
This Agreement is a Free Software license agreement that is the result
of discussions between its authors in order to ensure compliance with
the two main principles guiding its drafting:
* firstly, compliance with the principles governing the distribution
of Free Software: access to source code, broad rights granted to users,
* secondly, the election of a governing law, French law, with which it
is conformant, both as regards the law of torts and intellectual
property law, and the protection that it offers to both authors and
holders of the economic rights over software.
The authors of the CeCILL (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre])
license are:
Commissariat à l'énergie atomique et aux énergies alternatives - CEA, a
public scientific, technical and industrial research establishment,
having its principal place of business at 25 rue Leblanc, immeuble Le
Ponant D, 75015 Paris, France.
Centre National de la Recherche Scientifique - CNRS, a public scientific
and technological establishment, having its principal place of business
at 3 rue Michel-Ange, 75794 Paris cedex 16, France.
Institut National de Recherche en Informatique et en Automatique -
Inria, a public scientific and technological establishment, having its
principal place of business at Domaine de Voluceau, Rocquencourt, BP
105, 78153 Le Chesnay cedex, France.
Preamble
The purpose of this Free Software license agreement is to grant users
the right to modify and redistribute the software governed by this
license within the framework of an open source distribution model.
The exercising of this right is conditional upon certain obligations for
users so as to preserve this status for all subsequent redistributions.
In consideration of access to the source code and the rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's author, the holder of the
economic rights, and the successive licensors only have limited liability.
In this respect, the risks associated with loading, using, modifying
and/or developing or reproducing the software by the user are brought to
the user's attention, given its Free Software status, which may make it
complicated to use, with the result that its use is reserved for
developers and experienced professionals having in-depth computer
knowledge. Users are therefore encouraged to load and test the
suitability of the software as regards their requirements in conditions
enabling the security of their systems and/or data to be ensured and,
more generally, to use and operate it in the same conditions of
security. This Agreement may be freely reproduced and published,
provided it is not altered, and that no provisions are either added or
removed herefrom.
This Agreement may apply to any or all software for which the holder of
the economic rights decides to submit the use thereof to its provisions.
Frequently asked questions can be found on the official website of the
CeCILL licenses family (http://www.cecill.info/index.en.html) for any
necessary clarification.
Article 1 - DEFINITIONS
For the purpose of this Agreement, when the following expressions
commence with a capital letter, they shall have the following meaning:
Agreement: means this license agreement, and its possible subsequent
versions and annexes.
Software: means the software in its Object Code and/or Source Code form
and, where applicable, its documentation, "as is" when the Licensee
accepts the Agreement.
Initial Software: means the Software in its Source Code and possibly its
Object Code form and, where applicable, its documentation, "as is" when
it is first distributed under the terms and conditions of the Agreement.
Modified Software: means the Software modified by at least one
Contribution.
Source Code: means all the Software's instructions and program lines to
which access is required so as to modify the Software.
Object Code: means the binary files originating from the compilation of
the Source Code.
Holder: means the holder(s) of the economic rights over the Initial
Software.
Licensee: means the Software user(s) having accepted the Agreement.
Contributor: means a Licensee having made at least one Contribution.
Licensor: means the Holder, or any other individual or legal entity, who
distributes the Software under the Agreement.
Contribution: means any or all modifications, corrections, translations,
adaptations and/or new functions integrated into the Software by any or
all Contributors, as well as any or all Internal Modules.
Module: means a set of sources files including their documentation that
enables supplementary functions or services in addition to those offered
by the Software.
External Module: means any or all Modules, not derived from the
Software, so that this Module and the Software run in separate address
spaces, with one calling the other when they are run.
Internal Module: means any or all Module, connected to the Software so
that they both execute in the same address space.
GNU GPL: means the GNU General Public License version 2 or any
subsequent version, as published by the Free Software Foundation Inc.
GNU Affero GPL: means the GNU Affero General Public License version 3 or
any subsequent version, as published by the Free Software Foundation Inc.
EUPL: means the European Union Public License version 1.1 or any
subsequent version, as published by the European Commission.
Parties: mean both the Licensee and the Licensor.
These expressions may be used both in singular and plural form.
Article 2 - PURPOSE
The purpose of the Agreement is the grant by the Licensor to the
Licensee of a non-exclusive, transferable and worldwide license for the
Software as set forth in Article 5 <#scope> hereinafter for the whole
term of the protection granted by the rights over said Software.
Article 3 - ACCEPTANCE
3.1 The Licensee shall be deemed as having accepted the terms and
conditions of this Agreement upon the occurrence of the first of the
following events:
* (i) loading the Software by any or all means, notably, by
downloading from a remote server, or by loading from a physical medium;
* (ii) the first time the Licensee exercises any of the rights granted
hereunder.
3.2 One copy of the Agreement, containing a notice relating to the
characteristics of the Software, to the limited warranty, and to the
fact that its use is restricted to experienced users has been provided
to the Licensee prior to its acceptance as set forth in Article 3.1
<#accepting> hereinabove, and the Licensee hereby acknowledges that it
has read and understood it.
Article 4 - EFFECTIVE DATE AND TERM
4.1 EFFECTIVE DATE
The Agreement shall become effective on the date when it is accepted by
the Licensee as set forth in Article 3.1 <#accepting>.
4.2 TERM
The Agreement shall remain in force for the entire legal term of
protection of the economic rights over the Software.
Article 5 - SCOPE OF RIGHTS GRANTED
The Licensor hereby grants to the Licensee, who accepts, the following
rights over the Software for any or all use, and for the term of the
Agreement, on the basis of the terms and conditions set forth hereinafter.
Besides, if the Licensor owns or comes to own one or more patents
protecting all or part of the functions of the Software or of its
components, the Licensor undertakes not to enforce the rights granted by
these patents against successive Licensees using, exploiting or
modifying the Software. If these patents are transferred, the Licensor
undertakes to have the transferees subscribe to the obligations set
forth in this paragraph.
5.1 RIGHT OF USE
The Licensee is authorized to use the Software, without any limitation
as to its fields of application, with it being hereinafter specified
that this comprises:
1. permanent or temporary reproduction of all or part of the Software
by any or all means and in any or all form.
2. loading, displaying, running, or storing the Software on any or all
medium.
3. entitlement to observe, study or test its operation so as to
determine the ideas and principles behind any or all constituent
elements of said Software. This shall apply when the Licensee
carries out any or all loading, displaying, running, transmission or
storage operation as regards the Software, that it is entitled to
carry out hereunder.
5.2 ENTITLEMENT TO MAKE CONTRIBUTIONS
The right to make Contributions includes the right to translate, adapt,
arrange, or make any or all modifications to the Software, and the right
to reproduce the resulting software.
The Licensee is authorized to make any or all Contributions to the
Software provided that it includes an explicit notice that it is the
author of said Contribution and indicates the date of the creation thereof.
5.3 RIGHT OF DISTRIBUTION
In particular, the right of distribution includes the right to publish,
transmit and communicate the Software to the general public on any or
all medium, and by any or all means, and the right to market, either in
consideration of a fee, or free of charge, one or more copies of the
Software by any means.
The Licensee is further authorized to distribute copies of the modified
or unmodified Software to third parties according to the terms and
conditions set forth hereinafter.
5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION
The Licensee is authorized to distribute true copies of the Software in
Source Code or Object Code form, provided that said distribution
complies with all the provisions of the Agreement and is accompanied by:
1. a copy of the Agreement,
2. a notice relating to the limitation of both the Licensor's warranty
and liability as set forth in Articles 8 and 9,
and that, in the event that only the Object Code of the Software is
redistributed, the Licensee allows effective access to the full Source
Code of the Software for a period of at least three years from the
distribution of the Software, it being understood that the additional
acquisition cost of the Source Code shall not exceed the cost of the
data transfer.
5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE
When the Licensee makes a Contribution to the Software, the terms and
conditions for the distribution of the resulting Modified Software
become subject to all the provisions of this Agreement.
The Licensee is authorized to distribute the Modified Software, in
source code or object code form, provided that said distribution
complies with all the provisions of the Agreement and is accompanied by:
1. a copy of the Agreement,
2. a notice relating to the limitation of both the Licensor's warranty
and liability as set forth in Articles 8 and 9,
and, in the event that only the object code of the Modified Software is
redistributed,
3. a note stating the conditions of effective access to the full source
code of the Modified Software for a period of at least three years
from the distribution of the Modified Software, it being understood
that the additional acquisition cost of the source code shall not
exceed the cost of the data transfer.
5.3.3 DISTRIBUTION OF EXTERNAL MODULES
When the Licensee has developed an External Module, the terms and
conditions of this Agreement do not apply to said External Module, that
may be distributed under a separate license agreement.
5.3.4 COMPATIBILITY WITH OTHER LICENSES
The Licensee can include a code that is subject to the provisions of one
of the versions of the GNU GPL, GNU Affero GPL and/or EUPL in the
Modified or unmodified Software, and distribute that entire code under
the terms of the same version of the GNU GPL, GNU Affero GPL and/or EUPL.
The Licensee can include the Modified or unmodified Software in a code
that is subject to the provisions of one of the versions of the GNU GPL,
GNU Affero GPL and/or EUPL and distribute that entire code under the
terms of the same version of the GNU GPL, GNU Affero GPL and/or EUPL.
Article 6 - INTELLECTUAL PROPERTY
6.1 OVER THE INITIAL SOFTWARE
The Holder owns the economic rights over the Initial Software. Any or
all use of the Initial Software is subject to compliance with the terms
and conditions under which the Holder has elected to distribute its work
and no one shall be entitled to modify the terms and conditions for the
distribution of said Initial Software.
The Holder undertakes that the Initial Software will remain ruled at
least by this Agreement, for the duration set forth in Article 4.2 <#term>.
6.2 OVER THE CONTRIBUTIONS
The Licensee who develops a Contribution is the owner of the
intellectual property rights over this Contribution as defined by
applicable law.
6.3 OVER THE EXTERNAL MODULES
The Licensee who develops an External Module is the owner of the
intellectual property rights over this External Module as defined by
applicable law and is free to choose the type of agreement that shall
govern its distribution.
6.4 JOINT PROVISIONS
The Licensee expressly undertakes:
1. not to remove, or modify, in any manner, the intellectual property
notices attached to the Software;
2. to reproduce said notices, in an identical manner, in the copies of
the Software modified or not.
The Licensee undertakes not to directly or indirectly infringe the
intellectual property rights on the Software of the Holder and/or
Contributors, and to take, where applicable, vis-à-vis its staff, any
and all measures required to ensure respect of said intellectual
property rights of the Holder and/or Contributors.
Article 7 - RELATED SERVICES
7.1 Under no circumstances shall the Agreement oblige the Licensor to
provide technical assistance or maintenance services for the Software.
However, the Licensor is entitled to offer this type of services. The
terms and conditions of such technical assistance, and/or such
maintenance, shall be set forth in a separate instrument. Only the
Licensor offering said maintenance and/or technical assistance services
shall incur liability therefor.
7.2 Similarly, any Licensor is entitled to offer to its licensees, under
its sole responsibility, a warranty, that shall only be binding upon
itself, for the redistribution of the Software and/or the Modified
Software, under terms and conditions that it is free to decide. Said
warranty, and the financial terms and conditions of its application,
shall be subject of a separate instrument executed between the Licensor
and the Licensee.
Article 8 - LIABILITY
8.1 Subject to the provisions of Article 8.2, the Licensee shall be
entitled to claim compensation for any direct loss it may have suffered
from the Software as a result of a fault on the part of the relevant
Licensor, subject to providing evidence thereof.
8.2 The Licensor's liability is limited to the commitments made under
this Agreement and shall not be incurred as a result of in particular:
(i) loss due the Licensee's total or partial failure to fulfill its
obligations, (ii) direct or consequential loss that is suffered by the
Licensee due to the use or performance of the Software, and (iii) more
generally, any consequential loss. In particular the Parties expressly
agree that any or all pecuniary or business loss (i.e. loss of data,
loss of profits, operating loss, loss of customers or orders,
opportunity cost, any disturbance to business activities) or any or all
legal proceedings instituted against the Licensee by a third party,
shall constitute consequential loss and shall not provide entitlement to
any or all compensation from the Licensor.
Article 9 - WARRANTY
9.1 The Licensee acknowledges that the scientific and technical
state-of-the-art when the Software was distributed did not enable all
possible uses to be tested and verified, nor for the presence of
possible defects to be detected. In this respect, the Licensee's
attention has been drawn to the risks associated with loading, using,
modifying and/or developing and reproducing the Software which are
reserved for experienced users.
The Licensee shall be responsible for verifying, by any or all means,
the suitability of the product for its requirements, its good working
order, and for ensuring that it shall not cause damage to either persons
or properties.
9.2 The Licensor hereby represents, in good faith, that it is entitled
to grant all the rights over the Software (including in particular the
rights set forth in Article 5 <#scope>).
9.3 The Licensee acknowledges that the Software is supplied "as is" by
the Licensor without any other express or tacit warranty, other than
that provided for in Article 9.2 <#good-faith> and, in particular,
without any warranty as to its commercial value, its secured, safe,
innovative or relevant nature.
Specifically, the Licensor does not warrant that the Software is free
from any error, that it will operate without interruption, that it will
be compatible with the Licensee's own equipment and software
configuration, nor that it will meet the Licensee's requirements.
9.4 The Licensor does not either expressly or tacitly warrant that the
Software does not infringe any third party intellectual property right
relating to a patent, software or any other property right. Therefore,
the Licensor disclaims any and all liability towards the Licensee
arising out of any or all proceedings for infringement that may be
instituted in respect of the use, modification and redistribution of the
Software. Nevertheless, should such proceedings be instituted against
the Licensee, the Licensor shall provide it with technical and legal
expertise for its defense. Such technical and legal expertise shall be
decided on a case-by-case basis between the relevant Licensor and the
Licensee pursuant to a memorandum of understanding. The Licensor
disclaims any and all liability as regards the Licensee's use of the
name of the Software. No warranty is given as regards the existence of
prior rights over the name of the Software or as regards the existence
of a trademark.
Article 10 - TERMINATION
10.1 In the event of a breach by the Licensee of its obligations
hereunder, the Licensor may automatically terminate this Agreement
thirty (30) days after notice has been sent to the Licensee and has
remained ineffective.
10.2 A Licensee whose Agreement is terminated shall no longer be
authorized to use, modify or distribute the Software. However, any
licenses that it may have granted prior to termination of the Agreement
shall remain valid subject to their having been granted in compliance
with the terms and conditions hereof.
Article 11 - MISCELLANEOUS
11.1 EXCUSABLE EVENTS
Neither Party shall be liable for any or all delay, or failure to
perform the Agreement, that may be attributable to an event of force
majeure, an act of God or an outside cause, such as defective
functioning or interruptions of the electricity or telecommunications
networks, network paralysis following a virus attack, intervention by
government authorities, natural disasters, water damage, earthquakes,
fire, explosions, strikes and labor unrest, war, etc.
11.2 Any failure by either Party, on one or more occasions, to invoke
one or more of the provisions hereof, shall under no circumstances be
interpreted as being a waiver by the interested Party of its right to
invoke said provision(s) subsequently.
11.3 The Agreement cancels and replaces any or all previous agreements,
whether written or oral, between the Parties and having the same
purpose, and constitutes the entirety of the agreement between said
Parties concerning said purpose. No supplement or modification to the
terms and conditions hereof shall be effective as between the Parties
unless it is made in writing and signed by their duly authorized
representatives.
11.4 In the event that one or more of the provisions hereof were to
conflict with a current or future applicable act or legislative text,
said act or legislative text shall prevail, and the Parties shall make
the necessary amendments so as to comply with said act or legislative
text. All other provisions shall remain effective. Similarly, invalidity
of a provision of the Agreement, for any reason whatsoever, shall not
cause the Agreement as a whole to be invalid.
11.5 LANGUAGE
The Agreement is drafted in both French and English and both versions
are deemed authentic.
Article 12 - NEW VERSIONS OF THE AGREEMENT
12.1 Any person is authorized to duplicate and distribute copies of this
Agreement.
12.2 So as to ensure coherence, the wording of this Agreement is
protected and may only be modified by the authors of the License, who
reserve the right to periodically publish updates or new versions of the
Agreement, each with a separate number. These subsequent versions may
address new issues encountered by Free Software.
12.3 Any Software distributed under a given version of the Agreement may
only be subsequently distributed under the same version of the Agreement
or a subsequent version, subject to the provisions of Article 5.3.4
<#compatibility>.
Article 13 - GOVERNING LAW AND JURISDICTION
13.1 The Agreement is governed by French law. The Parties agree to
endeavor to seek an amicable solution to any disagreements or disputes
that may arise during the performance of the Agreement.
13.2 Failing an amicable solution within two (2) months as from their
occurrence, and unless emergency proceedings are necessary, the
disagreements or disputes shall be referred to the Paris Courts having
jurisdiction, by the more diligent Party.
+138 -34
View File
@@ -29,35 +29,73 @@ $(MKDOCS): $(VENV)/bin/activate
mkdocs-bibtex
$(PIP) install --quiet --upgrade InSilicoSeq
# ── obikmer binary ───────────────────────────────────────────────────────────
# ── standard targets (names and behaviour follow crate-kit's crate.mk) ───────────
# obiskim is an application workspace: cargo runs on $(CARGO_DIR)/Cargo.toml, default features.
CARGO ?= cargo
CARGO_MANIFEST := $(CARGO_DIR)/Cargo.toml
GREEN ?= \033[0;32m
YELLOW ?= \033[1;33m
BLUE ?= \033[1;34m
NC ?= \033[0m
.DEFAULT_GOAL := build
.PHONY: help build release test check fmt fmt-check clippy ci
## help: Lists the documented targets (this Makefile and the kit's)
help:
@echo "$(GREEN)Available commands:$(NC)"
@sed -n "s/^## *\([^:]*\): */\1$$(printf '\t')/p" $(MAKEFILE_LIST) | column -t -s "$$(printf '\t')" | sed -e 's/^/ /'
## build: Release build of the obiskim binary (alias of release)
build: release
## release: Release build of the obiskim binary
release: obiskim
## test: Workspace tests
test:
$(CARGO) test --workspace --manifest-path $(CARGO_MANIFEST)
## check: Code check (all targets of the workspace)
check:
$(CARGO) check --workspace --all-targets --manifest-path $(CARGO_MANIFEST)
## fmt: Code formatting
fmt:
$(CARGO) fmt --all --manifest-path $(CARGO_MANIFEST)
## fmt-check: Formatting check
fmt-check:
$(CARGO) fmt --all --manifest-path $(CARGO_MANIFEST) -- --check
## clippy: Static analysis (warnings = errors)
clippy:
$(CARGO) clippy --workspace --all-targets --manifest-path $(CARGO_MANIFEST) -- -D warnings
## ci: Verification pipeline (deps-check fmt-check clippy test)
ci: deps-check fmt-check clippy test
@echo "$(GREEN)✓ All CI checks passed$(NC)"
# ── obiskim binary ───────────────────────────────────────────────────────────
PROFILE_FILE := profile.pb
PPROF_PORT := 8081
.PHONY: obikmer
obikmer:
cargo build --release --manifest-path $(CARGO_DIR)/Cargo.toml --bin obikmer
.PHONY: obiskim
## obiskim: Release build of the obiskim binary
obiskim:
cargo build --release --manifest-path $(CARGO_DIR)/Cargo.toml --bin obiskim
.PHONY: debug
## debug: Debug build of the obiskim binary
debug:
cargo build --manifest-path $(CARGO_DIR)/Cargo.toml --bin obikmer
# One-shot converter of indexes built with ptr_hash 1.x (see tools/migrate-mphf).
# Standalone crate, outside the src/ workspace, with its own Cargo.lock/target.
MIGRATE_MPHF_DIR := tools/migrate-mphf
.PHONY: migrate-mphf
migrate-mphf:
cargo build --release --manifest-path $(MIGRATE_MPHF_DIR)/Cargo.toml
.PHONY: clean-migrate-mphf
clean-migrate-mphf:
rm -rf $(MIGRATE_MPHF_DIR)/target
cargo build --manifest-path $(CARGO_DIR)/Cargo.toml --bin obiskim
.PHONY: profile-build
profile-build:
cargo build --release --manifest-path $(CARGO_DIR)/Cargo.toml \
--bin obikmer --features obikmer/profiling
--bin obiskim --features obiskim/profiling
.PHONY: profile-view
profile-view:
@@ -65,6 +103,7 @@ profile-view:
# ── documentation ─────────────────────────────────────────────────────────────
.PHONY: doc
## doc: Builds the developer documentation (DevDoc/)
doc: $(MKDOCS)
$(MKDOCS) build -f $(DOC_FILE)
@@ -78,6 +117,7 @@ clean-doc:
rm -rf $(DOC_SITE)/
.PHONY: doc-user
## doc-user: Builds the user documentation (doc/)
doc-user: $(MKDOCS)
$(MKDOCS) build -f $(DOC_USER_FILE)
@@ -91,16 +131,43 @@ doc-user-serve: $(MKDOCS)
clean-doc-user:
rm -rf $(DOC_USER_SITE)/
# Regenerates the Gitea/Forgejo wiki (a separate repository, checked out next
# to this one) from the user documentation. Only rewrites its working tree:
# committing and pushing it stays a manual step. Not part of `clean`.
DOC_WIKI_DIR := ../obiskim.wiki
.PHONY: wiki
## wiki: Regenerates the wiki working tree (../obiskim.wiki); commit and push stay manual
wiki:
@command -v pmotransdoc >/dev/null || { echo "pmotransdoc not found in PATH" >&2; exit 1; }
@test -d $(DOC_WIKI_DIR)/.git || { echo "$(DOC_WIKI_DIR) is not a git checkout of the wiki" >&2; exit 1; }
pmotransdoc $(DOC_USER_DIR) $(DOC_WIKI_DIR)
.PHONY: clean
clean: clean-doc clean-doc-user
rm -rf $(VENV)
# ── release ───────────────────────────────────────────────────────────────────
# ── release (jj only; the kit's norms for a repository that is not a crate) ───────
# Version: patch bump of the obiskim crate (RELEASE=x.y.z forces it). Tag: v<version> (what release.yml
# triggers on), created and pushed with jj, lightweight: the CI release body is the tagged commit's
# message. Release notes: ReleaseNotes/version-<version>.md (jj release-notes), committed with the release.
# No git command is run. The user runs `make jjrelease`; it never runs by itself.
CARGO_TOML := $(CARGO_DIR)/obikmer/Cargo.toml
CARGO_TOML := $(CARGO_DIR)/obiskim/Cargo.toml
RELEASE_NOTES_DIR := ReleaseNotes
API_DIR := api
RELEASE_PROJECT_DESC := obiskim (Rust k-mer genomics tool)
TAG_PREFIX := v
# Backlog of outdated external dependencies: not enforced until TASK-24 of the obi backlog is done.
# The private-registry check (neighbours, lock, duplicates) stays active.
export DEPS_CHECK_EXTERNAL ?= 0
export RELEASE_NOTES_DIR API_DIR RELEASE_PROJECT_DESC TAG_PREFIX
.PHONY: bump-version
.PHONY: bump-version jjpush jjrelease bookmark-check print-%
## bump-version: Next patch version of the obiskim crate, or fixed RELEASE=x.y.z (refused if the tag exists)
bump-version:
@jj git fetch
@current=$$(grep '^version = ' $(CARGO_TOML) | head -n 1 | sed 's/version = "\(.*\)"/\1/'); \
if [ -n "$(RELEASE)" ]; then \
new_version="$(RELEASE)"; \
@@ -108,22 +175,59 @@ bump-version:
major=$$(echo $$current | cut -d. -f1); \
minor=$$(echo $$current | cut -d. -f2); \
patch=$$(echo $$current | cut -d. -f3); \
new_patch=$$((patch + 1)); \
new_version="$$major.$$minor.$$new_patch"; \
new_version="$$major.$$minor.$$((patch + 1))"; \
fi; \
if [ -n "$$(jj tag list "$(TAG_PREFIX)$$new_version" 2>/dev/null)" ]; then \
echo "✗ tag $(TAG_PREFIX)$$new_version already exists (use RELEASE=x.y.z)" >&2; exit 1; \
fi; \
echo "Version: $$current -> $$new_version"; \
sed -i.bak "s/^version = \"$$current\"/version = \"$$new_version\"/" $(CARGO_TOML) && \
rm $(CARGO_TOML).bak
.PHONY: release
release: bump-version
## bookmark-check: Does main track main@origin? Otherwise the push of main would fail (read-only)
bookmark-check:
@.crate-kit/scripts/bookmark-check.sh
## jjpush: Documents the commit, advances main to it and pushes main (no PR branch), then starts a new commit
jjpush: bookmark-check deps-check
@echo "$(YELLOW)→ Pushing the commit to main...$(NC)"
@jj auto-doc
@jj git push --change @
@new_version=$$(grep '^version = ' $(CARGO_TOML) | head -n 1 | sed 's/version = "\(.*\)"/\1/'); \
git_hash=$$(jj log -r @ --no-graph -T 'commit_id'); \
commits=$$(jj log -r 'latest(tags())..@' --no-graph -T 'description ++ "\n"' 2>/dev/null || \
jj log --no-graph -T 'description ++ "\n"' --limit 30); \
notes=$$(printf 'Write concise markdown release notes for obikmer (a Rust kmer genomics tool). Be technical and direct. Base them strictly on these commit messages:\n\n%s' "$$commits" | aichat 2>/dev/null); \
tag_msg="$${notes:-Release v$$new_version}"; \
git tag -a "v$$new_version" -m "$$tag_msg" "$$git_hash" && \
git push origin "v$$new_version"
@.crate-kit/scripts/push-main.sh
@.crate-kit/scripts/new-commit.sh
@echo "$(GREEN)✓ main pushed; new working commit created on top of it$(NC)"
## jjrelease: Release (ci, version bump, notes, push of main, tag v<version> pushed; release.yml then builds)
jjrelease: bookmark-check ci bump-version
@echo "$(BLUE)→ Documenting the undocumented commits...$(NC)"
@jj auto-doc
@.crate-kit/scripts/release-notes.sh
@echo "$(BLUE)→ Documenting the current commit...$(NC)"
@jj auto-doc
@echo "$(BLUE)→ Pushing main...$(NC)"
@.crate-kit/scripts/push-main.sh
@scripts/jj-tag.sh
@.crate-kit/scripts/new-commit.sh
@echo "$(GREEN)✓ Tag pushed: the CI (release.yml) builds and publishes the release$(NC)"
## print-%: Value of a make variable (e.g. make print-REGISTRY)
print-%:
@echo '$($*)'
# ── crate-kit (registry `obi`, joint development) ─────────────────────────────
# obiskim is an APPLICATION workspace, not a crate. It includes dev-patch.mk (private registry
# definition, local patches to neighbouring crates, deps-check/deps-bump) and jj.mk (jjnew, jjfetch).
# The crate targets of crate.mk (publish, api-*, kit-check: it requires a release.yaml workflow) do NOT
# apply; the release targets above are the application's own, built on the kit's scripts.
# .crate-kit/ is resynchronized from obi-kit (which assembles crate-kit) at every make, before the include.
# Skipped when obi-kit is absent (CI, repository cloned alone): the committed copy is used.
# Included last so that the default goal stays `build`.
KIT_SRC ?= ../obi-kit
$(shell [ -x '$(KIT_SRC)/tools/kit-copy.sh' ] && '$(KIT_SRC)/tools/kit-copy.sh' .crate-kit)
include .crate-kit/dev-patch.mk
include .crate-kit/jj.mk
# Exported after the includes: KIT_LANG comes from org.mk (`?=`), and an earlier `export KIT_LANG` would
# define it empty with GNU make 3.81 (macOS).
export KIT_LANG CARGO_TOML
export PMOJJ_LANG = $(KIT_LANG)
+8 -8
View File
@@ -1,6 +1,6 @@
# obikmer
# obiskim
`obikmer` is a Rust toolkit for indexing, querying, and comparing DNA sequences
`obiskim` is a Rust toolkit for indexing, querying, and comparing DNA sequences
represented as sets of k-mers. It targets individual genome datasets (tens of
Gbases) with maximum efficiency in computation, memory, and disk usage.
@@ -95,20 +95,20 @@ Non-ACGT characters act as hard breaks between k-mer segments in all formats.
```sh
# Build an exact index for each genome independently
obikmer index --kmer-size 31 --label genome_a genome_a.fa --output index_a/
obikmer index --kmer-size 31 --label genome_b genome_b.fa --output index_b/
obiskim index --kmer-size 31 --label genome_a genome_a.fa --output index_a/
obiskim index --kmer-size 31 --label genome_b genome_b.fa --output index_b/
# Merge into a single multi-genome index
obikmer merge --output index/ index_a/ index_b/
obiskim merge --output index/ index_a/ index_b/
# Convert to approximate index (z=5, 8-bit fingerprints)
obikmer reindex --approx -z 5 --evidence-bits 8 index/
obiskim reindex --approx -z 5 --evidence-bits 8 index/
# Query reads
obikmer query index/ reads.fq.gz > annotated.fa
obiskim query index/ reads.fq.gz > annotated.fa
# Pairwise distances
obikmer phylo index/ > distances.tsv
obiskim phylo index/ > distances.tsv
```
## Parameter constraints
+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`.
+1 -1
View File
@@ -1,6 +1,6 @@
# Architecture notes for advanced use
This page describes execution-level behavior relevant to sizing and running `obikmer` on large datasets or multi-socket machines. It complements the [index format](formats/index_layout.md) and [theory](theory/kmer_indexing/indexing_architecture.md) pages.
This page describes execution-level behavior relevant to sizing and running `obiskim` on large datasets or multi-socket machines. It complements the [index format](formats/index_layout.md) and [theory](theory/kmer_indexing/indexing_architecture.md) pages.
## Sequence invariant
+39 -28
View File
@@ -4,14 +4,13 @@
Building an index ([`index`](../usage/index_command.md)) proceeds through a fixed sequence of phases, each operating independently per partition (see [Partitioning and indexing architecture](../theory/kmer_indexing/indexing_architecture.md)):
1. **Scatter.** A single streaming pass over the input. Each sequence fragment is cut at non-ACGT bases, passed through the low-complexity entropy filter (see [Low-complexity kmer filter](../theory/kmer_indexing/entropy_filter.md)), and any resulting segment shorter than k is dropped. Surviving segments are decomposed into super-kmers, canonicalized, and routed by `hash(minimizer) mod n_partitions` into one file per partition.
1. **Scatter.** A single streaming pass over the input. Each sequence fragment is cut at non-ACGT bases, passed through the low-complexity entropy filter (see [Low-complexity kmer filter](../theory/kmer_indexing/entropy_filter.md)), and any resulting segment shorter than k is dropped. Surviving segments are decomposed into super-kmers, canonicalized, and routed by `hash(minimizer) mod n_partitions` into one file per partition. The number of partitions is always a power of two, so this routing amounts to keeping the low bits of the hash.
2. **Dereplication.** Within each partition, identical super-kmer sequences are merged and their occurrence counts summed. This count is per super-kmer, not per kmer — a kmer's true abundance is the sum of the counts of every super-kmer containing it.
3. **Exact counting.** Every kmer in every dereplicated super-kmer is enumerated and its exact total count computed. A per-genome kmer frequency spectrum is produced at this stage.
4. **Quorum filtering.** Kmers outside the `--min-abundance`/`--max-abundance` range are dropped, and super-kmers are recompacted around the surviving kmer set.
5. **Local assembly.** The surviving kmers of each partition are assembled into unitigs — maximal non-branching runs of a local de Bruijn graph — such that every kmer appears exactly once, at one (unitig, offset) location.
6. **MPHF and evidence construction.** A minimal perfect hash function is built over the canonical kmers of each partition, together with the evidence structure needed to verify that a queried kmer was genuinely indexed (see below). Per-genome counts or presence bits are recorded alongside if requested.
3. **Exact counting.** Every kmer in every dereplicated super-kmer is enumerated and its exact total count computed. To accumulate these counts, a provisional minimal perfect hash function is built over the distinct kmers of the partition and a temporary count file is filled through it. Both are working files: they are deleted at the end of the build unless `--keep-intermediate` is given. A per-genome kmer frequency spectrum is produced at this stage, from the counts as they are before any abundance filtering.
4. **Quorum filtering and local assembly.** The kmers of the dereplicated super-kmers are fed one by one into a local de Bruijn graph of the partition. A kmer whose count falls outside the `--min-abundance`/`--max-abundance` range is dropped at this point, and never enters the graph; the super-kmers themselves are not rewritten. The kmers that remain are assembled into unitigs — maximal non-branching runs of the graph — such that every kmer appears exactly once, at one (unitig, offset) location.
5. **MPHF and evidence construction.** The final minimal perfect hash function is built over the canonical kmers that survived, together with the evidence structure needed to verify that a queried kmer was genuinely indexed (see below). Per-genome counts or presence bits are recorded alongside if requested; the counts come from the counting phase.
Phases 1–5 are independent per partition and run in parallel; phase 6 finalizes each partition once its kmer set is fixed.
Within each phase, the partitions are independent of one another and are processed in parallel. The phases themselves follow one another over the whole index, and the index records in its `index.meta` file how far the build has gone (after scatter, after counting, and when fully built). A build that was interrupted can therefore be resumed: the phases already completed are skipped.
## Minimal perfect hash function (MPHF)
@@ -19,38 +18,50 @@ Each partition's surviving kmers are mapped to a dense range of integer slots by
## Evidence: exact vs. approximate
Two verification modes are available, selected at build time (`index --approx`) and convertible afterwards ([`convert`](../usage/convert.md)):
Three verification modes exist. The exact and approximate modes are selected at build time (`index --approx`), and any of the three can be reached afterwards with [`convert`](../usage/convert.md):
- **Exact** (default): the hashed slot stores a pointer back into the partition's unitig data. At query time the kmer is reconstructed from that location and compared directly to the query. Zero false positives, at the cost of one extra random read per lookup.
- **Approximate** (`--approx`): the slot stores a short fingerprint (`--evidence-bits` bits) instead of a pointer; verification is a single fingerprint comparison. This trades a small, bounded false-positive rate ($1/2^b$ per kmer, reduced further to about $1/2^{b \cdot z}$ for a read requiring $z$ consecutive matching kmers via the `-z`/`--findere-z` parameter) for lower memory and disk usage, since no reconstruction index is needed. See [`estimate`](../usage/estimate.md) to explore this trade-off before building.
- **Hybrid** (`convert --hybrid-evidence`): both the fingerprint and the exact evidence are kept. A lookup uses the fingerprint, which is fast and approximate, while the exact evidence remains stored alongside it.
## On-disk layout
```
<index_root>/
index.meta global configuration (k, minimizer size, partition count,
evidence mode, whether counts are stored) and genome list/metadata
scatter.done / count.done / index.done build-progress sentinels
spectrums/<label>.json per-genome kmer frequency histogram
partitions/
part_00000/ ... part_NNNNN/
index/
meta.json number of layers in this partition
layer_0/
unitigs.bin reconstructible kmer sequence data — always kept
unitigs.bin.idx random-access index into unitigs.bin (exact evidence only)
mphf.bin the minimal perfect hash function
evidence.bin exact evidence (exact mode only)
fingerprint.bin approximate evidence (approximate mode only)
counts/ per-genome kmer counts (if counts were requested)
presence/ per-genome presence/absence bits
layer_1/, layer_2/, ... added by later merges, same internal structure
📁 <index_root>/
├── 📄 index.meta configuration (k, minimizer size, partition count,
│ evidence mode, counts stored or not), genome list
│ and metadata, build state (empty, scattered,
│ counted, indexed)
├── 📄 .obiskim.lock lock files: commands that read the index share it,
├── 📄 .obiskim.gate commands that write into it hold it exclusively
├── 📁 spectrums/
│ └── 📄 <label>.json per-genome kmer frequency histogram
└── 📁 partitions/
├── 📁 part_00000/
│ └── 📁 index/
│ ├── 📁 layer_0/
│ │ ├── 📄 layer_meta.json number of kmers in this layer
│ │ ├── 📄 unitigs.bin reconstructible kmer sequence data — always kept
│ │ ├── 📄 unitigs.bin.idx random access into unitigs.bin (exact, hybrid)
│ │ ├── 📄 mphf.bin the minimal perfect hash function
│ │ ├── 📄 evidence.bin exact evidence (exact, hybrid)
│ │ ├── 📄 fingerprint.bin approximate evidence (approximate, hybrid)
│ │ ├── 📁 counts/ per-genome kmer counts (if requested)
│ │ └── 📁 presence/ per-genome presence/absence bits
│ └── 📁 layer_1/, layer_2/, … added by later merges, same structure
├── 📁 part_00001/
│ └── …
└── 📁 part_NNNNN/
```
The build state is stored in `index.meta` and not in separate marker files: it is what allows an interrupted build to resume. The number of layers of a partition is not stored anywhere either; it is found by looking for `layer_0`, `layer_1`, ... until one is missing. A partition that received no kmer at all (which happens with small inputs and many partitions) has no layer on disk.
The matrix directory of a layer, `counts/` or `presence/`, exists in three forms, which hold the same information. A freshly built index stores one file per genome, with a small metadata file (for counts, `col_000000.pciv`, `col_000001.pciv`, ... and `meta.json`). The dense packed form, produced by [`pack`](../usage/pack.md), stores the whole matrix in a single file. The sparse packed form, produced by `pack --sparse` and, by default, by [`merge`](../usage/merge.md), stores for each kmer only the list of genomes that carry it, with the lists shared between kmers deduplicated (for counts, the directory then holds files such as `dict_values.bin`, `singleton.pfiv`, `multi.pfiv` and `sparse_meta.json`). Which form a layer uses is detected from the files found in the directory.
`unitigs.bin` is the only file from which the indexed kmer content can be fully recovered; it is always retained. Every other file (MPHF, evidence, counts) is derived from it.
A **layer** corresponds to one increment of kmer content added to a partition — most commonly, one [`merge`](../usage/merge.md) operation that introduces kmers not already present in the index. Genomes already present in the index simply gain new columns in the existing layers' count/presence data; only genuinely new kmer content is assembled into a new layer. Because of this, merging cost scales with the novel kmer content being added, not with the accumulated size of the index. A query against an index with several layers checks each layer's MPHF in turn.
A **layer** corresponds to one increment of kmer content added to a partition — most commonly, one [`merge`](../usage/merge.md) operation that introduces kmers not already present in the index. The genomes of the merged sources are added as new columns to the count/presence data of the existing layers; only genuinely new kmer content, that is kmers absent from every existing layer of the partition, is assembled into a new layer. A kmer therefore belongs to exactly one layer of its partition. Because of this, merging cost scales with the novel kmer content being added, not with the accumulated size of the index. A query against an index with several layers checks each layer's MPHF in turn.
Sources merged together must share the same kmer size, minimizer size, partition count, and evidence mode (including matching approximate-mode parameters); mismatches are rejected rather than silently reconciled — [`convert`](../usage/convert.md) one of the sources first if needed.
Sources merged together must share the same kmer size, minimizer size and partition count; any mismatch is rejected rather than silently reconciled. The evidence mode, on the other hand, may differ between sources: as soon as one source is approximate or hybrid, the destination is chosen among the approximate or hybrid sources, and the merged index takes its evidence mode. A count merge additionally requires every source to store counts. Finally, an index whose matrices are already packed, which includes any merge output, can be merged in as a source but not used as the destination, so at least one source must still be unpacked.
`obikmer pack` consolidates a partition's per-column files (counts/presence) into a single file, reducing the number of file opens needed at query time.
[`pack`](../usage/pack.md) consolidates a partition's per-column files (counts/presence) into a single file, reducing the number of file opens needed at query time; with `--sparse`, it also switches to the sparse form described above.
+10 -10
View File
@@ -11,10 +11,10 @@ Nothing here comes from a reference genome. The file has no real coordinates, an
## Producing the file
```
obikmer phylo --vcf --n-sites 5000000 -o run1 my_index
obiskim phylo --vcf --n-sites 5000000 -o run1 my_index
```
`--vcf` implies `--pseudo-alignment`, so `--n-sites N|all` is required, together with an already-built sibling annex (see [`phylo`](../usage/phylo.md)). `--fasta` and `--vcf` can be given together to get both files from the same draw; with neither, only the FASTA is written. Every option that shapes the draw (`--free-loss`, `--no-ambiguity`, `--only-diploid`, `--quartet`, `--exclude-genome`, ...) applies to the VCF exactly as to the FASTA, since both describe the same sites.
`--vcf` implies `--pseudo-alignment`, so `--n-sites N|all` is required, (the sibling annex it reads is built automatically if missing; see [`phylo`](../usage/phylo.md)). `--fasta` and `--vcf` can be given together to get both files from the same draw; with neither, only the FASTA is written. Every option that shapes the draw (`--free-loss`, `--no-ambiguity`, `--only-diploid`, `--quartet`, `--exclude-genome`, ...) applies to the VCF exactly as to the FASTA, since both describe the same sites.
## Layout
@@ -22,23 +22,23 @@ An illustrative excerpt (columns are tab-separated in the file):
```
##fileformat=VCFv4.5
##source=obikmer
##contig=<ID=obikmer_0_0>
##contig=<ID=obikmer_0_1>
##source=obiskim
##contig=<ID=obiskim_0_0>
##contig=<ID=obiskim_0_1>
##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype (diploid)">
#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
obikmer_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_0 440 CGATTNGTTAA A G . . . GT 0/0 1/1 0/0 0/0
obiskim_0_0 1511 CACGANTGTAG A G,T . . . GT 0/0 0/0 1/1 2/2
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 `.`: obikmer 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.
## Coordinates: `CHROM` and `POS`
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.
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`.
+3 -3
View File
@@ -1,8 +1,8 @@
# obikmer
# obiskim
`obikmer` is a command-line tool for counting, indexing, querying and comparing DNA sequences represented as kmer sets. It targets individual genome datasets of tens of gigabases, with an emphasis on computational, memory, and disk efficiency.
`obiskim` is a command-line tool for counting, indexing, querying and comparing DNA sequences represented as kmer sets. It targets individual genome datasets of tens of gigabases, with an emphasis on computational, memory, and disk efficiency.
All functionality is exposed through a single binary, `obikmer`, organized as subcommands.
All functionality is exposed through a single binary, `obiskim`, organized as subcommands.
## Core principles
+6 -6
View File
@@ -4,7 +4,7 @@
### 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
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
@@ -13,7 +13,7 @@ rustup update stable
### 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, which 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, which requires a standard C build environment.
#### Linux (Debian/Ubuntu)
@@ -47,11 +47,11 @@ brew install automake libtool autoconf pkg-config
```bash
git clone <repository-url>
cd obikmer/src
cd obiskim/src
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)
@@ -66,7 +66,7 @@ CARGO_TARGET_DIR=/scratch/$USER/cargo-target cargo build --release
Adapt the path to the scratch space available on your cluster (`/var/tmp`, `/tmp`, `/scratch/local`, etc.). Once built, copy the binary to a permanent location:
```bash
cp /scratch/$USER/cargo-target/release/obikmer ~/bin/
cp /scratch/$USER/cargo-target/release/obiskim ~/bin/
```
## NUMA support
@@ -80,5 +80,5 @@ NUMA-aware thread placement is active automatically on multi-socket Linux machin
## Verifying the installation
```bash
obikmer --help
obiskim --help
```
+232
View File
@@ -857,3 +857,235 @@
doi = "10.1214/aop/1176996461",
issn = "0091-1798,2168-894X"
}
@ARTICLE{Karlin1997-lm,
title = "{Compositional differences within and between eukaryotic genomes}",
author = "Karlin, S and Mrázek, J",
journal = "Proceedings of the National Academy of Sciences of the United
States of America",
publisher = "Proceedings of the National Academy of Sciences",
volume = 94,
number = 19,
pages = "10227--10232",
abstract = "Eukaryotic genome similarity relationships are inferred using
sequence information derived from large aggregates of genomic
sequences. Comparisons within and between species sample
sequences are based on the profile of dinucleotide relative
abundance values (The profile is ρ* XY = f * XY / f * X f * Y for
all XY , where f * X denotes the frequency of the nucleotide X
and f * XY denotes the frequency of the dinucleotide XY , both
computed from the sequence concatenated with its inverted
complement). Previous studies with respect to prokaryotes and
this study document that profiles of different DNA sequence
samples (sample size ≥50 kb) from the same organism are generally
much more similar to each other than they are to profiles from
other organisms, and that closely related organisms generally
have more similar profiles than do distantly related organisms.
On this basis we refer to the collection {ρ* XY } as the genome
signature . This paper identifies ρ* XY extremes and compares
genome signature differences for a diverse range of eukaryotic
species. Interpretations on the mechanisms maintaining these
profile differences center on genome-wide replication, repair,
DNA structures, and context-dependent mutational biases. It is
also observed that mitochondrial genome signature differences
between species parallel the corresponding nuclear genome
signature differences despite large differences between
corresponding mitochondrial and nuclear signatures. The genome
signature differences also have implications for contrasts
between rodents and other mammals, and between monocot and dicot
plants, as well as providing evidence for similarities among
fungi and the diversity of protists.",
month = sep,
year = 1997,
url = "http://dx.doi.org/10.1073/pnas.94.19.10227",
doi = "10.1073/pnas.94.19.10227",
pmc = "PMC23344",
pmid = 9294192,
issn = "0027-8424,1091-6490",
language = "en"
}
@ARTICLE{Karlin1997-vm,
title = "{Compositional biases of bacterial genomes and evolutionary
implications}",
author = "Karlin, S and Mrázek, J and Campbell, A M",
journal = "Journal of Bacteriology",
publisher = "American Society for Microbiology",
volume = 179,
number = 12,
pages = "3899--3913",
abstract = "We compare and contrast genome-wide compositional biases and
distributions of short oligonucleotides across 15 diverse
prokaryotes that have substantial genomic sequence collections.
These include seven complete genomes (Escherichia coli,
Haemophilus influenzae, Mycoplasma genitalium, Mycoplasma
pneumoniae, Synechocystis sp. strain PCC6803, Methanococcus
jannaschii, and Pyrobaculum aerophilum). A key observation
concerns the constancy of the dinucleotide relative abundance
profiles over multiple 50-kb disjoint contigs within the same
genome. (The profile is rhoXY* = fXY*/fX*fY* for all XY, where
fX* denotes the frequency of the nucleotide X and fY* denotes the
frequency of the dinucleotide XY, both computed from the sequence
concatenated with its inverted complementary sequence.) On the
basis of this constancy, we refer to the collection [rhoXY*] as
the genome signature. We establish that the differences between
[rhoXY*] vectors of 50-kb sample contigs of different genomes
virtually always exceed the differences between those of the same
genomes. Various di- and tetranucleotide biases are identified.
In particular, we find that the dinucleotide CpG=CG is
underrepresented in many thermophiles (e.g., M. jannaschii,
Sulfolobus sp., and M. thermoautotrophicum) but overrepresented
in halobacteria. TA is broadly underrepresented in prokaryotes
and eukaryotes, but normal counts appear in Sulfolobus and P.
aerophilum sequences. More than for any other bacterial genome,
palindromic tetranucleotides are underrepresented in H.
influenzae. The M. jannaschii sequence is unprecedented in its
extreme underrepresentation of CTAG tetranucleotides and in the
anomalous distribution of CTAG sites around the genome.
Comparative analysis of numbers of long tetranucleotide
microsatellites distinguishes H. influenzae. Dinucleotide
relative abundance differences between bacterial sequences are
compared. For example, in these assessments of differences, the
cyanobacteria Synechocystis, Synechococcus, and Anabaena do not
form a coherent group and are as far from each other as general
gram-negative sequences are from general gram-positive sequences.
The difference of M. jannaschii from low-G+C gram-positive
proteobacteria is one-half of the difference from gram-negative
proteobacteria. Interpretations and hypotheses center on the role
of the genome signature in highlighting similarities and
dissimilarities across different classes of prokaryotic species,
possible mechanisms underlying the genome signature, the form and
level of genome compositional flux, the use of the genome
signature as a chronometer of molecular phylogeny, and
implications with respect to the three putative eubacterial,
archaeal, and eukaryote domains of life and to the origin and
early evolution of eukaryotes.",
month = jun,
year = 1997,
url = "http://dx.doi.org/10.1128/jb.179.12.3899-3913.1997",
doi = "10.1128/jb.179.12.3899-3913.1997",
pmc = "PMC179198",
pmid = 9190805,
issn = "0021-9193,1098-5530",
language = "en"
}
@ARTICLE{Karlin1995-lt,
title = "{Dinucleotide relative abundance extremes: a genomic signature}",
author = "Karlin, S and Burge, C",
journal = "Trends in Genetics: TIG",
publisher = "Elsevier BV",
volume = 11,
number = 7,
pages = "283--290",
abstract = "Early biochemical experiments established that the set of
dinucleotide odds ratios or 'general design' is a remarkably
stable property of the DNA of an organism, which is essentially
the same in protein-coding DNA, bulk genomic DNA, and in
different renaturation rate and density gradient fractions of
genomic DNA in many organisms. Analysis of currently available
genomic sequence data has extended these earlier results, showing
that the general designs of disjoint samples of a genome are
substantially more similar to each other than to those of
sequences from other organisms and that closely related organisms
have similar general designs. From this perspective, the set of
dinucleotide odds ratio (relative abundance) values constitute a
signature of each DNA genome, which can discriminate between
sequences from different organisms. Dinucleotide-odds ratio
values appear to reflect not only the chemistry of dinucleotide
stacking energies and base-step conformational preferences, but
also the species-specific properties of DNA modification,
replication and repair mechanisms.",
month = jul,
year = 1995,
url = "http://dx.doi.org/10.1016/s0168-9525(00)89076-9",
doi = "10.1016/s0168-9525(00)89076-9",
pmid = 7482779,
issn = "0168-9525,1362-4555",
language = "en"
}
@ARTICLE{Karlin1994-on,
title = "{Heterogeneity of genomes: measures and values}",
author = "Karlin, S and Ladunga, I and Blaisdell, B E",
journal = "Proceedings of the National Academy of Sciences of the United
States of America",
publisher = "Proceedings of the National Academy of Sciences",
volume = 91,
number = 26,
pages = "12837--12841",
abstract = "Genomic homogeneity is investigated for a broad base of DNA
sequences in terms of dinucleotide relative abundance distances
(abbreviated delta-distances) and of oligonucleotide
compositional extremes. It is shown that delta-distances between
different genomic sequences in the same species are low, only
about 2 or 3 times the distance found in random DNA, and are
generally smaller than the between-species delta-distances.
Extremes in short oligonucleotides include underrepresentation of
TpA and overrepresentation of GpC in most temperate bacteriophage
sequences; underrepresentation of CTAG in most eubacterial
genomes; underrepresentation of GATC in most bacteriophage; CpG
suppression in vertebrates, in all animal mitochondrial genomes,
and in many thermophilic bacterial sequences; and
overrepresentation of GpG/CpC in all animal mitochondrial sets
and chloroplast genomes. Interpretations center on DNA structures
(dinucleotide stacking energies, DNA curvature and superhelicity,
nucleosome organization), context-dependent mutational events,
methylation effects, and processes of replication and repair.",
month = dec,
year = 1994,
url = "http://dx.doi.org/10.1073/pnas.91.26.12837",
doi = "10.1073/pnas.91.26.12837",
pmc = "PMC45535",
pmid = 7809131,
issn = "0027-8424,1091-6490",
language = "en"
}
@ARTICLE{Bennett2013-cl,
title = "{Small, smaller, smallest: the origins and evolution of ancient
dual symbioses in a Phloem-feeding insect}",
author = "Bennett, Gordon M and Moran, Nancy A",
journal = "Genome Biology and Evolution",
publisher = "Oxford University Press (OUP)",
volume = 5,
number = 9,
pages = "1675--1688",
abstract = "Many insects rely on bacterial symbionts with tiny genomes
specialized for provisioning nutrients lacking in host diets.
Xylem sap and phloem sap are both deficient as insect diets, but
differ dramatically in nutrient content, potentially affecting
symbiont genome evolution. For sap-feeding insects, sequenced
symbiont genomes are available only for phloem-feeding examples
from the suborder Sternorrhyncha and xylem-feeding examples from
the suborder Auchenorrhyncha, confounding comparisons. We
sequenced genomes of the obligate symbionts, Sulcia muelleri and
Nasuia deltocephalinicola, of the phloem-feeding pest insect,
Macrosteles quadrilineatus (Auchenorrhyncha: Cicadellidae). Our
results reveal that Nasuia-ALF has the smallest bacterial genome
yet sequenced (112 kb), and that the Sulcia-ALF genome (190 kb)
is smaller than that of Sulcia in other insect lineages.
Together, these symbionts retain the capability to synthesize the
10 essential amino acids, as observed for several symbiont pairs
from xylem-feeding Auchenorrhyncha. Nasuia retains genes enabling
synthesis of two amino acids, DNA replication, transcription, and
translation. Both symbionts have lost genes underlying ATP
synthesis through oxidative phosphorylation, possibly as a
consequence of the enriched sugar content of phloem. Shared
genomic features, including reassignment of the UGA codon from
Stop to tryptophan, and phylogenetic results suggest that
Nasuia-ALF is most closely related to Zinderia, the
betaproteobacterial symbiont of spittlebugs. Thus,
Nasuia/Zinderia and Sulcia likely represent ancient associates
that have co-resided in hosts since the divergence of leafhoppers
and spittlebugs >200 Ma, and possibly since the origin of the
Auchenorrhyncha, >260 Ma.",
month = aug,
year = 2013,
url = "http://dx.doi.org/10.1093/gbe/evt118",
keywords = "Nasuia deltocephalinicola; Sulcia muelleri; gene loss; genome
evolution; leafhopper; nutritional symbioses",
doi = "10.1093/gbe/evt118",
pmc = "PMC3787670",
pmid = 23918810,
issn = "1759-6653",
language = "en"
}
@@ -1,6 +1,6 @@
# Low-complexity kmer filter
Low-complexity kmers (homopolymer runs, tandem repeats) can dominate an index without carrying useful information. `obikmer` detects and excludes them during index construction using a normalized Shannon entropy score.
Low-complexity kmers (homopolymer runs, tandem repeats) can dominate an index without carrying useful information. `obiskim` detects and excludes them during index construction using a normalized Shannon entropy score.
## Sub-word frequencies
+226 -333
View File
@@ -1,6 +1,12 @@
# K-mer size
A k-mer is a DNA sequence of length $k$. OBIKmer is designed to index large k-mers. Here, *large* refers to a k-mer length for which the probability of observing the same k-mer in several genomes by chance alone is sufficiently small. The k-mer length must therefore be large enough that, when a k-mer is observed in several genomes of the dataset, the probability that this shared occurrence is due to chance alone is sufficiently low for the match to be considered evidence of homology.
A k-mer is a DNA sequence of length $k$. OBIKmer is designed to index
large k-mers. Here, *large* refers to a k-mer length for which the
probability of observing the same k-mer in several genomes by chance
alone is sufficiently small. The k-mer length must therefore be large
enough that, when a k-mer is observed in several genomes of the dataset,
the probability that this shared occurrence is due to chance alone is
sufficiently low for the match to be considered evidence of homology.
OBIKmer restricts $k$ to odd values in the range
@@ -8,409 +14,296 @@ $$
11 \leq k \leq 31.
$$
These limits result from two different considerations. The upper bound is imposed by the representation used by OBIKmer, whereas the lower bound defines a practical range of k-mer lengths for genome-scale sequence comparisons. This range covers most practical applications: the lower limit is well below the k-mer size that can be considered large, even for the smallest bacterial genomes, whereas the upper limit provides sufficient specificity for most applications, including those involving very large genomes.
These limits result from two different considerations. The upper bound
is imposed by the representation used by OBIKmer, whereas the lower
bound defines a practical range of k-mer lengths for genome-scale
sequence comparisons. This range covers most practical applications: the
lower limit is well below the k-mer size that can be considered large,
even for the smallest bacterial genomes, whereas the upper limit
provides sufficient specificity for most applications, including those
involving very large genomes.
## Representation limit
OBIKmer uses two bits to encode each nucleotide. Therefore, a k-mer requires $2k$ bits. To ensure computational efficiency, OBIKmer limits the representation of k-mers to a single 64-bit word, thereby restricting their length.
OBIKmer uses two bits to encode each nucleotide. Therefore, a k-mer
requires $2k$ bits. To ensure computational efficiency, OBIKmer limits
the representation of k-mers to a single 64-bit word, thereby
restricting their length.
$$
2k \leq 64,
$$
This gives the hard representation limit: $k \leq 32.$ Furthermore, OBIKmer only considers odd values of $k$, meaning the largest supported k-mer size is $31$.
### K-mer specificity
One simple way to illustrate the effect of k-mer size is to consider a random DNA sequence in which the four nucleotides are independent and equally probable. There are $4^k$ possible k-mers, so a particular k-mer is expected to occur once every $4^k$ positions on average. In a sequence of length $G$, the expected number of occurrences of a particular k-mer is approximately $G \cdot 4^{-k}$. When k is large enough to ensure $4^k >> G$, the chance of a second occurrence of the same k-mer becomes close to zero. Consequently, observing the same k-mer twice can only be explained by a homology relationship, except for low-complexity k-mers, which are overrepresented in genomes.
### Estimating False discovery rate on homology inference
OBIKmer uses k-mers long enough that their occurrence in multiple indexed genomes provides evidence of homology. The corresponding false discovery rate (FDR) can be expressed in terms of the probability of observing a k-mer in at least $R$ of the $S$ indexed genomes under a purely random model.
#### The random model
The random model, or null hypothesis, assumes that the $S$ genomes are unrelated and that each genome is an independent random sequence in which each nucleotide occurs with equal probability. Rejecting this hypothesis for a given k-mer indicates that its presence in multiple genomes is unlikely to be explained by chance alone, providing evidence for homology.
For a genome of size $G$, the number of occurrences of a given canonical k-mer $K$ is approximated by a Poisson distribution with parameter
$$ \lambda = 2\frac{G}{4^k}, $$
which is also the expected number of occurrences under the random model. The factor of two accounts for k-mer canonicalisation, which halves the k-mer space when $k$ is odd.
The probability of observing at least one occurrence of this k-mer is therefore
$$
\begin{aligned}
P(n_K > 0) &= 1-e^{-\lambda} \\
&= 1-e^{-2G/4^k}.
\end{aligned}
$$
Assuming equal genome lengths, the number of genomes containing at least one occurrence of $K$ among the $S$ sequences follows a binomial distribution. The probability of observing $K$ in at least $r$ genomes is therefore
$$
P(X \geq r)=\sum_{j=r}^{S}\binom{S}{j}\left(1-e^{-2G/4^k}\right)^j\left(e^{-2G/4^k}\right)^{S-j}.
$$
This sum is the regularized incomplete beta function $I_p(r,\,S-r+1)$, where
$$
p = 1-e^{-2G/4^k}.
$$
Different genome sizes
When genome sizes differ, the probability of observing a given k-mer also differs between genomes. A simple approximation is to replace the individual genome sizes $G_i$ by their mean
$$ \bar G = \frac{1}{S}\sum_{i=1}^{S}G_i. $$
This gives a common probability
$$ \bar p = 1-e^{-2\bar G/4^k}, $$
and the number of genomes containing the k-mer can then be approximated by a binomial distribution:
$$ P(X\geq r)=\sum_{j=r}^{S}\binom{S}{j}\bar p^j(1-\bar p)^{S-j}. $$
This approximation is conservative for the upper tail. Hoeffding [-@Hoeffding1956-bx, p. 717, Eq. 26] shows that, for a fixed mean, the binomial upper tail is at least as large as the corresponding Poisson-binomial tail for
$$ r\geq S\bar p+1. $$
Using the mean genome size therefore provides a conservative estimate of the FDR.
When genome sizes differ substantially, however, this approximation can become overly conservative. In that case, the exact Poisson-binomial distribution can be computed directly from the individual genome-specific probabilities $p_i$.
### Exact tail probability
With genome-specific probabilities $p_i$, the number of genomes containing the k-mer follows a Poisson-binomial distribution. Writing the probability of exactly $j$ presences as a sum over all subsets of $j$ genomes would be impractical, since there can be up to $2^S$ subsets. The distribution can instead be obtained by adding the genomes one at a time.
Let $d_j$ be the probability that exactly $j$ of the genomes processed so far contain the k-mer. Adding genome $i$ leaves $j$ unchanged if the genome does not contain the k-mer, and moves $j-1$ to $j$ if it does:
$$
\left \{
\begin{aligned}
d'_j &= d_j(1-p_i) + d_{j-1}p_i, \\
d_0&=1
\end{aligned}
\right .
$$
before processing the first genome.
The table $d$ only needs to record how many genomes contain the k-mer, not which ones, reducing the computational cost to $O(S^2)$. The result is independent of the order in which the genomes are processed and of the k-mer itself, so it can be computed once per index. The upper tail is then
$$
P(X\geq r)=1-\sum_{j=0}^{r-1}d_j.
$$
Only $d_0,\ldots,d_{r-1}$ are needed, reducing the cost to $O(Sr)$.
When all $p_i$ are small, as is typically the case for large $k$, the Poisson-binomial distribution can also be approximated by a Poisson distribution with mean
$$
\lambda=\sum_{i=1}^{S}p_i.
$$
The approximation error is bounded in terms of $\sum_i p_i^2$ by Le Cam's inequality [@LeCam1960-pe].
*******
This probability decreases by a factor of four for every additional nucleotide in the k-mer. Conversely, it increases linearly with the amount of sequence searched.
This simple model already shows why very short k-mers provide limited specificity for genome-scale analyses. With $k=11$,
$$
4^{11}\simeq4.2\times10^6,
$$
which is a small combinatorial space even compared with the size of very small bacterial genomes. In contrast,
$$
4^{31}\simeq4.6\times10^{18},
$$
which is vastly larger than the number of k-mer positions even in very large genomes. Thus, increasing $k$ from 11 to 31 provides an enormous increase in sequence specificity.
The estimate above is intentionally simplistic. Real genomes do not consist of independent, equiprobable nucleotides: nucleotide composition and sequence dependencies affect the probability of observing particular words. More accurate estimates of the probability of observing matches by chance therefore take sequence length and nucleotide composition into account.
Karlin and Ost provide an analytical framework for this problem based on the distribution of the longest exact match expected between random sequences. If $L_{\max}$ denotes the length of the longest seed observed in random sequences of given size and nucleotide composition, the corresponding seed-level probability is
$$
P_{\mathrm{seeds}}(L)=P(L_{\max}\geq L).
$$
Conversely, for a chosen false-positive probability $P$, one can determine the minimum seed length $L_{\min}$ such that matches of length $L_{\min}$ or greater are not expected to occur by chance. This is the approach used by Repseek to determine statistically significant seed lengths.
The simple $G/4^k$ estimate and the Karlin–Ost statistics therefore describe the same fundamental effect at different levels of approximation: the probability of a chance match decreases rapidly with k-mer length, while the amount of sequence being searched increases the opportunity for such matches.
Consequently, the appropriate value of $k$ depends on the total amount of sequence being compared and its nucleotide composition. Choosing $k$ appropriately allows the false-positive rate of homology inference to be controlled.
Considering that bacterial genomes are typically a few megabases long, with the smallesr plublished today *Mycoplasma genitalium* having a size $G=580\,Mb$ [@Fraser1995-jc], and the largest $13\,Mb$ in *Sorangium cellulosum* [@Schneiker2007-gs]. For such genomes, the space of 11-mers is already to small to get a reasonable false positive rate:
$$
\begin{aligned}
P(C\geq1) &= 1- e^{-\frac{580.000^2}{2 \cdot 4^{11}}} \\
&\simeq 1
\end{aligned}
$$
, whereas 21-mers already provide a space of several trillion possible sequences.
Plant genomes illustrate the opposite situation. Plant genome sizes span several orders of magnitude, from the smallest angiosperm genomes present in the carnivorous plans genus [@Fleischmann2014-ed] about 60 Mb to the largest one 160 Gb in Tmesipteris oblanceolata, a New Caledonian fork fern [@Fernandez2024-kd], and large genomes often contain substantial amounts of repeated sequence. Even at $k=31$, however, the theoretical k-mer space remains vastly larger than any individual genome. At these lengths, the limiting factor is therefore not exhaustion of the theoretical k-mer space but the biological repetitiveness and non-random composition of the genome.
For example, the number of possible k-mers grows as follows:
| $k$ | $4^k$ | $4^k/2$ after canonicalization |
| ----: | --------------------: | -------------------------------: |
| 11 | $4.19\times10^6$ | $2.10\times10^6$ |
| 15 | $1.07\times10^9$ | $5.37\times10^8$ |
| 21 | $4.40\times10^{12}$ | $2.20\times10^{12}$ |
| 25 | $1.13\times10^{15}$ | $5.63\times10^{14}$ |
| 31 | $4.61\times10^{18}$ | $2.31\times10^{18}$ |
Canonicalization approximately halves the number of possible representations because a k-mer and its reverse complement are represented by the same canonical form.
The distinction between the simple $4^k$ model and the Karlin--Ost framework is important. The former describes the size of the combinatorial k-mer space; the latter describes the probability of observing long matches in sequences whose composition may depart from the uniform random model. Consequently, the value of $k$ cannot be selected from genome size alone.
These scales have very different implications for different genome sizes.
The random-sequence calculation is only a null model. Real genomes exhibit strong and reproducible oligonucleotide composition biases. Karlin and colleagues showed that relative abundances of short oligonucleotides, in particular dinucleotides, form characteristic genomic signatures that remain relatively stable within genomes and differ between organisms [@Karlin1995; @Karlin1997]. More generally, short k-mer frequencies can therefore capture compositional properties of genomes rather than provide highly specific sequence identifiers.
This distinction is important for whole-genome k-mer comparison. Increasing $k$ increases the theoretical diversity of the k-mer space exponentially and generally increases the proportion of k-mers that occur at unique genomic positions. Conversely, shorter k-mers occur more frequently and are more strongly influenced by genomic composition and repeated sequence. Empirical studies of k-mer spectra show this transition clearly: for example, k-mers of length $k\leq11$ can behave primarily as genomic-composition signatures, whereas longer k-mers progressively provide greater sequence specificity.
The supported range $11\leq k\leq31$ should therefore be understood as an engineering compromise rather than as a universal biological optimum. Smaller values increase the probability that unrelated genomic regions share the same k-mers, while larger values increase specificity but also make the representation more sensitive to substitutions, indels, and incomplete homology. The appropriate value within this range consequently depends on the biological scale and comparison task.
This gives the hard representation limit: $k \leq 32.$ Furthermore,
OBIKmer only considers odd values of $k$, meaning the largest supported
k-mer size is $31$.
## Odd k-mer lengths
OBIKmer additionally requires $k$ to be odd. This constraint is independent of the resolution argument above.
OBIKmer additionally requires $k$ to be odd. This constraint is
independent of the specificity considerations discussed below.
For an odd-length DNA sequence, a k-mer cannot be identical to its own reverse complement. Consequently, every k-mer has two distinct orientations, which can be unambiguously collapsed into a canonical representation. For even $k$, self-reverse-complementary sequences exist, so a k-mer can coincide with its own reverse complement.
For an odd-length DNA sequence, a k-mer cannot be identical to its own
reverse complement. Every k-mer therefore belongs to a pair of distinct
orientations, which can be represented by a single canonical k-mer. For
even $k$, self-reverse-complementary sequences exist.
Odd $k$ is therefore **not required for canonicalization itself**: the canonical form
Odd $k$ is not required for canonicalization itself: the canonical form
$$
s^c=\min_{\mathrm{lex}}\left(s,\operatorname{RC}(s)\right)
$$
remains well defined for even $k$. The odd-$k$ restriction instead guarantees that the two orientations are always distinct, which simplifies the representation and orientation handling used by OBIKmer.
is well defined for both odd and even lengths. Restricting $k$ to odd
values guarantees that the two orientations are always distinct,
simplifying the representation and orientation handling used by OBIKmer.
## Karlin--Ost (1988) formula
## K-mer specificity
[@Karlin1988] considers $s$ independent stationary letter sequences over a finite alphabet and studies $K_{r,s}(N)$, the length of the longest word common to $r$ of the $s$ sequences, each of length $N$. For i.i.d. equiprobable letters over an alphabet of size $m$ (here $m=4$ for DNA), the characteristic local match parameter reduces to
A simple way to illustrate the effect of k-mer size is to consider a
random DNA sequence in which the four nucleotides are independent and
equally probable. There are $4^k$ possible oriented k-mers, so the
expected number of occurrences of a particular oriented k-mer in a
sequence of length $G$ is approximately $G/4^k$. For canonical k-mers,
the corresponding number of possible sequences is halved, and the
expected number of occurrences is approximately $2G/4^k$.
Increasing $k$ therefore reduces the probability that a particular k-mer
occurs by chance. However, the probability of a match somewhere in a
collection of sequences also depends on the amount of sequence searched
and on the number of possible k-mers considered. The following sections
formalize this distinction and describe how chance sharing can be
assessed across an indexed set of genomes.
## Choosing an appropriate k-mer size
The theoretical k-mer space grows exponentially with $k$. Thus, increasing $k$ from 11 to 31 greatly expands the sequence space and reduces the probability that unrelated sequences share a particular k-mer by chance. The following table gives the size of the theoretical k-mer space and, after canonicalization, the number of distinct representations.
| $k$ | $4^k$ | $4^k/2$ after canonicalization |
|---:|---:|---:|
| 11 | $4.19\times10^6$ | $2.10\times10^6$ |
| 15 | $1.07\times10^9$ | $5.37\times10^8$ |
| 21 | $4.40\times10^{12}$ | $2.20\times10^{12}$ |
| 25 | $1.13\times10^{15}$ | $5.63\times10^{14}$ |
| 31 | $4.61\times10^{18}$ | $2.31\times10^{18}$ |
Genome sizes illustrate the range of sequence scales for which k-mers may be used. Bacterial genomes are typically a few megabases long, although some symbiotic bacteria have much smaller genomes, while other bacteria have genomes exceeding ten megabases. Plant genomes span an even wider range, from tens of megabases to more than one hundred gigabases. In very large and repeat-rich genomes, the main limitation is not necessarily the exhaustion of the theoretical k-mer space, but the non-uniform distribution of k-mers caused by sequence composition and repeated DNA.
The supported range $11\leq k\leq31$ should therefore be understood as an engineering and application-oriented compromise, not as a universal biological optimum. Shorter k-mers are more likely to be shared by unrelated regions, whereas longer k-mers provide greater sequence specificity. However, longer k-mers are also more sensitive to substitutions and indels: a single difference can disrupt an exact match across the whole k-mer. The appropriate value within the supported range consequently depends on the size and characteristics of the genomes being compared, as well as on the biological question.
The following section introduces a random-sequence model to quantify the probability of chance sharing across an indexed set of genomes. This provides a formal basis for assessing how the choice of $k$ affects the interpretation of shared k-mers.
## Chance sharing across genomes
OBIKmer indexes distinct canonical k-mers and records the genomes in
which each k-mer occurs. This makes it possible to compare the observed
sharing of k-mers with the sharing expected under a random-sequence
model. The same probability model can be used for two related purposes:
measuring the excess of sharing among k-mers present in the index, and
estimating the number of chance k-mers among those shared by at least a
specified number of genomes.
### The null model and genome-specific probabilities
The null hypothesis assumes that the $S$ indexed genomes are unrelated
and that each genome is an independent random sequence in which
nucleotides are independent and equiprobable.
Since OBIKmer uses odd-length canonical k-mers, reverse-complement
canonicalization reduces the number of possible k-mers by half. The size
of the canonical k-mer space is therefore
$$
\lambda^{[r]} = m^{1-r},
M_k=\frac{4^k}{2}.
$$
so for $r=2$ (a word shared by two occurrences), $\lambda = m^{-1} = 1/4$.
The expected number of common words of length $k$ among the $\binom{s}{r}$ relevant groups of sequences is
Let $N_i$ be the number of distinct canonical k-mers recorded for genome
$i$ in the index. Under the null model, these can be regarded as a
uniform sample without replacement from the $M_k$ possible canonical
k-mers. The probability that a given canonical k-mer is present in
genome $i$ is then
$$
S_1(N,k) = N^{r}\binom{s}{r}\gamma\,\lambda^{k}\,(1+o(1)),
p_i=\frac{N_i}{M_k}=\frac{2N_i}{4^k}.
$$
with $\gamma=1$ exactly in the i.i.d. equiprobable case. Theorem 2.2 gives the limiting distribution of $K_{r,s}(N)$, with $k$ set on the scale $k=\left[\dfrac{\log N^{r}}{-\log\lambda^{*}}+x+1\right]$:
This is the inclusion probability for a distinct k-mer. It differs from
the probability of at least one occurrence in a positional model,
because repeated occurrences within a genome are not counted separately.
Let $X$ denote the number of genomes, among the $S$ indexed genomes,
that contain a given canonical k-mer under the null model. Since genomes
are assumed to be independent, $X$ is a sum of independent presence
indicators with probabilities $p_1,\ldots,p_S$. When these probabilities
differ, $X$ follows a Poisson-binomial distribution.
### Computing the Poisson-binomial distribution
The distribution of $X$ can be computed by processing genomes one at a
time. Let $P_i(j)$ denote the probability that the k-mer occurs in
exactly $j$ of the first $i$ genomes. Initially,
$$
\lim_{N\to\infty}\left[\Pr\{K_{r,s}(N)<k\} - \exp\{-(1-\lambda^{*})\,S_1(N,k)\}\right] = 0,
P_0(0)=1,\qquad P_0(j)=0 \quad (j>0).
$$
equivalently
When genome $i$ is added, the k-mer is either absent, with probability
$1-p_i$, or present, with probability $p_i$. Thus,
$$
\frac{-\log\Pr\{K_{r,s}(N)<k\}}{(\lambda^{*})^{\rho(N,x)}} \xrightarrow[N\to\infty]{} (1-\lambda^{*})\,\gamma^{*}(\lambda^{*})^{x}.
P_i(j)=(1-p_i)P_{i-1}(j)+p_iP_{i-1}(j-1).
$$
The factor $(1-\lambda^{*})$ multiplying $S_1(N,k)$ is the key correction over the naive pairwise-collision count: it de-clumps overlapping candidate matches, which are not independent events, into an effective Poisson rate. This theorem is stated for $s\geq2$ independent sequences (e.g. comparing two distinct genomes); the intra-sequence self-repeat case (a single genome compared to itself) is treated separately, via the reverse-complement match length $R(N)$, in [@Karlin1985].
$o(1)$ (« petit o de 1 ») désigne une quantité qui **tend vers 0 quand $N\to\infty$**, mais dont on ne précise pas la vitesse exacte ni la formule exacte. C'est une façon d'écrire « il reste un terme d'erreur, mais il devient négligeable ».
Concrètement dans $S_1(N,k) = N^{r}\binom{s}{r}\gamma\,\lambda^{k}\,(1+o(1))$ :
- $N^{r}\binom{s}{r}\gamma\,\lambda^{k}$ est la valeur **exacte à la limite**, celle qu'on utilise en pratique (c'est elle qui redonne $E[C]$ de notre discussion).
- $(1+o(1))$ dit : « la vraie valeur de $S_1(N,k)$ n'est pas *exactement* égale à ce produit pour $N$ fini, mais le rapport entre les deux tend vers 1 quand $N\to\infty$ ». Autrement dit $S_1(N,k) / \left[N^{r}\binom{s}{r}\gamma\lambda^{k}\right] \to 1$.
Pourquoi ce terme existe : la formule $F_\sigma(k)/\lambda^k \to \gamma$ (éq. 2.8 du papier) est elle-même une limite quand $k\to\infty$ — pour $k$ fini, il y a un petit écart entre $F_\sigma(k)$ et $\gamma\lambda^k$. C'est cet écart-là qui devient le $o(1)$.
Ce que ça implique pour l'usage pratique : dans le cas iid équiprobable que tu utilises (ADN, $\gamma=1$ exactement, pas seulement à la limite — je l'ai vérifié directement sur la dérivation : $F_\sigma(k)=m^{-k}=\lambda^k$ pour tout $k$, pas juste asymptotiquement), le $o(1)$ est en réalité **nul** dans ce cas précis, pas juste négligeable. La formule $S_1(N,k)=N^r\binom{s}{r}\lambda^k$ est donc exacte (à l'asymptotique en $N$ près, qui elle vient d'ailleurs — de l'approximation de Poisson elle-même, pas de ce $\gamma$).
Les deux approches sont légitimes, mais elles répondent à des questions différentes — et il y a une relation algébrique exacte entre les deux qui vaut la peine d'être explicitée.
**Ce que calcule l'approche naïve.** Pour **un k-mer $w$ déjà observé et fixé**, $p_i\simeq1-\exp(-G_i/4^k)$ est la probabilité que *ce mot précis* apparaisse quelque part dans le génome $i$ par hasard, et $P(R\geq r)$ (Poisson-binomiale ou binomiale) est la probabilité que *ce mot précis* soit partagé par au moins $r$ des $S$ génomes par hasard. C'est une **p-value par observation** : « j'ai vu ce k-mer particulier dans 5 génomes sur 10, est-ce surprenant pour lui ? »
**Ce que calcule Karlin-Ost.** $S_1(k)$ et $P(K_{r,s}\geq k)$ répondent à : « parmi **tous les $4^k$ mots possibles**, quelle est la probabilité qu'au moins un seul d'entre eux atteigne ce seuil de partage par hasard, n'importe où dans les génomes ? » C'est une question **globale sur tout l'espace des k-mers**, pas sur un mot déjà identifié.
**La relation exacte entre les deux.** Reprenons le cas $r=s=2$, génomes égaux de taille $G$ :
- Naïf (mot $w$ fixé) : $P(R=2\mid w)\simeq p^2=(G\cdot4^{-k})^2=G^2\cdot4^{-2k}$
- Karlin-Ost : $S_1=G^2\cdot4^{-k}$
Le rapport est exactement $S_1 / P(R=2\mid w) = 4^{k}$ — c'est-à-dire le nombre de mots possibles. Ce n'est pas une coïncidence : $S_1=N^r\binom{s}{r}\lambda^k$ vient de $\lambda^k=\sum_w \Pr\{w\}^r$, une somme explicite sur les $4^k$ mots, alors que le calcul naïf tel que présenté ne somme sur rien — il traite $w$ comme donné.
**Donc l'approche naïve, formellement, c'est Karlin-Ost auquel il manque le facteur « nombre de k-mers testés ».** Pour la rendre comparable à la question « dois-je m'attendre à *une* collision fortuite n'importe où dans mon jeu de données », il faudrait une correction à la Bonferroni : multiplier $P(R\geq r\mid w)$ par le nombre effectif de k-mers canoniques testables ($\approx4^k/2$). Karlin-Ost fait cette correction analytiquement et correctement (avec en prime le facteur de déclumping $(1-\lambda)$ qu'on a discuté, qui corrige le sur-comptage des matches chevauchants — une union bound brute comme le Bonferroni décrit ci-dessus le surestimerait légèrement).
**Ce qui veut dire, en pratique, que les deux outils ne sont pas concurrents mais complémentaires :**
- **Choix a priori de $k$ / FPR global du dataset** (la question de `kmers.md` depuis le début de cette conversation) → Karlin-Ost, parce qu'il intègre nativement la multiplicité sur tous les mots possibles.
- **Score de significativité a posteriori pour un k-mer effectivement observé dans l'index** (« ce hit précis, présent dans $r$ génomes sur $S$, est-il compatible avec le hasard ? ») → l'approche Poisson-binomiale est exactement le bon outil, et même préférable à Karlin-Ost pour cet usage : elle gère nativement des $G_i$ inégaux sans les subtilités de convergence du théorème 2.2, et elle donne directement une p-value par hit exploitable pour filtrer les résultats d'un index présence/absence — ce qui correspond bien à l'usage qu'a en tête ton correspondant.
Une seule réserve sur le texte proposé tel quel : $p_i\simeq1-\exp(-G_i/4^k)$ souffre du même biais que celui identifié plus tôt dans notre discussion — un mot de longueur $k$ n'est pas indépendant à chaque position (chevauchement), donc ce $p_i$ est un peu optimiste (légèrement trop haut) pour les mêmes raisons que $E[C]$ l'était. Négligeable pour $k\geq21$, plus discutable à $k=11$.
## Chance sharing across genomes and the FDR of homology
The formulas above ask how likely a match is between two sequences. The question OBIKmer actually has to answer is different: a k-mer is found in $r$ of the $S$ indexed genomes, and one wants to know whether this sharing can be explained by chance or whether it is evidence of homology. This section builds a null model for that question and turns it into a false discovery rate (FDR) for the call "a k-mer shared by at least $r$ genomes is homologous".
### The null model
The null hypothesis is that the $S$ genomes are unrelated, that is, that each one is an independent random sequence. Rejecting it for a k-mer means that chance alone cannot explain why the k-mer is shared, which is the signal of homology one is looking for.
The model only records whether a k-mer is present in a genome, not how many times. Two consequences follow. First, repeats inside a genome are irrelevant, and the size $G_i$ of genome $i$ is its number of **distinct canonical k-mers**. Second, a repeat family shared between genomes is paralogy, which is a form of homology; it is a true positive and not a false one. The only k-mers that could be shared by composition rather than by descent are low-complexity ones, which OBIKmer removes beforehand with its entropy filter.
Everything takes place in canonical space. Because $k$ is odd, no k-mer equals its own reverse complement, so the $4^k$ k-mers pair up perfectly and the space contains exactly
This recurrence avoids enumerating the subsets of genomes. Computing the
complete distribution requires $O(S^2)$ operations and $O(S)$ memory. To
compute the upper-tail probability, only the probabilities for fewer
than $r$ presences need to be tracked:
$$
N=\frac{4^k}{2}
P_{\mathrm{null}}(X\geq r)=1-\sum_{j=0}^{r-1}P_S(j).
$$
canonical k-mers. A given canonical k-mer is present in genome $i$ by chance with probability
The computation can therefore be restricted to $P_i(0),\ldots,P_i(r-1)$,
requiring $O(Sr)$ operations and $O(r)$ memory. The resulting
distribution depends on the genome-specific values $N_i$, but not on the
identity of the k-mer, and can thus be computed once for a given index
and k-mer length.
### Comparing observed and expected sharing in the index
The index contains only k-mers observed in at least one genome.
Consequently, when comparing sharing proportions among the k-mers
recorded in the index, the relevant null probability is conditional on
at least one presence:
$$
p_i = 1-\left(1-\frac1N\right)^{G_i}\simeq \frac{G_i}{N}=\frac{2\,G_i}{4^k}.
q_r=P(X\geq r\mid X\geq 1)
=\frac{P_{\mathrm{null}}(X\geq r)}{P_{\mathrm{null}}(X\geq 1)}.
$$
This is twice the $G/4^k$ used earlier in this page, because there $G$ is a number of positions on one strand, whereas $G_i$ here counts canonical k-mers, for which both strands are already merged.
Let $R$ be the number of genomes, out of $S$, that contain a given canonical k-mer by chance. Genomes are independent under the null, so $R$ is a sum of independent presence indicators, each with its own probability $p_i$.
### Exact tail probability
When genome sizes differ, the $p_i$ differ, and $R$ follows a Poisson-binomial distribution. Writing the probability of exactly $j$ presences as a sum over all subsets of $j$ genomes would be hopeless, since there are up to $2^S$ subsets. The distribution is instead obtained by adding the genomes one at a time. Let $d_j$ be the probability that exactly $j$ of the genomes processed so far contain the k-mer. Adding genome $i$ leaves $j$ unchanged if the genome does not contain the k-mer, and moves $j-1$ to $j$ if it does:
Let $n_{\geq r}$ be the number of distinct canonical k-mers observed in
at least $r$ genomes, and let $n_{\geq 1}$ be the total number of
distinct canonical k-mers recorded in the index. The observed proportion
of indexed k-mers shared by at least $r$ genomes is
$$
d'_j = d_j\,(1-p_i) + d_{j-1}\,p_i, \qquad d_0=1 \text{ before the first genome.}
O_r=\frac{n_{\geq r}}{n_{\geq 1}}.
$$
The table $d$ only needs to remember how many genomes were hit, not which ones, and this brings the cost down to $O(S^2)$. The result does not depend on the order in which the genomes are processed. It does not depend on the k-mer either, so it is computed once per index. The upper tail is then
Under the random-sequence model, the expected proportion is $q_r$. The
difference
$$
P_0(R\geq r) = 1-\sum_{j=0}^{r-1} d_j .
D_r=O_r-q_r
$$
Only $d_0,\dots,d_{r-1}$ are needed, so the cost is $O(S\,r)$.
therefore measures the excess or deficit of sharing relative to the null
expectation. Positive values indicate that k-mers are shared across
genomes more frequently than expected by chance, whereas negative values
indicate less frequent sharing. A value of zero indicates agreement with
the random-sequence model.
### Approximation with equal genome sizes
If all genomes are given the same size, taken as the mean
Since both $O_r$ and $q_r$ are proportions between zero and one, $D_r$
is bounded:
$$
\bar G=\frac1S\sum_{i=1}^{S}G_i, \qquad \bar p=\frac{2\bar G}{4^k},
-1\leq D_r\leq 1.
$$
then $R$ follows a plain binomial distribution and the tail is
More precisely, for a given $q_r$, its bounds are $-q_r$ and $1-q_r$. By
construction, $D_1=0$, since all k-mers recorded in the index occur in
at least one genome. Unlike a ratio-based measure, this difference
remains defined when no k-mers are observed in at least $r$ genomes.
### Estimating the false discovery rate
The probability $P_{\mathrm{null}}(X\geq r)$ applies to one specified canonical k-mer.
To estimate the number of k-mers that could reach this sharing threshold
by chance across the entire canonical k-mer space, this probability must
be considered over all $M_k$ possible canonical k-mers.
The expected number of chance k-mers present in at least $r$ genomes is
$$
P_0(R\geq r)\simeq\sum_{j=r}^{S}\binom{S}{j}\,\bar p^{\,j}(1-\bar p)^{S-j}.
E[\mathrm{FP}(r)]=M_kP_{\mathrm{null}}(X\geq r).
$$
This sum is the regularized incomplete beta function $I_{\bar p}(r,\,S-r+1)$, available in standard statistical libraries. If it is summed by hand, the terms are obtained one from the next by $t_{j+1}=t_j\,\frac{S-j}{j+1}\,\frac{\bar p}{1-\bar p}$.
A theorem of Hoeffding [@Hoeffding1956-bx] shows that this approximation errs on the safe side. For a fixed mean, the Poisson-binomial distribution is more concentrated than the binomial one, so for $r\geq S\bar p+1$ the binomial tail is never smaller than the exact tail. Using the mean genome size therefore overestimates the chance of sharing and can only make the FDR more pessimistic. Gleser [@Gleser1975-yu] refines this result: replacing the $p_i$ by any partial average of themselves, not only by their full mean, also moves the upper tail towards the binomial one, provided $r-1\geq S\bar p+2$. Grouping genomes of similar size is therefore safe in the same sense. What it loses is power when genome sizes differ by orders of magnitude, since one large genome then weighs as much as several small ones in $\bar p$.
When all $p_i$ are small, which is the case for large $k$, the number of hits is also well approximated by a Poisson distribution of mean $\lambda=\sum_i p_i$, with an error bounded by $\sum_i p_i^2$ [@Le-Cam1960-pe].
For the numerical evaluation, the tail that does not contain the mode $S\bar p$ should be summed directly. When $r>S\bar p$, computing the sum from $j=r$ upwards is accurate even for very small probabilities, whereas computing $1$ minus the sum of the lower terms loses all precision once the tail falls below the machine epsilon.
### False discovery rate
The FDR of the call "present in at least $r$ genomes" is the fraction of retained k-mers expected to be pure chance:
The observed number of k-mers passing the threshold is $n_{\geq r}$. An
estimate of the false discovery rate (FDR) for this set is therefore
$$
\widehat{\mathrm{FDR}}(r)=\min\!\left(1,\ \frac{N\,P_0(R\geq r)}{n_{\geq r}}\right).
\widehat{\mathrm{FDR}}(r)=
\begin{cases}
1 & \text{if } n_{\geq r}=0,\\[4pt]
\displaystyle
\min\left(1,
\frac{M_k P_{\mathrm{null}}(X\geq r)}
{n_{\geq r}}\right)
& \text{otherwise}.
\end{cases}
$$
The numerator is the number of k-mers expected to reach $r$ genomes by chance if the genomes were unrelated. Each of the $N$ canonical k-mers has probability $P_0(R\geq r)$ of doing so, and no further correction for multiple testing is needed because the number of tests is already in the product. The denominator $n_{\geq r}$ is the number of distinct k-mers actually observed in at least $r$ genomes, which is read directly from the index. The observed count mixes chance and true homology, so the ratio is an upper bound on the true FDR: it implicitly assumes that all k-mers are null, and it never underestimates the noise. The minimal $r$ for which $\widehat{\mathrm{FDR}}(r)$ falls below the accepted level, for example 5 %, is the sharing threshold to use.
The numerator estimates the number of false positives under the null
model, while the denominator is the observed number of k-mers passing
the sharing threshold. This estimate assumes that all possible canonical
k-mers are subject to the null model. It is therefore conservative in
the sense that it does not attempt to estimate the proportion of the
k-mer space corresponding to true homology. The estimate is capped at
one because a proportion cannot exceed one.
As an illustration, take $k=21$ (so $N=2.2\times10^{12}$), $S=10$ genomes and $G_i=10^9$ distinct canonical k-mers each, hence $p=4.5\times10^{-4}$. The number of k-mers expected to be shared by chance is:
The distinction between $D_r$ and the FDR is important. $D_r$ compares
the observed and expected proportions among k-mers already present in
the index. The FDR estimate instead compares the expected number of
chance k-mers in the entire canonical k-mer space with the observed
number passing the sharing threshold.
| $r$ | $N\,P_0(R\geq r)$ |
The smallest value of $r$ for which $\widehat{\mathrm{FDR}}(r)$ falls
below a chosen threshold, for example 5%, can be used as a minimum
sharing threshold. This interpretation is conditional on the assumptions
of the null model and should not be taken as a model-independent
guarantee of the biological false discovery rate.
As an illustration, consider $k=21$, for which
$M_k\simeq2.2\times10^{12}$, and an index containing $S=10$ genomes.
Suppose that the numbers of distinct canonical k-mers in these genomes
range from $0.5\times10^9$ to $1.4\times10^9$, in increments of
$0.1\times10^9$. Applying the Poisson-binomial model with the
corresponding genome-specific probabilities gives the following
expected numbers of k-mers shared by chance:
| $r$ | $M_kP_{\mathrm{null}}(X\geq r)$ |
| ---: | ---: |
| 2 | $2\times10^{7}$ |
| 3 | $2.5\times10^{4}$ |
| 4 | $\approx 20$ |
| 5 | $\approx 0.01$ |
| 2 | $1.82\times10^7$ |
| 3 | $2.06\times10^4$ |
| 4 | $15$ |
| 5 | $0.0075$ |
Chance alone produces millions of pairwise shared 21-mers at this genome size, a few tens of thousands shared by three genomes, and almost none shared by five or more. Whether a given $r$ is acceptable then depends on how many k-mers the index actually reports at that level.
In this example, chance alone can produce many pairwise shared 21-mers,
whereas the expected number of k-mers shared by five or more genomes is
very small. Whether a given sharing threshold is sufficiently stringent
depends on the number of k-mers actually observed at that level.
### Limits of the model
- The FDR is computed per k-mer. Neighbouring k-mers of a shared region overlap and are not independent, so a single homologous region contributes many correlated k-mers. A per-region FDR would count regions instead of k-mers and is not covered here.
- The probability $p_i$ assumes equiprobable, independent nucleotides. The composition biases discussed earlier in this page violate this assumption, and the resulting error is not accounted for.
The FDR estimate is based on a simplified null model and has two
important limitations.
---
First, the model assumes independent, equiprobable nucleotides. Real
genomes exhibit nucleotide-composition biases, oligonucleotide
dependencies, and repeated sequences. These properties can increase the
probability of particular k-mers beyond the uniform expectation.
Removing low-complexity k-mers reduces some of these effects but does
not eliminate all compositional biases. Karlin and colleagues showed
that relative oligonucleotide abundances, including dinucleotide
frequencies, form characteristic genomic signatures that can differ
between organisms and remain relatively stable within genomes
[@Karlin1995-lt; @Karlin1994-on].
Je n'ai rien modifié. Voici la formalisation des deux points, à valider avant de l'écrire dans `kmers.md`.
## 1. FDR d'un ensemble de k-mers sélectionnés
**Estimation de l'espérance du nombre de faux positifs.** Soit $M$ le nombre de k-mers canoniques testés, $M = 4^k/2$ pour k impair. Soit $q(r)=P(X\ge r)$ la queue du modèle nul. Le nombre attendu de k-mers présents par hasard dans au moins $r$ génomes vaut
$$
E[\mathrm{FP}(r)] = M\,q(r).
$$
Cette égalité est exacte par linéarité de l'espérance, même si les k-mers chevauchants sont dépendants. La dépendance n'affecte que la variance, pas l'espérance. Seule l'approximation de Poisson par génome reste une approximation.
**FDR.** Soit $N(r)=\#\{i : r_i\ge r\}$ le nombre observé de k-mers couvrant au moins $r$ génomes. Alors
$$
\mathrm{FDR}(r)=\min\!\Big(1,\ \frac{M\,q(r)}{N(r)}\Big).
$$
Cette estimation est légèrement conservatrice. Elle suppose $\pi_0=1$, c'est-à-dire que presque tout l'espace $M$ est nul, ce qui est vrai pour k grand.
**Ensemble hétérogène en $r_i$.** Si le jeu n'est pas défini par un seuil unique, on utilise le local fdr par classe de couverture :
$$
\mathrm{fdr}(r)=\frac{M\,P(X=r)}{N_r},\qquad N_r=\#\{i : r_i=r\}.
$$
Le FDR de l'ensemble est alors la moyenne $\frac1N\sum_i \mathrm{fdr}(r_i)$. Pour un ensemble défini par seuil $r_{\min}$, cela redonne exactement la formule précédente.
**Remarque.** $M\,p\approx G$, d'où $E[\mathrm{FP}(r)]\approx\binom{S}{r}\,G^r/M^{r-1}$ en régime de petits $p$. Cela donne une lecture directe de la quantité.
## 2. Markov d'ordre 0 avec fréquences inégales
Soit $\pi_b$ la fréquence du nucléotide $b$. Pour un k-mer $w$ de composition $n=(n_A,n_C,n_G,n_T)$ avec $\sum n_b=k$, on a $P(w)=\prod_b \pi_b^{n_b}$.
**Attendu par génome.** Le k-mer canonique $K=\{w,\overline w\}$ est vu quand le brin direct porte $w$ ou $\overline w$, donc
$$
\lambda_K = G\,\big(P(w)+P(\overline w)\big)=G\Big(\prod_b\pi_b^{n_b}+\pi_A^{n_T}\pi_T^{n_A}\pi_C^{n_G}\pi_G^{n_C}\Big).
$$
Cela ne dépend que de la composition. Si $\pi_A=\pi_T$ et $\pi_C=\pi_G$, on retrouve $2P(w)$.
**Faux positifs.** Le test n'est plus homogène : chaque composition a sa propre $p(n)=1-e^{-\lambda(n)}$. Il faut donc sommer sur les classes de composition (un k-mer et son complément inverse partagent le même $\lambda$, d'où le facteur ½) :
$$
E[\mathrm{FP}(r)]=\frac12\sum_{n}\binom{k}{n_A,n_C,n_G,n_T}\,P\big(X\ge r\mid p(n)\big).
$$
Cette somme porte sur $\binom{k+3}{3}$ compositions, soit 5 984 pour k = 31. Elle est donc légère avec la binomiale de la moyenne, ou avec une Poisson-binomiale par composition si les $G_i$ diffèrent. Si les $\pi_b$ varient d'un génome à l'autre (GC différent), les $p_i(n)$ se construisent par génome.
**Effet attendu.** La moyenne de $\lambda_w$ sur tous les k-mers reste $2G/4^k$, car $\sum_w P(w)=1$. Dans le régime de petits $p$, le terme dominant $\binom{S}{r}p^r$ est convexe en $\lambda$. Par Jensen, le modèle équiprobable est donc le minimum de $E[\mathrm{FP}]$, et la déviation de composition ne peut qu'augmenter le FDR. Les k-mers riches en AT ou GC dominent la somme, ce qui rejoint ton remarque sur la faible complexité. C'est un résultat sur le terme dominant, pas une preuve pour la queue exacte.
**Limites à signaler dans le texte.** Markov 0 ignore les dinucléotides, comme les CpG ou les répétitions, et le $M$ du modèle nul reste celui de l'espace total.
Veux-tu que j'écrive ces deux sections, avec les corrections de numérique évoquées plus haut (`expm1`, somme directe de la queue) ?
Second, the FDR is computed per k-mer. Consecutive k-mers extracted from
the same homologous region overlap and are therefore not independent
observations. A single homologous region can contribute many correlated
k-mers to the index. The estimate presented here consequently describes
the expected fraction of chance k-mers, not the fraction of false
homologous regions. A region-level FDR would require a model that treats
matching regions, rather than individual k-mers, as the units of
observation.
@@ -32,7 +32,7 @@ Applying the minimizer to consecutive k-mers partitions a sequence into super-km
## Hash-based minimizer ordering
`obikmer` selects minimizers by hash order rather than plain lexicographic order. Ordering m-mers lexicographically on their 2-bit encoding systematically favors AT-rich m-mers (an all-A m-mer always encodes to 0), which causes low-complexity regions to dominate as minimizers and produces unbalanced partitions [@Zheng2020-ji; @Zheng2021-cc; @Pan2024-hb; @Kille2023-px; @Golan2025-xf].
`obiskim` selects minimizers by hash order rather than plain lexicographic order. Ordering m-mers lexicographically on their 2-bit encoding systematically favors AT-rich m-mers (an all-A m-mer always encodes to 0), which causes low-complexity regions to dominate as minimizers and produces unbalanced partitions [@Zheng2020-ji; @Zheng2021-cc; @Pan2024-hb; @Kille2023-px; @Golan2025-xf].
Instead, a well-distributed hash function $H$ is applied to the canonical (lexicographically minimal) form of each m-mer, and the m-mer with the smallest $H$ value wins. Because $H$ is a bijective mixing function with good avalanche properties [@Steele2014-cz], its output behaves approximately as a composition-independent pseudorandom ordering of distinct m-mers. Under the usual random-hash assumption, each distinct m-mer in a window has approximately the same probability of being the minimum, independently of nucleotide composition.
@@ -34,7 +34,7 @@ $$
D = \sum_i \mathbb{1}[a_i \ne b_i],
$$
where $a_i,b_i\in\{0,1\}$ indicate the presence of k-mer $i$ in the two genomes. It counts the number of k-mers for which the two incidence vectors differ, without normalization by the size of the k-mer space. As an $L^1$ distance, Hamming distance is a metric. Unlike abundance-based measures, it cannot be recovered from k-mer counts alone once the presence/absence representation has been discarded.
where $a_i,b_i\in\{0,1\}$ indicate the presence of k-mer $i$ in the two genomes. It counts the number of k-mers for which the two incidence vectors differ, without normalization by the size of the k-mer space. As an $L^1$ distance, Hamming distance is a metric. Unlike abundance-based measures, it cannot be recovered from k-mer counts alone once the presence/absence representation has been discarded. On an index that stores counts, a k-mer is taken as present when its count reaches the presence threshold (`--presence-threshold`, 1 by default).
**Mash** is not an independent set dissimilarity but a nonlinear transformation of the Jaccard similarity [@Ondov2016-dq]. If
@@ -22,6 +22,6 @@ $$\hat\alpha = \frac{\hat\mu^2}{V - \hat\mu/\bar L}$$
If the measured variance $V$ doesn't exceed the Poisson floor $\hat\mu/\bar L$ (no detectable over-dispersion across partitions — the data are consistent with a single shared rate), $\alpha$ is left undefined: the correction is silently disabled for that run rather than applying a fabricated value, and a warning is logged.
**This is not Jin & Nei's (1990) original estimator.** Their publication defines the $+\Gamma$ distance formula itself and, absent an estimate, recommends the fixed default $\alpha = 1$ — it does not propose a way to estimate $\alpha$ from data. The method-of-moments estimator above is a standard consequence of the Poisson–Gamma relationship between substitution counts and gamma-distributed rate variation, applied per-partition; it is `obikmer`'s own addition, not part of the cited correction.
**This is not Jin & Nei's (1990) original estimator.** Their publication defines the $+\Gamma$ distance formula itself and, absent an estimate, recommends the fixed default $\alpha = 1$ — it does not propose a way to estimate $\alpha$ from data. The method-of-moments estimator above is a standard consequence of the Poisson–Gamma relationship between substitution counts and gamma-distributed rate variation, applied per-partition; it is `obiskim`'s own addition, not part of the cited correction.
See [`phylo`](../../../usage/phylo.md#distance-matrix---distance) for how to select a fixed $\alpha$ or request automatic estimation.
See [`phylo`](../../../usage/phylo.md#distance-estimation-and-tree-reconstruction) for how to select a fixed $\alpha$ or request automatic estimation.
@@ -21,7 +21,7 @@ A family where every genome carries the same single state has entropy 0 (uninfor
## Quartet restriction
A family only constrains the shape of a tree if its carrier genomes show a bipartition: two distinct states, each carried by at least two genomes. With fewer carriers, or with a single variant against a uniform background, every topology explains the family equally well. In a skimming dataset many families have only two or three carriers, so a uniform draw spends a large share of its quota on them. `--quartet` removes them before the draw. The test counts called states only, so absence never forms one of the two pairs.
A family only constrains the shape of a tree if its carrier genomes show a bipartition: two distinct states, each carried by at least two genomes. With fewer carriers, or with a single variant against a uniform background, every topology explains the family equally well. In a skimming dataset many families have only two or three carriers, so a uniform draw spends a large share of its quota on them. `--quartet` removes them before the draw. The test counts the states of the alignment: without `--free-loss`, absence is a state like any other and can form one of the two pairs; with `--free-loss` it is missing data and never does.
## Pair balance
@@ -31,4 +31,4 @@ How well a pair of genomes is represented in a sample depends on how many famili
By default, sampling draws families uniformly. Weighting instead by informativeness biases the draw toward a target entropy $\mu$ with a Gaussian curve of width $\sigma$: a family's probability of being kept scales with $\exp\!\left(-\dfrac{(\text{entropy15} - \mu)^2}{2\sigma^2}\right)$ — a soft preference, not a hard cutoff, so no family is categorically excluded purely for having low or high entropy.
See [`phylo`](../../../usage/phylo.md#sampling-at-scale---n-sites---shannon---entropy) for how to bound and bias the sample, and for session/checkpointing behavior.
See [`phylo`](../../../usage/phylo.md#snp-character-selection-and-sampling) for how to bound and bias the sample.
+2 -2
View File
@@ -3,8 +3,8 @@
Add or update genome metadata of an index from a CSV file, or dump the current metadata as CSV.
```bash
obikmer annotate INDEX --csv FILE [OPTIONS]
obikmer annotate INDEX --dump
obiskim annotate INDEX --csv FILE [OPTIONS]
obiskim annotate INDEX --dump
```
## Arguments
+1 -1
View File
@@ -3,7 +3,7 @@
Convert an existing index's evidence representation in place, between exact, approximate, and hybrid.
```bash
obikmer convert INDEX (--exact-evidence | --approx-evidence BITS | --hybrid-evidence) [OPTIONS]
obiskim convert INDEX (--exact-evidence | --approx-evidence BITS | --hybrid-evidence) [OPTIONS]
```
## Arguments
+1 -1
View File
@@ -3,7 +3,7 @@
Dump all kmers of an index as CSV, one row per kmer, with per-genome counts or presence.
```bash
obikmer dump INDEX [OPTIONS]
obiskim dump INDEX [OPTIONS]
```
## Arguments
+34 -2
View File
@@ -1,9 +1,9 @@
# estimate
Estimate approximate-index parameters (z, evidence bits, false-positive rate) before building an index with `--approx`, without touching any files.
`estimate` has two independent uses. Without `--index`, it estimates approximate-index parameters (z, evidence bits, false-positive rate) before building an index with `--approx`, without touching any files. With `--index`, it compares the k-mer sharing observed in an existing index with the sharing expected by chance (see the last section).
```bash
obikmer estimate [OPTIONS]
obiskim estimate [OPTIONS]
```
## Options
@@ -16,3 +16,35 @@ obikmer estimate [OPTIONS]
| `--fp` | none | Target false-positive rate per z-window |
Any two of `-z`, `--evidence-bits`, `--fp` may be given; the third is derived using the same model as `index --approx` and `convert --approx-evidence` ($FP = 1 / 2^{b \cdot z}$). The report printed to stdout includes: query $k$, effective indexed $k$ ($k-z+1$), $z$, evidence bits, per-kmer false-positive rate, and per-z-window false-positive rate.
## Comparing an index with random sharing
```bash
obiskim estimate --index INDEX [--presence-threshold N] [-o FILE]
```
With `--index`, `estimate` reads an existing index instead of computing approximate-index parameters, and it cannot be combined with `-k`, `-z`, `--evidence-bits` or `--fp`. Its purpose is to tell how much of the k-mer sharing between the genomes of the index goes beyond what chance alone would produce, which is the question behind the choice of $k$ (see [K-mer size](../theory/kmer_indexing/kmers.md)).
The command writes a CSV, to standard output or to `FILE`, with one row for each $r$ from 1 to the number of genomes $S$:
| Column | Meaning |
|---|---|
| `r` | Minimum number of genomes sharing a k-mer |
| `k_r` | Number of k-mers present in at least `r` genomes |
| `O_r` | Observed proportion $k_r / k_1$ |
| `q_r` | Proportion expected by chance, $P(X \geq r \mid X \geq 1)$, where $X$ is the number of genomes containing a given k-mer under the random-sequence model |
| `D_r` | Deviation $O_r - q_r$ |
| `FP_r` | Number of k-mers expected to be present in at least `r` genomes by chance over the whole canonical k-mer space, $M_k \, P(X \geq r)$ |
| `FDR_r` | Estimated false discovery rate of the k-mers shared by at least `r` genomes: 1 when `k_r` is 0, otherwise $\min(1, \mathrm{FP}_r / k_r)$ |
A positive `D_r` means that k-mers are shared by at least `r` genomes more often than random sequences would share them; a negative value means less often. The first row always has `D_1 = 0`, because $k_1$ counts only k-mers present in at least one genome.
When no k-mer is shared by at least `r` genomes (`k_r = 0`), there is no set of k-mers whose false discovery rate could be estimated, and `FDR_r` is set to 1 by convention. This value means that nothing can be claimed at this level; it does not mean that the observed k-mers are false positives. The `FP_r` column of the same row shows how many k-mers chance alone would have produced.
The expected proportion is computed under the random-sequence model of the theory page: the genomes are unrelated, and each genome is a set of $N_i$ distinct canonical k-mers drawn without replacement and uniformly from the $M_k = 4^k/2$ canonical k-mers. A given k-mer is then present in genome $i$ with probability $p_i = N_i / M_k = 2N_i/4^k$, where $N_i$ is the number of distinct canonical k-mers considered as present in genome $i$. Genome sizes are rarely known, in particular when the index was built from unassembled reads, and the number of distinct k-mers has the advantage of being measured on the index itself and of not depending on the sequencing coverage.
Because the $N_i$ differ between genomes, the number $X$ of genomes containing a k-mer follows an exact Poisson-binomial distribution, from which $P(X \geq r)$ is obtained for every $r$ in a single pass. The approximation by a binomial distribution based on the mean genome size is not used.
`--presence-threshold` (default 1) has the same meaning as in `phylo`: on an index that stores counts, a k-mer is present in a genome only when its count reaches the threshold. Both $N_i$ and $k_r$ are computed with this same threshold, so the observed and expected proportions describe the same data. It has no effect on an index without counts.
The `k` used is the k-mer size stored in the index (for an approximate index, the effective indexed size $k-z+1$).
+1 -1
View File
@@ -3,7 +3,7 @@
Apply row-level selection to an index: retain only kmers matching ingroup/outgroup predicates over genome membership, plus optional total-count and complexity thresholds. The output is a new, single-layer index.
```bash
obikmer filter SOURCE -o OUTPUT [OPTIONS]
obiskim filter SOURCE -o OUTPUT [OPTIONS]
```
## Arguments
+9 -1
View File
@@ -3,7 +3,7 @@
Build a genome index from one or more sequence files. Construction proceeds in phases (scatter → dereplicate → count → layered MPHF), described in [On-disk storage](../formats/index_layout.md).
```bash
obikmer index -o OUTPUT [OPTIONS] [INPUTS...]
obiskim index -o OUTPUT [OPTIONS] [INPUTS...]
```
## Arguments
@@ -12,6 +12,14 @@ obikmer index -o OUTPUT [OPTIONS] [INPUTS...]
|---|---|
| `INPUTS...` | Input sequence files or directories (FASTA/FASTQ/GenBank, gzip optional). If omitted, reads from stdin. |
## Which files are read
A file named explicitly on the command line is always read, whatever its extension: the format (FASTA, FASTQ or GenBank) and the compression (gzip, bzip2, xz or zstd) are detected from the content. If the content is not a sequence file, the command reports an error rather than skipping the file.
When an input is a directory, the files inside it are selected by extension: `.fasta`, `.fa`, `.fna` (the extension of NCBI genome downloads), `.ffn`, `.fas`, `.fsa`, `.fastq`, `.fq`, `.gbff`, `.gbk` and `.gb`, each optionally followed by `.gz`.
A small input spread over many partitions leaves most partitions empty. This is valid: the index is built normally and empty partitions simply hold no k-mers.
## Options
| Option | Default | Description |
+18 -2
View File
@@ -3,7 +3,7 @@
Merge multiple built indexes into a single index.
```bash
obikmer merge -o OUTPUT SOURCE... [OPTIONS]
obiskim merge -o OUTPUT SOURCE... [OPTIONS]
```
## Arguments
@@ -20,10 +20,26 @@ obikmer merge -o OUTPUT SOURCE... [OPTIONS]
| `--force` | off | Overwrite an existing output directory |
| `--force-presence` | off | Store the merged index as presence/absence even if all sources have counts |
| `--rename-duplicates` | off | Disambiguate duplicate genome labels (`.1`, `.2`, …) instead of failing |
| `--budget-fraction` | `0.5` | Fraction of available RAM reserved as the memory budget for parallel partition merging |
| `--dense` | off | Store the merged index's presence/absence matrices in the dense packed format instead of the default sparse one (see [pack](pack.md)) |
## Behaviour
The output mode is chosen automatically: if every source index stores counts, the merged index stores counts too; otherwise it is presence/absence. `--force-presence` forces presence/absence regardless of the sources.
By default, merging two indexes that share a genome label fails with an error; `--rename-duplicates` instead appends a numeric suffix to keep both copies.
The merged index is written in the sparse packed format by default, because it is usually several times smaller on disk; `--dense` keeps the dense format, which is faster when whole genome columns are read at once, for example for distance matrices. The [pack](pack.md) page explains the trade-off between the two formats.
## Resource usage
The merge works partition by partition, and processes several partitions in parallel. Within a partition, the source indexes are read two at a time rather than all at once. The memory and the number of files mapped into memory for one partition therefore depend on how many k-mers the partition holds, not on how many indexes are being merged: merging hundreds of genomes maps about as many files per partition as merging three. The partitions do grow as more diverse genomes are added, so the total memory still rises with the size of the merged collection.
Each genome column being filled is held in memory and written to disk in one go once it is complete. A full disk or an exhausted quota is therefore reported as an ordinary error rather than crashing the program. The largest memory cost comes from the k-mers that are new to the merged index, which are assembled in memory, partition by partition, before being written out.
## Merging an index that was already merged
An index produced by `merge` can be used as one of the sources of a later merge, which is how a collection is extended without starting again from the original genomes. There is one rule: among the sources, at least one must not have been through a merge. A merged index is stored in a compact packed format (see [pack](pack.md)) that is read very efficiently but cannot be extended in place. The merge therefore takes a freshly built index as its starting point and brings the packed index in as a source. A typical case is a merged index of many genomes plus one or a few newly built single-genome indexes, and this works.
If every source has already been merged or packed, the command stops before doing any work and says so. In that case, merge the original single-genome indexes together instead.
The genome columns of the result follow the order of the starting index first, then the other sources, so they may not come out in the order the sources were listed. The genome labels always identify each column unambiguously.
+1 -1
View File
@@ -3,7 +3,7 @@
Pack an index's per-column matrix files into a single-file format to reduce query-time I/O (fewer file opens per query).
```bash
obikmer pack INDEX [--sparse]
obiskim pack INDEX [--sparse]
```
## Arguments
+114 -93
View File
@@ -1,9 +1,16 @@
# phylo
Compute pairwise distances between the genomes stored in an index, optionally build trees (NJ/UPGMA) from them, and optionally calibrate a 16-state parsimony model for a central-position SNP character with exports for external phylogenetic tools (TNT, PhyG, IQ-TREE).
Compare the genomes stored in an index and build phylogenetic trees from them. Two complementary approaches are available:
- **Whole-genome distances** compare the k-mer content of the genomes, without any alignment.
- **SNP-based distances and analyses** compare the nucleotide variants found at the central position of related k-mers.
Distance matrices can be used to build Neighbor-Joining or UPGMA trees. SNP-based analyses can also produce a pseudo-alignment and calibrated substitution costs, with exports for external phylogenetic tools (TNT, PhyG, IQ-TREE).
## Usage
```bash
obikmer phylo INDEX [OPTIONS]
obiskim phylo INDEX [OPTIONS]
```
## Arguments
@@ -12,28 +19,43 @@ obikmer phylo INDEX [OPTIONS]
|---|---|
| `INDEX` | Index directory |
## Distance matrix (`--distance`)
## General options
| Option | Default | Description |
|---|---|---|
| `--distance` | none | Compute and write a distance matrix. See the two tables below for the full list of accepted values. No matrix is computed unless this is given, or `--nj`, `--upgma` or `--shared-kmers` is (they need a matrix and then use `jaccard`) |
| `--cpu-max N` | all available cores | Maximum number of CPU cores to use. It caps every thread pool of the process and can only lower the number of cores, never raise it above those available. Common to all subcommands |
| `-o, --output PREFIX` | none | Prefix of the output files. Without it, the distance matrix goes to standard output and every other file is written in the current directory under its name without the prefix. See "Output files" below |
## SNP families
SNP-based analyses use groups of k-mers that differ only at their central nucleotide. These groups are called families (see the [central-position SNP model](../theory/phylogeny/snp_based/central_snp_model.md) for the exact definitions and eligibility rules). A variable family is one character of the analysis, and the variants a genome carries give its state for that character.
## Distance estimation and tree reconstruction
| Option | Default | Description |
|---|---|---|
| `--distance` | none | Compute and write a distance matrix. The accepted values are listed just below the table. No matrix is computed unless this is given, or `--nj` or `--upgma` is (they need a matrix and then use `jaccard`) |
| `--gamma-shape ALPHA\|auto` | none | Rate-heterogeneity correction, for `snp-*` values that support it (see [Gamma rate heterogeneity](../theory/phylogeny/snp_based/gamma_rate_heterogeneity.md)). Either a fixed $\alpha$ or `auto`/`estimate` to fit it from the data. No effect on the other values; rejected if given together with a value that doesn't support it |
| `--presence-threshold` | `1` | Minimum count for a kmer to be considered present, for `jaccard`/`mash` on a count index |
| `--presence-threshold` | `1` | How counts are turned into presence/absence on an index that stores counts: a kmer is present in a genome only when its count reaches this value. Used by `jaccard`, `mash` and `hamming`, and by the shared-kmer counts of `--shared-kmers`. No effect on an index without counts, nor on the distances that use the counts themselves |
| `--session DIR`, `--session-force` | none | Save and reuse the sample of a `snp-*` distance. Currently unavailable, see `--session` below |
| `--csv` | off | Write the matrix as plain CSV instead of the default relaxed-PHYLIP format |
| `--shared-kmers` | off | Also write the shared-kmer count matrix. Only valid with a whole-index distance, not a `snp-*` value |
| `--shared-kmers` | off | Write the shared-kmer count matrix (`<prefix>_shared.csv`). It can be used alone, without any distance, or together with a whole-index distance; it is refused with a `snp-*` value |
| `--nj` | off | Compute and write a Neighbor-Joining tree (Newick) |
| `--upgma` | off | Compute and write a UPGMA tree (Newick) |
| `-o, --output` | none (stdout) | Output file prefix |
Every value routes to one of two independent computations: **whole-index distances** (`jaccard`, `mash`, `hamming`, `bray-curtis`, `relfreq-bray-curtis`, `euclidean`, `relfreq-euclidean`, `hellinger`, `hellinger-euclidean` — see [Whole k-mer set distances](../theory/phylogeny/kmer_based/kmer_set_distances.md) for the definitions; `hamming` requires a presence/absence index, the others work on either index type), or **`snp-*` corrections** (`snp-raw`, `snp-jc`, `snp-k2p`, `snp-k81`, `snp-f81`, `snp-t92`, `snp-tn93`, `snp-tv` — see the [central-position SNP model](../theory/phylogeny/snp_based/central_snp_model.md) for the definitions).
Every value routes to one of two independent computations: **whole-index distances** (`jaccard`, `mash`, `hamming`, `bray-curtis`, `relfreq-bray-curtis`, `euclidean`, `relfreq-euclidean`, `hellinger`, `hellinger-euclidean` — see [Whole k-mer set distances](../theory/phylogeny/kmer_based/kmer_set_distances.md) for the definitions; `jaccard`, `mash` and `hamming` compare which kmers are present and work on either index type; the six others (`bray-curtis`, `relfreq-bray-curtis`, `euclidean`, `relfreq-euclidean`, `hellinger`, `hellinger-euclidean`) use the counts and need an index that stores them), or **`snp-*` corrections** (`snp-raw`, `snp-jc`, `snp-k2p`, `snp-k81`, `snp-f81`, `snp-t92`, `snp-tn93`, `snp-tv` — see the [central-position SNP model](../theory/phylogeny/snp_based/central_snp_model.md) for the definitions).
`snp-*` values require the sibling annex (`--sibling-annex`, below) and are, by default, computed exhaustively over every non-monomorphic family in the index; add `--n-sites N` to bound the computation to approximately `N` families instead (see "Sampling at scale" below — the same option `--pseudo-alignment`/`--sankoff` use, but optional here).
`snp-*` values read the sibling annex (below), which is built automatically the first time it is needed, and are, by default, computed exhaustively over every non-monomorphic family in the index; add `--n-sites N` to bound the computation to approximately `N` families instead (see "SNP character selection and sampling" below — the same option `--pseudo-alignment`/`--sankoff` use, but optional here).
### Output
### Matrix format
When a matrix is computed and there is no `-o`, it goes to stdout in relaxed-PHYLIP format (`n` on the first line, then one `label<TAB>value...` row per genome). With `--csv`, the format is instead a header row `genome,<label1>,<label2>,...` followed by one `<label>,<value1>,<value2>,...` row per genome, 6 decimals. Both formats are symmetric with a zero diagonal, except where noted below.
## `--exclude-genome`, `--min-shared-family`
### `--session`: currently unavailable
`--session DIR` and `--session-force` are meant to save the sample of a `snp-*` `--distance` run in a directory, so that a later run with identical selection parameters reuses it instead of drawing again. This feature is being rebuilt and is not available for now: giving either option stops the command with an error. Until it returns, keep the output files of a run (the alignment, or the distance matrix) rather than relying on re-drawing the same sample.
## Genome selection and filtering
| Option | Description |
|---|---|
@@ -42,21 +64,79 @@ When a matrix is computed and there is no `-o`, it goes to stdout in relaxed-PHY
Neighbor-Joining and UPGMA trees (`--nj`/`--upgma`) are always built from every genome in the index, regardless of `--exclude-genome`/`--min-shared-family`.
## Central-position SNP model
## SNP character selection and sampling
See [Central-position SNP model](../theory/phylogeny/snp_based/central_snp_model.md) for the family/eligibility definitions. Requires the sibling annex, built once per index:
SNP-based analyses can use every eligible variable family, or a sample drawn from the index. The options below control which characters are selected, which genomes and states are kept, and how the sample is spread over the index.
`--n-sites`, `--free-loss`, `--no-ambiguity`, `--quartet`, `--pair-balance`, `--entropy`/`--entropy-sd` are shared by `--pseudo-alignment`, `--sankoff` (and everything it implies: `--tnt`/`--phyg`/`--iqtree`), and a `snp-*` `--distance` value — one draw feeds all of them in a single invocation. `--n-sites` is mandatory for `--pseudo-alignment`/`--sankoff`, where it takes either a number of sites or `all`; for a `snp-*` `--distance` value it is optional, and omitting it is the same as `all` (every non-monomorphic family in the index, not an approximation).
Combining `--sankoff` (or `--tnt`/`--phyg`/`--iqtree`) with a `snp-*` `--distance` value in the same command reuses that one draw for both — the distance and the Sankoff calibration/alignment are guaranteed to be computed from the *identical* set of sampled sites, never two independent samples, so the two outputs are directly comparable. This only holds within a single command; running them as two separate `obiskim phylo` invocations draws two independent samples even with the same flags.
Every invocation draws its own fresh random sample: running the same command twice gives two different (but equally valid) samples, which is useful for measuring sampling variance and is kept that way deliberately.
With `--n-sites all` (or, for a `snp-*` `--distance` value, without `--n-sites`), every variable family (family size ≥ 2) that passes the other filters is used. With `--n-sites N`, roughly `N` families are kept instead (see [Sampling design](../theory/phylogeny/snp_based/sampling_design.md) for how the draw stays representative of the whole index). If fewer than `N` candidate families remain, `--n-sites` has no effect.
| Option | Default | Description |
|---|---|---|
| `--n-sites N\|all` | none (mandatory for `--pseudo-alignment` and `--sankoff`) | Number of families to draw, or `all` to use every variable family that passes the other filters, with no sampling. A number is a target, not a guarantee. |
| `--free-loss` | off | Treat a genome carrying none of a family's observed members as missing data (`?`) instead of `-` |
| `--no-ambiguity` | off | Treat a genome carrying more than one member of a family as missing data (`?`) instead of an IUPAC ambiguity code |
| `--only-diploid` | off | Milder than `--no-ambiguity` (the two cannot be combined): keep the genomes carrying one or two members of a family (a base, or a two-base IUPAC code such as `R`) and treat those carrying three or four as missing data (`?`) |
| `--quartet` | off | Keep only the families that can separate two pairs of genomes from each other: at least two distinct states, each carried by at least two genomes. Absence counts as a state unless `--free-loss` is given. Which genomes count as carriers follows `--no-ambiguity` |
| `--pair-balance` | off | Favour the families covering the pairs of genomes that share the fewest families across the index, so that every pair is better represented in the sample. Which genomes count as carriers follows `--no-ambiguity` |
| `--sample-stats` | off | Write three CSV files describing what the draw contains (see "Describing a draw" below) |
| `--sample-plan` | off | Write `<prefix>_sample_plan.csv`: how the draw was spread over the layers of the index |
| `--entropy MU` | off (`1.0` if only `--entropy-sd` is given) | Center of the entropy band to favor when sampling |
| `--entropy-sd SIGMA` | off (`0.5` if only `--entropy` is given) | Width of that band |
### `--quartet`: keeping only families that can resolve a tree
A family carried by fewer than four genomes, or whose genomes all share one state except a single variant, fits every tree topology equally well and so tells a tree nothing: to separate two pairs of genomes from each other (`AB|CD`) it takes at least two distinct states, each carried by at least two genomes. `--quartet` restricts the draw to the families that show this pattern. The states are those of the alignment. Without `--free-loss`, the absence of a family is a state of its own, so two genomes that carry a base and two genomes that lack the family do form two pairs. With `--free-loss`, absence is missing data and never forms a pair. A genome carrying several members of the family counts as a carrier of its own combination of bases, unless `--no-ambiguity` is given, in which case it is left out, as in the alignment.
The restriction is applied before the draw, from a persisted annex (one bit per variable family, built the first time `--quartet` is used with a given `--no-ambiguity` / `--only-diploid` convention and with or without `--free-loss`, in one pass shared with the other annexes, or ahead of time by `--sibling-annex --quartet`), then checked exactly on each family drawn, taking `--exclude-genome` into account. The quota given to `--n-sites` is therefore spent only on usable families.
### `--pair-balance`: representing every pair of genomes
Two genomes that are distantly related share few families, so a uniform draw covers such a pair with few sites, far fewer than a close pair: the pairs that matter for the deep branches of a tree are the worst represented. `--pair-balance` compensates. Each family is weighted by the mean, over the pairs of genomes carrying it, of 1 divided by the number of families that pair shares across the whole index (the matrix `--family-overlap` writes): a family carried by a rarely-sharing pair weighs more. It is the mean, not the sum, so a family carried by most genomes — in skimming data often a high-copy region — is not favoured merely for covering many pairs.
Each layer's share of the draw is proportional to the total weight of its families, and a family's chance of being drawn is proportional to its own weight. The weights are persisted (one value per variable family, built the first time `--pair-balance` is used with a given `--no-ambiguity` / `--only-diploid` convention, after the family-overlap matrix it depends on, or ahead of time by `--sibling-annex --pair-balance`). They combine with `--entropy` and `--quartet`: the weight multiplies the entropy kernel, and `--quartet` restricts the families first.
### `--entropy MU` / `--entropy-sd SIGMA`: biasing the sample toward informative families
By default, `--n-sites N` draws families uniformly. With `--entropy`/`--entropy-sd`, each family's chance of being kept is instead weighted by how close its own entropy (`entropy15`) is to `MU`, using a Gaussian curve of width `SIGMA` — no hard cutoff (see [Sampling design](../theory/phylogeny/snp_based/sampling_design.md) for the weighting formula). The filter activates as soon as either flag is given; the other defaults to `1.0`/`0.5`. Combine with `--n-sites N` (expect somewhat fewer than `N` families kept in practice) or use alone (a soft filter over the whole index, no size target).
The first `phylo` run on a given index that uses `--entropy`/`--entropy-sd` pays a one-time extra cost (every candidate family's entropy is computed once and saved alongside the index); later runs, even with different `MU`/`SIGMA`, reuse that saved data.
The entropy that weights the draw follows `--no-ambiguity` and `--only-diploid`, so that it describes the same genomes as the alignment. By default, every genome carrying the family counts, and a genome carrying several members of it is a state of its own (`entropy15`). With `--no-ambiguity`, only the genomes carrying exactly one member count, since the others become missing data (`entropy4`). With `--only-diploid`, the genomes carrying one or two members count and those carrying three or four become missing data. The three entropies are saved separately: switching convention builds the missing one once, without discarding the others, and `--sibling-annex --entropy` builds the one of the convention given.
### Describing a draw: `--sample-stats`, `--sample-plan`
Both need a draw to describe (`--pseudo-alignment`, `--sankoff` or a `snp-*` `--distance`) and are computed from the very sites the draw kept, in the same pass, so they cost almost nothing and always agree with the alignment.
`--sample-stats` writes three files:
| File | Content |
|---|---|
| `<prefix>_sample_genomes.csv` | per genome (`genome,excluded,sites_with_call,share_of_sites,informative_sites`): the sampled sites it has a call in, their share of all sampled sites, and the informative sites (two states each carried by at least two genomes) in which its own state is one of those carried by at least two genomes. A genome with almost no calls cannot be placed whatever the tree method |
| `<prefix>_sample_carriers.csv` | per number of carriers (`n_carriers,sites,informative_sites`): how many sampled sites have that many genomes with a call, and how many of them are informative. Shows how much of the sample can resolve a tree at all |
| `<prefix>_sample_overlap.csv` | the sample's own genome × genome matrix, same layout as `--family-overlap`: sampled sites both genomes have a call in. Compare it with the index's matrix to see which pairs the draw under- or over-represents |
A call is any state other than the empty one: absence is never a call, with or without `--free-loss`. A site is informative under the same rule as `--quartet`: without `--free-loss`, absence is a state of its own and can form one of the two pairs; with `--free-loss` it is missing data and cannot. Excluded genomes are listed with zeros in the first file and count nowhere.
`--sample-plan` writes `<prefix>_sample_plan.csv`, one line per layer of the index in the order the draw visited them (`partition,layer,eligible,mass,quota,resolved,kept`): the variable families eligible when the draw starts, their total weight (their number, or with `--pair-balance` the sum of their pair weights), the layer's share of the target, the families drawn and resolved, and the ones kept after masking. A low `kept` against `resolved` means masking removes most of what is drawn in that layer; a `quota` summing to less than the target means some layers had nothing eligible. The target and the total kept are logged.
## SNP family preparation and diagnostics
SNP-based options read precomputed tables describing the families: the sibling annex, and tables derived from it (entropy, quartet, family overlap, pair weights). They are built automatically the first time they are needed and reused afterwards. The options below prepare them in advance, or describe the families.
| Option | Description |
|---|---|
| `--sibling-annex` | Build (or rebuild) the sibling-count/minorant annex. Rebuilding it makes the annexes derived from it obsolete, so they are dropped; then only the derived annexes that the other options of the same command read are rebuilt, each under the `--no-ambiguity` / `--only-diploid` convention given: `--entropy` the entropy annex, `--quartet` the quartet annex, `--pair-balance` the pair-weight and family-overlap annexes, `--family-overlap` or `--min-shared-family` the family-overlap annex. For example `--sibling-annex --quartet --only-diploid` prepares exactly the quartet annex of that convention, and `--sibling-annex` alone prepares none. An annex that is not prepared is built later, on demand, by the computation that reads it. Every option in this section needs the sibling annex, and builds it by itself, under an exclusive lock on the index, if it is missing (as it is after `migrate-mphf`); running `--sibling-annex` first does the same work once, which is the safe way to start several `phylo` runs on the same index at the same time |
| `--sibling-annex` | Build (or rebuild) the sibling-count/minorant annex. Rebuilding it makes the annexes derived from it obsolete, so they are dropped; then only the derived annexes that the other options of the same command read are rebuilt, each under the `--no-ambiguity` / `--only-diploid` convention given: `--entropy` the entropy annex, `--quartet` the quartet annex, `--pair-balance` the pair-weight and family-overlap annexes, `--family-overlap` or `--min-shared-family` the family-overlap annex. For example `--sibling-annex --quartet --only-diploid` prepares exactly the quartet annex of that convention, and `--sibling-annex` alone prepares none. An annex that is not prepared is built later, on demand, by the computation that reads it. Every option in this section needs the sibling annex, and builds it by itself, under an exclusive lock on the index, if it is missing; running `--sibling-annex` first does the same work once, which is the safe way to start several `phylo` runs on the same index at the same time |
| `--sibling-stats` | Write `<prefix>_siblings.csv`: the family-size distribution, per genome and globally |
| `--sibling-hist` | Print the global family-size histogram (1-4 members) only |
| `--sibling-hist` | Write `<prefix>_sibling_hist.csv` (columns `size,count`): the global family-size histogram (1-4 members) only, without the per-genome breakdown |
| `--family-overlap` | Write `<prefix>_family_overlap.csv`: for every genome pair, how many variable families both genomes carry a call for |
| `--shannon` | Write `<prefix>_entropy.csv`: per-family Shannon entropy, one row per family, full unsampled scan |
| `--shannon-summary` | Write `<prefix>_shannon_summary.csv`: the same scan as `--shannon`, reduced to a distribution (see below) — a few hundred thousand lines at most, whatever the size of the index |
| `--pseudo-alignment` | Write `<prefix>_alignment.fasta`: a SNP-only pseudo-alignment. Requires `--n-sites N\|all` |
| `--fasta` | Choose FASTA as the pseudo-alignment format (the default when neither `--fasta` nor `--vcf` is given). Implies `--pseudo-alignment` |
| `--vcf` | Also (or instead) write `<prefix>_alignment.vcf`, the same sites as a VCF. Implies `--pseudo-alignment`; combinable with `--fasta` |
### `--sibling-stats`
@@ -73,50 +153,6 @@ See [Central-position SNP model](../theory/phylogeny/snp_based/central_snp_model
`--min-shared-family N` uses the mean of each genome's own row (excluding the diagonal) against this same matrix as its exclusion statistic. There is no universal value for `N` — inspect `--family-overlap`'s own output to find where the real gap sits in a given genome collection before choosing a threshold.
### `--pseudo-alignment`
`<prefix>_alignment.fasta` — one record per non-excluded genome, one column per variable family (family size ≥ 2). Each site is IUPAC-coded from the genome's presence mask at that family: a single observed form → the plain base; several forms → the matching IUPAC ambiguity code; no form → `-`.
#### VCF output (`--vcf`)
The same drawn sites can be written as `<prefix>_alignment.vcf`, with `--fasta` and `--vcf` freely combined (FASTA alone remains the default). The coordinates, identifiers, alleles and genotypes of this file follow conventions of their own, described on the [VCF pseudo-alignment](../formats/vcf.md) page. The genotype ploidy follows `--no-ambiguity` (haploid) and `--only-diploid` (diploid, with the genomes carrying three or four forms of a family removed beforehand).
| Option | Default | Description |
|---|---|---|
| `--n-sites N\|all` | none (mandatory here) | Number of families to draw, or `all` to use every variable family that passes the other filters, with no sampling. A number is a target, not a guarantee. |
| `--free-loss` | off | Treat a genome carrying none of a family's observed members as missing data (`?`) instead of `-` |
| `--no-ambiguity` | off | Treat a genome carrying more than one member of a family as missing data (`?`) instead of an IUPAC ambiguity code |
| `--only-diploid` | off | Milder than `--no-ambiguity` (the two cannot be combined): keep the genomes carrying one or two members of a family (a base, or a two-base IUPAC code such as `R`) and treat those carrying three or four as missing data (`?`) |
| `--quartet` | off | Keep only the families that can separate two pairs of genomes from each other: at least two distinct called states, each carried by at least two genomes. Which genomes count as carriers follows `--no-ambiguity` |
| `--pair-balance` | off | Favour the families covering the pairs of genomes that share the fewest families across the index, so that every pair is better represented in the sample. Which genomes count as carriers follows `--no-ambiguity` |
| `--sample-stats` | off | Write three CSV files describing what the draw contains (see "Describing a draw" below) |
| `--sample-plan` | off | Write `<prefix>_sample_plan.csv`: how the draw was spread over the layers of the index |
| `--entropy MU` | off (`1.0` if only `--entropy-sd` is given) | Center of the entropy band to favor when sampling |
| `--entropy-sd SIGMA` | off (`0.5` if only `--entropy` is given) | Width of that band |
## Sampling at scale: `--n-sites`, `--shannon`, `--entropy`
`--n-sites`, `--free-loss`, `--no-ambiguity`, `--quartet`, `--pair-balance`, `--entropy`/`--entropy-sd` are shared by `--pseudo-alignment`, `--sankoff` (and everything it implies: `--tnt`/`--phyg`/`--iqtree`), and a `snp-*` `--distance` value — one draw feeds all of them in a single invocation. `--n-sites` is mandatory for `--pseudo-alignment`/`--sankoff`, where it takes either a number of sites or `all`; for a `snp-*` `--distance` value it is optional, and omitting it is the same as `all` (every non-monomorphic family in the index, not an approximation).
Combining `--sankoff` (or `--tnt`/`--phyg`/`--iqtree`) with a `snp-*` `--distance` value in the same command reuses that one draw for both — the distance and the Sankoff calibration/alignment are guaranteed to be computed from the *identical* set of sampled sites, never two independent samples, so the two outputs are directly comparable. This only holds within a single command; running them as two separate `obikmer phylo` invocations draws two independent samples even with the same flags — unless `--session` is used (below).
Every invocation, with or without `--session`, draws its own fresh random sample by default — running the same command twice gives two different (but equally valid) samples, which is useful for measuring sampling variance and is kept that way deliberately. `--session` does not change this: it makes a *specific* sample reusable on request, it does not make sampling itself reproducible from one independent run to the next.
### `--session`: reusing a sample across separate commands
| Option | Default | Description |
|---|---|---|
| `--session DIR` | none | Persist the sample (and, for `--sankoff`, its calibration/alignment) in `DIR` so a later, separate `obikmer phylo` invocation with the exact same selection parameters restores it instead of resampling |
| `--session-force` | off | With `--session DIR`: overwrite its saved parameters and cached sample instead of erroring out when this run's parameters don't match. No effect without `--session` |
`DIR` is created if it doesn't exist. If it already holds a sample built with different `--n-sites`/`--free-loss`/`--no-ambiguity`/`--quartet`/`--exclude-genome`/`--min-shared-family`/`--entropy`/`--entropy-sd` values than this run, the command exits with an error rather than silently using either the old or the new values — pass `--session-force` to discard the old sample and rebuild under the new parameters, or point `--session` at a different directory to keep both.
A `--sankoff`-family run and a `snp-*` `--distance` run share the same cached sample when pointed at the same `--session DIR` — build it once with either, reuse it from the other, in either order, across separate commands.
If a run using `--session` is interrupted (crash, kill, `Ctrl-C`), the next run against the same `--session DIR` resumes from the last automatic checkpoint (roughly every 8 partitions'-worth of sampling progress) instead of starting over. The resumed run's sample is **not** guaranteed to be identical to what an uninterrupted run would have produced past that checkpoint — each process draws its own independent random sequence, same as any two separate invocations do — but nothing already checkpointed is lost, and no work needs redoing beyond that point.
With `--n-sites all` (or, for a `snp-*` `--distance` value, without `--n-sites`), every variable family (family size ≥ 2) that passes the other filters is used. With `--n-sites N`, roughly `N` families are kept instead (see [Sampling design](../theory/phylogeny/snp_based/sampling_design.md) for how the draw stays representative of the whole index). If fewer than `N` candidate families remain, `--n-sites` has no effect.
### `--shannon`: measuring how informative a family is
`<prefix>_entropy.csv` has one row per family visited:
@@ -134,43 +170,27 @@ With `--n-sites all` (or, for a `snp-*` `--distance` value, without `--n-sites`)
`--shannon` always scans every non-monomorphic family of the whole index; `--n-sites`, `--entropy` and `--entropy-sd` have no effect on it. The output therefore grows with the index, with one row per family, and can reach hundreds of millions of rows (tens of gigabytes) on a large index. Analyse it with a tool that reads the file as a stream (for example DuckDB or Miller) rather than loading it whole. It is nevertheless the right basis for choosing `--entropy`/`--entropy-sd` values, since it gives the complete entropy distribution, including how it varies with `n_genomes_present`, rather than an estimate from a sample.
### `--quartet`: keeping only families that can resolve a tree
A family carried by fewer than four genomes, or whose genomes all share one state except a single variant, fits every tree topology equally well and so tells a tree nothing: to separate two pairs of genomes from each other (`AB|CD`) it takes at least two distinct states, each carried by at least two genomes. `--quartet` restricts the draw to the families that show this pattern. Absence is never a state here: a genome that does not carry the family does not count, with or without `--free-loss`. A genome carrying several members of the family counts as a carrier of its own combination of bases, unless `--no-ambiguity` is given, in which case it is left out, as in the alignment.
The restriction is applied before the draw, from a persisted annex (one bit per variable family, built the first time `--quartet` is used with a given `--no-ambiguity` / `--only-diploid` convention, in one pass shared with the other annexes, or ahead of time by `--sibling-annex --quartet`), then checked exactly on each family drawn, taking `--exclude-genome` into account. The quota given to `--n-sites` is therefore spent only on usable families.
### Describing a draw: `--sample-stats`, `--sample-plan`
Both need a draw to describe (`--pseudo-alignment`, `--sankoff` or a `snp-*` `--distance`) and are computed from the very sites the draw kept, in the same pass, so they cost almost nothing and always agree with the alignment.
`--sample-stats` writes three files:
| File | Content |
|---|---|
| `<prefix>_sample_genomes.csv` | per genome (`genome,excluded,sites_with_call,share_of_sites,informative_sites`): the sampled sites it has a call in, their share of all sampled sites, and the informative sites (two states each carried by at least two genomes) in which its own state is one of those carried by at least two genomes. A genome with almost no calls cannot be placed whatever the tree method |
| `<prefix>_sample_carriers.csv` | per number of carriers (`n_carriers,sites,informative_sites`): how many sampled sites have that many genomes with a call, and how many of them are informative. Shows how much of the sample can resolve a tree at all |
| `<prefix>_sample_overlap.csv` | the sample's own genome × genome matrix, same layout as `--family-overlap`: sampled sites both genomes have a call in. Compare it with the index's matrix to see which pairs the draw under- or over-represents |
A call is any state other than the empty one: absence is never a call, with or without `--free-loss`. Excluded genomes are listed with zeros in the first file and count nowhere.
`--sample-plan` writes `<prefix>_sample_plan.csv`, one line per layer of the index in the order the draw visited them (`partition,layer,eligible,mass,quota,resolved,kept`): the variable families eligible when the draw starts, their total weight (their number, or with `--pair-balance` the sum of their pair weights), the layer's share of the target, the families drawn and resolved, and the ones kept after masking. A low `kept` against `resolved` means masking removes most of what is drawn in that layer; a `quota` summing to less than the target means some layers had nothing eligible. The target and the total kept are logged.
### `--shannon-summary`
`--shannon-summary` writes `<prefix>_shannon_summary.csv` (`entropy,n_genomes_present,n_genomes_unambiguous,bin_start,n_families`): the number of variable families per entropy (`entropy15` over every carrier, `entropy4` over the single-member genomes only — families with none are left out of its lines), number of genomes carrying the family, number of those without ambiguity, and 0.05-bit entropy bin (`bin_start` is its lower bound). It answers how entropy varies with the number of carriers, or how many carriers `--no-ambiguity` loses, from the same scan as `--shannon` but without one line per family.
### `--pair-balance`: representing every pair of genomes
## SNP pseudo-alignment
Two genomes that are distantly related share few families, so a uniform draw covers such a pair with few sites, far fewer than a close pair: the pairs that matter for the deep branches of a tree are the worst represented. `--pair-balance` compensates. Each family is weighted by the mean, over the pairs of genomes carrying it, of 1 divided by the number of families that pair shares across the whole index (the matrix `--family-overlap` writes): a family carried by a rarely-sharing pair weighs more. It is the mean, not the sum, so a family carried by most genomes — in skimming data often a high-copy region — is not favoured merely for covering many pairs.
A pseudo-alignment has one column per variable family and one state per genome. Unlike a conventional sequence alignment, its columns come directly from groups of related k-mers of the index. The number of sites is set with `--n-sites`, and the options of "SNP character selection and sampling" above control which families are included and how ambiguous or absent states are written.
Each layer's share of the draw is proportional to the total weight of its families, and a family's chance of being drawn is proportional to its own weight. The weights are persisted (one value per variable family, built the first time `--pair-balance` is used with a given `--no-ambiguity` / `--only-diploid` convention, after the family-overlap matrix it depends on, or ahead of time by `--sibling-annex --pair-balance`). They combine with `--entropy` and `--quartet`: the weight multiplies the entropy kernel, and `--quartet` restricts the families first.
| Option | Description |
|---|---|
| `--pseudo-alignment` | Write `<prefix>_alignment.fasta`: a SNP-only pseudo-alignment. Requires `--n-sites N\|all` |
| `--fasta` | Choose FASTA as the pseudo-alignment format (the default when neither `--fasta` nor `--vcf` is given). Implies `--pseudo-alignment` |
| `--vcf` | Also (or instead) write `<prefix>_alignment.vcf`, the same sites as a VCF. Implies `--pseudo-alignment`; combinable with `--fasta` |
### `--entropy MU` / `--entropy-sd SIGMA`: biasing the sample toward informative families
### `--pseudo-alignment`
By default, `--n-sites N` draws families uniformly. With `--entropy`/`--entropy-sd`, each family's chance of being kept is instead weighted by how close its own entropy (`entropy15`) is to `MU`, using a Gaussian curve of width `SIGMA` — no hard cutoff (see [Sampling design](../theory/phylogeny/snp_based/sampling_design.md) for the weighting formula). The filter activates as soon as either flag is given; the other defaults to `1.0`/`0.5`. Combine with `--n-sites N` (expect somewhat fewer than `N` families kept in practice) or use alone (a soft filter over the whole index, no size target).
`<prefix>_alignment.fasta` — one record per non-excluded genome, one column per variable family (family size ≥ 2). Each site is IUPAC-coded from the genome's presence mask at that family: a single observed form → the plain base; several forms → the matching IUPAC ambiguity code; no form → `-`.
The first `phylo` run on a given index that uses `--entropy`/`--entropy-sd` pays a one-time extra cost (every candidate family's entropy is computed once and saved alongside the index); later runs, even with different `MU`/`SIGMA`, reuse that saved data.
#### VCF output (`--vcf`)
The entropy that weights the draw follows `--no-ambiguity` and `--only-diploid`, so that it describes the same genomes as the alignment. By default, every genome carrying the family counts, and a genome carrying several members of it is a state of its own (`entropy15`). With `--no-ambiguity`, only the genomes carrying exactly one member count, since the others become missing data (`entropy4`). With `--only-diploid`, the genomes carrying one or two members count and those carrying three or four become missing data. The three entropies are saved separately: switching convention builds the missing one once, without discarding the others, and `--sibling-annex --entropy` builds the one of the convention given.
The same drawn sites can be written as `<prefix>_alignment.vcf`, with `--fasta` and `--vcf` freely combined (FASTA alone remains the default). The coordinates, identifiers, alleles and genotypes of this file follow conventions of their own, described on the [VCF pseudo-alignment](../formats/vcf.md) page. The genotype ploidy follows `--no-ambiguity` (haploid) and `--only-diploid` (diploid, with the genomes carrying three or four forms of a family removed beforehand).
## Sankoff calibration and phylogenetic exports
@@ -205,7 +225,7 @@ TNT and PhyG both write trees with bare numeric leaf labels (`1`, `2`, ..., in t
## Output files
With `-o/--output PREFIX`, the relevant subset of the files below is written. Without `-o`, only the distance matrix, if one is computed, is produced, on stdout. All matrices use genome labels as row/column headers, in index order.
With `-o/--output PREFIX`, the relevant subset of the files below is written. Without `-o`, the distance matrix goes to standard output and every other file is written in the current directory under its name without the `<prefix>_` part (for example `nj.nwk`, `entropy.csv`, `alignment.fasta`). All matrices use genome labels as row/column headers, in index order.
### Distance matrix
@@ -219,13 +239,14 @@ With `-o/--output PREFIX`, the relevant subset of the files below is written. Wi
CSV matrix layout (`_dist.csv`, `_shared.csv`, `_family_overlap.csv`): header `genome,<label1>,<label2>,...`, one data row per genome, `<label>,<value1>,<value2>,...`.
### Central-position SNP model
### SNP analyses
| File | Written by | Format | Content |
|---|---|---|---|
| `<prefix>_siblings.csv` | `--sibling-stats` | CSV table | family-size distribution, per genome and global |
| `<prefix>_sibling_hist.csv` | `--sibling-hist` | CSV table | global family-size histogram (`size,count`) |
| `<prefix>_family_overlap.csv` | `--family-overlap` | CSV matrix | variable families both genomes of a pair carry a call for |
| `<prefix>_entropy.csv` | `--shannon` | CSV table | per-family Shannon entropy, see "Sampling at scale" above |
| `<prefix>_entropy.csv` | `--shannon` | CSV table | per-family Shannon entropy, see `--shannon` above |
| `<prefix>_shannon_summary.csv` | `--shannon-summary` | CSV table | families per entropy bin, number of carriers and number of single-member carriers |
| `<prefix>_sample_genomes.csv`, `<prefix>_sample_carriers.csv`, `<prefix>_sample_overlap.csv` | `--sample-stats` | CSV | what the draw contains: per genome, per number of carriers, per pair of genomes |
| `<prefix>_sample_plan.csv` | `--sample-plan` | CSV table | per layer: eligible families, weight, quota, drawn, kept |
+1 -1
View File
@@ -42,5 +42,5 @@ A rank-qualified query, `key@rank=value`, matches only when the path's segment a
### Example
```bash
obikmer filter source -o output --ingroup "taxon~/Betulaceae/Betula"
obiskim filter source -o output --ingroup "taxon~/Betulaceae/Betula"
```
+1 -1
View File
@@ -3,7 +3,7 @@
Query an index with sequences and annotate each query with the kmer matches found.
```bash
obikmer query INDEX INPUTS... [OPTIONS]
obiskim query INDEX INPUTS... [OPTIONS]
```
## Arguments
+2 -2
View File
@@ -3,7 +3,7 @@
Project and/or aggregate the genome columns of an index into a new index. Where [`filter`](filter.md) selects rows (kmers), `select` operates on columns (genomes): grouping several genomes into one aggregated column, reordering columns, or dropping some.
```bash
obikmer select SOURCE --output OUTPUT [OPTIONS]
obiskim select SOURCE --output OUTPUT [OPTIONS]
```
## Arguments
@@ -42,7 +42,7 @@ At least one output column must be defined; every name listed in `--select` must
To replace an index with a selected version of itself, select to a temporary directory and swap it in:
```bash
obikmer select INDEX --output INDEX.tmp --group ... --group-op ... --select ...
obiskim select INDEX --output INDEX.tmp --group ... --group-op ... --select ...
rm -rf INDEX
mv INDEX.tmp INDEX
```
+1 -1
View File
@@ -3,7 +3,7 @@
Extract super-kmers from one or more sequence files and write them to stdout, without building a full index. Useful for inspecting or piping the super-kmer decomposition of a dataset.
```bash
obikmer superkmer [OPTIONS] [INPUTS...]
obiskim superkmer [OPTIONS] [INPUTS...]
```
## Arguments
+1 -1
View File
@@ -3,7 +3,7 @@
Dump the unitigs of an index as FASTA. A unitig is a maximal non-branching path through the de Bruijn graph implied by the index's kmers; the concatenation of every unitig reconstructs every stored kmer exactly once.
```bash
obikmer unitig INDEX [OPTIONS]
obiskim unitig INDEX [OPTIONS]
```
## Arguments
+1 -1
View File
@@ -3,7 +3,7 @@
Miscellaneous index maintenance and inspection utilities.
```bash
obikmer utils INDEXES... [OPTIONS]
obiskim utils INDEXES... [OPTIONS]
```
## Arguments
+20 -20
View File
@@ -1,5 +1,5 @@
# Requires GNU Make >= 4.3 (grouped targets &:) — use gmake on macOS
BINARY := ../src/target/release/obikmer
BINARY := ../src/target/release/obiskim
VENV_PY := ../.venv/bin/python3
# All generated/downloaded artifacts live under RUN/ so the whole tree can be
@@ -19,10 +19,10 @@ REF_DIST_CSVS := $(addprefix $(RUN)/reference_dist/, \
bray_curtis_dist.csv relfreq_bray_curtis_dist.csv \
euclidean_dist.csv relfreq_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 \
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 \
bray_curtis_dist.csv 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:
.PHONY: all simulate reference reference_dist \
obikmer_dist obikmer_dist_presence obikmer_dist_count \
obiskim_dist obiskim_dist_presence obiskim_dist_count \
dist_comparison \
index_presence index_count \
aggregate_index_presence aggregate_index_count \
@@ -121,57 +121,57 @@ $(REF_DIST_CSVS) &: $(REF_NPZS) build_reference_dist.py
reference_dist: $(REF_DIST_CSVS)
# ── obikmer phylo (presence index) ──────────────────────────────────────────
# ── obiskim phylo (presence index) ──────────────────────────────────────────
$(OBIKMER_PRESENCE_DIST) &: $(RUN)/global_index_presence/index.done $(BINARY)
mkdir -p $(RUN)/obikmer_dist/presence
mkdir -p $(RUN)/obiskim_dist/presence
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/presence/jaccard \
--output $(RUN)/obiskim_dist/presence/jaccard \
--distance jaccard --csv --shared-kmers --nj \
$(RUN)/global_index_presence
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/presence/hamming \
--output $(RUN)/obiskim_dist/presence/hamming \
--distance hamming --csv --nj \
$(RUN)/global_index_presence
obikmer_dist_presence: $(OBIKMER_PRESENCE_DIST)
obiskim_dist_presence: $(OBIKMER_PRESENCE_DIST)
# ── obikmer phylo (count index) ─────────────────────────────────────────────
# ── obiskim phylo (count index) ─────────────────────────────────────────────
$(OBIKMER_COUNT_DIST) &: $(RUN)/global_index_count/index.done $(BINARY)
mkdir -p $(RUN)/obikmer_dist/count
mkdir -p $(RUN)/obiskim_dist/count
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/jaccard \
--output $(RUN)/obiskim_dist/count/jaccard \
--distance jaccard --csv --shared-kmers --nj \
$(RUN)/global_index_count
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/bray_curtis \
--output $(RUN)/obiskim_dist/count/bray_curtis \
--distance bray-curtis --csv --nj \
$(RUN)/global_index_count
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/relfreq_bray_curtis \
--output $(RUN)/obiskim_dist/count/relfreq_bray_curtis \
--distance relfreq-bray-curtis --csv --nj \
$(RUN)/global_index_count
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/euclidean \
--output $(RUN)/obiskim_dist/count/euclidean \
--distance euclidean --csv --nj \
$(RUN)/global_index_count
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/relfreq_euclidean \
--output $(RUN)/obiskim_dist/count/relfreq_euclidean \
--distance relfreq-euclidean --csv --nj \
$(RUN)/global_index_count
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/hellinger \
--output $(RUN)/obiskim_dist/count/hellinger \
--distance hellinger --csv --nj \
$(RUN)/global_index_count
$(BINARY) phylo \
--output $(RUN)/obikmer_dist/count/hellinger_euclidean \
--output $(RUN)/obiskim_dist/count/hellinger_euclidean \
--distance hellinger-euclidean --csv --nj \
$(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 ───────────────────────────────────────────────────────
+2 -2
View File
@@ -17,7 +17,7 @@ a single `benchmark/run/` entry.
```mermaid
flowchart TD
GENOMES["run/genomes/*.fna.gz"]
BIN["obikmer binary"]
BIN["obiskim binary"]
GENOMES --> simulate
simulate --> simdata[("run/simulated_data/")]
@@ -178,7 +178,7 @@ benchmark/
│ └── <species>/<specimen>/
├── reference_index/ # reference kmer sets (.npz)
├── 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_count/ # per-specimen count indexes
├── global_index_presence/ # merged global presence index (sparse, as merged)
+3 -3
View File
@@ -1,13 +1,13 @@
#!/usr/bin/env bash
# Usage: bench_mphf.sh LABEL
#
# Measures the obikmer commands that sit on MPHF lookups (see
# Measures the obiskim commands that sit on MPHF lookups (see
# DevDocMD/implementation/mphf_batch_queries.md for the site inventory), on the
# 20-genome benchmark data already built under run/ (`gmake all` first).
# Nothing under run/ other than run/bench_mphf/ is written.
#
# Env:
# BINARY obikmer binary to measure (default ../src/target/release/obikmer)
# BINARY obiskim binary to measure (default ../src/target/release/obiskim)
# REPS repetitions per step (default 3)
# CPU_MAX passed as --cpu-max when set (default: all cores)
#
@@ -19,7 +19,7 @@ set -euo pipefail
LABEL="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${BINARY:-${SCRIPT_DIR}/../src/target/release/obikmer}"
BINARY="${BINARY:-${SCRIPT_DIR}/../src/target/release/obiskim}"
REPS="${REPS:-3}"
OUT="${RUN_DIR}/bench_mphf/${LABEL}"
CPU=()
+2 -2
View File
@@ -2,10 +2,10 @@
"""Compute reference pairwise distance matrices from per-specimen .npz kmer indexes.
Reads all .npz files in reference_index/ (each containing sorted uint64 `kmers`
and uint32 `counts`), computes all distance metrics supported by `obikmer phylo`,
and uint32 `counts`), computes all distance metrics supported by `obiskim phylo`,
and writes one CSV per metric to reference_dist/.
Output CSV format matches `obikmer phylo --output`:
Output CSV format matches `obiskim phylo --output`:
- first row: "genome", then specimen names
- subsequent rows: specimen name, then float or int values
+15 -15
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
"""Compare all reference distance matrices against obikmer phylo outputs.
"""Compare all reference distance matrices against obiskim phylo outputs.
Reads from:
reference_dist/ — ground-truth matrices computed by build_reference_dist.py
obikmer_dist/ — matrices produced by `obikmer phylo`
obiskim_dist/ — matrices produced by `obiskim phylo`
Handles label reordering: both matrices are sorted by genome label before
element-wise comparison, so column/row order differences are irrelevant.
@@ -89,56 +89,56 @@ def compare(label: str,
# ── comparison table ──────────────────────────────────────────────────────────
# (label, ref_csv, obikmer_csv)
# (label, ref_csv, obiskim_csv)
# The reference jaccard/shared is presence-based, which should match both
# presence/jaccard and count/jaccard (threshold=1).
COMPARISONS = [
# ── presence index ────────────────────────────────────────────────────────
('presence/jaccard_dist',
'reference_dist/jaccard_dist.csv',
'obikmer_dist/presence/jaccard_dist.csv'),
'obiskim_dist/presence/jaccard_dist.csv'),
('presence/jaccard_shared',
'reference_dist/shared_kmers.csv',
'obikmer_dist/presence/jaccard_shared.csv'),
'obiskim_dist/presence/jaccard_shared.csv'),
('presence/hamming_dist',
'reference_dist/hamming_dist.csv',
'obikmer_dist/presence/hamming_dist.csv'),
'obiskim_dist/presence/hamming_dist.csv'),
# ── count index (jaccard cross-check) ─────────────────────────────────────
('count/jaccard_dist',
'reference_dist/jaccard_dist.csv',
'obikmer_dist/count/jaccard_dist.csv'),
'obiskim_dist/count/jaccard_dist.csv'),
('count/jaccard_shared',
'reference_dist/shared_kmers.csv',
'obikmer_dist/count/jaccard_shared.csv'),
'obiskim_dist/count/jaccard_shared.csv'),
# ── count index (count-based metrics) ────────────────────────────────────
('count/bray_curtis_dist',
'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',
'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',
'reference_dist/euclidean_dist.csv',
'obikmer_dist/count/euclidean_dist.csv'),
'obiskim_dist/count/euclidean_dist.csv'),
('count/relfreq_euclidean_dist',
'reference_dist/relfreq_euclidean_dist.csv',
'obikmer_dist/count/relfreq_euclidean_dist.csv'),
'obiskim_dist/count/relfreq_euclidean_dist.csv'),
('count/hellinger_dist',
'reference_dist/hellinger_dist.csv',
'obikmer_dist/count/hellinger_dist.csv'),
'obiskim_dist/count/hellinger_dist.csv'),
('count/hellinger_euclidean_dist',
'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,
help='Max abs diff threshold for PASS/FAIL (default 1e-4)')
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',
help='Output summary CSV path')
args = ap.parse_args()
+3 -3
View File
@@ -2,18 +2,18 @@
# Usage: filter_one_count.sh SPECIES
# Filters global_index_count to keep only kmers specific to SPECIES,
# then selects the SPECIES column (to a temp dir, swapped over the
# original — obikmer select has no --in-place mode, but its output hard-
# original — obiskim select has no --in-place mode, but its output hard-
# links each layer's unchanged kmer-identity files rather than copying
# them, so this costs no extra disk for those).
# Outputs:
# specific_index_count/SPECIES/index.done (written by obikmer select)
# specific_index_count/SPECIES/index.done (written by obiskim select)
# stats/specific_kmer_count/SPECIES.stats (one CSV data row, no header)
set -euo pipefail
SPECIES="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
SOURCE="${RUN_DIR}/global_index_count"
OUTPUT="${RUN_DIR}/specific_index_count/${SPECIES}"
+3 -3
View File
@@ -2,18 +2,18 @@
# Usage: filter_one_presence.sh SPECIES
# Filters global_index_presence to keep only kmers specific to SPECIES,
# then selects the SPECIES column (to a temp dir, swapped over the
# original — obikmer select has no --in-place mode, but its output hard-
# original — obiskim select has no --in-place mode, but its output hard-
# links each layer's unchanged kmer-identity files rather than copying
# them, so this costs no extra disk for those).
# Outputs:
# specific_index_presence/SPECIES/index.done (written by obikmer select)
# specific_index_presence/SPECIES/index.done (written by obiskim select)
# stats/specific_kmer_presence/SPECIES.stats (one CSV data row, no header)
set -euo pipefail
SPECIES="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
SOURCE="${RUN_DIR}/global_index_presence"
OUTPUT="${RUN_DIR}/specific_index_presence/${SPECIES}"
+2 -2
View File
@@ -2,14 +2,14 @@
# Usage: index_one_count.sh SPECIMEN
# SPECIMEN = "species--strain" (Make pattern stem)
# Outputs:
# specimen_index_count/SPECIMEN/index.done (written by obikmer)
# specimen_index_count/SPECIMEN/index.done (written by obiskim)
# stats/indexing_count/SPECIMEN.stats (one CSV data row, no header)
set -euo pipefail
SPECIMEN="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
species="${SPECIMEN%%--*}"
strain="${SPECIMEN#*--}"
+2 -2
View File
@@ -2,14 +2,14 @@
# Usage: index_one_presence.sh SPECIMEN
# SPECIMEN = "species--strain" (Make pattern stem)
# Outputs:
# specimen_index_presence/SPECIMEN/index.done (written by obikmer)
# specimen_index_presence/SPECIMEN/index.done (written by obiskim)
# stats/indexing_presence/SPECIMEN.stats (one CSV data row, no header)
set -euo pipefail
SPECIMEN="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
species="${SPECIMEN%%--*}"
strain="${SPECIMEN#*--}"
+1 -1
View File
@@ -3,7 +3,7 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
IDX_DIR="${RUN_DIR}/specimen_index_count"
OUTPUT="${RUN_DIR}/global_index_count"
STATS_DIR="${RUN_DIR}/stats/merge_count"
+1 -1
View File
@@ -3,7 +3,7 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
IDX_DIR="${RUN_DIR}/specimen_index_presence"
OUTPUT="${RUN_DIR}/global_index_presence"
STATS_DIR="${RUN_DIR}/stats/merge_presence"
+3 -3
View File
@@ -5,7 +5,7 @@
# sparse by default (2026-08-28), so the dense comparison arm needs an
# explicit rebuild.
#
# `obikmer pack --dense` cannot do this: it only converts the raw, freshly-
# `obiskim pack --dense` cannot do this: it only converts the raw, freshly-
# built columnar (per-genome-file, unpacked) matrix into a packed format —
# `finalize_indexed` already packs (sparse by default) as the last step of
# every index-building command, so there is no columnar leftover for a
@@ -13,7 +13,7 @@
# directory", `obicompactvec::bitmatrix::packed::pack_bit_matrix` looking
# for a `meta.json` that packing already cleaned up).
#
# `obikmer select` doesn't have that limitation — it always rebuilds its
# `obiskim select` doesn't have that limitation — it always rebuilds its
# output from scratch via `MatrixBuilder`, reading the source through the
# format-agnostic `PersistentBitMatrix`/`PersistentIntMatrix` (Sparse
# included, both content kinds — see `obicompactvec::batch_presence_counts`/
@@ -31,7 +31,7 @@ set -euo pipefail
KIND="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
SOURCE="${RUN_DIR}/global_index_${KIND}"
OUTPUT="${RUN_DIR}/global_index_${KIND}_dense"
STATS_DIR="${RUN_DIR}/stats/pack_dense_${KIND}"
+2 -2
View File
@@ -6,7 +6,7 @@
# explicitly repacked global_index_KIND_dense (see pack_dense.sh).
# SPECIMEN = "species--strain" (Make pattern stem), reads from query_data/
# Outputs:
# query_KIND_MODE/SPECIMEN.fasta.gz (obikmer query output, --count-missing)
# query_KIND_MODE/SPECIMEN.fasta.gz (obiskim query output, --count-missing)
# stats/query_KIND_MODE/SPECIMEN.stats (one CSV data row, no header)
set -euo pipefail
@@ -15,7 +15,7 @@ MODE="$2"
SPECIMEN="$3"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${SCRIPT_DIR}/run"
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
case "${KIND}" in
presence|count) ;;
+1 -1
View File
@@ -14,7 +14,7 @@ out_dir="$2"
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
gzip -dc "${genome_file}" > "${tmp_fasta}"
Loaded 100 of 453 files, more files were not shown because too many files have changed in this diff. Show more