Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
917cb26186 | ||
|
|
42d5b881ec | ||
|
|
a71e59d6f0 | ||
|
|
f022d83394 | ||
|
|
ed0d563995 | ||
|
|
8159137f8b | ||
|
|
58e57ceae5 | ||
|
|
b95348b226 | ||
|
|
d7ea6973e3 |
No files matched your search
@@ -0,0 +1 @@
|
||||
0.3.4+0.1.1
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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
|
||||
Executable
+96
@@ -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"
|
||||
Executable
+20
@@ -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"
|
||||
Executable
+14
@@ -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
|
||||
Executable
+67
@@ -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)"
|
||||
Executable
+266
@@ -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
|
||||
}
|
||||
Executable
+193
@@ -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)"
|
||||
Executable
+166
@@ -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)"
|
||||
@@ -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
|
||||
Executable
+70
@@ -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
|
||||
Executable
+56
@@ -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
|
||||
Executable
+74
@@ -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
|
||||
Executable
+68
@@ -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
|
||||
Executable
+77
@@ -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; }
|
||||
Executable
+14
@@ -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
|
||||
Executable
+12
@@ -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
|
||||
Executable
+38
@@ -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
|
||||
Executable
+16
@@ -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
|
||||
Executable
+24
@@ -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
|
||||
Executable
+17
@@ -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
|
||||
Executable
+20
@@ -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"
|
||||
Executable
+141
@@ -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)"
|
||||
@@ -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
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
@@ -64,7 +64,7 @@ Check all sources against the constraints above. Abort on any mismatch.
|
||||
|
||||
### 2. Bootstrap output from the base source
|
||||
|
||||
The base is chosen by `choose_base` (`merge.rs`): the source with the largest total `unitigs.bin` size (restricted to approximate-evidence sources when the output must be approximate). It is not necessarily `sources[0]`, and the genome columns follow the base first. Because `obikmer index` is not byte-reproducible (unitig segmentation varies), two near-equal sources can swap roles between runs. Its directory is copied to `output` (hard links for files `merge_partition` never rewrites, see below). Immediately after the copy:
|
||||
The base is chosen by `choose_base` (`merge.rs`): the source with the largest total `unitigs.bin` size (restricted to approximate-evidence sources when the output must be approximate). It is not necessarily `sources[0]`, and the genome columns follow the base first. Because `obiskim index` is not byte-reproducible (unitig segmentation varies), two near-equal sources can swap roles between runs. Its directory is copied to `output` (hard links for files `merge_partition` never rewrites, see below). Immediately after the copy:
|
||||
|
||||
- `index.meta` is rewritten with the final genome list (all sources, possibly renamed) and the effective evidence kind.
|
||||
- In `Presence` mode, any `counts/` directories inherited from source_0 are removed.
|
||||
@@ -185,7 +185,7 @@ index.meta ← complete genome list + evidence kind written at
|
||||
|
||||
## Known issue (not yet fixed, 2026-08-28)
|
||||
|
||||
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.
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -38,4 +38,4 @@ Merge discovers values **column by column** (source by source), in **random slot
|
||||
## 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). `obikmer index` shows the same behaviour. Merge oracles therefore compare sorted dumps, not file hashes. Where the non-determinism originates (parallel graph fill or unitig walk) is not established.
|
||||
- The new layer of a merge is not byte-reproducible run to run: unitig segmentation varies, so the MPHF, evidence and matrix row order vary with it (measured 2026-11-17, `layer_1/*` differs in all 256 partitions; `layer_0` and metadata are identical). `obiskim index` shows the same behaviour. Merge oracles therefore compare sorted dumps, not file hashes. Where the non-determinism originates (parallel graph fill or unitig walk) is not established.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
+2
-2
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
```
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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`).
|
||||
@@ -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$.
|
||||
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -94,9 +134,10 @@ clean-doc-user:
|
||||
# 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 := ../obikmer.wiki
|
||||
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; }
|
||||
@@ -106,12 +147,27 @@ wiki:
|
||||
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)"; \
|
||||
@@ -119,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)
|
||||
@@ -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
|
||||
|
||||
@@ -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,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
|
||||
|
||||
|
||||
@@ -32,8 +32,8 @@ Three verification modes exist. The exact and approximate modes are selected at
|
||||
│ evidence mode, counts stored or not), genome list
|
||||
│ and metadata, build state (empty, scattered,
|
||||
│ counted, indexed)
|
||||
├── 📄 .obikmer.lock lock files: commands that read the index share it,
|
||||
├── 📄 .obikmer.gate commands that write into it hold it exclusively
|
||||
├── 📄 .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/
|
||||
|
||||
@@ -11,7 +11,7 @@ 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, (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.
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
```
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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-estimation-and-tree-reconstruction) for how to select a fixed $\alpha$ or request automatic estimation.
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
`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
|
||||
@@ -20,7 +20,7 @@ Any two of `-z`, `--evidence-bits`, `--fp` may be given; the third is derived us
|
||||
## Comparing an index with random sharing
|
||||
|
||||
```bash
|
||||
obikmer estimate --index INDEX [--presence-threshold N] [-o FILE]
|
||||
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)).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -10,7 +10,7 @@ Distance matrices can be used to build Neighbor-Joining or UPGMA trees. SNP-base
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
obikmer phylo INDEX [OPTIONS]
|
||||
obiskim phylo INDEX [OPTIONS]
|
||||
```
|
||||
|
||||
## Arguments
|
||||
@@ -70,7 +70,7 @@ SNP-based analyses can use every eligible variable family, or a sample drawn fro
|
||||
|
||||
`--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.
|
||||
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.
|
||||
|
||||
@@ -131,7 +131,7 @@ SNP-based options read precomputed tables describing the families: the sibling a
|
||||
|
||||
| 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` | 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 |
|
||||
|
||||
@@ -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"
|
||||
```
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
```
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Miscellaneous index maintenance and inspection utilities.
|
||||
|
||||
```bash
|
||||
obikmer utils INDEXES... [OPTIONS]
|
||||
obiskim utils INDEXES... [OPTIONS]
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
+20
-20
@@ -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
@@ -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)
|
||||
|
||||
@@ -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,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
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -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,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,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#*--}"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -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) ;;
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -18,7 +18,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}"
|
||||
|
||||
@@ -14,7 +14,7 @@ set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ISS="${SCRIPT_DIR}/../.venv/bin/iss"
|
||||
BINARY="${SCRIPT_DIR}/../src/target/release/obikmer"
|
||||
BINARY="${SCRIPT_DIR}/../src/target/release/obiskim"
|
||||
COVERAGE="${COVERAGE:-1}"
|
||||
SEED="${SEED:-1}"
|
||||
READ_LENGTH=150
|
||||
@@ -23,7 +23,7 @@ CPUS="${CPUS:-$(sysctl -n hw.logicalcpu 2>/dev/null || nproc 2>/dev/null || echo
|
||||
OUT="${SCRIPT_DIR}/run/skim_${COVERAGE}x_s${SEED}"
|
||||
mkdir -p "${OUT}/simulated_data" "${OUT}/specimen_index_presence"
|
||||
|
||||
tmp_fasta=$(mktemp "${TMPDIR:-/tmp}/obikmer_skim_XXXXXX.fna")
|
||||
tmp_fasta=$(mktemp "${TMPDIR:-/tmp}/obiskim_skim_XXXXXX.fna")
|
||||
trap 'rm -f "${tmp_fasta}"' EXIT
|
||||
|
||||
# lines of the form run/simulated_data/<species>/<strain>/reads_R1.fastq.gz: run/genomes/<file>
|
||||
|
||||
+11
-11
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare an obikmer count index against a reference kmer set (presence + counts).
|
||||
"""Compare an obiskim count index against a reference kmer set (presence + counts).
|
||||
|
||||
Loads the reference .npz (sorted uint64 kmers + uint32 counts from build_reference.py),
|
||||
streams `obikmer dump` from a --with-counts index, then reports:
|
||||
streams `obiskim dump` from a --with-counts index, then reports:
|
||||
- false negatives : kmers in reference absent from the index
|
||||
- false positives : kmers in the index absent from the reference
|
||||
- count mismatches: kmers present in both but with differing counts
|
||||
@@ -43,9 +43,9 @@ def decode_kmer(val: int, k: int) -> str:
|
||||
|
||||
# ── dump parsing ──────────────────────────────────────────────────────────────
|
||||
|
||||
def load_index(obikmer_bin: str, index_dir: str) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Stream `obikmer dump` and return (kmers_sorted_uint64, counts_uint32)."""
|
||||
cmd = [obikmer_bin, 'dump', index_dir]
|
||||
def load_index(obiskim_bin: str, index_dir: str) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Stream `obiskim dump` and return (kmers_sorted_uint64, counts_uint32)."""
|
||||
cmd = [obiskim_bin, 'dump', index_dir]
|
||||
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
text=True)
|
||||
kmers, counts = [], []
|
||||
@@ -59,7 +59,7 @@ def load_index(obikmer_bin: str, index_dir: str) -> tuple[np.ndarray, np.ndarray
|
||||
counts.append(int(parts[1]))
|
||||
proc.wait()
|
||||
if proc.returncode != 0:
|
||||
print(f'ERROR: obikmer dump exited {proc.returncode}', file=sys.stderr)
|
||||
print(f'ERROR: obiskim dump exited {proc.returncode}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
order = np.argsort(np.array(kmers, dtype=np.uint64), kind='stable')
|
||||
return (np.array(kmers, dtype=np.uint64)[order],
|
||||
@@ -104,9 +104,9 @@ def main() -> None:
|
||||
ap.add_argument('reference', metavar='REF_NPZ', nargs='?',
|
||||
help='Reference .npz file')
|
||||
ap.add_argument('index', metavar='INDEX_DIR', nargs='?',
|
||||
help='obikmer index directory (built with --with-counts)')
|
||||
ap.add_argument('--obikmer', default='obikmer',
|
||||
help='Path to obikmer binary')
|
||||
help='obiskim index directory (built with --with-counts)')
|
||||
ap.add_argument('--obiskim', default='obiskim',
|
||||
help='Path to obiskim binary')
|
||||
ap.add_argument('--species', default='')
|
||||
ap.add_argument('--strain', default='')
|
||||
ap.add_argument('--header', action='store_true',
|
||||
@@ -126,7 +126,7 @@ def main() -> None:
|
||||
return
|
||||
|
||||
# Detect k
|
||||
cmd1 = [args.obikmer, 'dump', '--head', '1', args.index]
|
||||
cmd1 = [args.obiskim, 'dump', '--head', '1', args.index]
|
||||
out1 = subprocess.check_output(cmd1, stderr=subprocess.DEVNULL, text=True)
|
||||
k = len(out1.splitlines()[1].split(',')[0])
|
||||
|
||||
@@ -138,7 +138,7 @@ def main() -> None:
|
||||
|
||||
# Load index
|
||||
print(f'Streaming dump (k={k}): {args.index}', file=sys.stderr)
|
||||
idx_kmers, idx_counts = load_index(args.obikmer, args.index)
|
||||
idx_kmers, idx_counts = load_index(args.obiskim, args.index)
|
||||
|
||||
print(f'k={k} ref={len(ref_kmers):,} idx={len(idx_kmers):,}', file=sys.stderr)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the merged count index against all per-specimen reference sets.
|
||||
|
||||
Streams `obikmer dump` once on the merged index, accumulates per-specimen
|
||||
Streams `obiskim dump` once on the merged index, accumulates per-specimen
|
||||
kmer+count pairs from each column, then compares each against its reference .npz.
|
||||
|
||||
Output to stdout: one CSV row per specimen (same columns as verify_count.py)
|
||||
@@ -41,7 +41,7 @@ def decode_kmer(val: int, k: int) -> str:
|
||||
|
||||
# ── single-pass dump ──────────────────────────────────────────────────────────
|
||||
|
||||
def stream_merged_dump(obikmer_bin: str, index_dir: str,
|
||||
def stream_merged_dump(obiskim_bin: str, index_dir: str,
|
||||
) -> tuple[list[str], dict[str, tuple[list[int], list[int]]]]:
|
||||
"""Stream the merged dump once.
|
||||
|
||||
@@ -49,7 +49,7 @@ def stream_merged_dump(obikmer_bin: str, index_dir: str,
|
||||
specimen_names : column labels in dump order
|
||||
per_specimen : mapping label → (kmer_ints, counts) for entries > 0
|
||||
"""
|
||||
cmd = [obikmer_bin, 'dump', index_dir]
|
||||
cmd = [obiskim_bin, 'dump', index_dir]
|
||||
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
text=True)
|
||||
|
||||
@@ -70,7 +70,7 @@ def stream_merged_dump(obikmer_bin: str, index_dir: str,
|
||||
|
||||
proc.wait()
|
||||
if proc.returncode != 0:
|
||||
print(f'ERROR: obikmer dump exited {proc.returncode}', file=sys.stderr)
|
||||
print(f'ERROR: obiskim dump exited {proc.returncode}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
return specimen_names, per_specimen
|
||||
@@ -156,7 +156,7 @@ def main() -> None:
|
||||
help='Merged count index directory')
|
||||
ap.add_argument('ref_dir', metavar='REF_DIR', nargs='?',
|
||||
help='Directory containing per-specimen .npz reference files')
|
||||
ap.add_argument('--obikmer', default='obikmer')
|
||||
ap.add_argument('--obiskim', default='obiskim')
|
||||
ap.add_argument('--header', action='store_true',
|
||||
help='Print CSV header and exit')
|
||||
ap.add_argument('--save-fn', metavar='DIR',
|
||||
@@ -181,12 +181,12 @@ def main() -> None:
|
||||
if d: d.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
out1 = subprocess.check_output(
|
||||
[args.obikmer, 'dump', '--head', '1', args.index],
|
||||
[args.obiskim, 'dump', '--head', '1', args.index],
|
||||
stderr=subprocess.DEVNULL, text=True)
|
||||
k = len(out1.splitlines()[1].split(',')[0])
|
||||
|
||||
print(f'k={k} streaming merged dump: {args.index}', file=sys.stderr)
|
||||
specimen_names, per_specimen = stream_merged_dump(args.obikmer, args.index)
|
||||
specimen_names, per_specimen = stream_merged_dump(args.obiskim, args.index)
|
||||
print(f'{len(specimen_names)} specimen columns loaded', file=sys.stderr)
|
||||
|
||||
for name in specimen_names:
|
||||
|
||||
@@ -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"
|
||||
INDEX="${RUN_DIR}/global_index_count"
|
||||
REF_DIR="${RUN_DIR}/reference_index"
|
||||
STATS_DIR="${RUN_DIR}/stats/verify_merge_count"
|
||||
@@ -17,7 +17,7 @@ CURRENT="${STATS_DIR}/current.csv"
|
||||
"${PYTHON}" "${VERIFY_PY}" --header >"${CURRENT}"
|
||||
|
||||
"${PYTHON}" "${VERIFY_PY}" \
|
||||
--obikmer "${BINARY}" \
|
||||
--obiskim "${BINARY}" \
|
||||
"${INDEX}" "${REF_DIR}" \
|
||||
>>"${CURRENT}"
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the merged presence index against all per-specimen reference sets.
|
||||
|
||||
Streams `obikmer dump` once on the merged index, accumulates per-specimen
|
||||
Streams `obiskim dump` once on the merged index, accumulates per-specimen
|
||||
kmer sets from each column, then compares each against its reference .npz.
|
||||
|
||||
Output to stdout: one CSV row per specimen (same columns as verify_presence.py)
|
||||
@@ -40,7 +40,7 @@ def decode_kmer(val: int, k: int) -> str:
|
||||
|
||||
# ── single-pass dump ──────────────────────────────────────────────────────────
|
||||
|
||||
def stream_merged_dump(obikmer_bin: str, index_dir: str,
|
||||
def stream_merged_dump(obiskim_bin: str, index_dir: str,
|
||||
) -> tuple[list[str], dict[str, list[int]]]:
|
||||
"""Stream the merged dump once.
|
||||
|
||||
@@ -48,7 +48,7 @@ def stream_merged_dump(obikmer_bin: str, index_dir: str,
|
||||
specimen_names : column labels in dump order (excluding 'kmer')
|
||||
per_specimen : mapping label → list of kmer ints where presence > 0
|
||||
"""
|
||||
cmd = [obikmer_bin, 'dump', index_dir]
|
||||
cmd = [obiskim_bin, 'dump', index_dir]
|
||||
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
text=True)
|
||||
|
||||
@@ -66,7 +66,7 @@ def stream_merged_dump(obikmer_bin: str, index_dir: str,
|
||||
|
||||
proc.wait()
|
||||
if proc.returncode != 0:
|
||||
print(f'ERROR: obikmer dump exited {proc.returncode}', file=sys.stderr)
|
||||
print(f'ERROR: obiskim dump exited {proc.returncode}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
return specimen_names, per_specimen
|
||||
@@ -130,7 +130,7 @@ def main() -> None:
|
||||
help='Merged presence index directory')
|
||||
ap.add_argument('ref_dir', metavar='REF_DIR', nargs='?',
|
||||
help='Directory containing per-specimen .npz reference files')
|
||||
ap.add_argument('--obikmer', default='obikmer')
|
||||
ap.add_argument('--obiskim', default='obiskim')
|
||||
ap.add_argument('--header', action='store_true',
|
||||
help='Print CSV header and exit')
|
||||
ap.add_argument('--save-fn', metavar='DIR',
|
||||
@@ -152,12 +152,12 @@ def main() -> None:
|
||||
|
||||
# Detect k
|
||||
out1 = subprocess.check_output(
|
||||
[args.obikmer, 'dump', '--head', '1', args.index],
|
||||
[args.obiskim, 'dump', '--head', '1', args.index],
|
||||
stderr=subprocess.DEVNULL, text=True)
|
||||
k = len(out1.splitlines()[1].split(',')[0])
|
||||
|
||||
print(f'k={k} streaming merged dump: {args.index}', file=sys.stderr)
|
||||
specimen_names, per_specimen = stream_merged_dump(args.obikmer, args.index)
|
||||
specimen_names, per_specimen = stream_merged_dump(args.obiskim, args.index)
|
||||
print(f'{len(specimen_names)} specimen columns loaded', file=sys.stderr)
|
||||
|
||||
for name in specimen_names:
|
||||
|
||||
@@ -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"
|
||||
INDEX="${RUN_DIR}/global_index_presence"
|
||||
REF_DIR="${RUN_DIR}/reference_index"
|
||||
STATS_DIR="${RUN_DIR}/stats/verify_merge_presence"
|
||||
@@ -17,7 +17,7 @@ CURRENT="${STATS_DIR}/current.csv"
|
||||
"${PYTHON}" "${VERIFY_PY}" --header >"${CURRENT}"
|
||||
|
||||
"${PYTHON}" "${VERIFY_PY}" \
|
||||
--obikmer "${BINARY}" \
|
||||
--obiskim "${BINARY}" \
|
||||
"${INDEX}" "${REF_DIR}" \
|
||||
>>"${CURRENT}"
|
||||
|
||||
|
||||
Loaded 100 of 398 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user