Files
obikmer/UserDocMD/theory/kmer_indexing/kmers.md
T
Eric Coissac 0d1ecac233 Refactor k-mer indexing, enhance session features, and update documentation
This commit introduces significant refinements across the codebase. Core indexing logic is updated with hard constraints on k-mer length, statistical modeling clarifications, and the implementation of the Karlin & Ost theory for chance-collision statistics. Session management features are enhanced with robust memoization capabilities, atomic file operations, per-key locking, and memory mapping support. Additionally, documentation is updated, including a new citation style, and new mathematical notebook support is added.
2026-10-13 08:41:42 +02:00

19 KiB

K-mer size

A k-mer is a DNA sequence of length k. OBIKmer is designed to index large k-mers. Here, large refers to a k-mer length for which the probability of observing the same k-mer in several genomes by chance alone is sufficiently small. The k-mer length must therefore be large enough that, when a k-mer is observed in several genomes of the dataset, the probability that this shared occurrence is due to chance alone is sufficiently low for the match to be considered evidence of homology.

OBIKmer restricts k to odd values in the range


11 \leq k \leq 31.

These limits result from two different considerations. The upper bound is imposed by the representation used by OBIKmer, whereas the lower bound defines a practical range of k-mer lengths for genome-scale sequence comparisons. This range covers most practical applications: the lower limit is well below the k-mer size that can be considered large, even for the smallest bacterial genomes, whereas the upper limit provides sufficient specificity for most applications, including those involving very large genomes.

Representation limit

OBIKmer uses two bits to encode each nucleotide. Therefore, a k-mer requires 2k bits. To ensure computational efficiency, OBIKmer limits the representation of k-mers to a single 64-bit word, thereby restricting their length.


2k \leq 64,

This gives the hard representation limit: k \leq 32. Furthermore, OBIKmer only considers odd values of k, meaning the largest supported k-mer size is 31.

K-mer specificity

A simple way to illustrate the effect of k-mer size is to consider a random DNA sequence in which the four nucleotides are independent and equally probable. There are


4^k

possible k-mers, and a particular k-mer is therefore expected to occur once every 4^k positions on average. In a sequence of length G, the expected number of occurrences of a particular k-mer is approximately


E[n_K] \simeq \frac{G}{4^k}.

When 4^k\gg G, this quantity is also a good approximation of the probability that an observed k-mer will occur at least once by chance elsewhere in a sequence of length G. It therefore provides a simple measure of the risk of a chance recurrence of an observed k-mer:


P_{\mathrm{chance}}(k,G) \simeq \frac{G}{4^k}.

This probability decreases by a factor of four for every additional nucleotide in the k-mer. Conversely, it increases linearly with the amount of sequence searched.

This simple model already shows why very short k-mers provide limited specificity for genome-scale analyses. With k=11,


4^{11}\simeq4.2\times10^6,

which is a small combinatorial space even compared with the size of very small bacterial genomes. In contrast,


4^{31}\simeq4.6\times10^{18},

which is vastly larger than the number of k-mer positions even in very large genomes. Thus, increasing k from 11 to 31 provides an enormous increase in sequence specificity.

The estimate above is intentionally simplistic. Real genomes do not consist of independent, equiprobable nucleotides: nucleotide composition and sequence dependencies affect the probability of observing particular words. More accurate estimates of the probability of observing matches by chance therefore take sequence length and nucleotide composition into account.

Karlin and Ost provide an analytical framework for this problem based on the distribution of the longest exact match expected between random sequences. If L_{\max} denotes the length of the longest seed observed in random sequences of given size and nucleotide composition, the corresponding seed-level probability is


P_{\mathrm{seeds}}(L)=P(L_{\max}\geq L).

Conversely, for a chosen false-positive probability P, one can determine the minimum seed length L_{\min} such that matches of length L_{\min} or greater are not expected to occur by chance. This is the approach used by Repseek to determine statistically significant seed lengths.

The simple G/4^k estimate and the Karlin–Ost statistics therefore describe the same fundamental effect at different levels of approximation: the probability of a chance match decreases rapidly with k-mer length, while the amount of sequence being searched increases the opportunity for such matches.

Consequently, the appropriate value of k depends on the total amount of sequence being compared and its nucleotide composition. Choosing k appropriately allows the false-positive rate of homology inference to be controlled.

Considering that bacterial genomes are typically a few megabases long, with the smallesr plublished today Mycoplasma genitalium having a size G=580\,Mb [@Fraser1995-jc], and the largest 13\,Mb in Sorangium cellulosum [@Schneiker2007-gs]. For such genomes, the space of 11-mers is already to small to get a reasonable false positive rate:


\begin{aligned}
P(C\geq1) &= 1- e^{-\frac{580.000^2}{2 \cdot 4^{11}}} \\
&\simeq 1
\end{aligned}

, whereas 21-mers already provide a space of several trillion possible sequences.

Plant genomes illustrate the opposite situation. Plant genome sizes span several orders of magnitude, from the smallest angiosperm genomes present in the carnivorous plans genus [@Fleischmann2014-ed] about 60 Mb to the largest one 160 Gb in Tmesipteris oblanceolata, a New Caledonian fork fern [@Fernandez2024-kd], and large genomes often contain substantial amounts of repeated sequence. Even at k=31, however, the theoretical k-mer space remains vastly larger than any individual genome. At these lengths, the limiting factor is therefore not exhaustion of the theoretical k-mer space but the biological repetitiveness and non-random composition of the genome.

For example, the number of possible k-mers grows as follows:

k 4^k 4^k/2 after canonicalization
11 4.19\times10^6 2.10\times10^6
15 1.07\times10^9 5.37\times10^8
21 4.40\times10^{12} 2.20\times10^{12}
25 1.13\times10^{15} 5.63\times10^{14}
31 4.61\times10^{18} 2.31\times10^{18}

Canonicalization approximately halves the number of possible representations because a k-mer and its reverse complement are represented by the same canonical form.

The distinction between the simple 4^k model and the Karlin--Ost framework is important. The former describes the size of the combinatorial k-mer space; the latter describes the probability of observing long matches in sequences whose composition may depart from the uniform random model. Consequently, the value of k cannot be selected from genome size alone.

These scales have very different implications for different genome sizes.

The random-sequence calculation is only a null model. Real genomes exhibit strong and reproducible oligonucleotide composition biases. Karlin and colleagues showed that relative abundances of short oligonucleotides, in particular dinucleotides, form characteristic genomic signatures that remain relatively stable within genomes and differ between organisms [@Karlin1995; @Karlin1997]. More generally, short k-mer frequencies can therefore capture compositional properties of genomes rather than provide highly specific sequence identifiers.

This distinction is important for whole-genome k-mer comparison. Increasing k increases the theoretical diversity of the k-mer space exponentially and generally increases the proportion of k-mers that occur at unique genomic positions. Conversely, shorter k-mers occur more frequently and are more strongly influenced by genomic composition and repeated sequence. Empirical studies of k-mer spectra show this transition clearly: for example, k-mers of length k\leq11 can behave primarily as genomic-composition signatures, whereas longer k-mers progressively provide greater sequence specificity.

The supported range 11\leq k\leq31 should therefore be understood as an engineering compromise rather than as a universal biological optimum. Smaller values increase the probability that unrelated genomic regions share the same k-mers, while larger values increase specificity but also make the representation more sensitive to substitutions, indels, and incomplete homology. The appropriate value within this range consequently depends on the biological scale and comparison task.

Odd k-mer lengths

OBIKmer additionally requires k to be odd. This constraint is independent of the resolution argument above.

For an odd-length DNA sequence, a k-mer cannot be identical to its own reverse complement. Consequently, every k-mer has two distinct orientations, which can be unambiguously collapsed into a canonical representation. For even k, self-reverse-complementary sequences exist, so a k-mer can coincide with its own reverse complement.

Odd k is therefore not required for canonicalization itself: the canonical form


s^c=\min_{\mathrm{lex}}\left(s,\operatorname{RC}(s)\right)

remains well defined for even k. The odd-k restriction instead guarantees that the two orientations are always distinct, which simplifies the representation and orientation handling used by OBIKmer.

Karlin--Ost (1988) formula

[@Karlin1988] considers s independent stationary letter sequences over a finite alphabet and studies K_{r,s}(N), the length of the longest word common to r of the s sequences, each of length N. For i.i.d. equiprobable letters over an alphabet of size m (here m=4 for DNA), the characteristic local match parameter reduces to


\lambda^{[r]} = m^{1-r},

so for r=2 (a word shared by two occurrences), \lambda = m^{-1} = 1/4.

The expected number of common words of length k among the \binom{s}{r} relevant groups of sequences is


S_1(N,k) = N^{r}\binom{s}{r}\gamma\,\lambda^{k}\,(1+o(1)),

with \gamma=1 exactly in the i.i.d. equiprobable case. Theorem 2.2 gives the limiting distribution of K_{r,s}(N), with k set on the scale k=\left[\dfrac{\log N^{r}}{-\log\lambda^{*}}+x+1\right]:


\lim_{N\to\infty}\left[\Pr\{K_{r,s}(N)<k\} - \exp\{-(1-\lambda^{*})\,S_1(N,k)\}\right] = 0,

equivalently


\frac{-\log\Pr\{K_{r,s}(N)<k\}}{(\lambda^{*})^{\rho(N,x)}} \xrightarrow[N\to\infty]{} (1-\lambda^{*})\,\gamma^{*}(\lambda^{*})^{x}.

The factor (1-\lambda^{*}) multiplying S_1(N,k) is the key correction over the naive pairwise-collision count: it de-clumps overlapping candidate matches, which are not independent events, into an effective Poisson rate. This theorem is stated for s\geq2 independent sequences (e.g. comparing two distinct genomes); the intra-sequence self-repeat case (a single genome compared to itself) is treated separately, via the reverse-complement match length R(N), in [@Karlin1985].

o(1) (« petit o de 1 ») désigne une quantité qui tend vers 0 quand $N\to\infty$, mais dont on ne précise pas la vitesse exacte ni la formule exacte. C'est une façon d'écrire « il reste un terme d'erreur, mais il devient négligeable ».

Concrètement dans S_1(N,k) = N^{r}\binom{s}{r}\gamma\,\lambda^{k}\,(1+o(1)) :

  • N^{r}\binom{s}{r}\gamma\,\lambda^{k} est la valeur exacte à la limite, celle qu'on utilise en pratique (c'est elle qui redonne E[C] de notre discussion).
  • (1+o(1)) dit : « la vraie valeur de S_1(N,k) n'est pas exactement égale à ce produit pour N fini, mais le rapport entre les deux tend vers 1 quand N\to\infty ». Autrement dit S_1(N,k) / \left[N^{r}\binom{s}{r}\gamma\lambda^{k}\right] \to 1.

Pourquoi ce terme existe : la formule F_\sigma(k)/\lambda^k \to \gamma (éq. 2.8 du papier) est elle-même une limite quand k\to\infty — pour k fini, il y a un petit écart entre F_\sigma(k) et \gamma\lambda^k. C'est cet écart-là qui devient le o(1).

Ce que ça implique pour l'usage pratique : dans le cas iid équiprobable que tu utilises (ADN, \gamma=1 exactement, pas seulement à la limite — je l'ai vérifié directement sur la dérivation : F_\sigma(k)=m^{-k}=\lambda^k pour tout k, pas juste asymptotiquement), le o(1) est en réalité nul dans ce cas précis, pas juste négligeable. La formule S_1(N,k)=N^r\binom{s}{r}\lambda^k est donc exacte (à l'asymptotique en N près, qui elle vient d'ailleurs — de l'approximation de Poisson elle-même, pas de ce \gamma).

Les deux approches sont légitimes, mais elles répondent à des questions différentes — et il y a une relation algébrique exacte entre les deux qui vaut la peine d'être explicitée.

Ce que calcule l'approche naïve. Pour un k-mer w déjà observé et fixé, p_i\simeq1-\exp(-G_i/4^k) est la probabilité que ce mot précis apparaisse quelque part dans le génome i par hasard, et P(R\geq r) (Poisson-binomiale ou binomiale) est la probabilité que ce mot précis soit partagé par au moins r des S génomes par hasard. C'est une p-value par observation : « j'ai vu ce k-mer particulier dans 5 génomes sur 10, est-ce surprenant pour lui ? »

Ce que calcule Karlin-Ost. S_1(k) et P(K_{r,s}\geq k) répondent à : « parmi tous les 4^k mots possibles, quelle est la probabilité qu'au moins un seul d'entre eux atteigne ce seuil de partage par hasard, n'importe où dans les génomes ? » C'est une question globale sur tout l'espace des k-mers, pas sur un mot déjà identifié.

La relation exacte entre les deux. Reprenons le cas r=s=2, génomes égaux de taille G :

  • Naïf (mot w fixé) : P(R=2\mid w)\simeq p^2=(G\cdot4^{-k})^2=G^2\cdot4^{-2k}
  • Karlin-Ost : S_1=G^2\cdot4^{-k}

Le rapport est exactement S_1 / P(R=2\mid w) = 4^{k} — c'est-à-dire le nombre de mots possibles. Ce n'est pas une coïncidence : S_1=N^r\binom{s}{r}\lambda^k vient de \lambda^k=\sum_w \Pr\{w\}^r, une somme explicite sur les 4^k mots, alors que le calcul naïf tel que présenté ne somme sur rien — il traite w comme donné.

Donc l'approche naïve, formellement, c'est Karlin-Ost auquel il manque le facteur « nombre de k-mers testés ». Pour la rendre comparable à la question « dois-je m'attendre à une collision fortuite n'importe où dans mon jeu de données », il faudrait une correction à la Bonferroni : multiplier P(R\geq r\mid w) par le nombre effectif de k-mers canoniques testables (\approx4^k/2). Karlin-Ost fait cette correction analytiquement et correctement (avec en prime le facteur de déclumping (1-\lambda) qu'on a discuté, qui corrige le sur-comptage des matches chevauchants — une union bound brute comme le Bonferroni décrit ci-dessus le surestimerait légèrement).

Ce qui veut dire, en pratique, que les deux outils ne sont pas concurrents mais complémentaires :

  • Choix a priori de k / FPR global du dataset (la question de kmers.md depuis le début de cette conversation) → Karlin-Ost, parce qu'il intègre nativement la multiplicité sur tous les mots possibles.
  • Score de significativité a posteriori pour un k-mer effectivement observé dans l'index (« ce hit précis, présent dans r génomes sur S, est-il compatible avec le hasard ? ») → l'approche Poisson-binomiale est exactement le bon outil, et même préférable à Karlin-Ost pour cet usage : elle gère nativement des G_i inégaux sans les subtilités de convergence du théorème 2.2, et elle donne directement une p-value par hit exploitable pour filtrer les résultats d'un index présence/absence — ce qui correspond bien à l'usage qu'a en tête ton correspondant.

Une seule réserve sur le texte proposé tel quel : p_i\simeq1-\exp(-G_i/4^k) souffre du même biais que celui identifié plus tôt dans notre discussion — un mot de longueur k n'est pas indépendant à chaque position (chevauchement), donc ce p_i est un peu optimiste (légèrement trop haut) pour les mêmes raisons que E[C] l'était. Négligeable pour k\geq21, plus discutable à k=11.

FDR

C'est exactement la bonne question à se poser — ni la p-value par hit, ni la probabilité globale « y a-t-il au moins une collision quelque part », mais la fraction de tes appels d'homologie qui sont du bruit. C'est un problème de type FDR (false discovery rate), et il se construit directement à partir des deux briques qu'on a déjà :


\widehat{FDR}(r) = \frac{\text{nombre de k-mers *attendus par hasard* avec }R\geq r}{\text{nombre de k-mers *observés* avec }R\geq r}

Le numérateur (bruit attendu) : c'est la généralisation, au seuil \geq r (pas seulement « partagé par exactement ces r génomes »), de la quantité pont qu'on vient d'identifier — le nombre de k-mers testés M multiplié par la probabilité par-mot sous le null :


E[\text{faux positifs}] \simeq M \cdot P_0(R\geq r) = M\sum_{j=r}^{S}\binom{S}{j}p^{j}(1-p)^{S-j}

avec p\simeq G/4^k (ou la version Poisson-binomiale à G_i inégaux) et M le nombre de k-mers canoniques réellement testés (pas 4^k/2 théorique, mais le nombre de k-mers effectivement présents dans ton index — c'est cette correction, plutôt que le 4^k théorique, qui rend l'estimation réaliste, puisque la plupart des 4^k mots possibles n'apparaissent jamais dans de vrais génomes).

Le dénominateur (bruit + vrai signal, observé) : le nombre de k-mers de ton index dont le masque de présence a une cardinalité \geq r — une donnée que FamilyMask/SiblingAnnex dans obikphylo::siblings te donne déjà directement, sans aucun calcul supplémentaire.

Ce que ça donne concrètement. Tu n'as besoin que de trois nombres, tous déjà disponibles ou calculables :

  1. M = cardinalité totale de ton set de k-mers indexés (mesure directe de l'index)
  2. N_{obs}(r) = nombre de familles/k-mers avec présence \geq r (mesure directe, déjà dans FamilyMask)
  3. P_0(R\geq r) = calculé depuis le modèle nul (le p de l'approche « naïve » du tour précédent)

et \widehat{FDR}(r) = M\cdot P_0(R\geq r) / N_{obs}(r) te dit directement : « sur les k-mers que j'ai retenus comme preuve d'homologie au seuil r, telle fraction (%) est attendue être du pur hasard ».

Pourquoi c'est mieux que ce qu'on avait avant :

  • Le P(K_{r,s}\geq k) de Karlin-Ost (tour précédent) répond à « y a-t-il au moins un faux positif quelque part » — binaire, ne dit rien sur combien.
  • La p-value par hit répond à « ce hit précis est-il suspect » — mot par mot, ne donne pas de vue d'ensemble.
  • Le \widehat{FDR} répond directement à ta question : quelle proportion de l'ensemble retenu est due au hasard — c'est la quantité qu'on utiliserait pour dire « à ce seuil r, mon jeu de zones d'homologie candidates est fiable à 95 % » ou pour choisir le r minimal qui ramène le \widehat{FDR} sous un seuil acceptable, à k fixé par la contrainte de représentation (64 bits).

Un point à trancher avec toi avant d'aller plus loin : pour M, préfères-tu le nombre théorique de k-mers canoniques possibles (4^k/2) ou le nombre réel de k-mers distincts dans ton index (qui donnerait un \widehat{FDR} beaucoup plus conservateur et réaliste, mais nécessite de le lire depuis l'index au moment du calcul plutôt que de le dériver de k seul) ?