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.
This commit is contained in:
Eric Coissac committed 2026-10-13 08:41:42 +02:00
1 parent e715528d34
commit 0d1ecac233
13 files changed
+1683 -18

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
<?xml version="1.0" encoding="utf-8"?>
<style xmlns="http://purl.org/net/xbiblio/csl" class="in-text" version="1.0" default-locale="en-US" demote-non-dropping-particle="sort-only">
<info>
<title>Molecular Ecology Modified</title>
<id>http://www.zotero.org/styles/molecular-ecology</id>
<link href="http://www.zotero.org/styles/molecular-ecology" rel="self"/>
<link href="http://www.zotero.org/styles/ecology-letters" rel="template"/>
<link href="http://onlinelibrary.wiley.com/journal/10.1111/%28ISSN%291365-294X/homepage/ForAuthors.html" rel="documentation"/>
<author>
<name>Xiaodong Dang</name>
<email>dangxdong@gmail.com</email>
</author>
<contributor>
<name>Johan Asplund</name>
<email>asplundj@gmail.com</email>
</contributor>
<contributor>
<name>David Kaplan</name>
<email>david.kaplan@ird.fr</email>
</contributor>
<category citation-format="author-date"/>
<category field="biology"/>
<issn>0962-1083</issn>
<eissn>1365-294X</eissn>
<updated>2012-09-09T22:24:43+00:00</updated>
<rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
</info>
<macro name="editor-translator">
<names variable="editor translator" prefix=" (" delimiter=", " suffix=")">
<name initialize-with="" delimiter=", "/>
<label form="short" prefix=", " text-case="capitalize-first" suffix="," strip-periods="true"/>
</names>
</macro>
<macro name="author">
<names variable="author">
<name name-as-sort-order="all" sort-separator=" " initialize-with="" delimiter=", " delimiter-precedes-et-al="never"/>
<label form="short" prefix=" (" suffix=")" text-case="capitalize-first"/>
<et-al font-style="italic"/>
<substitute>
<names variable="editor"/>
<names variable="translator"/>
<text macro="title"/>
</substitute>
</names>
</macro>
<macro name="author-short">
<names variable="author">
<name form="short" and="symbol" delimiter=", " initialize-with=". "/>
<et-al font-style="italic"/>
<substitute>
<names variable="editor"/>
<names variable="translator"/>
<choose>
<if type="bill book graphic legal_case legislation motion_picture report song" match="any">
<text variable="title" form="short" font-style="italic"/>
</if>
<else>
<text variable="title" form="short" quotes="true"/>
</else>
</choose>
</substitute>
</names>
</macro>
<macro name="title">
<choose>
<if type="bill book graphic legal_case legislation motion_picture report song" match="any">
<text variable="title" font-style="italic"/>
</if>
<else>
<text variable="title"/>
</else>
</choose>
</macro>
<macro name="publisher">
<group delimiter=", ">
<text variable="publisher"/>
<text variable="publisher-place"/>
</group>
</macro>
<citation collapse="year-suffix" et-al-min="3" et-al-use-first="1" disambiguate-add-year-suffix="true">
<sort>
<key variable="issued"/>
<key variable="author"/>
</sort>
<layout prefix="(" suffix=")" delimiter="; ">
<group delimiter=" ">
<text macro="author-short"/>
<date variable="issued">
<date-part name="year"/>
</date>
<group>
<label variable="locator" form="short"/>
<text variable="locator" prefix=" "/>
</group>
</group>
</layout>
</citation>
<bibliography hanging-indent="true" et-al-min="6" et-al-use-first="1000" entry-spacing="0.5" line-spacing="1">
<sort>
<key macro="author-short"/>
<key variable="issued"/>
</sort>
<layout>
<text macro="author" suffix=" "/>
<date variable="issued" prefix="(" suffix=")">
<date-part name="year"/>
</date>
<choose>
<if type="bill book graphic legal_case legislation motion_picture report song" match="any">
<group suffix=".">
<text macro="title" prefix=" "/>
<text macro="editor-translator" prefix=" "/>
</group>
<text prefix=" " suffix="." macro="publisher"/>
</if>
<else-if type="thesis" match="any">
<group suffix=".">
<text macro="title" prefix=" " suffix="."/>
<text variable="genre" prefix=" " suffix=" Thesis."/>
<text prefix=" " macro="publisher"/>
</group>
</else-if>
<else-if type="chapter paper-conference" match="any">
<text macro="title" prefix=" "/>
<group prefix=".">
<group prefix=" In:">
<text variable="container-title" font-style="italic" prefix=" "/>
<text variable="collection-title" prefix=" " suffix="."/>
<names variable="editor translator" prefix=" (" delimiter=", " suffix=")">
<label form="short" suffix=" " strip-periods="true"/>
<name name-as-sort-order="all" sort-separator=" " initialize-with="" delimiter=", " delimiter-precedes-last="never"/>
</names>
<group suffix=".">
<label variable="page" form="short" prefix=", " suffix=" "/>
<text variable="page"/>
<text macro="publisher" prefix=". " suffix="."/>
</group>
</group>
</group>
</else-if>
<else>
<group suffix=".">
<text macro="title" prefix=" "/>
<text macro="editor-translator" prefix=" "/>
</group>
<group prefix=" " suffix=".">
<text variable="container-title" text-case="title" font-style="italic"/>
<group prefix=", ">
<text variable="volume" font-weight="bold"/>
</group>
<text variable="page" prefix=", "/>
</group>
</else>
</choose>
</layout>
</bibliography>
</style>
+202
View File
@@ -566,3 +566,205 @@
issn = "0167-8655,1872-7344",
language = "en"
}
@ARTICLE{Fleischmann2014-ed,
title = {Evolution of genome size and chromosome number in the
carnivorous plant genus Genlisea (Lentibulariaceae), with a new
estimate of the minimum genome size in angiosperms},
author = "Fleischmann, Andreas and Michael, Todd P and Rivadavia, Fernando
and Sousa, Aretuza and Wang, Wenqin and Temsch, Eva M and
Greilhuber, Johann and Müller, Kai F and Heubl, Günther",
journal = "Annals of Botany",
publisher = "Oxford University Press (OUP)",
volume = 114,
number = 8,
pages = "1651--1663",
abstract = "BACKGROUND AND AIMS: Some species of Genlisea possess ultrasmall
nuclear genomes, the smallest known among angiosperms, and some
have been found to have chromosomes of diminutive size, which may
explain why chromosome numbers and karyotypes are not known for
the majority of species of the genus. However, other members of
the genus do not possess ultrasmall genomes, nor do most taxa
studied in related genera of the family or order. This study
therefore examined the evolution of genome sizes and chromosome
numbers in Genlisea in a phylogenetic context. The correlations
of genome size with chromosome number and size, with the
phylogeny of the group and with growth forms and habitats were
also examined. METHODS: Nuclear genome sizes were measured from
cultivated plant material for a comprehensive sampling of taxa,
including nearly half of all species of Genlisea and representing
all major lineages. Flow cytometric measurements were conducted
in parallel in two laboratories in order to compare the
consistency of different methods and controls. Chromosome counts
were performed for the majority of taxa, comparing different
staining techniques for the ultrasmall chromosomes. KEY RESULTS:
Genome sizes of 15 taxa of Genlisea are presented and interpreted
in a phylogenetic context. A high degree of congruence was found
between genome size distribution and the major phylogenetic
lineages. Ultrasmall genomes with 1C values of <100 Mbp were
almost exclusively found in a derived lineage of South American
species. The ancestral haploid chromosome number was inferred to
be n = 8. Chromosome numbers in Genlisea ranged from 2n = 2x = 16
to 2n = 4x = 32. Ascendant dysploid series (2n = 36, 38) are
documented for three derived taxa. The different ploidy levels
corresponded to the two subgenera, but were not directly
correlated to differences in genome size; the three different
karyotype ranges mirrored the different sections of the genus.
The smallest known plant genomes were not found in G. margaretae,
as previously reported, but in G. tuberosa (1C ≈ 61 Mbp) and some
strains of G. aurea (1C ≈ 64 Mbp). CONCLUSIONS: Genlisea is an
ideal candidate model organism for the understanding of genome
reduction as the genus includes species with both relatively
large (∼1700 Mbp) and ultrasmall (∼61 Mbp) genomes. This
comparative, phylogeny-based analysis of genome sizes and
karyotypes in Genlisea provides essential data for selection of
suitable species for comparative whole-genome analyses, as well
as for further studies on both the molecular and cytogenetic
basis of genome reduction in plants.",
month = dec,
year = 2014,
url = "http://dx.doi.org/10.1093/aob/mcu189",
keywords = "Bladderwort; Genlisea; Lamiales; Lentibulariaceae; carnivorous
plant; chromosome number; flow cytometry; genome miniaturization;
genome size",
doi = "10.1093/aob/mcu189",
pmc = "PMC4649684",
pmid = 25274549,
issn = "0305-7364,1095-8290",
language = "en"
}
@ARTICLE{Fernandez2024-kd,
title = "A 160 Gbp fork fern genome shatters size record for eukaryotes",
author = "Fernández, Pol and Amice, Rémy and Bruy, David and Christenhusz,
Maarten J M and Leitch, Ilia J and Leitch, Andrew L and Pokorny,
Lisa and Hidalgo, Oriane and Pellicer, Jaume",
journal = "iScience",
publisher = "Elsevier BV",
volume = 27,
number = 6,
pages = 109889,
abstract = "Vascular plants are exceptional among eukaryotes due to their
outstanding genome size diversity which ranges ∼2,400-fold,
including the largest genome so far recorded in the angiosperm
Paris japonica (148.89 Gbp/1C). Despite available data showing
that giant genomes are restricted across the Tree of Life, the
biological limits to genome size expansion remain to be
established. Here, we report the discovery of an even larger
eukaryotic genome in Tmesipteris oblanceolata, a New Caledonian
fork fern. At 160.45 Gbp/1C, this record-breaking genome
challenges current understanding and opens new avenues to explore
the evolutionary dynamics of genomic gigantism.",
month = jun,
year = 2024,
url = "http://dx.doi.org/10.1016/j.isci.2024.109889",
keywords = "Plant evolution; Plant genetics",
doi = "10.1016/j.isci.2024.109889",
pmc = "PMC11270024",
pmid = 39055604,
issn = "2589-0042",
language = "en"
}
@ARTICLE{Fraser1995-jc,
title = "The minimal gene complement of Mycoplasma genitalium",
author = "Fraser, C M and Gocayne, J D and White, O and Adams, M D and
Clayton, R A and Fleischmann, R D and Bult, C J and Kerlavage, A
R and Sutton, G and Kelley, J M and Fritchman, R D and Weidman, J
F and Small, K V and Sandusky, M and Fuhrmann, J and Nguyen, D
and Utterback, T R and Saudek, D M and Phillips, C A and Merrick,
J M and Tomb, J F and Dougherty, B A and Bott, K F and Hu, P C
and Lucier, T S and Peterson, S N and Smith, H O and Hutchison,
3rd, C A and Venter, J C",
journal = "Science (New York, N.Y.)",
publisher = "American Association for the Advancement of Science (AAAS)",
volume = 270,
number = 5235,
pages = "397--403",
abstract = "The complete nucleotide sequence (580,070 base pairs) of the
Mycoplasma genitalium genome, the smallest known genome of any
free-living organism, has been determined by whole-genome random
sequencing and assembly. A total of only 470 predicted coding
regions were identified that include genes required for DNA
replication, transcription and translation, DNA repair, cellular
transport, and energy metabolism. Comparison of this genome to
that of Haemophilus influenzae suggests that differences in
genome content are reflected as profound differences in
physiology and metabolic capacity between these two organisms.",
month = oct,
year = 1995,
url = "http://dx.doi.org/10.1126/science.270.5235.397",
doi = "10.1126/science.270.5235.397",
pmid = 7569993,
issn = "0036-8075,1095-9203",
language = "en"
}
@ARTICLE{Schneiker2007-gs,
title = "Complete genome sequence of the myxobacterium Sorangium
cellulosum",
author = "Schneiker, Susanne and Perlova, Olena and Kaiser, Olaf and Gerth,
Klaus and Alici, Aysel and Altmeyer, Matthias O and Bartels,
Daniela and Bekel, Thomas and Beyer, Stefan and Bode, Edna and
Bode, Helge B and Bolten, Christoph J and Choudhuri, Jomuna V and
Doss, Sabrina and Elnakady, Yasser A and Frank, Bettina and
Gaigalat, Lars and Goesmann, Alexander and Groeger, Carolin and
Gross, Frank and Jelsbak, Lars and Jelsbak, Lotte and Kalinowski,
Jörn and Kegler, Carsten and Knauber, Tina and Konietzny,
Sebastian and Kopp, Maren and Krause, Lutz and Krug, Daniel and
Linke, Bukhard and Mahmud, Taifo and Martinez-Arias, Rosa and
McHardy, Alice C and Merai, Michelle and Meyer, Folker and
Mormann, Sascha and Muñoz-Dorado, Jose and Perez, Juana and
Pradella, Silke and Rachid, Shwan and Raddatz, Günter and
Rosenau, Frank and Rückert, Christian and Sasse, Florenz and
Scharfe, Maren and Schuster, Stephan C and Suen, Garret and
Treuner-Lange, Anke and Velicer, Gregory J and Vorhölter,
Frank-Jörg and Weissman, Kira J and Welch, Roy D and Wenzel,
Silke C and Whitworth, David E and Wilhelm, Susanne and Wittmann,
Christoph and Blöcker, Helmut and Pühler, Alfred and Müller, Rolf",
journal = "Nature Biotechnology",
publisher = "Springer Science and Business Media LLC",
volume = 25,
number = 11,
pages = "1281--1289",
abstract = "The genus Sorangium synthesizes approximately half of the
secondary metabolites isolated from myxobacteria, including the
anti-cancer metabolite epothilone. We report the complete genome
sequence of the model Sorangium strain S. cellulosum So ce56,
which produces several natural products and has morphological and
physiological properties typical of the genus. The circular
genome, comprising 13,033,779 base pairs, is the largest
bacterial genome sequenced to date. No global synteny with the
genome of Myxococcus xanthus is apparent, revealing an
unanticipated level of divergence between these myxobacteria. A
large percentage of the genome is devoted to regulation,
particularly post-translational phosphorylation, which probably
supports the strain's complex, social lifestyle. This regulatory
network includes the highest number of eukaryotic protein
kinase-like kinases discovered in any organism. Seventeen
secondary metabolite loci are encoded in the genome, as well as
many enzymes with potential utility in industry.",
month = nov,
year = 2007,
url = "http://dx.doi.org/10.1038/nbt1354",
doi = "10.1038/nbt1354",
pmid = 17965706,
issn = "1087-0156,1546-1696",
language = "en"
}
@incollection{Karlin1985,
author = {Karlin, Samuel and Ost, Fr{\'e}d{\'e}ric},
title = {Maximal segmental match length among random sequences from a finite alphabet},
booktitle = {Proceedings of the Berkeley Conference in Honor of Jerzy Neyman and Jack Kiefer},
editor = {Le Cam, Lucien M. and Olshen, Richard A.},
volume = {1},
pages = {225--243},
year = {1985},
publisher = {Wadsworth},
address = {Monterey, CA}
}
@article{Karlin1988,
author = {Karlin, Samuel and Ost, Fr{\'e}d{\'e}ric},
title = {Maximal length of common words among random letter sequences},
journal = {The Annals of Probability},
volume = {16},
number = {2},
pages = {535--563},
year = {1988}
}
+220 -4
View File
@@ -1,6 +1,222 @@
# Kmers
# K-mer size
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):
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.
- $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.
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) ?