From e715528d344bf71a5eff6670d57f5879361db4bc Mon Sep 17 00:00:00 2001 From: Eric Coissac Date: Mon, 14 Sep 2026 13:06:14 +0200 Subject: [PATCH] Refactor documentation for kmer indexing and phylogenetic models This commit updates documentation across the board, introducing definitions for kmer constraints, super-kmers, k-mer set distances, SNP models, and sampling design principles. It also clarifies the index construction pipeline and the underlying mathematical models used for genome pair calibration. --- UserDocMD/architecture.md | 4 +- UserDocMD/formats/index_layout.md | 4 +- UserDocMD/index.md | 8 +- UserDocMD/references.bib | 221 ++++++++ .../theory/{ => kmer_indexing}/encoding.md | 6 +- .../{ => kmer_indexing}/entropy_filter.md | 0 .../indexing_architecture.md | 6 +- UserDocMD/theory/kmer_indexing/kmers.md | 6 + .../minimizer_selection.md | 20 +- UserDocMD/theory/kmer_indexing/superkmers.md | 15 + UserDocMD/theory/kmers_and_superkmers.md | 24 - .../kmer_based/kmer_set_distances.md | 140 +++++ .../phylogeny/snp_based/central_snp_model.md | 85 +++ .../snp_based/gamma_rate_heterogeneity.md | 27 + .../phylogeny/snp_based/sampling_design.md | 24 + .../phylogeny/snp_based/sankoff_model.md | 22 + UserDocMD/usage/phylo.md | 134 +---- mkdocs-user.yml | 20 +- scripts/mk_wiki.py | 528 ------------------ 19 files changed, 582 insertions(+), 712 deletions(-) rename UserDocMD/theory/{ => kmer_indexing}/encoding.md (60%) rename UserDocMD/theory/{ => kmer_indexing}/entropy_filter.md (100%) rename UserDocMD/theory/{ => kmer_indexing}/indexing_architecture.md (83%) create mode 100644 UserDocMD/theory/kmer_indexing/kmers.md rename UserDocMD/theory/{ => kmer_indexing}/minimizer_selection.md (88%) create mode 100644 UserDocMD/theory/kmer_indexing/superkmers.md delete mode 100644 UserDocMD/theory/kmers_and_superkmers.md create mode 100644 UserDocMD/theory/phylogeny/kmer_based/kmer_set_distances.md create mode 100644 UserDocMD/theory/phylogeny/snp_based/central_snp_model.md create mode 100644 UserDocMD/theory/phylogeny/snp_based/gamma_rate_heterogeneity.md create mode 100644 UserDocMD/theory/phylogeny/snp_based/sampling_design.md create mode 100644 UserDocMD/theory/phylogeny/snp_based/sankoff_model.md delete mode 100755 scripts/mk_wiki.py diff --git a/UserDocMD/architecture.md b/UserDocMD/architecture.md index a3da8b95..2e7a205b 100644 --- a/UserDocMD/architecture.md +++ b/UserDocMD/architecture.md @@ -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/indexing_architecture.md) pages. +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. ## Sequence invariant @@ -8,7 +8,7 @@ Every input sequence is treated purely as a compact representation of a set of o - Only the `A`/`C`/`G`/`T` alphabet (case-insensitive) is recognized; a sequence is cut at any other character (including IUPAC ambiguity codes), so runs containing them are not represented in the index. - Sequences are internally processed in chunks of at most 256 nucleotides; a chunk shorter than k is dropped. This is invisible to the user beyond the ACGT-only, minimum-length-k constraints above. -- Kmers are always handled in canonical form (see [DNA encoding](theory/encoding.md)), so the tool is strand-agnostic throughout: a kmer and its reverse complement are always the same entry. +- Kmers are always handled in canonical form (see [DNA encoding](theory/kmer_indexing/encoding.md)), so the tool is strand-agnostic throughout: a kmer and its reverse complement are always the same entry. ## Index dimensioning diff --git a/UserDocMD/formats/index_layout.md b/UserDocMD/formats/index_layout.md index b590364f..46303b39 100644 --- a/UserDocMD/formats/index_layout.md +++ b/UserDocMD/formats/index_layout.md @@ -2,9 +2,9 @@ ## Construction pipeline -Building an index ([`index`](../usage/index_command.md)) proceeds through a fixed sequence of phases, each operating independently per partition (see [Partitioning and indexing architecture](../theory/indexing_architecture.md)): +Building an index ([`index`](../usage/index_command.md)) proceeds through a fixed sequence of phases, each operating independently per partition (see [Partitioning and indexing architecture](../theory/kmer_indexing/indexing_architecture.md)): -1. **Scatter.** A single streaming pass over the input. Each sequence fragment is cut at non-ACGT bases, passed through the low-complexity entropy filter (see [Low-complexity kmer filter](../theory/entropy_filter.md)), and any resulting segment shorter than k is dropped. Surviving segments are decomposed into super-kmers, canonicalized, and routed by `hash(minimizer) mod n_partitions` into one file per partition. +1. **Scatter.** A single streaming pass over the input. Each sequence fragment is cut at non-ACGT bases, passed through the low-complexity entropy filter (see [Low-complexity kmer filter](../theory/kmer_indexing/entropy_filter.md)), and any resulting segment shorter than k is dropped. Surviving segments are decomposed into super-kmers, canonicalized, and routed by `hash(minimizer) mod n_partitions` into one file per partition. 2. **Dereplication.** Within each partition, identical super-kmer sequences are merged and their occurrence counts summed. This count is per super-kmer, not per kmer — a kmer's true abundance is the sum of the counts of every super-kmer containing it. 3. **Exact counting.** Every kmer in every dereplicated super-kmer is enumerated and its exact total count computed. A per-genome kmer frequency spectrum is produced at this stage. 4. **Quorum filtering.** Kmers outside the `--min-abundance`/`--max-abundance` range are dropped, and super-kmers are recompacted around the surviving kmer set. diff --git a/UserDocMD/index.md b/UserDocMD/index.md index aa1fcc7b..b050433d 100644 --- a/UserDocMD/index.md +++ b/UserDocMD/index.md @@ -6,11 +6,11 @@ All functionality is exposed through a single binary, `obikmer`, organized as su ## Core principles -- Kmers are of fixed, odd length $k$, chosen at index-construction time in the range $[11, 31]$ (see [Kmers and super-kmers](theory/kmers_and_superkmers.md)). -- Each kmer fits in a 64-bit word using a 2-bit-per-base encoding (see [DNA encoding](theory/encoding.md)). +- Kmers are of fixed, odd length $k$, chosen at index-construction time in the range $[11, 31]$ (see [Kmers](theory/kmer_indexing/kmers.md)). +- Each kmer fits in a 64-bit word using a 2-bit-per-base encoding (see [DNA encoding](theory/kmer_indexing/encoding.md)). - Kmers are handled in **canonical form** ($\text{canonical}(kmer) = \min(kmer, \text{revcomp}(kmer))$), making counting strand-independent. -- Sequences are decomposed into **super-kmers** before storage, anchored on a hash-selected **minimizer** (see [Minimizer selection](theory/minimizer_selection.md)), then routed to one of several **partitions** for parallel, memory-bounded processing (see [Partitioning and indexing architecture](theory/indexing_architecture.md)). -- Low-complexity kmers can be filtered out at index-construction time using an entropy-based score (see [Low-complexity kmer filter](theory/entropy_filter.md)). +- Sequences are decomposed into **super-kmers** before storage, anchored on a hash-selected **minimizer** (see [Minimizer selection](theory/kmer_indexing/minimizer_selection.md)), then routed to one of several **partitions** for parallel, memory-bounded processing (see [Partitioning and indexing architecture](theory/kmer_indexing/indexing_architecture.md)). +- Low-complexity kmers can be filtered out at index-construction time using an entropy-based score (see [Low-complexity kmer filter](theory/kmer_indexing/entropy_filter.md)). ## Commands diff --git a/UserDocMD/references.bib b/UserDocMD/references.bib index ce2b810f..1dbf1ef4 100644 --- a/UserDocMD/references.bib +++ b/UserDocMD/references.bib @@ -345,3 +345,224 @@ url = {https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html}, urldate = {2026-09-12} } + + @ARTICLE{Hamming1950-cw, + title = "{Error detecting and error correcting codes}", + author = "Hamming, R W", + journal = "The Bell System Technical Journal", + publisher = "Institute of Electrical and Electronics Engineers (IEEE)", + volume = 29, + number = 2, + pages = "147--160", + abstract = "The author was led to the study given in this paper from a + consideration of large scale computing machines in which a large + number of operations must be performed without a single error in + the end result. This problem of “doing things right” on a large + scale is not essentially new; in a telephone central office, for + example, a very large number of operations are performed while + the errors leading to wrong numbers are kept well under control, + though they have not been completely eliminated. This has been + achieved, in part, through the use of self-checking circuits. The + occasional failure that escapes routine checking is still + detected by the customer and will, if it persists, result in + customer complaint, while if it is transient it will produce only + occasional wrong numbers. At the same time the rest of the + central office functions satisfactorily. In a digital computer, + on the other hand, a single failure usually means the complete + failure, in the sense that if it is detected no more computing + can be done until the failure is located and corrected, while if + it escapes detection then it invalidates all subsequent + operations of the machine. Put in other words, in a telephone + central office there are a number of parallel paths which are + more or less independent of each other; in a digital machine + there is usually a single long path which passes through the same + piece of equipment many, many times before the answer is + obtained.", + month = apr, + year = 1950, + url = "http://dx.doi.org/10.1002/j.1538-7305.1950.tb00463.x", + doi = "10.1002/j.1538-7305.1950.tb00463.x", + issn = "0005-8580" + } + + @ARTICLE{Ondov2016-dq, + title = "{Mash: fast genome and metagenome distance estimation using + {MinHash}}", + author = "Ondov, Brian D and Treangen, Todd J and Melsted, Páll and + Mallonee, Adam B and Bergman, Nicholas H and Koren, Sergey and + Phillippy, Adam M", + journal = "Genome biology", + volume = 17, + number = 1, + pages = 132, + abstract = "Mash extends the MinHash dimensionality-reduction technique to + include a pairwise mutation distance and P value significance + test, enabling the efficient clustering and search of massive + sequence collections. Mash reduces large sequences and sequence + sets to small, representative sketches, from which global mutation + distances can be rapidly estimated. We demonstrate several use + cases, including the clustering of all 54,118 NCBI RefSeq genomes + in 33 CPU h; real-time database search using assembled or + unassembled Illumina, Pacific Biosciences, and Oxford Nanopore + data; and the scalable clustering of hundreds of metagenomic + samples by composition. Mash is freely released under a BSD + license ( https://github.com/marbl/mash ).", + month = jun, + year = 2016, + url = "http://dx.doi.org/10.1186/s13059-016-0997-x", + keywords = "Alignment; Comparative genomics; Genomic distance; Metagenomics; + Nanopore; Sequencing", + doi = "10.1186/s13059-016-0997-x", + pmc = "PMC4915045", + pmid = 27323842, + issn = "1465-6906", + language = "en" + } + @ARTICLE{Bray1957-vv, + title = "{An ordination of the upland forest communities of southern + Wisconsin}", + author = "Bray, J Roger and Curtis, J T", + journal = "Ecological Monographs", + publisher = "Wiley", + volume = 27, + number = 4, + pages = "325--349", + month = oct, + year = 1957, + url = "http://dx.doi.org/10.2307/1942268", + doi = "10.2307/1942268", + issn = "0012-9615,1557-7015", + language = "en" + } + @ARTICLE{Gower1986-ri, + title = "{Metric and Euclidean properties of dissimilarity coefficients}", + author = "Gower, J C and Legendre, P", + journal = "Journal of Classification", + publisher = "Springer Science and Business Media LLC", + volume = 3, + number = 1, + pages = "5--48", + abstract = "We assemble here properties of certain dissimilarity coefficients + and are specially concerned with their metric and Euclidean + status. No attempt is made to be exhaustive as far as + coefficients are concerned, but certain mathematical results that + we have found useful are presented and should help establish + similar properties for other coefficients. The response to + different types of data is investigated, leading to guidance on + the choice of an appropriate coefficient.", + month = mar, + year = 1986, + url = "http://dx.doi.org/10.1007/bf01896809", + doi = "10.1007/bf01896809", + issn = "0176-4268,1432-1343", + language = "en" + } + @ARTICLE{Legendre2001-cq, + title = "{Ecologically meaningful transformations for ordination of species + data}", + author = "Legendre, Pierre and Gallagher, Eugene D", + journal = "Oecologia", + volume = 129, + number = 2, + pages = "271--280", + abstract = "This paper examines how to obtain species biplots in unconstrained + or constrained ordination without resorting to the Euclidean + distance [used in principal-component analysis (PCA) and + redundancy analysis (RDA)] or the chi-square distance [preserved + in correspondence analysis (CA) and canonical correspondence + analysis (CCA)] which are not always appropriate for the analysis + of community composition data. To achieve this goal, + transformations are proposed for species data tables. They allow + ecologists to use ordination methods such as PCA and RDA, which + are Euclidean-based, for the analysis of community data, while + circumventing the problems associated with the Euclidean distance, + and avoiding CA and CCA which present problems of their own in + some cases. This allows the use of the original (transformed) + species data in RDA carried out to test for relationships with + explanatory variables (i.e. environmental variables, or factors of + a multifactorial analysis-of-variance model); ecologists can then + draw biplots displaying the relationships of the species to the + explanatory variables. Another application allows the use of + species data in other methods of multivariate data analysis which + optimize a least-squares loss function; an example is K-means + partitioning.", + month = oct, + year = 2001, + url = "http://dx.doi.org/10.1007/s004420100716", + keywords = "Biplot diagram; Canonical correspondence analysis; Correspondence + analysis; Principal-component analysis; Redundancy analysis", + doi = "10.1007/s004420100716", + pmid = 28547606, + issn = "0029-8549,1432-1939", + language = "en" + } + @ARTICLE{Anderson2011-rq, + title = "{Navigating the multiple meanings of β diversity: a roadmap for + the practicing ecologist}", + author = "Anderson, Marti J and Crist, Thomas O and Chase, Jonathan M and + Vellend, Mark and Inouye, Brian D and Freestone, Amy L and + Sanders, Nathan J and Cornell, Howard V and Comita, Liza S and + Davies, Kendi F and Harrison, Susan P and Kraft, Nathan J B and + Stegen, James C and Swenson, Nathan G", + journal = "Ecology Letters", + publisher = "Wiley", + volume = 14, + number = 1, + pages = "19--28", + abstract = "A recent increase in studies of β diversity has yielded a + confusing array of concepts, measures and methods. Here, we + provide a roadmap of the most widely used and ecologically + relevant approaches for analysis through a series of mission + statements. We distinguish two types of β diversity: directional + turnover along a gradient vs. non-directional variation. + Different measures emphasize different properties of ecological + data. Such properties include the degree of emphasis on + presence/absence vs. relative abundance information and the + inclusion vs. exclusion of joint absences. Judicious use of + multiple measures in concert can uncover the underlying nature of + patterns in β diversity for a given dataset. A case study of + Indonesian coral assemblages shows the utility of a multi-faceted + approach. We advocate careful consideration of relevant + questions, matched by appropriate analyses. The rigorous + application of null models will also help to reveal potential + processes driving observed patterns in β diversity.", + month = jan, + year = 2011, + url = "http://dx.doi.org/10.1111/j.1461-0248.2010.01552.x", + doi = "10.1111/j.1461-0248.2010.01552.x", + pmid = 21070562, + issn = "1461-023X,1461-0248", + language = "en" + } + @ARTICLE{Jaccard1901-mx, + title = "{Étude comparative de la distribution florale dans une portion + des Alpes et du Jura}", + author = "Jaccard, Paul", + journal = "Bulletin de la Société vaudoise des sciences naturelles", + publisher = "Imprimerie Corbaz \& Comp.", + volume = 37, + number = 142, + pages = "547--579", + abstract = "Schweizer Zeitschriften online - Ein Service der ETH-Bibliothek. + Revues suisses en ligne - Un service de ETH Library. Swiss + journals online - A service by ETH Library.", + year = 1901, + url = "http://dx.doi.org/10.5169/seals-266450", + doi = "10.5169/seals-266450", + issn = "0037-9603", + language = "de" + } + @ARTICLE{Kosub2019-xt, + title = "{A note on the triangle inequality for the Jaccard distance}", + author = "Kosub, Sven", + journal = "Pattern Recognition Letters", + publisher = "Elsevier BV", + volume = 120, + pages = "36--38", + month = apr, + year = 2019, + url = "http://dx.doi.org/10.1016/j.patrec.2018.12.007", + doi = "10.1016/j.patrec.2018.12.007", + issn = "0167-8655,1872-7344", + language = "en" + } diff --git a/UserDocMD/theory/encoding.md b/UserDocMD/theory/kmer_indexing/encoding.md similarity index 60% rename from UserDocMD/theory/encoding.md rename to UserDocMD/theory/kmer_indexing/encoding.md index 80230a92..a9fcefb7 100644 --- a/UserDocMD/theory/encoding.md +++ b/UserDocMD/theory/kmer_indexing/encoding.md @@ -21,8 +21,8 @@ Reverse complement is computed by bit manipulation directly on the packed word, ## Canonical form -The canonical form of a kmer is the lexicographic minimum of the kmer and its reverse complement: +The canonical form of a packed 2-bit sequence is the lexicographic minimum of the sequence and its reverse complement: -$$\text{canonical}(kmer) = \min\big(kmer,\ \text{revcomp}(kmer)\big)$$ +$$\text{canonical}(x) = \min\big(x,\ \text{revcomp}(x)\big)$$ -Using the canonical form halves the kmer space and makes counting strand-independent: a kmer and its reverse complement are always treated as the same entity, regardless of which DNA strand was sequenced. +This is a single operation on the packed representation, so it applies identically regardless of what `x` represents — a kmer (see [Kmers](kmers.md)), an m-mer (see [Minimizer selection](minimizer_selection.md)), or a super-kmer (see [Super-kmers](superkmers.md)). Using the canonical form halves the relevant space and makes counting/selection strand-independent: a sequence and its reverse complement are always treated as the same entity, regardless of which DNA strand was sequenced. diff --git a/UserDocMD/theory/entropy_filter.md b/UserDocMD/theory/kmer_indexing/entropy_filter.md similarity index 100% rename from UserDocMD/theory/entropy_filter.md rename to UserDocMD/theory/kmer_indexing/entropy_filter.md diff --git a/UserDocMD/theory/indexing_architecture.md b/UserDocMD/theory/kmer_indexing/indexing_architecture.md similarity index 83% rename from UserDocMD/theory/indexing_architecture.md rename to UserDocMD/theory/kmer_indexing/indexing_architecture.md index 43c72fab..f95514fa 100644 --- a/UserDocMD/theory/indexing_architecture.md +++ b/UserDocMD/theory/kmer_indexing/indexing_architecture.md @@ -4,13 +4,15 @@ An index is split into a fixed number of **partitions**, each handling an indepe ## Routing -The canonical minimizer of a super-kmer (see [Minimizer selection](minimizer_selection.md)) is hashed to produce a $p$-bit routing value that selects the destination partition: +The canonical minimizer of a super-kmer (see [Minimizer selection](minimizer_selection.md)) is hashed to produce a $p$-bit routing value that selects the destination partition — the low $p$ bits of the minimizer's hash: ``` canonical minimizer → hash(minimizer) → p-bit value → partition index ``` -Within a partition, kmers are indexed as plain values via a minimal perfect hash function (see [On-disk storage](../formats/index_layout.md)); the minimizer plays no further role once a super-kmer has reached its partition. +$$\text{partition} = H(\text{minimizer}) \bmod 2^p$$ + +Within a partition, kmers are indexed as plain values via a minimal perfect hash function (see [On-disk storage](../../formats/index_layout.md)); the minimizer plays no further role once a super-kmer has reached its partition. ## Parameter guidance diff --git a/UserDocMD/theory/kmer_indexing/kmers.md b/UserDocMD/theory/kmer_indexing/kmers.md new file mode 100644 index 00000000..dae3acd7 --- /dev/null +++ b/UserDocMD/theory/kmer_indexing/kmers.md @@ -0,0 +1,6 @@ +# Kmers + +A **kmer** is a DNA subsequence of fixed length $k$. Two constraints apply to $k$, both enforced when a command starts (an invalid value exits immediately with an error): + +- $k \in [11, 31]$: long enough to be specific, short enough to fit in a single 64-bit word at 2 bits/base ($k \le 32$ is the hard limit; $k < 11$ gives insufficient specificity). +- $k$ **is odd**: an odd-length sequence can never equal its own reverse complement, so the two orientations of any kmer are always distinct. This is required for the canonical form (see [DNA encoding](encoding.md)) to be well defined. diff --git a/UserDocMD/theory/minimizer_selection.md b/UserDocMD/theory/kmer_indexing/minimizer_selection.md similarity index 88% rename from UserDocMD/theory/minimizer_selection.md rename to UserDocMD/theory/kmer_indexing/minimizer_selection.md index 430610ec..3dec6fe4 100644 --- a/UserDocMD/theory/minimizer_selection.md +++ b/UserDocMD/theory/kmer_indexing/minimizer_selection.md @@ -2,15 +2,7 @@ ## Definition -The **minimizer** of a k-mer is the canonical form of the m-mer that is smallest according to a chosen ordering among the $k-m+1$ overlapping m-mers contained in the k-mer, with $m_entropy.csv`: per-family Shannon entropy, one row per family, full unsampled scan | | `--pseudo-alignment` | Write `_alignment.fasta`: a SNP-only pseudo-alignment. Requires `--subsample N` | -A family is eligible for a genome pair $(i,j)$ only if both genomes carry exactly one of its observed forms (single-copy, unambiguous). - ### `--sibling-stats` `_siblings.csv` — family size = number of distinct central bases observed at a family (1-4). @@ -219,7 +103,7 @@ A `--sankoff`-family run and a `snp-*` `--distance` run share the same cached sa If a run using `--session` is interrupted (crash, kill, `Ctrl-C`), the next run against the same `--session DIR` resumes from the last automatic checkpoint (roughly every 8 partitions'-worth of sampling progress) instead of starting over. The resumed run's sample is **not** guaranteed to be identical to what an uninterrupted run would have produced past that checkpoint — each process draws its own independent random sequence, same as any two separate invocations do — but nothing already checkpointed is lost, and no work needs redoing beyond that point. -Without `--subsample`, every variable family (family size ≥ 2) is used. With `--subsample N`, roughly `N` families are kept instead, drawn in proportion to how many candidate families each part of the index actually holds, so the sample stays representative of the whole index. If the index has fewer than `N` candidate families, `--subsample` has no effect. +Without `--subsample`, every variable family (family size ≥ 2) is used. With `--subsample N`, roughly `N` families are kept instead (see [Sampling design](../theory/phylogeny/snp_based/sampling_design.md) for how the draw stays representative of the whole index). If the index has fewer than `N` candidate families, `--subsample` has no effect. ### `--shannon`: measuring how informative a family is @@ -238,7 +122,7 @@ Run with `--subsample N --shannon` to get a bounded diagnostic sample instead of ### `--entropy MU` / `--entropy-sd SIGMA`: biasing the sample toward informative families -By default, `--subsample` draws families uniformly. With `--entropy`/`--entropy-sd`, each family's chance of being kept is instead weighted by how close its own entropy (`entropy15`) is to `MU`, using a Gaussian curve of width `SIGMA` — no hard cutoff. The filter activates as soon as either flag is given; the other defaults to `1.0`/`0.5`. Combine with `--subsample N` (expect somewhat fewer than `N` families kept in practice) or use alone (a soft filter over the whole index, no size target). +By default, `--subsample` draws families uniformly. With `--entropy`/`--entropy-sd`, each family's chance of being kept is instead weighted by how close its own entropy (`entropy15`) is to `MU`, using a Gaussian curve of width `SIGMA` — no hard cutoff (see [Sampling design](../theory/phylogeny/snp_based/sampling_design.md) for the weighting formula). The filter activates as soon as either flag is given; the other defaults to `1.0`/`0.5`. Combine with `--subsample N` (expect somewhat fewer than `N` families kept in practice) or use alone (a soft filter over the whole index, no size target). The first `phylo` run on a given index that uses `--entropy`/`--entropy-sd` pays a one-time extra cost (every candidate family's entropy is computed once and saved alongside the index); later runs, even with different `MU`/`SIGMA`, reuse that saved data. @@ -257,7 +141,7 @@ The first `phylo` run on a given index that uses `--entropy`/`--entropy-sd` pays ### The 16-state model -Each family is a character with 16 possible states: one per subset of the 4 possible central bases (including the empty subset). Calibration combines a $5 \times 5$ transition matrix over family cardinality (0-4 observed forms) and a $4 \times 4$ base-substitution matrix from unambiguous single-copy loci, both restricted to genome pairs at or below `--sankoff-ratio-ceiling`, into a row-normalized $16 \times 16$ transition probability matrix $P$, converted to a symmetric cost matrix via $\text{cost}(a,b) = -\ln P(a,b)$. +Each family is a character with 16 possible states: one per subset of the 4 possible central bases (including the empty subset). See [The 16-state Sankoff model](../theory/phylogeny/snp_based/sankoff_model.md) for how the calibrated cost matrix is built from cardinality and base-composition transitions. `--sankoff` alone writes the cost matrix, the calibration parameters, and a pseudo-alignment recoded so the empty state uses the symbol `0` (never a gap character). It does not run any external tool. diff --git a/mkdocs-user.yml b/mkdocs-user.yml index cfe95afb..838d1e7c 100644 --- a/mkdocs-user.yml +++ b/mkdocs-user.yml @@ -31,11 +31,21 @@ nav: - Home: index.md - Installation: installation.md - Theory: - - Kmers and super-kmers: theory/kmers_and_superkmers.md - - DNA encoding: theory/encoding.md - - Low-complexity kmer filter: theory/entropy_filter.md - - Minimizer selection: theory/minimizer_selection.md - - Partitioning and indexing architecture: theory/indexing_architecture.md + - Kmer indexing: + - DNA encoding: theory/kmer_indexing/encoding.md + - Kmers: theory/kmer_indexing/kmers.md + - Minimizer selection: theory/kmer_indexing/minimizer_selection.md + - Super-kmers: theory/kmer_indexing/superkmers.md + - Partitioning and indexing architecture: theory/kmer_indexing/indexing_architecture.md + - Low-complexity kmer filter: theory/kmer_indexing/entropy_filter.md + - Phylogeny: + - Kmer-based: + - Whole k-mer set distances: theory/phylogeny/kmer_based/kmer_set_distances.md + - SNP-based: + - Central-position SNP model: theory/phylogeny/snp_based/central_snp_model.md + - Gamma rate heterogeneity: theory/phylogeny/snp_based/gamma_rate_heterogeneity.md + - Sankoff model: theory/phylogeny/snp_based/sankoff_model.md + - Sampling design: theory/phylogeny/snp_based/sampling_design.md - Usage: - superkmer: usage/superkmer.md - index: usage/index_command.md diff --git a/scripts/mk_wiki.py b/scripts/mk_wiki.py deleted file mode 100755 index b395027d..00000000 --- a/scripts/mk_wiki.py +++ /dev/null @@ -1,528 +0,0 @@ -#!/usr/bin/env python3 -"""Convert the MkDocs user documentation (UserDocMD/) into a Gitea/Forgejo wiki tree. - -Gitea/Forgejo wikis use a different link syntax than MkDocs and cannot render -multi-line `$$...$$` display math (a known Goldmark/KaTeX limitation: the -parser only recognizes the delimiters when the whole block sits on one -physical line). This script rewrites the three constructs that would -otherwise break, flattens the tree onto page basenames, and copies everything -else verbatim: - - * Markdown links [text](path.md) -> [text](PageName) - Relative paths (including MkDocs root-relative `/path.md` links) are - resolved against the source tree and then flattened to a wiki page id; - only the target is rewritten, the label is left untouched. Gitea/Forgejo's - own `[[page|label]]` shortlink syntax is deliberately not used: it is - post-processed on rendered HTML text nodes, so it cannot match when the - label contains inline formatting (a `` `code` `` span splits the text - into separate DOM nodes around it) — confirmed empirically on the target - instance, where such labels never became links at all, and even a plain - label put target and display text in the position swapped from what the - MediaWiki-style `[[target|label]]` convention would suggest. A native - Markdown link is a real AST link node, so it has neither problem. - External links (http(s)://, mailto:) and links pointing outside the - source tree are left untouched. - * Pandoc citations [@key; @key] -> formatted, CSL-styled citation - Gitea/Forgejo's Goldmark does not support the [@key] citation syntax, and - a bare `(@key)` fallback is meaningless to a reader without the .bib file - open. Files containing citations are instead piped through `pandoc - --citeproc` with the project's own `references.bib` and `ecology-letters - .csl` — the same files `mkdocs-bibtex` uses for the real site — so the - wiki gets the identical citation style, e.g. `[@Zheng2020-ji]` becomes - `(Zheng et al. 2020)`, with a formatted bibliography (one `
` per entry, real title/journal/DOI) appended to that page. This - duplicates entries across pages that cite the same source rather than - centralizing them on one wiki page — an acceptable tradeoff for a - handful of references, and far simpler than inventing a cross-page - anchor scheme. Files with no `[@key]` at all skip pandoc entirely. - * Multi-line display math $$\\n...\\n$$ -> single-line $$...$$ - Collapsed onto one line (interior newlines replaced by spaces; `\\\\` - row separators are preserved) so Gitea/Forgejo's renderer recognizes it. - Inline `$...$` and already single-line `$$...$$` need no change and pass - through as-is. - -None of these rewrites touch fenced code blocks (```` ``` ```` or `~~~`, -including openings longer than three characters, e.g. ```` ```` ```` wrapping -a literal triple-backtick example). - -Wiki page ids are flat (no directories), so a source file living in a -sub-directory gets its directory path folded into the page id: a file at -`theory/encoding.md` becomes the page `theory-encoding`. Files at the root keep -their bare stem, except `index.md` which maps to `Home` — the page name -Gitea/Forgejo treats as the wiki's landing page. The same mapping is used to -resolve internal links, so cross-directory references stay consistent. If -folding still produces a collision the script refuses to write rather than -silently dropping a page. - -The `nav:` section of the MkDocs config is reproduced as a `_Sidebar.md` so the -wiki keeps the same top-level grouping (Home / Installation / Theory / Usage / -Formats / Architecture). Nav entries are usually `{label: path}` mappings, but -a bare `path` entry (no explicit label) is also honored: the label is taken -from the target file's first `# ` heading, falling back to a prettified -filename. The sidebar is static and shown on every page, which is the only -way Gitea/Forgejo expose a structured menu; the file is hidden from the page -list because its name starts with `_`. - -Usage: - mk_wiki.py OUTPUT [OPTIONS] - -Options: - --source DIR Source tree (default: UserDocMD next to this script's parent) - --config FILE MkDocs user config (default: /mkdocs-user.yml) - --csl FILE CSL citation style (default: /ecology-letters.csl) - --bib FILE BibTeX bibliography (default: /references.bib) - --no-sidebar do not generate _Sidebar.md - --verbose print every conversion -""" - -from __future__ import annotations - -import argparse -import re -import subprocess -import sys -from pathlib import Path - -import yaml - - -class ConversionError(Exception): - """Raised when a source file cannot be converted faithfully.""" - - -def _make_lenient_loader() -> type[yaml.SafeLoader]: - """A SafeLoader that ignores unknown YAML tags instead of erroring. - - The MkDocs config uses `!!python/name:pymdownx.superfences.fence_code_format` - on a custom-fence entry; PyYAML cannot resolve that tag without an unsafe - loader, but the script only needs the `nav:` section, which is plain YAML. - Treating unknown tags as their literal scalar value is enough. - """ - - class _LenientLoader(yaml.SafeLoader): - pass - - def _unknown_constructor(loader: yaml.Loader, node: yaml.Node): # type: ignore[no-untyped-def] - if isinstance(node, yaml.ScalarNode): - return loader.construct_scalar(node) - if isinstance(node, yaml.SequenceNode): - return loader.construct_sequence(node) - if isinstance(node, yaml.MappingNode): - return loader.construct_mapping(node) - return None - - _LenientLoader.add_constructor(None, _unknown_constructor) - return _LenientLoader - - -def find_repo_root(start: Path) -> Path: - """Walk up until we find a directory containing UserDocMD/.""" - for candidate in [start.resolve(), *start.resolve().parents]: - if (candidate / "UserDocMD").is_dir(): - return candidate - return start.resolve() - - -def is_external(target: str) -> bool: - return bool(re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", target)) or target.startswith("mailto:") - - -def split_anchor(target: str) -> tuple[str, str]: - if "#" in target: - path, anchor = target.split("#", 1) - return path, "#" + anchor - return target, "" - - -def wiki_page_id(src_root: Path, abs_target: Path) -> str: - """Map a source file to its wiki page id. - - Wikis are flat, so the directory path is folded into the id: a file at - `theory/encoding.md` becomes `theory-encoding`, while a root file keeps its - bare stem, except `index.md` which maps to `Home` — the page name - Gitea/Forgejo renders as the wiki's landing page. - """ - rel = abs_target.relative_to(src_root.resolve()) - parts = list(rel.parts) - if len(parts) > 1: - # Drop the .md suffix from the last part, join the rest with '-'. - return "-".join([*parts[:-1], parts[-1][:-3]]) - stem = parts[0][:-3] - return "Home" if stem == "index" else stem - - -def resolve_wiki_path(src_root: Path, src_file: Path, target: str) -> str | None: - """Turn a relative markdown target into a wiki page id. - - Returns None for targets we should leave as plain Markdown links - (external URLs, non-markdown files, missing files, or targets outside the - source tree). - """ - path, anchor = split_anchor(target) - if is_external(path) or path == "": - return None - if path.startswith("/"): - # MkDocs root-relative link: resolved against the docs root, not the - # current file's directory (Path("a") / "/b" would silently discard - # "a" and resolve "/b" from the filesystem root, which is wrong here). - abs_target = (src_root / path.lstrip("/")).resolve() - else: - abs_target = (src_file.parent / path).resolve() - try: - abs_target.relative_to(src_root.resolve()) - except ValueError: - return None - if abs_target.suffix != ".md": - return None - if not abs_target.is_file(): - return None - return wiki_page_id(src_root, abs_target) + anchor - - -LINK_RE = re.compile(r"\[([^\]]*)\]\(([^)\s]+)\)") -FENCE_RE = re.compile(r"^(`{3,}|~{3,})") -# Pandoc citation syntax, e.g. [@Zheng2020-ji; @Golan2025-xf] — just used to -# detect whether a file has any citation worth running through pandoc at all. -HAS_CITATION_RE = re.compile(r"\[@[^\]]+\]") - -# pandoc's markdown writer must be told, relative to its own defaults, to: -# -smart leave dashes/quotes as written (no em-dash -> "---") -# -fenced_divs emit the bibliography as raw HTML
(Goldmark -# has no ``:::`` fenced-div extension) -# -simple_tables, -multiline_tables, -grid_tables, +pipe_tables -# keep GFM pipe-table syntax, the only kind Goldmark -# parses, instead of pandoc's space-aligned tables -# +fenced_code_blocks (pandoc still emits an indented block for a fence -# with no language tag regardless of this extension — -# such fences need a language hint in the source) -# -header_attributes Goldmark has no `{#id .class}` heading-attribute -# syntax; without this the "Bibliography" heading pandoc -# adds (see BIBLIOGRAPHY_TITLE below) would render with -# a literal `{#bibliography .unnumbered}` after it -PANDOC_MARKDOWN_FORMAT = ( - "markdown-smart-fenced_divs-simple_tables-multiline_tables-grid_tables" - "-header_attributes+pipe_tables+fenced_code_blocks" -) - -# Title pandoc gives the generated bibliography section (always emitted as a -# level-1 `# ` heading, with no option to pick the level) — demoted to `##` -# below to match the rest of this doc set's heading hierarchy. -BIBLIOGRAPHY_TITLE = "Bibliography" - - -class FenceState: - """Tracks whether the current line is inside a fenced code block. - - A closing fence must use the same character and be at least as long as - the opening one (CommonMark rule) — this is what lets a source file wrap - a literal ``` example inside a longer ```` fence. - """ - - def __init__(self) -> None: - self.marker = "" - - def toggle(self, line: str) -> bool: - """Update state for a fence delimiter line; return True if it is one.""" - m = FENCE_RE.match(line.rstrip("\n")) - if not m: - return False - run = m.group(1) - if not self.marker: - self.marker = run - elif run[0] == self.marker[0] and len(run) >= len(self.marker): - self.marker = "" - return True - - @property - def active(self) -> bool: - return bool(self.marker) - - -def convert_links(text: str, src_root: Path, src_file: Path, verbose: bool) -> str: - out_lines: list[str] = [] - fence = FenceState() - - for line in text.splitlines(keepends=True): - if fence.toggle(line) or fence.active: - out_lines.append(line) - continue - - def repl(m: re.Match) -> str: - label, target = m.group(1), m.group(2) - wiki = resolve_wiki_path(src_root, src_file, target) - if wiki is None: - return m.group(0) # external or non-md: leave as Markdown - if verbose: - print(f" {src_file.relative_to(src_root)}: [{label}]({target}) -> [{label}]({wiki})") - return f"[{label}]({wiki})" - - out_lines.append(LINK_RE.sub(repl, line)) - - return "".join(out_lines) - - -def convert_citations( - text: str, src_root: Path, src_file: Path, csl_path: Path, bib_path: Path, verbose: bool -) -> str: - """Render Pandoc `[@key; @key]` citations with the project's real CSL style. - - Skips files with no citation entirely, so a missing `--csl`/`--bib` or a - missing `pandoc` binary is only an error for files that actually need it. - """ - if not HAS_CITATION_RE.search(text): - return text - - if not csl_path.is_file(): - raise ConversionError(f"{src_file.relative_to(src_root)}: CSL style not found: {csl_path}") - if not bib_path.is_file(): - raise ConversionError(f"{src_file.relative_to(src_root)}: bibliography not found: {bib_path}") - - try: - result = subprocess.run( - [ - "pandoc", - "--citeproc", - f"--csl={csl_path}", - f"--bibliography={bib_path}", - "--wrap=none", - f"--metadata=link-citations=true", - f"--metadata=reference-section-title={BIBLIOGRAPHY_TITLE}", - "-f", - "markdown-smart", - "-t", - PANDOC_MARKDOWN_FORMAT, - ], - input=text, - capture_output=True, - text=True, - ) - except FileNotFoundError: - raise ConversionError( - f"{src_file.relative_to(src_root)}: 'pandoc' not found on PATH, needed to render citations" - ) from None - - if result.returncode != 0: - raise ConversionError( - f"{src_file.relative_to(src_root)}: pandoc failed to render citations:\n{result.stderr}" - ) - - # pandoc always emits the bibliography title as a level-1 heading; demote - # it to `##` to match the rest of this doc set's hierarchy. - out = result.stdout.replace(f"\n# {BIBLIOGRAPHY_TITLE}\n", f"\n## {BIBLIOGRAPHY_TITLE}\n") - - if verbose: - n = len(HAS_CITATION_RE.findall(text)) - print(f" {src_file.relative_to(src_root)}: rendered {n} citation group(s) via pandoc/{csl_path.name}") - - return out - - -def convert_math(text: str, src_root: Path, src_file: Path, verbose: bool) -> str: - """Collapse multi-line `$$...$$` display blocks onto a single line. - - Gitea/Forgejo's math renderer only recognizes `$$...$$` when it sits on - one physical line; a block opened and closed on their own bare `$$` line - (the natural Pandoc/MkDocs style) renders as literal text otherwise. - Interior line breaks are replaced by spaces (insignificant in math mode); - `\\\\` row separators inside `aligned`/`cases` environments are untouched. - Already single-line `$$...$$` and inline `$...$` need no change. - """ - lines = text.split("\n") - out: list[str] = [] - fence = FenceState() - i = 0 - n = len(lines) - while i < n: - line = lines[i] - if fence.toggle(line) or fence.active: - out.append(line) - i += 1 - continue - - if line.strip() == "$$": - body: list[str] = [] - i += 1 - closed = False - while i < n: - if lines[i].strip() == "$$": - closed = True - i += 1 - break - body.append(lines[i].strip()) - i += 1 - if not closed: - raise ConversionError( - f"{src_file.relative_to(src_root)}: unterminated $$ display math block" - ) - collapsed = "$$" + " ".join(part for part in body if part) + "$$" - if verbose: - print(f" {src_file.relative_to(src_root)}: collapsed {len(body)}-line $$ block") - out.append(collapsed) - continue - - out.append(line) - i += 1 - - return "\n".join(out) - - -def convert_file( - src_root: Path, src_file: Path, csl_path: Path, bib_path: Path, verbose: bool -) -> str: - text = src_file.read_text(encoding="utf-8") - # Citations first, before pandoc has seen any of our own wiki-specific - # rewrites: it needs to parse plain, unmodified Markdown. - text = convert_citations(text, src_root, src_file, csl_path, bib_path, verbose) - text = convert_math(text, src_root, src_file, verbose) - text = convert_links(text, src_root, src_file, verbose) - return text - - -def _default_label(src_root: Path, rel_path: str) -> str: - """Derive a nav label for a bare `path.md` entry (no explicit label). - - Mirrors MkDocs' own fallback: use the page's first `# ` heading if it has - one, otherwise prettify the filename. - """ - target = src_root / rel_path - if target.is_file(): - for line in target.read_text(encoding="utf-8").splitlines(): - if line.startswith("# "): - return line[2:].strip() - return Path(rel_path).stem.replace("_", " ").replace("-", " ").title() - - -def build_sidebar(src_root: Path, config_path: Path) -> str | None: - """Render the MkDocs `nav:` section as a Gitea/Forgejo `_Sidebar.md`. - - Returns None if the config is missing or has no usable `nav:` section. - Each nav entry is either a bare `path` string or a `{label: path}` pair - (or a nested list for a group); the path is mapped through `wiki_page_id` - so the sidebar links to the flattened page ids. - """ - if not config_path.is_file(): - print(f"warning: config not found, skipping sidebar: {config_path}") - return None - - try: - with config_path.open(encoding="utf-8") as fh: - cfg = yaml.safe_load(fh) - except yaml.YAMLError: - # The MkDocs config carries `!!python/name:...` tags that SafeLoader - # cannot resolve; fall back to a lenient loader that treats unknown - # tags as plain scalars so the `nav:` section is still readable. - try: - with config_path.open(encoding="utf-8") as fh: - cfg = yaml.load(fh, Loader=_make_lenient_loader()) - except yaml.YAMLError as exc2: - print(f"warning: could not parse {config_path}: {exc2}") - return None - - nav = cfg.get("nav") if isinstance(cfg, dict) else None - if not nav: - print(f"warning: no `nav:` section in {config_path}, skipping sidebar") - return None - - def link_line(depth: int, rel_path: str, label: str) -> str: - page = wiki_page_id(src_root, (src_root / rel_path).resolve()) - return f"{' ' * depth}- [{label}]({page})" - - def render_entry(entry: object, depth: int) -> list[str]: - if isinstance(entry, str): - return [link_line(depth, entry, _default_label(src_root, entry))] - if not isinstance(entry, dict): - return [] - lines: list[str] = [] - for label, target in entry.items(): - if isinstance(target, str): - lines.append(link_line(depth, target, label)) - elif isinstance(target, list): - # Headings must never be indented: CommonMark treats a line - # indented by 4+ spaces as a code block, not an ATX heading, - # which a depth-scaled indent would trigger from depth 2 on. - lines.append(f"## {label}") - lines.extend(render_subtree(target, depth + 1)) - return lines - - def render_subtree(nodes: list[object], depth: int) -> list[str]: - out: list[str] = [] - for node in nodes: - out.extend(render_entry(node, depth)) - return out - - body = render_subtree(nav, 0) - if not body: - return None - - return "# Wiki sidebar\n\n" + "\n".join(body) + "\n" - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("output", help="destination wiki directory (created if missing)") - ap.add_argument("--source", default=None, help="source Markdown tree (default: /UserDocMD)") - ap.add_argument("--config", default=None, - help="MkDocs user config (default: /mkdocs-user.yml)") - ap.add_argument("--csl", default=None, - help="CSL citation style (default: /ecology-letters.csl)") - ap.add_argument("--bib", default=None, - help="BibTeX bibliography (default: /references.bib)") - ap.add_argument("--no-sidebar", action="store_true", help="do not generate _Sidebar.md") - ap.add_argument("--verbose", action="store_true", help="print every conversion") - args = ap.parse_args() - - script_dir = Path(__file__).resolve().parent - repo_root = find_repo_root(script_dir) - src_root = Path(args.source).resolve() if args.source else (repo_root / "UserDocMD") - out_root = Path(args.output).resolve() - config_path = Path(args.config).resolve() if args.config else (repo_root / "mkdocs-user.yml") - csl_path = Path(args.csl).resolve() if args.csl else (src_root / "ecology-letters.csl") - bib_path = Path(args.bib).resolve() if args.bib else (src_root / "references.bib") - - if not src_root.is_dir(): - print(f"error: source tree not found: {src_root}", file=sys.stderr) - return 2 - - md_files = sorted(p for p in src_root.rglob("*.md") if p.is_file()) - if not md_files: - print(f"error: no Markdown files under {src_root}", file=sys.stderr) - return 2 - - # A wiki is flat, so the destination filename is the source path folded into - # a page id. Detect collisions up front so a silent overwrite does not drop - # a page. - by_name: dict[str, list[Path]] = {} - for src in md_files: - by_name.setdefault(wiki_page_id(src_root, src), []).append(src) - collisions = {name: paths for name, paths in by_name.items() if len(paths) > 1} - if collisions: - for name, paths in sorted(collisions.items()): - print(f"error: wiki page id collision '{name}':", file=sys.stderr) - for p in paths: - print(f" {p.relative_to(src_root)}", file=sys.stderr) - return 2 - - out_root.mkdir(parents=True, exist_ok=True) - written = 0 - for src in md_files: - dst = out_root / (wiki_page_id(src_root, src) + ".md") - try: - content = convert_file(src_root, src, csl_path, bib_path, args.verbose) - except ConversionError as exc: - print(f"error: {exc}", file=sys.stderr) - return 2 - dst.write_text(content, encoding="utf-8") - written += 1 - - if not args.no_sidebar: - sidebar = build_sidebar(src_root, config_path) - if sidebar is not None: - (out_root / "_Sidebar.md").write_text(sidebar, encoding="utf-8") - written += 1 - - print(f"converted {written} Markdown file(s) from {src_root} -> {out_root}") - return 0 - - -if __name__ == "__main__": - sys.exit(main())