docs: add VCF pseudo-alignment support and refine phylo/estimate commands

Add documentation for the new `--vcf` output format in `phylo`, which implements
pseudo-alignment where columns represent k-mer families. Update `usage-index_command`
to clarify input file handling and add `--dense` option to `usage-merge` for controlling
output storage format. Refine `usage-estimate` to support comparing index sharing against
random models, and update `usage-phylo` with new SNP-based sampling options like
`--quartet` and `--pair-balance`.

- Add `formats-vcf.md` documenting the VCF pseudo-alignment output, including column
  semantics (k-mer families), allele representation rules, and genotype conventions.
- Update `_Sidebar.md` to include a new "VCF pseudo-alignment" section under Formats.
- Modify `theory-kmer_indexing-kmers.md` to restrict k-mer size $k$ to odd values
  between 11 and 31, clarify null probability calculations, and add references for
  Karlin & Burge (1995) and Karlin et al. (1994).
- Update `theory-phylogeny-kmer_based-kmer_set_distances.md` to clarify that Hamming
  distance is used without normalization and explain the nonlinear transformation of
  Jaccard similarity in Mash.
- Modify `theory-phylogeny-snp_based-gamma_rate_heterogeneity.md` to clarify that the
  method-of-moments estimator is an `obikmer` addition, not part of Jin & Nei's (1990)
  correction, and update reference links.
- Update `theory-phylogeny-snp_based-sampling_design.md` to introduce `entropy4` calculation,
  "Quartet restriction" logic, and "Pair balance" weighting to address small carrier set
  issues and prevent weight growth.
- Modify `usage-estimate.md` to support two independent uses: estimating index parameters
  before building an index and comparing existing index sharing against expected random
  sharing via the new `--index` subcommand with CSV output.
- Update `usage-index_command.md` to document input file reading rules, including explicit
  file handling, format detection, and directory extension filtering.
- Modify `usage-merge.md` to add `--dense` option for storing merged indexes in a dense
  packed format, clarifying memory usage dependencies and merge source constraints.
- Update `usage-phylo.md` with new SNP-based options (`--n-sites`, `--free-loss`,
  `--no-ambiguity`, `--quartet`, `--pair-balance`, `--entropy`), `--sample-stats` CSV
  generation, and `--shannon-summary` for entropy distribution.
Eric Coissac committed 2026-11-20 14:21:57 +01:00
1 parent 5110e73f69
commit d0009f1292
11 files changed
+639 -103

No files matched your search

+1
@@ -36,4 +36,5 @@
- [Predicates and taxonomy paths](usage-predicates)
## Formats
- [Index construction and on-disk layout](formats-index_layout)
- [VCF pseudo-alignment](formats-vcf)
- [Architecture notes](architecture)
+39 -28
@@ -4,14 +4,13 @@
Building an index ([`index`](usage-index_command)) proceeds through a fixed sequence of phases, each operating independently per partition (see [Partitioning and indexing architecture](theory-kmer_indexing-indexing_architecture)):
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)), 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)), and any resulting segment shorter than k is dropped. Surviving segments are decomposed into super-kmers, canonicalized, and routed by `hash(minimizer) mod n_partitions` into one file per partition. The number of partitions is always a power of two, so this routing amounts to keeping the low bits of the hash.
2. **Dereplication.** Within each partition, identical super-kmer sequences are merged and their occurrence counts summed. This count is per super-kmer, not per kmer — a kmer's true abundance is the sum of the counts of every super-kmer containing it.
3. **Exact counting.** Every kmer in every dereplicated super-kmer is enumerated and its exact total count computed. A per-genome kmer frequency spectrum is produced at this stage.
4. **Quorum filtering.** Kmers outside the `--min-abundance`/`--max-abundance` range are dropped, and super-kmers are recompacted around the surviving kmer set.
5. **Local assembly.** The surviving kmers of each partition are assembled into unitigs — maximal non-branching runs of a local de Bruijn graph — such that every kmer appears exactly once, at one (unitig, offset) location.
6. **MPHF and evidence construction.** A minimal perfect hash function is built over the canonical kmers of each partition, together with the evidence structure needed to verify that a queried kmer was genuinely indexed (see below). Per-genome counts or presence bits are recorded alongside if requested.
3. **Exact counting.** Every kmer in every dereplicated super-kmer is enumerated and its exact total count computed. To accumulate these counts, a provisional minimal perfect hash function is built over the distinct kmers of the partition and a temporary count file is filled through it. Both are working files: they are deleted at the end of the build unless `--keep-intermediate` is given. A per-genome kmer frequency spectrum is produced at this stage, from the counts as they are before any abundance filtering.
4. **Quorum filtering and local assembly.** The kmers of the dereplicated super-kmers are fed one by one into a local de Bruijn graph of the partition. A kmer whose count falls outside the `--min-abundance`/`--max-abundance` range is dropped at this point, and never enters the graph; the super-kmers themselves are not rewritten. The kmers that remain are assembled into unitigs — maximal non-branching runs of the graph — such that every kmer appears exactly once, at one (unitig, offset) location.
5. **MPHF and evidence construction.** The final minimal perfect hash function is built over the canonical kmers that survived, together with the evidence structure needed to verify that a queried kmer was genuinely indexed (see below). Per-genome counts or presence bits are recorded alongside if requested; the counts come from the counting phase.
Phases 1–5 are independent per partition and run in parallel; phase 6 finalizes each partition once its kmer set is fixed.
Within each phase, the partitions are independent of one another and are processed in parallel. The phases themselves follow one another over the whole index, and the index records in its `index.meta` file how far the build has gone (after scatter, after counting, and when fully built). A build that was interrupted can therefore be resumed: the phases already completed are skipped.
## Minimal perfect hash function (MPHF)
@@ -19,36 +18,48 @@ Each partition's surviving kmers are mapped to a dense range of integer slots by
## Evidence: exact vs. approximate
Two verification modes are available, selected at build time (`index --approx`) and convertible afterwards ([`convert`](usage-convert)):
Three verification modes exist. The exact and approximate modes are selected at build time (`index --approx`), and any of the three can be reached afterwards with [`convert`](usage-convert):
- **Exact** (default): the hashed slot stores a pointer back into the partition's unitig data. At query time the kmer is reconstructed from that location and compared directly to the query. Zero false positives, at the cost of one extra random read per lookup.
- **Approximate** (`--approx`): the slot stores a short fingerprint (`--evidence-bits` bits) instead of a pointer; verification is a single fingerprint comparison. This trades a small, bounded false-positive rate ($1/2^b$ per kmer, reduced further to about $1/2^{b \cdot z}$ for a read requiring $z$ consecutive matching kmers via the `-z`/`--findere-z` parameter) for lower memory and disk usage, since no reconstruction index is needed. See [`estimate`](usage-estimate) to explore this trade-off before building.
- **Hybrid** (`convert --hybrid-evidence`): both the fingerprint and the exact evidence are kept. A lookup uses the fingerprint, which is fast and approximate, while the exact evidence remains stored alongside it.
## On-disk layout
<index_root>/
index.meta global configuration (k, minimizer size, partition count,
evidence mode, whether counts are stored) and genome list/metadata
scatter.done / count.done / index.done build-progress sentinels
spectrums/<label>.json per-genome kmer frequency histogram
partitions/
part_00000/ ... part_NNNNN/
index/
meta.json number of layers in this partition
layer_0/
unitigs.bin reconstructible kmer sequence data — always kept
unitigs.bin.idx random-access index into unitigs.bin (exact evidence only)
mphf.bin the minimal perfect hash function
evidence.bin exact evidence (exact mode only)
fingerprint.bin approximate evidence (approximate mode only)
counts/ per-genome kmer counts (if counts were requested)
presence/ per-genome presence/absence bits
layer_1/, layer_2/, ... added by later merges, same internal structure
📁 <index_root>/
├── 📄 index.meta configuration (k, minimizer size, partition count,
│ evidence mode, counts stored or not), genome list
│ and metadata, build state (empty, scattered,
│ counted, indexed)
├── 📄 .obikmer.lock lock files: commands that read the index share it,
├── 📄 .obikmer.gate commands that write into it hold it exclusively
├── 📁 spectrums/
│ └── 📄 <label>.json per-genome kmer frequency histogram
└── 📁 partitions/
├── 📁 part_00000/
│ └── 📁 index/
│ ├── 📁 layer_0/
│ │ ├── 📄 layer_meta.json number of kmers in this layer
│ │ ├── 📄 unitigs.bin reconstructible kmer sequence data — always kept
│ │ ├── 📄 unitigs.bin.idx random access into unitigs.bin (exact, hybrid)
│ │ ├── 📄 mphf.bin the minimal perfect hash function
│ │ ├── 📄 evidence.bin exact evidence (exact, hybrid)
│ │ ├── 📄 fingerprint.bin approximate evidence (approximate, hybrid)
│ │ ├── 📁 counts/ per-genome kmer counts (if requested)
│ │ └── 📁 presence/ per-genome presence/absence bits
│ └── 📁 layer_1/, layer_2/, … added by later merges, same structure
├── 📁 part_00001/
│ └── …
└── 📁 part_NNNNN/
The build state is stored in `index.meta` and not in separate marker files: it is what allows an interrupted build to resume. The number of layers of a partition is not stored anywhere either; it is found by looking for `layer_0`, `layer_1`, ... until one is missing. A partition that received no kmer at all (which happens with small inputs and many partitions) has no layer on disk.
The matrix directory of a layer, `counts/` or `presence/`, exists in three forms, which hold the same information. A freshly built index stores one file per genome, with a small metadata file (for counts, `col_000000.pciv`, `col_000001.pciv`, ... and `meta.json`). The dense packed form, produced by [`pack`](usage-pack), stores the whole matrix in a single file. The sparse packed form, produced by `pack --sparse` and, by default, by [`merge`](usage-merge), stores for each kmer only the list of genomes that carry it, with the lists shared between kmers deduplicated (for counts, the directory then holds files such as `dict_values.bin`, `singleton.pfiv`, `multi.pfiv` and `sparse_meta.json`). Which form a layer uses is detected from the files found in the directory.
`unitigs.bin` is the only file from which the indexed kmer content can be fully recovered; it is always retained. Every other file (MPHF, evidence, counts) is derived from it.
A **layer** corresponds to one increment of kmer content added to a partition — most commonly, one [`merge`](usage-merge) operation that introduces kmers not already present in the index. Genomes already present in the index simply gain new columns in the existing layers' count/presence data; only genuinely new kmer content is assembled into a new layer. Because of this, merging cost scales with the novel kmer content being added, not with the accumulated size of the index. A query against an index with several layers checks each layer's MPHF in turn.
A **layer** corresponds to one increment of kmer content added to a partition — most commonly, one [`merge`](usage-merge) operation that introduces kmers not already present in the index. The genomes of the merged sources are added as new columns to the count/presence data of the existing layers; only genuinely new kmer content, that is kmers absent from every existing layer of the partition, is assembled into a new layer. A kmer therefore belongs to exactly one layer of its partition. Because of this, merging cost scales with the novel kmer content being added, not with the accumulated size of the index. A query against an index with several layers checks each layer's MPHF in turn.
Sources merged together must share the same kmer size, minimizer size, partition count, and evidence mode (including matching approximate-mode parameters); mismatches are rejected rather than silently reconciled — [`convert`](usage-convert) one of the sources first if needed.
Sources merged together must share the same kmer size, minimizer size and partition count; any mismatch is rejected rather than silently reconciled. The evidence mode, on the other hand, may differ between sources: as soon as one source is approximate or hybrid, the destination is chosen among the approximate or hybrid sources, and the merged index takes its evidence mode. A count merge additionally requires every source to store counts. Finally, an index whose matrices are already packed, which includes any merge output, can be merged in as a source but not used as the destination, so at least one source must still be unpacked.
`obikmer pack` consolidates a partition's per-column files (counts/presence) into a single file, reducing the number of file opens needed at query time.
[`pack`](usage-pack) consolidates a partition's per-column files (counts/presence) into a single file, reducing the number of file opens needed at query time; with `--sparse`, it also switches to the sparse form described above.
+103
@@ -0,0 +1,103 @@
# VCF pseudo-alignment
[`phylo --vcf`](usage-phylo) writes the sites of a SNP pseudo-alignment as a VCF file, `<prefix>_alignment.vcf`. This page describes exactly what that file contains, because the k-mer families it is built from are not ordinary genomic variants and a few conventions follow from that.
## Why a VCF, and what a site is
The pseudo-alignment (see [Central-position SNP model](theory-phylogeny-snp_based-central_snp_model)) has one column per *family*: the up to four k-mers that share all their bases except the central one. A genome that carries one of these k-mers shows a particular base at the centre, and the columns of the alignment are those central bases, genome by genome. The FASTA output keeps this as a matrix of letters. The VCF output lists the same columns as sites with alleles and genotypes, which is the form that variant-oriented tools (`bcftools`, population-genetics software, genotype viewers) expect.
Nothing here comes from a reference genome. The file has no real coordinates, and the sites are not located on a chromosome: the positions below are labels that make the file valid and reproducible, not map positions.
## Producing the file
obikmer phylo --vcf --n-sites 5000000 -o run1 my_index
`--vcf` implies `--pseudo-alignment`, so `--n-sites N|all` is required, (the sibling annex it reads is built automatically if missing; see [`phylo`](usage-phylo)). `--fasta` and `--vcf` can be given together to get both files from the same draw; with neither, only the FASTA is written. Every option that shapes the draw (`--free-loss`, `--no-ambiguity`, `--only-diploid`, `--quartet`, `--exclude-genome`, ...) applies to the VCF exactly as to the FASTA, since both describe the same sites.
## Layout
An illustrative excerpt (columns are tab-separated in the file):
##fileformat=VCFv4.5
##source=obikmer
##contig=<ID=obikmer_0_0>
##contig=<ID=obikmer_0_1>
##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype (diploid)">
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT idx0 idx1 idx2 idx3
obikmer_0_0 440 CGATTNGTTAA A G . . . GT 0/0 1/1 0/0 0/0
obikmer_0_0 1511 CACGANTGTAG A G,T . . . GT 0/0 0/0 1/1 2/2
obikmer_0_1 9 TTACGNAGCTA C * . . . GT 0/0 0/0 1/1 0/0
There is one sample column per genome that takes part in the draw, named after the genome label, in the index's own order. A genome removed with `--exclude-genome` or `--min-shared-family` has no column at all. `QUAL`, `FILTER` and `INFO` are always `.`: obikmer applies no variant filter and attaches no annotation, and leaving them empty keeps a file of millions of sites compact.
## Coordinates: `CHROM` and `POS`
An index is organised in partitions, and each partition holds one or more layers of k-mers (see [Index construction and on-disk layout](formats-index_layout)). A family always belongs to exactly one layer of one partition, and the families of a layer are visited in a fixed order. The VCF uses that structure as coordinates:
- `CHROM` is `obikmer_<partition>_<layer>`, one virtual contig per layer of each partition in which at least one site was drawn;
- `POS` is the rank of the family inside that layer, starting at 1.
For a given index and a given sibling annex, a family therefore always receives the same `CHROM` and `POS`, whatever the draw, the options or the number of sites requested. Two runs on the same index can be compared position by position. This stability is lost if the sibling annex is rebuilt, or if the index is rebuilt, merged or filtered, because the families are then enumerated again. Positions are never comparable between two different indexes; use `ID` for that. Even rebuilding an index from the very same genomes may enumerate the families in another order: on a small test index built twice from identical input, the family `CGATTNGTTAA` had `POS` 440 the first time and 371 the second, with the same `ID`.
The file is sorted by partition, then layer, then position, which is also the order of the `##contig` lines, so tools that require a sorted file accept it directly. Positions are sparse: only the drawn families are written.
## Identifier: `ID`
The `ID` column holds a label for the family that does not depend on the index. It is built from one of the family's k-mers by replacing its central base with `N` (for example `CGATTNGTTAA` for k = 11), after choosing, among the family's possible orientations, the one that sorts first. All the members of a family, whichever strand they were read on, give the same label.
This is what makes two files comparable even when they come from different indexes: the same family has the same `ID` in both, while its `CHROM` and `POS` will generally differ. It is also unique within a file, since two different families never share a label.
## Alleles: `REF` and `ALT`
The alleles are the bases carried at the centre of the family's k-mers, as in the FASTA. Two points are worth knowing.
First, the base is the central base of the member's *canonical* form (the smaller of the k-mer and its reverse complement). That is not necessarily the strand of the `ID` label, so the letters should not be matched to the `ID` sequence by position; they are labels for the allele, not a reading of that sequence.
Second, `REF` carries no meaning of reference: it is simply the most frequent allele among the genomes of the draw, each allele copy counted once, with the alphabetical order A \< C \< G \< T deciding ties. `ALT` lists the remaining observed bases in the order A, C, G, T, separated by commas. There is no option to choose a reference genome.
### Absence: the `<ABS>` allele
A genome may carry none of the family's k-mers. Without `--free-loss` this absence is treated as a real state (the family was lost, or is absent from that genome), which the FASTA shows as `-`. In the VCF it becomes one more allele, the symbolic allele `<ABS>`, listed last in `ALT` and declared in the header by `##ALT=<ID=ABS,Description="Family absent from the genome">`. A genome without the family receives the genotype of `<ABS>`; for a site with `ALT` equal to `G,T,<ABS>` that is `3/3`. A site that differs between genomes only by presence versus absence has `ALT` equal to `<ABS>`.
The VCF specification gives the plain character `*` a meaning of its own (an allele missing because of an overlapping deletion described by another record), which is not the situation here, so it is deliberately not used. `<ABS>` is a free-form symbolic identifier, outside the reserved structural-variant names (`DEL`, `INS`, `DUP`, `INV`, `CNV`) and outside `<*>`, which belongs to reference blocks. Tools that only look at sequence alleles treat the site as having an alternative that is not a base.
With `--free-loss`, absence is declared missing data instead: `<ABS>` never appears, and the genomes concerned get a missing genotype.
## Genotypes
Every genome gets one `GT` value per site. The ploidy of these values is a convention chosen from the options, and the header says which (`Genotype (diploid)` or `Genotype (haploid)`).
| Cell in the alignment | Diploid (default, `--only-diploid`) | Haploid (`--no-ambiguity`) |
| --- | --- | --- |
| one base `X` | `X/X`, for example `0/0` or `1/1` | `X`, for example `0` |
| two bases (IUPAC `R Y S W K M`) | the heterozygote, for example `0/1` | does not occur |
| three or four bases (`B D H V N`) | `./.` (not expressible) | does not occur |
| absent family (`<ABS>`) | `<ABS>/<ABS>`, for example `3/3` | the index of `<ABS>` |
| missing (`?`) | `./.` | `.` |
The two allele indices of a diploid genotype are always written in increasing order (`0/1`, never `1/0`), and the separator is `/` because no phasing information exists.
Why diploid by default? A genome can carry several forms of the same family, which the alignment records as an IUPAC ambiguity code. A diploid genotype can express up to two forms, and `--only-diploid` removes the genomes that would need more (three or four forms) before the sites are selected, so that no `./.` comes from them. `--no-ambiguity` goes further and treats every such genome as missing, which makes all genotypes haploid.
This is a convention, not a measurement. The file records which forms a genome carries, not how many copies of each: `A/A/G` and `A/G/G` both give the code `R` and the genotype `0/1`. Likewise, a genome with two forms may be heterozygous at one locus, or it may carry two similar regions of its genome (paralogues, repeats); the file cannot tell these apart. Do not read the genotypes as calls from sequencing reads.
## Which sites are written
Only the families that survive the draw and its masking appear. Within those:
- a site needs at least one genome with a base or (in diploid mode) a two-base code, because `REF` is a base; a site where every genome is missing, absent or has an ambiguity code too wide for the mode is left out of the VCF while remaining in the FASTA;
- the log line at the end of the run gives the number of sites written out of the number drawn, so the difference is visible.
A site is selected because its genomes show at least two distinct states, and absence counts as a state. A site that differs between genomes only by presence versus absence is therefore a legitimate site, written with `ALT` equal to `<ABS>`.
## Using the file with other tools
- The contigs are virtual and have no declared length, and the file refers to no reference. Tools that need one (annotation, liftover) cannot use it; tools that only read sites and genotypes (`bcftools view`, `query`, `stats`, population-genetics software, PLINK-style converters) can.
- If a tool rejects multiallelic sites or the `<ABS>` allele, `bcftools view -m2 -M2` keeps biallelic sites only, and `bcftools view -e 'ALT="<ABS>"'` removes the sites involving absence. The file as written was read by `bcftools` and indexed by `tabix` without complaint on a small test index, in both diploid and haploid modes. `bcftools stats` counts the sites with `<ABS>` among the "others" (symbolic alleles) rather than as SNPs.
- If a tool expects haploid data, run `phylo` with `--no-ambiguity` rather than converting the genotypes afterwards.
## See also
- [`phylo`](usage-phylo): all the options that shape the draw.
- [Sampling design](theory-phylogeny-snp_based-sampling_design): how the sites are drawn.
- [Central-position SNP model](theory-phylogeny-snp_based-central_snp_model): what a family is.
+288 -4
@@ -1,6 +1,290 @@
# 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](theory-kmer_indexing-encoding)) 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$.
## Odd k-mer lengths
OBIKmer additionally requires $k$ to be odd. This constraint is
independent of the specificity considerations discussed below.
For an odd-length DNA sequence, a k-mer cannot be identical to its own
reverse complement. Every k-mer therefore belongs to a pair of distinct
orientations, which can be represented by a single canonical k-mer. For
even $k$, self-reverse-complementary sequences exist.
Odd $k$ is not required for canonicalization itself: the canonical form
$$s^c=\min_{\mathrm{lex}}\left(s,\operatorname{RC}(s)\right)$$
is well defined for both odd and even lengths. Restricting $k$ to odd
values guarantees that the two orientations are always distinct,
simplifying the representation and orientation handling used by OBIKmer.
## 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 oriented k-mers, so the
expected number of occurrences of a particular oriented k-mer in a
sequence of length $G$ is approximately $G/4^k$. For canonical k-mers,
the corresponding number of possible sequences is halved, and the
expected number of occurrences is approximately $2G/4^k$.
Increasing $k$ therefore reduces the probability that a particular k-mer
occurs by chance. However, the probability of a match somewhere in a
collection of sequences also depends on the amount of sequence searched
and on the number of possible k-mers considered. The following sections
formalize this distinction and describe how chance sharing can be
assessed across an indexed set of genomes.
## Choosing an appropriate k-mer size
The theoretical k-mer space grows exponentially with $k$. Thus, increasing $k$ from 11 to 31 greatly expands the sequence space and reduces the probability that unrelated sequences share a particular k-mer by chance. The following table gives the size of the theoretical k-mer space and, after canonicalization, the number of distinct representations.
| $k$ | $4^k$ | $4^k/2$ after canonicalization |
| --: | --: | --: |
| 11 | $4.19\times10^6$ | $2.10\times10^6$ |
| 15 | $1.07\times10^9$ | $5.37\times10^8$ |
| 21 | $4.40\times10^{12}$ | $2.20\times10^{12}$ |
| 25 | $1.13\times10^{15}$ | $5.63\times10^{14}$ |
| 31 | $4.61\times10^{18}$ | $2.31\times10^{18}$ |
Genome sizes illustrate the range of sequence scales for which k-mers may be used. Bacterial genomes are typically a few megabases long, although some symbiotic bacteria have much smaller genomes, while other bacteria have genomes exceeding ten megabases. Plant genomes span an even wider range, from tens of megabases to more than one hundred gigabases. In very large and repeat-rich genomes, the main limitation is not necessarily the exhaustion of the theoretical k-mer space, but the non-uniform distribution of k-mers caused by sequence composition and repeated DNA.
The supported range $11\leq k\leq31$ should therefore be understood as an engineering and application-oriented compromise, not as a universal biological optimum. Shorter k-mers are more likely to be shared by unrelated regions, whereas longer k-mers provide greater sequence specificity. However, longer k-mers are also more sensitive to substitutions and indels: a single difference can disrupt an exact match across the whole k-mer. The appropriate value within the supported range consequently depends on the size and characteristics of the genomes being compared, as well as on the biological question.
The following section introduces a random-sequence model to quantify the probability of chance sharing across an indexed set of genomes. This provides a formal basis for assessing how the choice of $k$ affects the interpretation of shared k-mers.
## Chance sharing across genomes
OBIKmer indexes distinct canonical k-mers and records the genomes in
which each k-mer occurs. This makes it possible to compare the observed
sharing of k-mers with the sharing expected under a random-sequence
model. The same probability model can be used for two related purposes:
measuring the excess of sharing among k-mers present in the index, and
estimating the number of chance k-mers among those shared by at least a
specified number of genomes.
### The null model and genome-specific probabilities
The null hypothesis assumes that the $S$ indexed genomes are unrelated
and that each genome is an independent random sequence in which
nucleotides are independent and equiprobable.
Since OBIKmer uses odd-length canonical k-mers, reverse-complement
canonicalization reduces the number of possible k-mers by half. The size
of the canonical k-mer space is therefore
$$M_k=\frac{4^k}{2}.$$
Let $N_i$ be the number of distinct canonical k-mers recorded for genome
$i$ in the index. Under the null model, these can be regarded as a
uniform sample without replacement from the $M_k$ possible canonical
k-mers. The probability that a given canonical k-mer is present in
genome $i$ is then
$$p_i=\frac{N_i}{M_k}=\frac{2N_i}{4^k}.$$
This is the inclusion probability for a distinct k-mer. It differs from
the probability of at least one occurrence in a positional model,
because repeated occurrences within a genome are not counted separately.
Let $X$ denote the number of genomes, among the $S$ indexed genomes,
that contain a given canonical k-mer under the null model. Since genomes
are assumed to be independent, $X$ is a sum of independent presence
indicators with probabilities $p_1,\ldots,p_S$. When these probabilities
differ, $X$ follows a Poisson-binomial distribution.
### Computing the Poisson-binomial distribution
The distribution of $X$ can be computed by processing genomes one at a
time. Let $P_i(j)$ denote the probability that the k-mer occurs in
exactly $j$ of the first $i$ genomes. Initially,
$$P_0(0)=1,\qquad P_0(j)=0 \quad (j>0).$$
When genome $i$ is added, the k-mer is either absent, with probability
$1-p_i$, or present, with probability $p_i$. Thus,
$$P_i(j)=(1-p_i)P_{i-1}(j)+p_iP_{i-1}(j-1).$$
This recurrence avoids enumerating the subsets of genomes. Computing the
complete distribution requires $O(S^2)$ operations and $O(S)$ memory. To
compute the upper-tail probability, only the probabilities for fewer
than $r$ presences need to be tracked:
$$P_{\mathrm{null}}(X\geq r)=1-\sum_{j=0}^{r-1}P_S(j).$$
The computation can therefore be restricted to $P_i(0),\ldots,P_i(r-1)$,
requiring $O(Sr)$ operations and $O(r)$ memory. The resulting
distribution depends on the genome-specific values $N_i$, but not on the
identity of the k-mer, and can thus be computed once for a given index
and k-mer length.
### Comparing observed and expected sharing in the index
The index contains only k-mers observed in at least one genome.
Consequently, when comparing sharing proportions among the k-mers
recorded in the index, the relevant null probability is conditional on
at least one presence:
$$q_r=P(X\geq r\mid X\geq 1) =\frac{P_{\mathrm{null}}(X\geq r)}{P_{\mathrm{null}}(X\geq 1)}.$$
Let $n_{\geq r}$ be the number of distinct canonical k-mers observed in
at least $r$ genomes, and let $n_{\geq 1}$ be the total number of
distinct canonical k-mers recorded in the index. The observed proportion
of indexed k-mers shared by at least $r$ genomes is
$$O_r=\frac{n_{\geq r}}{n_{\geq 1}}.$$
Under the random-sequence model, the expected proportion is $q_r$. The
difference
$$D_r=O_r-q_r$$
therefore measures the excess or deficit of sharing relative to the null
expectation. Positive values indicate that k-mers are shared across
genomes more frequently than expected by chance, whereas negative values
indicate less frequent sharing. A value of zero indicates agreement with
the random-sequence model.
Since both $O_r$ and $q_r$ are proportions between zero and one, $D_r$
is bounded:
$$-1\leq D_r\leq 1.$$
More precisely, for a given $q_r$, its bounds are $-q_r$ and $1-q_r$. By
construction, $D_1=0$, since all k-mers recorded in the index occur in
at least one genome. Unlike a ratio-based measure, this difference
remains defined when no k-mers are observed in at least $r$ genomes.
### Estimating the false discovery rate
The probability $P_{\mathrm{null}}(X\geq r)$ applies to one specified canonical k-mer.
To estimate the number of k-mers that could reach this sharing threshold
by chance across the entire canonical k-mer space, this probability must
be considered over all $M_k$ possible canonical k-mers.
The expected number of chance k-mers present in at least $r$ genomes is
$$E[\mathrm{FP}(r)]=M_kP_{\mathrm{null}}(X\geq r).$$
The observed number of k-mers passing the threshold is $n_{\geq r}$. An
estimate of the false discovery rate (FDR) for this set is therefore
$$\widehat{\mathrm{FDR}}(r)= \begin{cases} 1 & \text{if } n_{\geq r}=0,\\[4pt] \displaystyle \min\left(1, \frac{M_k P_{\mathrm{null}}(X\geq r)} {n_{\geq r}}\right) & \text{otherwise}. \end{cases}$$
The numerator estimates the number of false positives under the null
model, while the denominator is the observed number of k-mers passing
the sharing threshold. This estimate assumes that all possible canonical
k-mers are subject to the null model. It is therefore conservative in
the sense that it does not attempt to estimate the proportion of the
k-mer space corresponding to true homology. The estimate is capped at
one because a proportion cannot exceed one.
The distinction between $D_r$ and the FDR is important. $D_r$ compares
the observed and expected proportions among k-mers already present in
the index. The FDR estimate instead compares the expected number of
chance k-mers in the entire canonical k-mer space with the observed
number passing the sharing threshold.
The smallest value of $r$ for which $\widehat{\mathrm{FDR}}(r)$ falls
below a chosen threshold, for example 5%, can be used as a minimum
sharing threshold. This interpretation is conditional on the assumptions
of the null model and should not be taken as a model-independent
guarantee of the biological false discovery rate.
As an illustration, consider $k=21$, for which
$M_k\simeq2.2\times10^{12}$, and an index containing $S=10$ genomes.
Suppose that the numbers of distinct canonical k-mers in these genomes
range from $0.5\times10^9$ to $1.4\times10^9$, in increments of
$0.1\times10^9$. Applying the Poisson-binomial model with the
corresponding genome-specific probabilities gives the following
expected numbers of k-mers shared by chance:
| $r$ | $M_kP_{\mathrm{null}}(X\geq r)$ |
| --: | --: |
| 2 | $1.82\times10^7$ |
| 3 | $2.06\times10^4$ |
| 4 | $15$ |
| 5 | $0.0075$ |
In this example, chance alone can produce many pairwise shared 21-mers,
whereas the expected number of k-mers shared by five or more genomes is
very small. Whether a given sharing threshold is sufficiently stringent
depends on the number of k-mers actually observed at that level.
### Limits of the model
The FDR estimate is based on a simplified null model and has two
important limitations.
First, the model assumes independent, equiprobable nucleotides. Real
genomes exhibit nucleotide-composition biases, oligonucleotide
dependencies, and repeated sequences. These properties can increase the
probability of particular k-mers beyond the uniform expectation.
Removing low-complexity k-mers reduces some of these effects but does
not eliminate all compositional biases. Karlin and colleagues showed
that relative oligonucleotide abundances, including dinucleotide
frequencies, form characteristic genomic signatures that can differ
between organisms and remain relatively stable within genomes
([Karlin & Burge 1995](#ref-Karlin1995-lt); [Karlin et al. 1994](#ref-Karlin1994-on)).
Second, the FDR is computed per k-mer. Consecutive k-mers extracted from
the same homologous region overlap and are therefore not independent
observations. A single homologous region can contribute many correlated
k-mers to the index. The estimate presented here consequently describes
the expected fraction of chance k-mers, not the fraction of false
homologous regions. A region-level FDR would require a model that treats
matching regions, rather than individual k-mers, as the units of
observation.
## Bibliography
<div id="refs" class="references csl-bib-body hanging-indent">
<div id="ref-Karlin1995-lt" class="csl-entry">
Karlin, S. & Burge, C. (1995). <a href="https://doi.org/10.1016/s0168-9525(00)89076-9">Dinucleotide relative abundance extremes: a genomic signature</a>. <span style="font-style: italic;">Trends in Genetics: TIG</span>, 11, 283–290.
</div>
<div id="ref-Karlin1994-on" class="csl-entry">
Karlin, S., Ladunga, I. & Blaisdell, B.E. (1994). <a href="https://doi.org/10.1073/pnas.91.26.12837">Heterogeneity of genomes: measures and values</a>. <span style="font-style: italic;">Proceedings of the National Academy of Sciences of the United States of America</span>, 91, 12837–12841.
</div>
</div>
+1 -1
@@ -26,7 +26,7 @@ The **Hamming distance** is the $L^1$ distance between the corresponding binary
$$D = \sum_i \mathbb{1}[a_i \ne b_i],$$
where $a_i,b_i\in\{0,1\}$ indicate the presence of k-mer $i$ in the two genomes. It counts the number of k-mers for which the two incidence vectors differ, without normalization by the size of the k-mer space. As an $L^1$ distance, Hamming distance is a metric. Unlike abundance-based measures, it cannot be recovered from k-mer counts alone once the presence/absence representation has been discarded.
where $a_i,b_i\in\{0,1\}$ indicate the presence of k-mer $i$ in the two genomes. It counts the number of k-mers for which the two incidence vectors differ, without normalization by the size of the k-mer space. As an $L^1$ distance, Hamming distance is a metric. Unlike abundance-based measures, it cannot be recovered from k-mer counts alone once the presence/absence representation has been discarded. On an index that stores counts, a k-mer is taken as present when its count reaches the presence threshold (`--presence-threshold`, 1 by default).
**Mash** is not an independent set dissimilarity but a nonlinear transformation of the Jaccard similarity ([Ondov et al. 2016](#ref-Ondov2016-dq)). If
@@ -24,4 +24,4 @@ If the measured variance $V$ doesn't exceed the Poisson floor $\hat\mu/\bar L$ (
**This is not Jin & Nei's (1990) original estimator.** Their publication defines the $+\Gamma$ distance formula itself and, absent an estimate, recommends the fixed default $\alpha = 1$ — it does not propose a way to estimate $\alpha$ from data. The method-of-moments estimator above is a standard consequence of the Poisson–Gamma relationship between substitution counts and gamma-distributed rate variation, applied per-partition; it is `obikmer`'s own addition, not part of the cited correction.
See [`phylo`](usage-phylo#distance-matrix---distance) for how to select a fixed $\alpha$ or request automatic estimation.
See [`phylo`](usage-phylo#distance-estimation-and-tree-reconstruction) for how to select a fixed $\alpha$ or request automatic estimation.
+12 -2
@@ -13,12 +13,22 @@ A family's informativeness is measured directly rather than assumed uniform. For
| Quantity | Definition |
| --- | --- |
| `entropy15` | Shannon entropy (bits) over the 16 possible states (the 15 non-empty subsets of `{A,C,G,T}`), genomes absent from the family excluded from the count |
| `entropy4` | the same, reduced to the 4 plain bases |
| `entropy4` | the same over the 4 plain bases, restricted to the genomes carrying exactly one member of the family (those that stay informative when multi-member genomes are treated as missing data) |
With `--no-ambiguity` the entropy is `entropy4`, computed over the genomes carrying exactly one member of the family, so that the weighting sees the same genomes as the final alignment; without it, `entropy15` is used. Each is stored in its own annex.
A family where every genome carries the same single state has entropy 0 (uninformative); one where genomes are spread evenly across several states has higher entropy (more informative for distinguishing genomes).
## Quartet restriction
A family only constrains the shape of a tree if its carrier genomes show a bipartition: two distinct states, each carried by at least two genomes. With fewer carriers, or with a single variant against a uniform background, every topology explains the family equally well. In a skimming dataset many families have only two or three carriers, so a uniform draw spends a large share of its quota on them. `--quartet` removes them before the draw. The test counts the states of the alignment: without `--free-loss`, absence is a state like any other and can form one of the two pairs; with `--free-loss` it is missing data and never does.
## Pair balance
How well a pair of genomes is represented in a sample depends on how many families the pair shares: pairs of distant genomes share few, so a uniform draw gives them few sites, and the deep branches of a tree — which rest on exactly those pairs — are the least supported. `--pair-balance` weights each family by the mean, over the pairs of genomes carrying it, of 1 / (families shared by the pair), computed on the whole index. Averaging rather than summing keeps the weight from growing with the number of carriers, which would favour the families carried by most genomes regardless of which pairs they inform. Layers are allotted their share of the draw in proportion to the total weight of their families.
## Entropy-biased sampling
By default, sampling draws families uniformly. Weighting instead by informativeness biases the draw toward a target entropy $\mu$ with a Gaussian curve of width $\sigma$: a family's probability of being kept scales with $\exp\!\left(-\dfrac{(\text{entropy15} - \mu)^2}{2\sigma^2}\right)$ — a soft preference, not a hard cutoff, so no family is categorically excluded purely for having low or high entropy.
See [`phylo`](usage-phylo#sampling-at-scale---subsample---shannon---entropy) for how to bound and bias the sample, and for session/checkpointing behavior.
See [`phylo`](usage-phylo#snp-character-selection-and-sampling) for how to bound and bias the sample.
+33 -1
@@ -1,6 +1,6 @@
# estimate
Estimate approximate-index parameters (z, evidence bits, false-positive rate) before building an index with `--approx`, without touching any files.
`estimate` has two independent uses. Without `--index`, it estimates approximate-index parameters (z, evidence bits, false-positive rate) before building an index with `--approx`, without touching any files. With `--index`, it compares the k-mer sharing observed in an existing index with the sharing expected by chance (see the last section).
```bash
obikmer estimate [OPTIONS]
@@ -16,3 +16,35 @@ obikmer estimate [OPTIONS]
| `--fp` | none | Target false-positive rate per z-window |
Any two of `-z`, `--evidence-bits`, `--fp` may be given; the third is derived using the same model as `index --approx` and `convert --approx-evidence` ($FP = 1 / 2^{b \cdot z}$). The report printed to stdout includes: query $k$, effective indexed $k$ ($k-z+1$), $z$, evidence bits, per-kmer false-positive rate, and per-z-window false-positive rate.
## Comparing an index with random sharing
```bash
obikmer estimate --index INDEX [--presence-threshold N] [-o FILE]
```
With `--index`, `estimate` reads an existing index instead of computing approximate-index parameters, and it cannot be combined with `-k`, `-z`, `--evidence-bits` or `--fp`. Its purpose is to tell how much of the k-mer sharing between the genomes of the index goes beyond what chance alone would produce, which is the question behind the choice of $k$ (see [K-mer size](theory-kmer_indexing-kmers)).
The command writes a CSV, to standard output or to `FILE`, with one row for each $r$ from 1 to the number of genomes $S$:
| Column | Meaning |
| --- | --- |
| `r` | Minimum number of genomes sharing a k-mer |
| `k_r` | Number of k-mers present in at least `r` genomes |
| `O_r` | Observed proportion $k_r / k_1$ |
| `q_r` | Proportion expected by chance, $P(X \geq r \mid X \geq 1)$, where $X$ is the number of genomes containing a given k-mer under the random-sequence model |
| `D_r` | Deviation $O_r - q_r$ |
| `FP_r` | Number of k-mers expected to be present in at least `r` genomes by chance over the whole canonical k-mer space, $M_k \, P(X \geq r)$ |
| `FDR_r` | Estimated false discovery rate of the k-mers shared by at least `r` genomes: 1 when `k_r` is 0, otherwise $\min(1, \mathrm{FP}_r / k_r)$ |
A positive `D_r` means that k-mers are shared by at least `r` genomes more often than random sequences would share them; a negative value means less often. The first row always has `D_1 = 0`, because $k_1$ counts only k-mers present in at least one genome.
When no k-mer is shared by at least `r` genomes (`k_r = 0`), there is no set of k-mers whose false discovery rate could be estimated, and `FDR_r` is set to 1 by convention. This value means that nothing can be claimed at this level; it does not mean that the observed k-mers are false positives. The `FP_r` column of the same row shows how many k-mers chance alone would have produced.
The expected proportion is computed under the random-sequence model of the theory page: the genomes are unrelated, and each genome is a set of $N_i$ distinct canonical k-mers drawn without replacement and uniformly from the $M_k = 4^k/2$ canonical k-mers. A given k-mer is then present in genome $i$ with probability $p_i = N_i / M_k = 2N_i/4^k$, where $N_i$ is the number of distinct canonical k-mers considered as present in genome $i$. Genome sizes are rarely known, in particular when the index was built from unassembled reads, and the number of distinct k-mers has the advantage of being measured on the index itself and of not depending on the sequencing coverage.
Because the $N_i$ differ between genomes, the number $X$ of genomes containing a k-mer follows an exact Poisson-binomial distribution, from which $P(X \geq r)$ is obtained for every $r$ in a single pass. The approximation by a binomial distribution based on the mean genome size is not used.
`--presence-threshold` (default 1) has the same meaning as in `phylo`: on an index that stores counts, a k-mer is present in a genome only when its count reaches the threshold. Both $N_i$ and $k_r$ are computed with this same threshold, so the observed and expected proportions describe the same data. It has no effect on an index without counts.
The `k` used is the k-mer size stored in the index (for an approximate index, the effective indexed size $k-z+1$).
+8
@@ -12,6 +12,14 @@ obikmer index -o OUTPUT [OPTIONS] [INPUTS...]
| --- | --- |
| `INPUTS...` | Input sequence files or directories (FASTA/FASTQ/GenBank, gzip optional). If omitted, reads from stdin. |
## Which files are read
A file named explicitly on the command line is always read, whatever its extension: the format (FASTA, FASTQ or GenBank) and the compression (gzip, bzip2, xz or zstd) are detected from the content. If the content is not a sequence file, the command reports an error rather than skipping the file.
When an input is a directory, the files inside it are selected by extension: `.fasta`, `.fa`, `.fna` (the extension of NCBI genome downloads), `.ffn`, `.fas`, `.fsa`, `.fastq`, `.fq`, `.gbff`, `.gbk` and `.gb`, each optionally followed by `.gz`.
A small input spread over many partitions leaves most partitions empty. This is valid: the index is built normally and empty partitions simply hold no k-mers.
## Options
| Option | Default | Description |
+17 -1
@@ -20,10 +20,26 @@ obikmer merge -o OUTPUT SOURCE... [OPTIONS]
| `--force` | off | Overwrite an existing output directory |
| `--force-presence` | off | Store the merged index as presence/absence even if all sources have counts |
| `--rename-duplicates` | off | Disambiguate duplicate genome labels (`.1`, `.2`, …) instead of failing |
| `--budget-fraction` | `0.5` | Fraction of available RAM reserved as the memory budget for parallel partition merging |
| `--dense` | off | Store the merged index's presence/absence matrices in the dense packed format instead of the default sparse one (see [pack](usage-pack)) |
## Behaviour
The output mode is chosen automatically: if every source index stores counts, the merged index stores counts too; otherwise it is presence/absence. `--force-presence` forces presence/absence regardless of the sources.
By default, merging two indexes that share a genome label fails with an error; `--rename-duplicates` instead appends a numeric suffix to keep both copies.
The merged index is written in the sparse packed format by default, because it is usually several times smaller on disk; `--dense` keeps the dense format, which is faster when whole genome columns are read at once, for example for distance matrices. The [pack](usage-pack) page explains the trade-off between the two formats.
## Resource usage
The merge works partition by partition, and processes several partitions in parallel. Within a partition, the source indexes are read two at a time rather than all at once. The memory and the number of files mapped into memory for one partition therefore depend on how many k-mers the partition holds, not on how many indexes are being merged: merging hundreds of genomes maps about as many files per partition as merging three. The partitions do grow as more diverse genomes are added, so the total memory still rises with the size of the merged collection.
Each genome column being filled is held in memory and written to disk in one go once it is complete. A full disk or an exhausted quota is therefore reported as an ordinary error rather than crashing the program. The largest memory cost comes from the k-mers that are new to the merged index, which are assembled in memory, partition by partition, before being written out.
## Merging an index that was already merged
An index produced by `merge` can be used as one of the sources of a later merge, which is how a collection is extended without starting again from the original genomes. There is one rule: among the sources, at least one must not have been through a merge. A merged index is stored in a compact packed format (see [pack](usage-pack)) that is read very efficiently but cannot be extended in place. The merge therefore takes a freshly built index as its starting point and brings the packed index in as a source. A typical case is a merged index of many genomes plus one or a few newly built single-genome indexes, and this works.
If every source has already been merged or packed, the command stops before doing any work and says so. In that case, merge the original single-genome indexes together instead.
The genome columns of the result follow the order of the starting index first, then the other sources, so they may not come out in the order the sources were listed. The genome labels always identify each column unambiguously.
+136 -65
@@ -1,6 +1,13 @@
# phylo
Compute pairwise distances between the genomes stored in an index, optionally build trees (NJ/UPGMA) from them, and optionally calibrate a 16-state parsimony model for a central-position SNP character with exports for external phylogenetic tools (TNT, PhyG, IQ-TREE).
Compare the genomes stored in an index and build phylogenetic trees from them. Two complementary approaches are available:
- **Whole-genome distances** compare the k-mer content of the genomes, without any alignment.
- **SNP-based distances and analyses** compare the nucleotide variants found at the central position of related k-mers.
Distance matrices can be used to build Neighbor-Joining or UPGMA trees. SNP-based analyses can also produce a pseudo-alignment and calibrated substitution costs, with exports for external phylogenetic tools (TNT, PhyG, IQ-TREE).
## Usage
```bash
obikmer phylo INDEX [OPTIONS]
@@ -12,28 +19,43 @@ obikmer phylo INDEX [OPTIONS]
| --- | --- |
| `INDEX` | Index directory |
## Distance matrix (`--distance`)
## General options
| Option | Default | Description |
| --- | --- | --- |
| `--distance` | `jaccard` | See the two tables below for the full list of accepted values |
| `--cpu-max N` | all available cores | Maximum number of CPU cores to use. It caps every thread pool of the process and can only lower the number of cores, never raise it above those available. Common to all subcommands |
| `-o, --output PREFIX` | none | Prefix of the output files. Without it, the distance matrix goes to standard output and every other file is written in the current directory under its name without the prefix. See "Output files" below |
## SNP families
SNP-based analyses use groups of k-mers that differ only at their central nucleotide. These groups are called families (see the [central-position SNP model](theory-phylogeny-snp_based-central_snp_model) for the exact definitions and eligibility rules). A variable family is one character of the analysis, and the variants a genome carries give its state for that character.
## Distance estimation and tree reconstruction
| Option | Default | Description |
| --- | --- | --- |
| `--distance` | none | Compute and write a distance matrix. The accepted values are listed just below the table. No matrix is computed unless this is given, or `--nj` or `--upgma` is (they need a matrix and then use `jaccard`) |
| `--gamma-shape ALPHA\|auto` | none | Rate-heterogeneity correction, for `snp-*` values that support it (see [Gamma rate heterogeneity](theory-phylogeny-snp_based-gamma_rate_heterogeneity)). Either a fixed $\alpha$ or `auto`/`estimate` to fit it from the data. No effect on the other values; rejected if given together with a value that doesn't support it |
| `--presence-threshold` | `1` | Minimum count for a kmer to be considered present, for `jaccard`/`mash` on a count index |
| `--presence-threshold` | `1` | How counts are turned into presence/absence on an index that stores counts: a kmer is present in a genome only when its count reaches this value. Used by `jaccard`, `mash` and `hamming`, and by the shared-kmer counts of `--shared-kmers`. No effect on an index without counts, nor on the distances that use the counts themselves |
| `--session DIR`, `--session-force` | none | Save and reuse the sample of a `snp-*` distance. Currently unavailable, see `--session` below |
| `--csv` | off | Write the matrix as plain CSV instead of the default relaxed-PHYLIP format |
| `--shared-kmers` | off | Also write the shared-kmer count matrix. Only valid with a whole-index distance, not a `snp-*` value |
| `--shared-kmers` | off | Write the shared-kmer count matrix (`<prefix>_shared.csv`). It can be used alone, without any distance, or together with a whole-index distance; it is refused with a `snp-*` value |
| `--nj` | off | Compute and write a Neighbor-Joining tree (Newick) |
| `--upgma` | off | Compute and write a UPGMA tree (Newick) |
| `-o, --output` | none (stdout) | Output file prefix |
Every value routes to one of two independent computations: **whole-index distances** (`jaccard`, `mash`, `hamming`, `bray-curtis`, `relfreq-bray-curtis`, `euclidean`, `relfreq-euclidean`, `hellinger`, `hellinger-euclidean` — see [Whole k-mer set distances](theory-phylogeny-kmer_based-kmer_set_distances) for the definitions; `hamming` requires a presence/absence index, the others work on either index type), or **`snp-*` corrections** (`snp-raw`, `snp-jc`, `snp-k2p`, `snp-k81`, `snp-f81`, `snp-t92`, `snp-tn93`, `snp-tv` — see the [central-position SNP model](theory-phylogeny-snp_based-central_snp_model) for the definitions).
Every value routes to one of two independent computations: **whole-index distances** (`jaccard`, `mash`, `hamming`, `bray-curtis`, `relfreq-bray-curtis`, `euclidean`, `relfreq-euclidean`, `hellinger`, `hellinger-euclidean` — see [Whole k-mer set distances](theory-phylogeny-kmer_based-kmer_set_distances) for the definitions; `jaccard`, `mash` and `hamming` compare which kmers are present and work on either index type; the six others (`bray-curtis`, `relfreq-bray-curtis`, `euclidean`, `relfreq-euclidean`, `hellinger`, `hellinger-euclidean`) use the counts and need an index that stores them), or **`snp-*` corrections** (`snp-raw`, `snp-jc`, `snp-k2p`, `snp-k81`, `snp-f81`, `snp-t92`, `snp-tn93`, `snp-tv` — see the [central-position SNP model](theory-phylogeny-snp_based-central_snp_model) for the definitions).
`snp-*` values require the sibling annex (`--sibling-annex`, below) and are, by default, computed exhaustively over every non-monomorphic family in the index; add `--subsample N` to bound the computation to approximately `N` families instead (see "Sampling at scale" below — the same flag `--pseudo-alignment`/`--sankoff` use, but optional here).
`snp-*` values read the sibling annex (below), which is built automatically the first time it is needed, and are, by default, computed exhaustively over every non-monomorphic family in the index; add `--n-sites N` to bound the computation to approximately `N` families instead (see "SNP character selection and sampling" below — the same option `--pseudo-alignment`/`--sankoff` use, but optional here).
### Output
### Matrix format
Without `-o`, the matrix goes to stdout in relaxed-PHYLIP format (`n` on the first line, then one `label<TAB>value...` row per genome). With `--csv`, the format is instead a header row `genome,<label1>,<label2>,...` followed by one `<label>,<value1>,<value2>,...` row per genome, 6 decimals. Both formats are symmetric with a zero diagonal, except where noted below.
When a matrix is computed and there is no `-o`, it goes to stdout in relaxed-PHYLIP format (`n` on the first line, then one `label<TAB>value...` row per genome). With `--csv`, the format is instead a header row `genome,<label1>,<label2>,...` followed by one `<label>,<value1>,<value2>,...` row per genome, 6 decimals. Both formats are symmetric with a zero diagonal, except where noted below.
## `--exclude-genome`, `--min-shared-family`
### `--session`: currently unavailable
`--session DIR` and `--session-force` are meant to save the sample of a `snp-*` `--distance` run in a directory, so that a later run with identical selection parameters reuses it instead of drawing again. This feature is being rebuilt and is not available for now: giving either option stops the command with an error. Until it returns, keep the output files of a run (the alignment, or the distance matrix) rather than relying on re-drawing the same sample.
## Genome selection and filtering
| Option | Description |
| --- | --- |
@@ -42,18 +64,79 @@ Without `-o`, the matrix goes to stdout in relaxed-PHYLIP format (`n` on the fir
Neighbor-Joining and UPGMA trees (`--nj`/`--upgma`) are always built from every genome in the index, regardless of `--exclude-genome`/`--min-shared-family`.
## Central-position SNP model
## SNP character selection and sampling
See [Central-position SNP model](theory-phylogeny-snp_based-central_snp_model) for the family/eligibility definitions. Requires the sibling annex, built once per index:
SNP-based analyses can use every eligible variable family, or a sample drawn from the index. The options below control which characters are selected, which genomes and states are kept, and how the sample is spread over the index.
`--n-sites`, `--free-loss`, `--no-ambiguity`, `--quartet`, `--pair-balance`, `--entropy`/`--entropy-sd` are shared by `--pseudo-alignment`, `--sankoff` (and everything it implies: `--tnt`/`--phyg`/`--iqtree`), and a `snp-*` `--distance` value — one draw feeds all of them in a single invocation. `--n-sites` is mandatory for `--pseudo-alignment`/`--sankoff`, where it takes either a number of sites or `all`; for a `snp-*` `--distance` value it is optional, and omitting it is the same as `all` (every non-monomorphic family in the index, not an approximation).
Combining `--sankoff` (or `--tnt`/`--phyg`/`--iqtree`) with a `snp-*` `--distance` value in the same command reuses that one draw for both — the distance and the Sankoff calibration/alignment are guaranteed to be computed from the *identical* set of sampled sites, never two independent samples, so the two outputs are directly comparable. This only holds within a single command; running them as two separate `obikmer phylo` invocations draws two independent samples even with the same flags.
Every invocation draws its own fresh random sample: running the same command twice gives two different (but equally valid) samples, which is useful for measuring sampling variance and is kept that way deliberately.
With `--n-sites all` (or, for a `snp-*` `--distance` value, without `--n-sites`), every variable family (family size ≥ 2) that passes the other filters is used. With `--n-sites N`, roughly `N` families are kept instead (see [Sampling design](theory-phylogeny-snp_based-sampling_design) for how the draw stays representative of the whole index). If fewer than `N` candidate families remain, `--n-sites` has no effect.
| Option | Default | Description |
| --- | --- | --- |
| `--n-sites N\|all` | none (mandatory for `--pseudo-alignment` and `--sankoff`) | Number of families to draw, or `all` to use every variable family that passes the other filters, with no sampling. A number is a target, not a guarantee. |
| `--free-loss` | off | Treat a genome carrying none of a family's observed members as missing data (`?`) instead of `-` |
| `--no-ambiguity` | off | Treat a genome carrying more than one member of a family as missing data (`?`) instead of an IUPAC ambiguity code |
| `--only-diploid` | off | Milder than `--no-ambiguity` (the two cannot be combined): keep the genomes carrying one or two members of a family (a base, or a two-base IUPAC code such as `R`) and treat those carrying three or four as missing data (`?`) |
| `--quartet` | off | Keep only the families that can separate two pairs of genomes from each other: at least two distinct states, each carried by at least two genomes. Absence counts as a state unless `--free-loss` is given. Which genomes count as carriers follows `--no-ambiguity` |
| `--pair-balance` | off | Favour the families covering the pairs of genomes that share the fewest families across the index, so that every pair is better represented in the sample. Which genomes count as carriers follows `--no-ambiguity` |
| `--sample-stats` | off | Write three CSV files describing what the draw contains (see "Describing a draw" below) |
| `--sample-plan` | off | Write `<prefix>_sample_plan.csv`: how the draw was spread over the layers of the index |
| `--entropy MU` | off (`1.0` if only `--entropy-sd` is given) | Center of the entropy band to favor when sampling |
| `--entropy-sd SIGMA` | off (`0.5` if only `--entropy` is given) | Width of that band |
### `--quartet`: keeping only families that can resolve a tree
A family carried by fewer than four genomes, or whose genomes all share one state except a single variant, fits every tree topology equally well and so tells a tree nothing: to separate two pairs of genomes from each other (`AB|CD`) it takes at least two distinct states, each carried by at least two genomes. `--quartet` restricts the draw to the families that show this pattern. The states are those of the alignment. Without `--free-loss`, the absence of a family is a state of its own, so two genomes that carry a base and two genomes that lack the family do form two pairs. With `--free-loss`, absence is missing data and never forms a pair. A genome carrying several members of the family counts as a carrier of its own combination of bases, unless `--no-ambiguity` is given, in which case it is left out, as in the alignment.
The restriction is applied before the draw, from a persisted annex (one bit per variable family, built the first time `--quartet` is used with a given `--no-ambiguity` / `--only-diploid` convention and with or without `--free-loss`, in one pass shared with the other annexes, or ahead of time by `--sibling-annex --quartet`), then checked exactly on each family drawn, taking `--exclude-genome` into account. The quota given to `--n-sites` is therefore spent only on usable families.
### `--pair-balance`: representing every pair of genomes
Two genomes that are distantly related share few families, so a uniform draw covers such a pair with few sites, far fewer than a close pair: the pairs that matter for the deep branches of a tree are the worst represented. `--pair-balance` compensates. Each family is weighted by the mean, over the pairs of genomes carrying it, of 1 divided by the number of families that pair shares across the whole index (the matrix `--family-overlap` writes): a family carried by a rarely-sharing pair weighs more. It is the mean, not the sum, so a family carried by most genomes — in skimming data often a high-copy region — is not favoured merely for covering many pairs.
Each layer's share of the draw is proportional to the total weight of its families, and a family's chance of being drawn is proportional to its own weight. The weights are persisted (one value per variable family, built the first time `--pair-balance` is used with a given `--no-ambiguity` / `--only-diploid` convention, after the family-overlap matrix it depends on, or ahead of time by `--sibling-annex --pair-balance`). They combine with `--entropy` and `--quartet`: the weight multiplies the entropy kernel, and `--quartet` restricts the families first.
### `--entropy MU` / `--entropy-sd SIGMA`: biasing the sample toward informative families
By default, `--n-sites N` draws families uniformly. With `--entropy`/`--entropy-sd`, each family's chance of being kept is instead weighted by how close its own entropy (`entropy15`) is to `MU`, using a Gaussian curve of width `SIGMA` — no hard cutoff (see [Sampling design](theory-phylogeny-snp_based-sampling_design) for the weighting formula). The filter activates as soon as either flag is given; the other defaults to `1.0`/`0.5`. Combine with `--n-sites N` (expect somewhat fewer than `N` families kept in practice) or use alone (a soft filter over the whole index, no size target).
The first `phylo` run on a given index that uses `--entropy`/`--entropy-sd` pays a one-time extra cost (every candidate family's entropy is computed once and saved alongside the index); later runs, even with different `MU`/`SIGMA`, reuse that saved data.
The entropy that weights the draw follows `--no-ambiguity` and `--only-diploid`, so that it describes the same genomes as the alignment. By default, every genome carrying the family counts, and a genome carrying several members of it is a state of its own (`entropy15`). With `--no-ambiguity`, only the genomes carrying exactly one member count, since the others become missing data (`entropy4`). With `--only-diploid`, the genomes carrying one or two members count and those carrying three or four become missing data. The three entropies are saved separately: switching convention builds the missing one once, without discarding the others, and `--sibling-annex --entropy` builds the one of the convention given.
### Describing a draw: `--sample-stats`, `--sample-plan`
Both need a draw to describe (`--pseudo-alignment`, `--sankoff` or a `snp-*` `--distance`) and are computed from the very sites the draw kept, in the same pass, so they cost almost nothing and always agree with the alignment.
`--sample-stats` writes three files:
| File | Content |
| --- | --- |
| `<prefix>_sample_genomes.csv` | per genome (`genome,excluded,sites_with_call,share_of_sites,informative_sites`): the sampled sites it has a call in, their share of all sampled sites, and the informative sites (two states each carried by at least two genomes) in which its own state is one of those carried by at least two genomes. A genome with almost no calls cannot be placed whatever the tree method |
| `<prefix>_sample_carriers.csv` | per number of carriers (`n_carriers,sites,informative_sites`): how many sampled sites have that many genomes with a call, and how many of them are informative. Shows how much of the sample can resolve a tree at all |
| `<prefix>_sample_overlap.csv` | the sample's own genome × genome matrix, same layout as `--family-overlap`: sampled sites both genomes have a call in. Compare it with the index's matrix to see which pairs the draw under- or over-represents |
A call is any state other than the empty one: absence is never a call, with or without `--free-loss`. A site is informative under the same rule as `--quartet`: without `--free-loss`, absence is a state of its own and can form one of the two pairs; with `--free-loss` it is missing data and cannot. Excluded genomes are listed with zeros in the first file and count nowhere.
`--sample-plan` writes `<prefix>_sample_plan.csv`, one line per layer of the index in the order the draw visited them (`partition,layer,eligible,mass,quota,resolved,kept`): the variable families eligible when the draw starts, their total weight (their number, or with `--pair-balance` the sum of their pair weights), the layer's share of the target, the families drawn and resolved, and the ones kept after masking. A low `kept` against `resolved` means masking removes most of what is drawn in that layer; a `quota` summing to less than the target means some layers had nothing eligible. The target and the total kept are logged.
## SNP family preparation and diagnostics
SNP-based options read precomputed tables describing the families: the sibling annex, and tables derived from it (entropy, quartet, family overlap, pair weights). They are built automatically the first time they are needed and reused afterwards. The options below prepare them in advance, or describe the families.
| Option | Description |
| --- | --- |
| `--sibling-annex` | Build (or rebuild) the sibling-count/minorant annex — prerequisite for every option in this section, and for a `snp-*` `--distance` value |
| `--sibling-annex` | Build (or rebuild) the sibling-count/minorant annex. Rebuilding it makes the annexes derived from it obsolete, so they are dropped; then only the derived annexes that the other options of the same command read are rebuilt, each under the `--no-ambiguity` / `--only-diploid` convention given: `--entropy` the entropy annex, `--quartet` the quartet annex, `--pair-balance` the pair-weight and family-overlap annexes, `--family-overlap` or `--min-shared-family` the family-overlap annex. For example `--sibling-annex --quartet --only-diploid` prepares exactly the quartet annex of that convention, and `--sibling-annex` alone prepares none. An annex that is not prepared is built later, on demand, by the computation that reads it. Every option in this section needs the sibling annex, and builds it by itself, under an exclusive lock on the index, if it is missing (as it is after `migrate-mphf`); running `--sibling-annex` first does the same work once, which is the safe way to start several `phylo` runs on the same index at the same time |
| `--sibling-stats` | Write `<prefix>_siblings.csv`: the family-size distribution, per genome and globally |
| `--sibling-hist` | Print the global family-size histogram (1-4 members) only |
| `--sibling-hist` | Write `<prefix>_sibling_hist.csv` (columns `size,count`): the global family-size histogram (1-4 members) only, without the per-genome breakdown |
| `--family-overlap` | Write `<prefix>_family_overlap.csv`: for every genome pair, how many variable families both genomes carry a call for |
| `--shannon` | Write `<prefix>_entropy.csv`: per-family Shannon entropy, one row per family, full unsampled scan |
| `--pseudo-alignment` | Write `<prefix>_alignment.fasta`: a SNP-only pseudo-alignment. Requires `--subsample N` |
| `--shannon-summary` | Write `<prefix>_shannon_summary.csv`: the same scan as `--shannon`, reduced to a distribution (see below) — a few hundred thousand lines at most, whatever the size of the index |
### `--sibling-stats`
@@ -66,71 +149,54 @@ See [Central-position SNP model](theory-phylogeny-snp_based-central_snp_model) f
### Family Overlap
`--family-overlap` writes `<prefix>_family_overlap.csv`: header `genome,<label1>,<label2>,...`, one row per genome, cell `[i][j]` = number of variable families (family size ≥ 2) where both genome `i` and genome `j` carry a call. The diagonal is always `0`. Every genome is written, unfiltered by `--exclude-genome`/`--min-shared-family`.
`--family-overlap` writes `<prefix>_family_overlap.csv`: header `genome,<label1>,<label2>,...`, one row per genome, cell `[i][j]` = number of variable families (family size ≥ 2) where both genome `i` and genome `j` carry a call. The diagonal is always `0`. Every genome is written, unfiltered by `--exclude-genome`/`--min-shared-family`. With `--no-ambiguity`, a genome carrying several members of a family is not counted as carrying it, as in the alignment; without it, any genome with a call counts. The matrix is stored once per convention, so switching `--no-ambiguity` builds the other one without discarding the first (`--min-shared-family` follows the same convention).
`--min-shared-family N` uses the mean of each genome's own row (excluding the diagonal) against this same matrix as its exclusion statistic. There is no universal value for `N` — inspect `--family-overlap`'s own output to find where the real gap sits in a given genome collection before choosing a threshold.
### `--pseudo-alignment`
`<prefix>_alignment.fasta` — one record per non-excluded genome, one column per variable family (family size ≥ 2). Each site is IUPAC-coded from the genome's presence mask at that family: a single observed form → the plain base; several forms → the matching IUPAC ambiguity code; no form → `-`.
| Option | Default | Description |
| --- | --- | --- |
| `--subsample N` | none (mandatory here) | Target number of families to sample |
| `--free-loss` | off | Treat a genome carrying none of a family's observed members as missing data (`?`) instead of `-` |
| `--no-ambiguity` | off | Treat a genome carrying more than one member of a family as missing data (`?`) instead of an IUPAC ambiguity code |
| `--entropy MU` | off (`1.0` if only `--entropy-sd` is given) | Center of the entropy band to favor when sampling |
| `--entropy-sd SIGMA` | off (`0.5` if only `--entropy` is given) | Width of that band |
## Sampling at scale: `--subsample`, `--shannon`, `--entropy`
`--subsample`, `--free-loss`, `--no-ambiguity`, `--entropy`/`--entropy-sd` are shared by `--pseudo-alignment`, `--sankoff` (and everything it implies: `--tnt`/`--phyg`/`--iqtree`), and a `snp-*` `--distance` value — one draw feeds all of them in a single invocation. `--subsample` is mandatory for `--pseudo-alignment`/`--sankoff`; for a `snp-*` `--distance` value it is optional (omitted means every non-monomorphic family in the index, not an approximation).
Combining `--sankoff` (or `--tnt`/`--phyg`/`--iqtree`) with a `snp-*` `--distance` value in the same command reuses that one draw for both — the distance and the Sankoff calibration/alignment are guaranteed to be computed from the *identical* set of sampled sites, never two independent samples, so the two outputs are directly comparable. This only holds within a single command; running them as two separate `obikmer phylo` invocations draws two independent samples even with the same flags — unless `--session` is used (below).
Every invocation, with or without `--session`, draws its own fresh random sample by default — running the same command twice gives two different (but equally valid) samples, which is useful for measuring sampling variance and is kept that way deliberately. `--session` does not change this: it makes a *specific* sample reusable on request, it does not make sampling itself reproducible from one independent run to the next.
### `--session`: reusing a sample across separate commands
| Option | Default | Description |
| --- | --- | --- |
| `--session DIR` | none | Persist the sample (and, for `--sankoff`, its calibration/alignment) in `DIR` so a later, separate `obikmer phylo` invocation with the exact same selection parameters restores it instead of resampling |
| `--session-force` | off | With `--session DIR`: overwrite its saved parameters and cached sample instead of erroring out when this run's parameters don't match. No effect without `--session` |
`DIR` is created if it doesn't exist. If it already holds a sample built with different `--subsample`/`--free-loss`/`--no-ambiguity`/`--exclude-genome`/`--min-shared-family`/`--entropy`/`--entropy-sd` values than this run, the command exits with an error rather than silently using either the old or the new values — pass `--session-force` to discard the old sample and rebuild under the new parameters, or point `--session` at a different directory to keep both.
A `--sankoff`-family run and a `snp-*` `--distance` run share the same cached sample when pointed at the same `--session DIR` — build it once with either, reuse it from the other, in either order, across separate commands.
If a run using `--session` is interrupted (crash, kill, `Ctrl-C`), the next run against the same `--session DIR` resumes from the last automatic checkpoint (roughly every 8 partitions'-worth of sampling progress) instead of starting over. The resumed run's sample is **not** guaranteed to be identical to what an uninterrupted run would have produced past that checkpoint — each process draws its own independent random sequence, same as any two separate invocations do — but nothing already checkpointed is lost, and no work needs redoing beyond that point.
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) 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
`<prefix>_entropy.csv` has one row per family visited:
| Column | Meaning |
| --- | --- |
| `partition` | the index partition that holds the family |
| `layer` | an internal index-layer identifier — stable within one run, not meaningful across indexes |
| `family_idx` | the family's position within that layer |
| `entropy15` | Shannon entropy (bits) over the 16 possible states (the 15 non-empty subsets of `{A,C,G,T}`), genomes absent from the family excluded from the count |
| `entropy4` | Shannon entropy (bits) reduced to the 4 plain bases, kept alongside `entropy15` for comparison |
| `entropy4` | Shannon entropy (bits) over the 4 plain bases, computed only over the genomes that carry exactly one member of the family — the genomes that remain informative under `--no-ambiguity`, since a genome carrying several members of a family (paralogous copies) is treated as missing data there. `0` when `n_genomes_unambiguous` is `0` |
| `family_size` | number of distinct central bases observed anywhere in the index for this family (2-4) |
| `n_genomes_present` | how many genomes the entropy was computed over |
| `n_genomes_present` | how many genomes the family is present in; `entropy15` is computed over these |
| `n_genomes_unambiguous` | how many of those genomes carry exactly one member of the family; `entropy4` is computed over these |
Run with `--subsample N --shannon` to get a bounded diagnostic sample instead of a full-index pass — useful for choosing `--entropy`/`--entropy-sd` values before a full run.
`--shannon` always scans every non-monomorphic family of the whole index; `--n-sites`, `--entropy` and `--entropy-sd` have no effect on it. The output therefore grows with the index, with one row per family, and can reach hundreds of millions of rows (tens of gigabytes) on a large index. Analyse it with a tool that reads the file as a stream (for example DuckDB or Miller) rather than loading it whole. It is nevertheless the right basis for choosing `--entropy`/`--entropy-sd` values, since it gives the complete entropy distribution, including how it varies with `n_genomes_present`, rather than an estimate from a sample.
### `--entropy MU` / `--entropy-sd SIGMA`: biasing the sample toward informative families
### `--shannon-summary`
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) 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).
`--shannon-summary` writes `<prefix>_shannon_summary.csv` (`entropy,n_genomes_present,n_genomes_unambiguous,bin_start,n_families`): the number of variable families per entropy (`entropy15` over every carrier, `entropy4` over the single-member genomes only — families with none are left out of its lines), number of genomes carrying the family, number of those without ambiguity, and 0.05-bit entropy bin (`bin_start` is its lower bound). It answers how entropy varies with the number of carriers, or how many carriers `--no-ambiguity` loses, from the same scan as `--shannon` but without one line per family.
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.
## SNP pseudo-alignment
A pseudo-alignment has one column per variable family and one state per genome. Unlike a conventional sequence alignment, its columns come directly from groups of related k-mers of the index. The number of sites is set with `--n-sites`, and the options of "SNP character selection and sampling" above control which families are included and how ambiguous or absent states are written.
| Option | Description |
| --- | --- |
| `--pseudo-alignment` | Write `<prefix>_alignment.fasta`: a SNP-only pseudo-alignment. Requires `--n-sites N\|all` |
| `--fasta` | Choose FASTA as the pseudo-alignment format (the default when neither `--fasta` nor `--vcf` is given). Implies `--pseudo-alignment` |
| `--vcf` | Also (or instead) write `<prefix>_alignment.vcf`, the same sites as a VCF. Implies `--pseudo-alignment`; combinable with `--fasta` |
### `--pseudo-alignment`
`<prefix>_alignment.fasta` — one record per non-excluded genome, one column per variable family (family size ≥ 2). Each site is IUPAC-coded from the genome's presence mask at that family: a single observed form → the plain base; several forms → the matching IUPAC ambiguity code; no form → `-`.
#### VCF output (`--vcf`)
The same drawn sites can be written as `<prefix>_alignment.vcf`, with `--fasta` and `--vcf` freely combined (FASTA alone remains the default). The coordinates, identifiers, alleles and genotypes of this file follow conventions of their own, described on the [VCF pseudo-alignment](formats-vcf) page. The genotype ploidy follows `--no-ambiguity` (haploid) and `--only-diploid` (diploid, with the genomes carrying three or four forms of a family removed beforehand).
## Sankoff calibration and phylogenetic exports
| Option | Default | Description |
| --- | --- | --- |
| `--sankoff` | off | Calibrate a 16-state parsimony cost matrix and matching pseudo-alignment. Requires `--subsample N` |
| `--sankoff` | off | Calibrate a 16-state parsimony cost matrix and matching pseudo-alignment. Requires `--n-sites N\|all` |
| `--sankoff-ratio-ceiling` | `0.5` | Exclude genome pairs whose raw SNP ratio exceeds this value from the base-composition part of the calibration |
| `--free-loss` | off | Recode a family's non-detection as the `?` missing-data symbol instead of an ordinary, costed state, throughout `--sankoff` and every export built from it |
| `--tnt` | off | Also write a TNT script (implies `--sankoff`) |
@@ -159,28 +225,33 @@ TNT and PhyG both write trees with bare numeric leaf labels (`1`, `2`, ..., in t
## Output files
With `-o/--output PREFIX`, the relevant subset of the files below is written. Without `-o`, only the distance matrix is produced, on stdout. All matrices use genome labels as row/column headers, in index order.
With `-o/--output PREFIX`, the relevant subset of the files below is written. Without `-o`, the distance matrix goes to standard output and every other file is written in the current directory under its name without the `<prefix>_` part (for example `nj.nwk`, `entropy.csv`, `alignment.fasta`). All matrices use genome labels as row/column headers, in index order.
### Distance matrix
| File | Written by | Format | Content |
| --- | --- | --- | --- |
| `<prefix>_dist.phy` | always, unless `--csv` | relaxed PHYLIP | the `--distance` matrix |
| `<prefix>_dist.csv` | `--csv` | CSV matrix | the `--distance` matrix, 6 decimals |
| `<prefix>_dist.phy` | a distance matrix is computed, unless `--csv` | relaxed PHYLIP | the `--distance` matrix |
| `<prefix>_dist.csv` | a distance matrix is computed, with `--csv` | CSV matrix | the `--distance` matrix, 6 decimals |
| `<prefix>_shared.csv` | `--shared-kmers` | CSV matrix | shared-kmer count per genome pair (integers) |
| `<prefix>_nj.nwk` | `--nj` | Newick | Neighbor-Joining tree |
| `<prefix>_upgma.nwk` | `--upgma` | Newick | UPGMA tree |
CSV matrix layout (`_dist.csv`, `_shared.csv`, `_family_overlap.csv`): header `genome,<label1>,<label2>,...`, one data row per genome, `<label>,<value1>,<value2>,...`.
### Central-position SNP model
### SNP analyses
| File | Written by | Format | Content |
| --- | --- | --- | --- |
| `<prefix>_siblings.csv` | `--sibling-stats` | CSV table | family-size distribution, per genome and global |
| `<prefix>_sibling_hist.csv` | `--sibling-hist` | CSV table | global family-size histogram (`size,count`) |
| `<prefix>_family_overlap.csv` | `--family-overlap` | CSV matrix | variable families both genomes of a pair carry a call for |
| `<prefix>_entropy.csv` | `--shannon` | CSV table | per-family Shannon entropy, see "Sampling at scale" above |
| `<prefix>_alignment.fasta` | `--pseudo-alignment` | FASTA | SNP-only pseudo-alignment, IUPAC-coded |
| `<prefix>_entropy.csv` | `--shannon` | CSV table | per-family Shannon entropy, see `--shannon` above |
| `<prefix>_shannon_summary.csv` | `--shannon-summary` | CSV table | families per entropy bin, number of carriers and number of single-member carriers |
| `<prefix>_sample_genomes.csv`, `<prefix>_sample_carriers.csv`, `<prefix>_sample_overlap.csv` | `--sample-stats` | CSV | what the draw contains: per genome, per number of carriers, per pair of genomes |
| `<prefix>_sample_plan.csv` | `--sample-plan` | CSV table | per layer: eligible families, weight, quota, drawn, kept |
| `<prefix>_alignment.fasta` | `--pseudo-alignment` or `--fasta` | FASTA | SNP-only pseudo-alignment, IUPAC-coded |
| `<prefix>_alignment.vcf` | `--vcf` | VCF | Same sites as the FASTA, with stable virtual coordinates and a k-mer-based `ID` |
### Sankoff calibration and exports