Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions docs/algorithms/assembly-classification.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ For each query genome (parallelized across genomes with rayon):

A k-mer says *what* it matched but not *where*, so a paralogous copy of either
allele reads as the marker's own locus. An anchor is only used when it occurs
once in the genome, so it does say where. Wherever an anchor can read the
once in the genome and once in the reference, so it does say where. Wherever an anchor can read the
locus, it decides:

| The anchors read | State |
Expand All @@ -75,10 +75,16 @@ And when no anchor can read it:

| ALT k-mer | REF k-mer of its site | State |
|---|---|---|
| found | not found | present |
| found, and the reference does not carry it | not found | present |
| found, but the reference carries it too | anything | undetermined, `alt_kmer_in_reference` |
| found | found | undetermined, `ambiguous_both_alleles` |
| not found | found, or any other marker of the site found | absent |
| not found | found as often as the reference has it | absent |
| not found | found, but the reference has more copies | undetermined, `ref_kmer_repeated` |
| not found | nothing of the site found | undetermined, `not_found` |
| anything | the marker has no reference k-mer at all | undetermined, `no_reference_kmer` |

Two anchors that both read the locus and disagree leave the marker undetermined
as `anchors_disagree`, whatever the k-mers found.

A k-mer is an exact match, so another change anywhere in the window (a
synonymous substitution, a lineage polymorphism) hides both alleles. Before the
Expand Down
48 changes: 43 additions & 5 deletions docs/algorithms/feature-hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,52 @@ Sparse vector: [(bucket_42, 3.0), (bucket_1087, 1.0), ...]

1. **K-mer extraction**: Uses [needletail](https://github.com/onecodex/needletail)'s `bit_kmers()` which encodes each k-mer as a 2-bit packed `u64`. This handles canonical k-mers (choosing the lexicographically smaller of forward and reverse complement) automatically.

2. **Hashing**: The bucket index is simply `bitkmer.0 & mask` where `mask = num_buckets - 1`.
2. **Bucketing**: The bucket index is `bitkmer.0 & mask` where `mask = num_buckets - 1`. needletail packs the first base into the high bits, so masking to 20 bits keeps the **last ten bases** of the canonical k-mer. This is not a hash: see [What the buckets really are](#what-the-buckets-really-are) below.

3. **Bucket count**: 2^20 = 1,048,576 buckets.

4. **Sparse representation**: Each sequence produces a `Vec<(usize, f32)>` — only non-zero buckets are stored, sorted by bucket index. This is critical for efficiency: a typical 4.4 Mb genome at k=21 produces ~4.4M k-mers but only ~800K–1M unique bucket entries.

!!! info "Why no extra hash function is needed"
Since needletail's 2-bit encoding already acts as a hash function (deterministic, uniform for biological sequences), no additional hash function is needed. The power-of-two constraint enables bitmask indexing (`& mask` instead of `% modulus`).
4. **Sparse representation**: Each sequence produces a `Vec<(usize, f32)>` of its non-zero buckets, sorted by bucket index. H37Rv at k=21 produces 4.41M k-mers that fall into 652,008 buckets, 62% of the space.

## What the buckets really are

Masking the 2-bit code keeps its last ten bases, so the buckets are the 4^10
ten-mers, whatever k was asked for. k only decides which strand's ten bases are
kept, through the choice of canonical k-mer:

| k | buckets occupied by H37Rv (one position in seven) |
|---|---|
| 11 | 27.8% |
| 15 | 28.2% |
| 21 | 28.2% |
| 31 | 28.3% |

Two k-mers that share their last ten bases always share a bucket:
`AAAAAAAAAAACCCGGGTTTA` and `ACGTACGTAGACCCGGGTTTA` both land in 355068. Across
H37Rv at k=21, 96.0% of k-mer occurrences fall in a bucket shared with another
position, 6.77 of them per occupied bucket on average.

**It costs no accuracy in what was measured.** Synthetic genomes built on the
MTB ancestor with the lineage panel's own SNPs, six per lineage to train and
four held out to predict:

| lineages | own SNPs each | these buckets | a full 64-bit hash |
|---|---|---|---|
| L1 to L7 and A4 | 41 to 294 | 32/32 | 32/32 |
| L4.1 to L4.9 | 6 to 8 | 36/36 | 36/36 |
| A4.1 to A4.8 (*M. bovis*) | 2 to 5 | 32/32 | 32/32 |

The full hash gave slightly more decisive votes (a mean margin of 0.61 against
0.50 on the *M. bovis* sublineages) at twice the training time, and it changes
every feature index, so it would invalidate every model already trained. With no
call to gain, the buckets stay as they are; what changes is that they are
described as what they are.

!!! warning "Reading the importance reports"
A bucket is not one k-mer. The `kmers` column of `*.importance.tsv` lists
every k-mer of the training data that ends in the same ten bases, and the
one a split actually used is among them without being singled out. Read the
list as candidates, and confirm a candidate on the genomes before treating
it as a marker.

### Why this works

Expand Down
6 changes: 5 additions & 1 deletion docs/algorithms/marker-genotyping.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,11 @@ about where it matched; a marker left without one is reported as
`no_unique_anchor`. A read spanning the whole locus matches both anchors, so the
two sides are never added up: the deeper one answers, and the other has to agree
if it was read deeply enough to have an opinion, or the marker is reported as
`anchors_disagree`. The pass runs over the reads a second time, with an index
`anchors_disagree`. A marker whose ALT k-mer the reference itself carries, or
whose window it carries twice, is never settled on read counts at all, because
reads from the other copy count towards it just as well: it goes straight to
the anchors, and is reported as `alt_kmer_in_reference` or `ref_kmer_repeated`
when they cannot settle it either. The pass runs over the reads a second time, with an index
holding only the markers still unsettled, and `--no-anchor-rescue` skips it.

### Marker TSV format
Expand Down
2 changes: 1 addition & 1 deletion docs/algorithms/random-forest.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ The top 500 features are exported with:
|---|---|---|
| `n_trees` | 100 | More trees → smoother predictions, diminishing returns past ~100 |
| `max_depth` | 20 | Limits tree complexity; prevents memorization of training noise |
| `min_samples_leaf` | 5 | Regularization — prevents splits that isolate individual samples |
| `min_samples_leaf` | 1 | The usual random-forest value: the bootstrap and the random choice of features already keep trees from memorising samples. It was 5, which kept trees too shallow to separate lineages with few genomes (on *M. bovis* sublineages of six genomes each: 31 of 32 calls at a vote margin of 0.15, against 32 of 32 at 0.50 with 1), and leaves every tree a single leaf on a panel of ten genomes. |
| `max_features` | √(n_features) | Standard RF: decorrelates trees by forcing different feature subsets |
| `bootstrap_seed` | 42 (master) | Ensures reproducibility; each tree derives its seed from this |

Expand Down
8 changes: 4 additions & 4 deletions docs/algorithms/reference-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ All FASTQ files are processed in parallel (one rayon task per file):

Singleton k-mers (count=1) are likely sequencing errors:

- Only applied when total unique k-mers > 100,000
- Applied whenever `--min-kmer-count` is above 1, and the default is 1, so by default nothing is dropped. It used to switch itself on above 100,000 unique k-mers, which made the score mean two different things either side of a line the user cannot see: 1,450 reads of a 0.15x sample scored 0.8886 and 1,500 scored 1.0000.
- Default threshold: `min_kmer_count = 2`
- Typical reduction: ~90-93% of unique k-mers removed
- Effect: faster scoring and fewer false matches
Expand Down Expand Up @@ -55,7 +55,7 @@ For each reference in the batch (parallelized with rayon):
### Score calculation

```text
Shared_Kmer_Fraction = Σ(query_count for shared k-mers) / Σ(all query k-mer counts)
Shared_Kmer_Fraction = Σ(query_count for shared k-mers) / Σ(retained query k-mer counts)
```

This is a **weighted containment score**: k-mers that appear more frequently in the reads contribute more. A perfect match (all query k-mers present in the reference) gives a score of 1.0.
Expand All @@ -77,15 +77,15 @@ This is a **weighted containment score**: k-mers that appear more frequently in
| Parameter | Default | Description |
|---|---|---|
| `--kmer-size` | 31 | Longer k = more specific matching |
| `--min-kmer-count` | 2 | Noise filter threshold |
| `--min-kmer-count` | 1 | Noise filter threshold; 1 keeps every k-mer |
| `--early-stop-confidence` | 0.0 | Reserved; not read in the current release (no effect) |
| `--early-stop-min-kmers` | 1,000,000 | Reserved; not read in the current release (no effect) |
| `--strict-percentages` | true | Reserved; scoring always uses weighted query counts |

## Output

```tsv
Query_Files Best_Match_Reference Shared_Kmer_Fraction
Query_Files Best_Match_Reference Shared_Kmer_Fraction Query_Kmers
reads_R1.fastq.gz,... GCF_000253355.1 0.5440
```

Expand Down
34 changes: 32 additions & 2 deletions docs/classify.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,32 @@ from the anchor instead of being recognised as a whole k-mer.
That reads alleles no catalogue lists, which an index of expected k-mers
cannot do:

### A k-mer the reference itself carries

Of the WHO catalogue markers `classify` indexes, two have an ALT k-mer that
already sits elsewhere in H37Rv (`ndh c.168C>T` and `PPE35 I417V`) and
seventy-one have a second copy of their reference window. Those words are in
**every** genome, so finding one says nothing about the marker's own locus:
before this was accounted for, those two read as present in every genome
tested, the ancestor included. The log gives the counts for the panel in use.
`split-fastq` indexes a different set (no indels, longer substitutions) and
finds five and sixty-seven.

The reference is read once when the index is built, which is what turns a
k-mer hit into the weak evidence it is:

| What the reference shows | What a k-mer hit can mean |
|---|---|
| the ALT k-mer is nowhere else | the marker is present |
| the ALT k-mer is somewhere else too | nothing: an anchor has to decide, or the marker is `alt_kmer_in_reference` |
| the window occurs once | a reference hit means the locus holds the reference allele |
| the window occurs twice and the genome showed both | still absent: every copy was read and every one is reference |
| the window occurs twice and the genome showed one | nothing: an anchor has to decide, or the marker is `ref_kmer_repeated` |

The count is what keeps this from crying wolf. A genome that shows as many
copies as the reference has proved the marker absent, which is the ordinary
case; only a genome missing a copy is genuinely ambiguous.

| What the anchors read | State | Where it is reported |
|---|---|---|
| the ALT allele | **present** | detailed TSV, `evidence` names the anchor used |
Expand All @@ -235,7 +261,11 @@ cannot do:
| nothing usable, and both k-mers had turned up | **undetermined**, `reason` = `ambiguous_both_alleles` | undetermined TSV |

An allele is read only from an anchor that occurs **exactly once** in the
genome; a repeated anchor says nothing about which copy was read. Only
genome **and once in the reference**; a repeated anchor says nothing about
which copy was read. The reference matters as much as the genome: when the
change the anchor exists to see past is what broke the real locus, the copy is
the one left looking unique, and the allele would be read from the wrong
place. Only
substitutions get anchors: with an indel the allele's own length is what is in
question, so bases counted from one anchor cannot settle it, and those markers
keep the k-mer answer.
Expand Down Expand Up @@ -340,7 +370,7 @@ Header: `genome SNPreference REF ALT lineage Gene mutation reason`
| `REF`, `ALT` | Alleles of the marker. |
| `lineage` | Lineage (or drug) path of the marker. |
| `Gene`, `mutation` | Gene and mutation from the marker TSV, empty when it has none. |
| `reason` | `not_found`: nothing of this marker occurs in the genome and no anchor could read it. `anchors_disagree`: the two anchors read different alleles. `ambiguous_both_alleles`: both k-mers turned up and no anchor could say which allele this locus carries. `no_reference_kmer`: the marker has no usable REF k-mer (its reference allele holds a base other than A, C, G or T) and the anchors could not read it either. |
| `reason` | `not_found`: nothing of this marker occurs in the genome and no anchor could read it. `anchors_disagree`: the two anchors read different alleles. `ambiguous_both_alleles`: both k-mers turned up and no anchor could say which allele this locus carries. `alt_kmer_in_reference`: the reference itself carries this marker's ALT k-mer, so finding it says nothing, and no anchor could tell the real locus from the copy. `ref_kmer_repeated`: the reference carries this marker's window more than once, the genome did not show every copy, and so a reference hit may be the other copy. `no_reference_kmer`: the marker has no usable REF k-mer (its reference allele holds a base other than A, C, G or T) and the anchors could not read it either. |

## See also

Expand Down
7 changes: 4 additions & 3 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,19 +187,20 @@ The companion `sample_lineage_summary.tsv` collapses this to a single row: the g

### `split-fastq` — mutations + summary

`sample_genotype_<sample>_mutations.tsv` lists each called marker with its position, REF/ALT alleles, REF and ALT read counts, ALT fraction, and lineage. `sample_genotype_summary.tsv` gives one row per sample: the per-lineage marker counts, the final major-lineage call, and how many markers the reads could answer neither way. Those are listed one per row in `sample_genotype_<sample>_undetermined.tsv`, with `not_found` when no read carried either allele and `low_depth` when the two together fall below `--min-depth`. A marker nobody could read is not a marker that is absent, which matters most with a resistance panel.
`sample_genotype_<sample>_mutations.tsv` lists each called marker with its position, REF/ALT alleles, REF and ALT read counts, ALT fraction, and lineage. `sample_genotype_summary.tsv` gives one row per sample: the per-lineage marker counts, the final major-lineage call, and how many markers the reads could answer neither way. Those are listed one per row in `sample_genotype_<sample>_undetermined.tsv`, with the reason: `not_found` when nothing read the locus, `low_depth` when too few reads did, and the rest explained in [split-fastq](split-fastq.md#per-sample-undetermined-tsv). A marker nobody could read is not a marker that is absent, which matters most with a resistance panel.

### `predict` — predictions TSV

`sample_prediction.tsv` has one row per input sequence — except sequences shorter than the model's k-mer size, which are skipped with a warning:
`sample_prediction.tsv` has one row per input sequence. A sequence that yields no k-mer (shorter than the model's k, or N-masked) is reported as `Undetermined` rather than dropped:

| Column | Meaning |
|---|---|
| `Header` | Sequence header from the input FASTA |
| `Predicted_Lineage` | Most-voted lineage label |
| `Predicted_Lineage` | Most-voted lineage label, or `Undetermined` |
| `Confidence` | Fraction of trees voting for the winner (0–1) |
| `Confidence_Margin` | Gap between winner and runner-up (0–1) |
| `Other_Votes` | Top 3 alternatives with their vote fractions |
| `Kmers_Used` | k-mers the sequence yielded; zero for an `Undetermined` row |

!!! example "Reading a confidence score"
A `Confidence` of `0.95` means 95% of the trees agreed on the call; a `Confidence_Margin` of `0.40` means the winner drew 40% of the whole ensemble more than the runner-up (e.g. 60% of trees vs 20%). High values on both signal a clean, unambiguous prediction.
Expand Down
Loading
Loading