diff --git a/docs/algorithms/assembly-classification.md b/docs/algorithms/assembly-classification.md index ce40398..e15e3a3 100644 --- a/docs/algorithms/assembly-classification.md +++ b/docs/algorithms/assembly-classification.md @@ -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 | @@ -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 diff --git a/docs/algorithms/feature-hashing.md b/docs/algorithms/feature-hashing.md index 73d15b3..db183b6 100644 --- a/docs/algorithms/feature-hashing.md +++ b/docs/algorithms/feature-hashing.md @@ -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 diff --git a/docs/algorithms/marker-genotyping.md b/docs/algorithms/marker-genotyping.md index 8edf8b1..acc5ba3 100644 --- a/docs/algorithms/marker-genotyping.md +++ b/docs/algorithms/marker-genotyping.md @@ -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 diff --git a/docs/algorithms/random-forest.md b/docs/algorithms/random-forest.md index c84105f..d0a34e5 100644 --- a/docs/algorithms/random-forest.md +++ b/docs/algorithms/random-forest.md @@ -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 | diff --git a/docs/algorithms/reference-matching.md b/docs/algorithms/reference-matching.md index 1ee20bf..c59ed30 100644 --- a/docs/algorithms/reference-matching.md +++ b/docs/algorithms/reference-matching.md @@ -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 @@ -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. @@ -77,7 +77,7 @@ 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 | @@ -85,7 +85,7 @@ This is a **weighted containment score**: k-mers that appear more frequently in ## 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 ``` diff --git a/docs/classify.md b/docs/classify.md index 64c1c74..4ffd620 100644 --- a/docs/classify.md +++ b/docs/classify.md @@ -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 | @@ -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. @@ -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 diff --git a/docs/getting-started.md b/docs/getting-started.md index e3dfd2f..5f45f35 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -187,19 +187,20 @@ The companion `sample_lineage_summary.tsv` collapses this to a single row: the g ### `split-fastq` — mutations + summary -`sample_genotype__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__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__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__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. diff --git a/docs/input-formats.md b/docs/input-formats.md index 0fb1588..8cf0dd8 100644 --- a/docs/input-formats.md +++ b/docs/input-formats.md @@ -1,6 +1,6 @@ # Input Format Reference -pathotypr reads a small set of plain-text formats. Every file is **UTF-8**; every tabular file is **tab-separated** (`\t`) with **no spaces around the delimiters**. This page is the authoritative reference for each one — which command consumes it, the exact column semantics, and the parsing rules the tools apply. +pathotypr reads a small set of plain-text formats. Every file is **UTF-8**; every tabular file is **tab-separated** (`\t`) with **no spaces around the delimiters**. No output may be named after an input: a command whose output would land on one of its input files stops before writing anything, and names both. This page is the authoritative reference for each one: which command consumes it, the exact column semantics, and the parsing rules the tools apply. !!! tip "Looking for one command's inputs?" This page is organised by **format**. Each command page also carries an @@ -25,18 +25,51 @@ pathotypr reads a small set of plain-text formats. Every file is **UTF-8**; ever --- +## Example dataset + +The examples on this page are invented, and they make up one small dataset. +[Output files](output-files.md) runs every command on it, so each output shown +there can be traced back to the inputs shown here. + +- `reference.fasta`: `toy_ref`, a random 4,000 bp sequence holding two invented genes, `geneR` (3001 to 3600, `+` strand) and `geneI` (3701 to 3898, `-` strand). +- `lineage_markers.tsv`: seven lineage markers, for L1, L1.1, L2, L2.2, L4, and two for L4.9, one of them a deletion. +- `resistance_markers.tsv`: four markers in the WHO shape, three in `geneR` for RIF and one in `geneI` for INH. +- `annotation.gff`: the two genes. +- `samples.tsv` and `genomes/`: three assemblies and the list that names them. +- `reads.tsv` and `reads/`: error-free 100 bp reads of those assemblies at 30x, from both strands, and their list. +- `training.fasta`: ten genomes of each of L1, L2 and L4. +- `references.fasta`: one genome per lineage, the candidates for `match`. +- `queries.fasta`: the three assemblies and `masked_1`, a record of 300 `N`, for `predict`. + +Every genome carries 15 SNPs its whole lineage shares, and each training genome +three of its own. The three samples differ in this: + +| Sample | Lineage | Resistance changes | Also | +|---|---|---|---| +| `sample_A` | L2.2 | `geneR` S50L | | +| `sample_B` | L4.9 | `geneI` S15T, `geneR` A70V | a second change at 2111, six bases from its L4.9 SNP at 2105 | +| `sample_C` | L4 | `geneR` c.-15C>T | it lost the 201 bases from 2050 to 2250, where both L4.9 markers sit | + +--- + ## Training FASTA (`train`) Standard FASTA. The **first whitespace-delimited token** of each header is used as the class label; everything after the first space is ignored for labeling (but preserved in the record header). ```text ->L4 sample_0001 collected_2021 -ACTGATCGATCG... ->L2 sample_0002 -ACTGATCGATCG... +>L1 toy_L1_01 +AATAAACGGCCTTACAGATTATACAGCCGGACCTGGCTTAATTCGTCTTATCTTAACCTC +TTCCACGTTGAACGGGAGGGTTCATGCTCTAACATCAGGGATCCATGCATTGTTTTCCAA +... +>L2 toy_L2_01 +AATAAACGGCCTTACAGATTATACAGCCGGACCTGGCTTAATTCGTCTTATCTTAACCTC +TTCCACGTTGACCGGGAGGGTTCATGCCCTAACATCAGGGATCCATGCATTGTTTTCCAA +... ``` -Labels parsed above: `L4`, `L2`. +The start of `training.fasta` in the [example dataset](#example-dataset). The +labels parsed are `L1` and `L2`; `toy_L1_01` stays in the header and plays no +part in the label. - The label token is taken verbatim — underscores, dots, and other characters are preserved (`L4.3.4.2`, `ST258`, `clade_A`, `L4_1_2` are all valid labels). - Sequences are normalized by the FASTA reader on load. @@ -55,7 +88,12 @@ Labels parsed above: `L4`, `L2`. ## Marker TSV (`classify` and `split-fastq`) -Tab-separated. Blank lines and lines beginning with `#` are ignored. A header row is **optional** and tolerated by both commands (see the admonition below). +Tab-separated, with LF or CRLF line endings (the deposited panels use CRLF; both are read the same). Blank lines and lines beginning with `#` are ignored. A header row is **optional** and tolerated by both commands (see the admonition below). + +The same file format carries two kinds of panel, and the tools treat them differently: + +- a **lineage panel**, where the columns after the alleles are lineage levels (`L4`, `L4.9`); +- a **resistance panel** in the shape of the WHO catalogue, where they are a drug, a phenotype, a marker name, a WHO grade, a gene and a mutation. See [Resistance panels](#resistance-panels-who-catalogue) below. ### Columns @@ -69,32 +107,43 @@ Tab-separated. Blank lines and lines beginning with `#` are ignored. A header ro ### Examples -=== "Lineage only" +=== "Lineage panel" ```text - #pos ref alt level1 level2 - 761155 C T L4 L4.9 - 2155168 G A L2 L2.2 + position ref_base alt_base lineage1 lineage2 + 301 T G L1 + 702 T G L1 L1.1 + 1103 G T L2 + 1504 C T L2 L2.2 + 2105 G C L4 L4.9 + 2207 CA C L4 L4.9 + 2606 A G L4 ``` + `lineage_markers.tsv` of the [example dataset](#example-dataset), with the + header the deposited lineage panel uses. A sublineage marker lists its + parent first, so `1504` is an L2.2 marker and counts for L2 as well. + === "With gene/mutation annotation" ```text #pos ref alt level1 level2 gene mutation - 761155 C T L4 L4.9 gyrA Ser95Thr - 2155168 G A L2 L2.2 katG Ser315Thr + 3149 C T RIF RIF-R geneR S50L + 3855 C G INH INH-R geneI S15T ``` - The blank column (two consecutive tabs) after `L4.9` / `L2.2` separates the lineage levels from the annotation columns. + The blank column (two consecutive tabs) after `RIF-R` / `INH-R` separates the levels from the annotation columns: the path of the first marker is `RIF;RIF-R`, its gene `geneR` and its mutation `S50L`. A panel written this way is read as a **lineage** panel, with `RIF` and `INH` as its top levels: `classify` calls `sample_A` `RIF`, as it would call a lineage. To be answered as a resistance panel it has to use the WHO shape below. === "Small indel (classify only)" ```text - #pos ref alt level1 level2 - 4247431 CC C L1 L1.1 + 2207 CA C L4 L4.9 ``` - Indel markers are used by [`classify`](classify.md) (FASTA) and **silently skipped** by [`split-fastq`](split-fastq.md) (FASTQ). + The deletion of the example panel: `CA` at 2207 and 2208 becomes `C`, so + the `A` at 2208 is gone. Indel markers are used by [`classify`](classify.md) + (FASTA) and skipped by [`split-fastq`](split-fastq.md) (FASTQ), which says + how many it skipped in its log. !!! warning "Annotations require an empty separator cell" @@ -105,7 +154,7 @@ Tab-separated. Blank lines and lines beginning with `#` are ignored. A header ro - **Positions are 1-based** relative to the [reference genome](#reference-fasta). - Lineage levels are combined into a hierarchical, semicolon-joined path internally: `L4` + `L4.9` → `L4;L4.9`. - Annotation columns: `classify` uses the **first** annotation cell as the gene and the **second** as the mutation; `split-fastq` retains all trailing annotation cells. When a GFF is supplied to `classify`, gene/amino-acid values derived from the GFF take precedence, falling back to these columns. -- A row is skipped if it has fewer than 4 columns, has a non-numeric position, or has an empty REF, ALT, or lineage path. +- A row is skipped, with a warning that names it, if it has fewer than 4 columns, has a non-numeric position, or has an empty REF, ALT, or lineage path. The rest of the file is still read. - **Allele-length limit:** an allele must be shorter than the k-mer size. For `classify`, the allele must also leave room for the flanks, so effectively `max(len(REF), len(ALT)) ≤ kmer_size − 2 × min_flank_bases` (default `min_flank_bases` = 10); markers that exceed this are skipped. !!! info "Supported variant types differ by command" @@ -126,6 +175,61 @@ Tab-separated. Blank lines and lines beginning with `#` are ignored. A header ro A header commented with a leading `#` works for both. See the [Marker format](marker_format.md) page for curation guidance and quality criteria. +### Resistance panels (WHO catalogue) + +A resistance panel has nine columns and **no empty separator cell**, so all six +columns after the alleles form the marker's path. This is +`resistance_markers.tsv` of the [example dataset](#example-dataset): + +```text +#pos ref alt drug resistance marker_name grade gene mutation +2986 C T RIF RIF-R geneR_c.-15C>T 5) Not assoc w R geneR c.-15C>T +3149 C T RIF RIF-R geneR_S50L 1) Assoc w R geneR S50L +3209 C T RIF RIF-R geneR_A70V 3) Uncertain significance geneR A70V +3855 C G INH INH-R geneI_S15T 1) Assoc w R geneI S15T +``` + +The path of `geneR_S50L` is `RIF;RIF-R;geneR_S50L;1) Assoc w R;geneR;S50L`, +and it is read by position: the **first** level is the drug and the **fourth** +is the WHO grade. The fifth and sixth are the gene and mutation the app shows on +its resistance card; in the TSV outputs they stay inside the path, and the +`Gene` column of `classify` is filled from the GFF when one is given. + +The deposited panel has the same shape. These three rows are taken from it: + +```text +#pos ref alt drug resistance marker_name grade gene mutation +761155 C T RIF RIF-R rpoB_S450L 1) Assoc w R rpoB S450L +2155168 C G INH INH-R katG_S315T 1) Assoc w R katG S315T +759545 TA CG RIF RIF-R rpoB_c.-261A>G 5) Not assoc w R rpoB c.-261A>G +``` + +A panel is recognised as a resistance panel when at least half of its markers +have a path of four levels or more whose fourth level reads as a WHO grade, so a +lineage panel with one odd row is never mistaken for one. The grade decides what +a marker found in a genome means: + +| Grade cell | Read as | +|---|---| +| `1) Assoc w R`, `2) Assoc w R - Interim` | associated with resistance: the drug is called resistant | +| `3) Uncertain significance` | uncertain: reported, never called resistant | +| `4) Not assoc w R - Interim`, `5) Not assoc w R` | not associated | +| anything else, such as `TBProfiler_literature` | left out of the resistance call; the marker is still found and listed | + +The number before the parenthesis is what is read; without one, a cell +containing "not assoc", "uncertain" or "assoc" is read by those words. The +deposited panel has 402 rows graded `TBProfiler_literature`, which the call +leaves out. With a +resistance panel the summary's call is the list of drugs with a grade 1 or 2 +marker, for example `Resistant: INH,RIF`, instead of a lineage; see +[classify](classify.md#resistance-panels). + +!!! note "Several rows per catalogue entry" + The deposited panel spells one catalogue mutation several ways: the single + base change, and longer alleles covering the same codon with its + neighbours. Each row is a marker of its own, and a sample can match more + than one of them for a single change. + --- ## Sample List TSV (`classify --input-list`) @@ -133,11 +237,14 @@ Tab-separated. Blank lines and lines beginning with `#` are ignored. A header ro Tab-separated. One sample per row: a name, a FASTA path, and an optional GFF path. ```text -sample_A /data/genomes/sample_A.fasta /data/gff/sample_A.gff3 -sample_B /data/genomes/sample_B.fasta -sample_C genomes/sample_C.fasta +sample_A genomes/sample_A.fasta annotation.gff +sample_B genomes/sample_B.fasta annotation.gff +sample_C genomes/sample_C.fasta annotation.gff ``` +`samples.tsv` of the [example dataset](#example-dataset). A sample without an +annotation leaves the third column out, and any path may be absolute. + | Column | Content | Required | |---|---|---| | 1 | Sample name (**must be unique**) | ✅ | @@ -146,6 +253,7 @@ sample_C genomes/sample_C.fasta - Sample names must be unique — a duplicate name aborts the run. - Every FASTA path (and every GFF path, when given) must exist, or the run aborts with a "file does not exist" error. +- A relative path is read from the directory pathotypr runs in, not from the list's own folder: the example list works from the folder that holds `genomes/`. - Blank first cells and rows beginning with `#` are skipped; a header row whose first cell is `sample`/`sample_name`/`genome` **and** whose second cell contains `fasta` or `path` is auto-detected and skipped. !!! tip "Alternatives to `--input-list`" @@ -159,8 +267,17 @@ sample_C genomes/sample_C.fasta Tab-separated. One sample per row: a name followed by one or more FASTQ paths (plain or gzipped). ```text -sample_A /data/reads/sample_A_R1.fastq.gz /data/reads/sample_A_R2.fastq.gz -sample_B /data/reads/sample_B.fastq.gz +sample_A reads/sample_A.fastq +sample_B reads/sample_B.fastq +sample_C reads/sample_C.fastq +``` + +`reads.tsv` of the [example dataset](#example-dataset): single-end reads, one +file per sample. A paired-end sample lists R1 and then R2 on its row, plain or +gzipped: + +```text +sample_D /data/reads/sample_D_R1.fastq.gz /data/reads/sample_D_R2.fastq.gz ``` | Column | Content | Required | @@ -169,6 +286,7 @@ sample_B /data/reads/sample_B.fastq.gz | 2+ | FASTQ path(s): **one** for single-end, **two** for paired-end (R1 then R2) | ✅ (at least one) | - Paths are validated up front — a missing FASTQ aborts the run. +- A relative path is read from the directory pathotypr runs in, not from the list's own folder. - Blank lines and lines beginning with `#` are skipped; rows with no FASTQ path are skipped with a warning. !!! warning "`split-fastq` vs `match` treat the list differently" @@ -184,7 +302,16 @@ The reference defines the coordinate system for marker positions (`classify`, `s === "classify / split-fastq — single-record" - `-r, --reference` — a **single-record** FASTA containing the genome the marker positions are numbered against. The sequence is normalized on load. A FASTA with **more than one record is rejected** with: + `-r, --reference`: a **single-record** FASTA containing the genome the marker positions are numbered against. The sequence is normalized on load. The reference of the [example dataset](#example-dataset): + + ```text + >toy_ref invented example reference + AATAAACGGCCTTACAGATTATACAGCCGGACCTGGCTTAATTCGTCTTATCTTAACCTC + TTCCACGTTGAACGGGAGGGTTCATGCTCTAACATCAGGGATCCATGCATTGTTTTCCAA + ... + ``` + + A FASTA with **more than one record is rejected** with: ```text Reference FASTA '' contains multiple records; provide a single-record FASTA. @@ -192,7 +319,19 @@ The reference defines the coordinate system for marker positions (`classify`, `s === "match — multi-record" - `-r, --references` — a **multi-record** (multi-FASTA) file where **each record is one candidate reference genome**. `match` scores the query reads against every record and reports the best containment match. + `-r, --references`: a **multi-record** (multi-FASTA) file where **each record is one candidate reference genome**. `match` scores the query reads against every record and reports the best containment match. The candidates of the [example dataset](#example-dataset): + + ```text + >ref_L1 invented L1 representative + AATAAACGGCCTTACAGATTATACAGCCGGACCTGGCTTAATTCGTCTTATCTTAACCTC + ... + >ref_L2 invented L2 representative + AATAAACGGCCTTACAGATTATACAGCCGGACCTGGCTTAATTCGTCTTATCTTAACCTC + ... + >ref_L4 invented L4 representative + AATAAACGGCCTTACAGATTATACAGCCGGACCTGGCTTAATTCGTCTTATCTTAACCTC + ... + ``` --- @@ -200,6 +339,15 @@ The reference defines the coordinate system for marker positions (`classify`, `s Standard 9-column, tab-delimited GFF3. Used only by [`classify`](classify.md) to translate variants into amino-acid changes. `split-fastq` and `match` do not consume GFF. +```text +##gff-version 3 +toy_ref invented CDS 3001 3600 . + 0 ID=cds-geneR;gene=geneR;locus_tag=TOY_0001 +toy_ref invented CDS 3701 3898 . - 0 ID=cds-geneI;gene=geneI;locus_tag=TOY_0002 +``` + +`annotation.gff` of the [example dataset](#example-dataset). The RefSeq +annotation of H37Rv has the same shape: + ```text ##gff-version 3 NC_000962.3 RefSeq CDS 7302 9818 . + 0 ID=cds-GyrA;gene=gyrA;locus_tag=Rv0006 @@ -207,14 +355,7 @@ NC_000962.3 RefSeq CDS 2153889 2156111 . - 0 ID=cds-KatG;gene=katG;locus_tag=Rv1 ``` - **Only `CDS` features are used**; all other feature types are ignored. -- **Gene name** is taken from the attributes column: `gene=` always wins when present; otherwise the **first** of `locus_tag=`, `Name=` or `ID=` **in the order they appear on the line** is used: - - 1. `gene=…` - 2. `locus_tag=…` - 3. `Name=…` - 4. `ID=…` - - A CDS with none of these is labeled `Unknown`. +- **Gene name** is taken from the attributes column. `gene=` wins wherever it appears; without it, whichever of `locus_tag=`, `Name=` or `ID=` comes **first on the line** is used, so `ID=cds-geneR;Name=GeneR;locus_tag=TOY_0001` is labeled `cds-geneR` and `locus_tag=TOY_0002;ID=cds-geneI` is labeled `TOY_0002`. A CDS with none of these is labeled `Unknown`. - **Strand** (`+` / `-`) sets the translation direction; any other value is treated as unknown and not translated. - **Coordinates are 1-based inclusive** (GFF3 standard) and converted internally to 0-based for interval-tree lookups. diff --git a/docs/match.md b/docs/match.md index 0608b0b..ca30cbc 100644 --- a/docs/match.md +++ b/docs/match.md @@ -20,7 +20,7 @@ You must supply exactly one input source (`-i/--input` or `-l/--input-list`) and | What | Flag | Format | |---|---|---| | Reference database | `-r, --references` | **Multi-record** FASTA: one record per candidate genome | -| Reads | `-i, --input` or `-l, --input-list` | FASTQ, plain or gzipped | +| Reads | `-i, --input` or `-l, --input-list` | FASTQ, plain or gzipped; a FASTA such as an assembly is read too | !!! danger "`match` pools everything into a single query" This is the one place where a sample list does **not** mean one result per @@ -46,7 +46,7 @@ You must supply exactly one input source (`-i/--input` or `-l/--input-list`) and ## How it works 1. **Count** k-mers across every input FASTQ file in parallel, tallying occurrence counts. -2. **Filter** likely sequencing noise by dropping low-count k-mers (see `--min-kmer-count`). +2. **Filter** likely sequencing noise by dropping low-count k-mers, if asked to (see `--min-kmer-count`; the default drops nothing). 3. **Stream** the reference multi-FASTA in batches, extracting the unique k-mers of each reference. 4. **Score** each reference by the weighted fraction of query k-mer occurrences it contains. 5. **Report** the highest-scoring reference and its `Shared_Kmer_Fraction`. @@ -69,7 +69,7 @@ You must supply exactly one input source (`-i/--input` or `-l/--input-list`) and | `--early-stop-confidence ` | `0.0` | no | Reserved; accepted but not read in the current release (no effect). | | `--early-stop-min-kmers ` | `1000000` | no | Reserved; accepted but not read in the current release (no effect). | | `--strict-percentages` | `true` | no | Legacy flag retained for backward compatibility (default on); it does not change current results. | -| `--min-kmer-count ` | `2` | no | Minimum k-mer count to keep (singleton filtering as noise). Set `1` to keep all. Only applied when there are more than 100k unique k-mers and this value is greater than `1`. | +| `--min-kmer-count ` | `1` | no | Query k-mers seen fewer than `N` times are dropped as sequencing noise, and both the shared count and the total are then taken over what is left. `1` keeps every k-mer. | | `--excel` | `false` | no | Also write an Excel (`.xlsx`) file. | ### Global flags @@ -130,7 +130,7 @@ Available on every subcommand: The report has a header row followed by exactly one data row. Columns are tab-separated: ```text -Query_Files Best_Match_Reference Shared_Kmer_Fraction +Query_Files Best_Match_Reference Shared_Kmer_Fraction Query_Kmers ``` | Column | Description | @@ -138,14 +138,33 @@ Query_Files Best_Match_Reference Shared_Kmer_Fraction | `Query_Files` | Comma-separated list of the input FASTQ file paths that were pooled into the query. | | `Best_Match_Reference` | FASTA header line of the highest-scoring reference, including any description after the first space. | | `Shared_Kmer_Fraction` | Weighted k-mer containment score between `0` and `1`, printed to four decimal places. Higher means more of the query's k-mer content is present in the matched reference. | +| `Query_Kmers` | The denominator: k-mer occurrences in the query after `--min-kmer-count`. A score is a fraction of this number, so two scores are comparable only when it was arrived at the same way. | + +!!! warning "Below a few fold coverage, do not raise `--min-kmer-count`" + At low coverage a real k-mer is usually seen once, so dropping singletons + throws away the evidence that tells two references apart and keeps the + repeats, which match everything. On 1 Mb of 0.15x reads, dropping them kept + 4.7% of the distinct k-mers and scored the correct reference **1.0000** and + a reference 250 SNPs away 0.9990: a perfect score from almost no data, a + thousandth ahead. Keeping them scored the two 0.8897 and 0.8821, a margin + eight times wider. + + This used to happen on its own: the filter switched itself on above 100,000 + unique k-mers, so 1,450 reads of that sample scored 0.8886 and 1,500 reads + scored 1.0000. It now applies only when you ask for it, and `Query_Kmers` + says what the score was divided by. Example: ```text -Query_Files Best_Match_Reference Shared_Kmer_Fraction -reads_R1.fastq.gz,reads_R2.fastq.gz NC_000962.3 0.9873 +Query_Files Best_Match_Reference Shared_Kmer_Fraction Query_Kmers +sample_reads.fastq reference_A 0.8886 101500 ``` +This is a real run of 1,450 reads at 0.15x against two references 250 SNPs +apart; the other one scored 0.8812. A whole-genome run gives a much larger +`Query_Kmers`: about 106 million k-mer occurrences at 30x with 150 bp reads. + If no reference shares any k-mers with the query, the first reference is still reported with a `Shared_Kmer_Fraction` of `0.0000` — read a near-zero score as "no usable match". Only an empty reference FASTA yields a header-only report. ### Excel report (optional) diff --git a/docs/output-files.md b/docs/output-files.md index 3f1e812..c29c1ec 100644 --- a/docs/output-files.md +++ b/docs/output-files.md @@ -2,10 +2,13 @@ Every `pathotypr` subcommand writes tab-separated (TSV) result files, and most can additionally emit an Excel (`.xlsx`) copy. This page is the authoritative reference for **what each command writes, where, and what every column means**. For flags, examples, and algorithm background, follow the per-command links. +Each command's first example is what it writes for the invented [example dataset](input-formats.md#example-dataset), run as shown, laid out as a table with one column per tab-separated field. Where a second example follows, it is an excerpt of a run on real genomes, shown as the raw text of the file. + !!! abstract "Conventions used throughout" - **TSV**: UTF-8, tab-delimited, exactly one header row, one record per line. Cells with no value are written **empty** (nothing between the tabs). - **`--excel`**: when supported and enabled, the same table is written to a `.xlsx` alongside the TSV. The Excel name is derived from the TSV path by replacing a trailing `.tsv` with `.xlsx`; if the name does not end in `.tsv`, `.xlsx` is appended. Excel sheets add an autofilter, auto-sized columns, and (on some columns) conditional-formatting colours. - **Coordinates** are **1-based** unless stated otherwise. + - **No output over an input**: a command whose output would be written over one of its own input files (for example `classify -l run.tsv -o run`, whose detail table is `run.tsv`) stops before writing anything and says which two files collide. - Numeric precision is fixed per column (e.g. `0.9800`) — see each table. !!! note "Global flags do not change file contents" @@ -46,7 +49,7 @@ Ranked by how often each bucket was chosen as a split across all 100 trees (high | `bucket` | Feature-hash bucket index (`0 … 1,048,575`). | | `split_count` | Number of times this bucket was used as a split across the ensemble. | | `importance_pct` | `split_count` as a percentage of the total split count over all buckets (4 decimals). | -| `kmers` | Comma-separated training k-mers that hash into this bucket. | +| `kmers` | Comma-separated training k-mers that fall into this bucket. A bucket is the last ten bases of the canonical k-mer, so these are every k-mer sharing them, and the one the splits used is among them without being singled out: read them as candidates. | ### `*.importance.coords.tsv` columns @@ -58,10 +61,51 @@ One row per occurrence of a discriminant k-mer, ordered by bucket rank, then seq | `bucket` | Feature-hash bucket index. | | `split_count` | Split count for the bucket. | | `importance_pct` | Percentage of total splits attributable to the bucket (4 decimals). | -| `kmer` | The specific k-mer occurrence. | +| `kmer` | The bases found at `position`, read on the sequence's own strand. That can be the reverse complement of the k-mer listed for the bucket in `*.importance.tsv`, which is the canonical one. | | `sequence` | Full FASTA header of the training sequence containing the k-mer. | | `lineage` | Class label of that sequence. | -| `position` | Position of the k-mer within the sequence. | +| `position` | 1-based start of those bases in the sequence. | + +On the [example dataset](input-formats.md#example-dataset), +`pathotypr train -i training.fasta -o model.pathotypr.zst` writes the model and +these two tables, of which the first rows are shown: + +| rank | bucket | split_count | importance_pct | kmers | +|---|---|---|---|---| +| 1 | 585506 | 4 | 2.0000 | CATGGATCCCTGATGTTAGAG | +| 2 | 978401 | 3 | 1.5000 | CCAGGGCTGTCTGTGTCTGAC | +| 3 | 730549 | 2 | 1.0000 | GCAACCGATCTGTAGCCGTCC | + +| rank | bucket | split_count | importance_pct | kmer | sequence | lineage | position | +|---|---|---|---|---|---|---|---| +| 1 | 585506 | 4 | 2.0000 | CTCTAACATCAGGGATCCATG | L1 toy_L1_01 | L1 | 87 | +| 1 | 585506 | 4 | 2.0000 | CTCTAACATCAGGGATCCATG | L1 toy_L1_02 | L1 | 87 | + +The most used bucket stands for a k-mer that starts at 87 in every L1 and L4 +genome, twenty rows in all, and in no L2 genome, because L2 has a change at 88. +The coordinate table gives it as `CTCTAACATCAGGGATCCATG`, the bases on the +genome's own strand, and the importance table as `CATGGATCCCTGATGTTAGAG`, its +reverse complement and the canonical form. The dataset is small enough that the +trees used only 189 buckets, so the importance table stops there instead of +at 500. + +Excerpts of a real run on four genomes of two lineages: + +```text +rank bucket split_count importance_pct kmers +1 603290 2 2.1739 CAGACCACCGGGCATCAGCGG,AACCGGATTGAGCATCAGCGG,AGTCTGCCACCGCATCAGCGG,… +``` + +```text +rank bucket split_count importance_pct kmer sequence lineage position +1 603290 2 2.1739 CCGCTGATGCCTACAAAACTG L1 train_L1_0 L1 8020 +1 603290 2 2.1739 CAGACCACCGGGCATCAGCGG L1 train_L1_0 L1 242297 +``` + +Every k-mer of bucket 603290 ends in `GCATCAGCGG`: those are the ten bases the +bucket is made of. The first coordinate row reads `CCGCTGATGCCTACAAAACTG` at +position 8020, the reverse complement of `CAGTTTTGTAGGCATCAGCGG`, which ends in +the same ten bases. See also: [Training pipeline](algorithms/training.md), [Feature hashing](algorithms/feature-hashing.md), [Input formats](input-formats.md). @@ -76,27 +120,43 @@ Writes one predictions table to `--output`, streamed as sequences are classified | `` | always | One row per input sequence. | | `` | with `--excel` | Same columns, with conditional-formatting colours (see below). | -**Header:** `Header Predicted_Lineage Confidence Confidence_Margin Other_Votes` +**Header:** `Header Predicted_Lineage Confidence Confidence_Margin Other_Votes Kmers_Used` | Column | Description | |---|---| | `Header` | Sequence header from the input FASTA. | -| `Predicted_Lineage` | Most-voted class label across the ensemble. A record on which no tree cast a usable vote still gets a label, but with a `Confidence` at or near zero. | +| `Predicted_Lineage` | Most-voted class label across the ensemble, or `Undetermined` when the record yielded no k-mer; `Confidence` and `Confidence_Margin` are then empty and `Kmers_Used` is zero. | | `Confidence` | Fraction of trees voting for the winner, `0`–`1` (4 decimals). | | `Confidence_Margin` | Winner votes minus runner-up votes, over total trees, `0`–`1` (4 decimals). | | `Other_Votes` | Up to the **top 3** runner-up labels as `label:fraction` (fraction to 2 decimals), comma-separated; empty when there are no other votes. | - -```text -Header Predicted_Lineage Confidence Confidence_Margin Other_Votes -sample_A L2.2.1 0.9800 0.9200 L2.2:0.04,L4:0.02 -sample_B L4.3.4.2 0.7500 0.3000 L4.3:0.20,L4:0.05 -``` +| `Kmers_Used` | k-mers the record yielded. Zero means the model said nothing about it, and `Predicted_Lineage` is then `Undetermined` with the confidence columns empty. | + +On the [example dataset](input-formats.md#example-dataset), with the model +`train` built above, +`pathotypr predict -i queries.fasta -m model.pathotypr.zst -o predictions.tsv` +writes: + +| Header | Predicted_Lineage | Confidence | Confidence_Margin | Other_Votes | Kmers_Used | +|---|---|---|---|---|---| +| sample_A | L2 | 1.0000 | 1.0000 | | 3980 | +| sample_B | L4 | 1.0000 | 1.0000 | | 3979 | +| sample_C | L4 | 0.9700 | 0.9500 | L2:0.02,L1:0.01 | 3779 | +| masked_1 all bases masked | Undetermined | | | | 0 | + +`Confidence` and the fractions in `Other_Votes` are shares of the same 100 +trees, so they add up to at most 1, and `Confidence_Margin` is `Confidence` +minus the first fraction in `Other_Votes`: for `sample_C`, 0.97 minus 0.02. +`Kmers_Used` counts the k-mers a record yields, one per position where 21 +bases of A, C, G and T fit: 4,000 - 21 + 1 = 3,980 for the 4,000 bases of +`sample_A`, fewer for `sample_B` and `sample_C`, which lost 1 and 201 bases. `masked_1` is 300 `N`: no window +of A, C, G and T is long enough, so no k-mer, no vote, and the row says so +instead of carrying a lineage. !!! tip "Excel colour coding" In the `.xlsx`, **Confidence** is shaded red `< 0.5`, yellow `0.5–0.9`, green `≥ 0.9`; **Confidence_Margin** is shaded red `< 0.1`, yellow `0.1–0.5`, green `≥ 0.5` — so low-confidence calls stand out at a glance. -!!! note "Sequences shorter than *k* are skipped" - Input records shorter than the model's k-mer size produce no row (a warning is logged). If **no** records qualify, the command errors instead of writing an empty file. +!!! note "Every input record gets a row" + A record that yields no k-mer, because it is shorter than the model's k or N-masked, is reported as `Undetermined` with `Kmers_Used` zero, and the run ends by saying how many came out that way. Only a file with no records at all is an error. See also: [Prediction](algorithms/prediction.md), [`train`](train.md). @@ -108,8 +168,8 @@ Marker-based variant calling on assemblies. Writes a detailed per-marker table, | File | When | Content | |---|---|---| -| `.tsv` | always | One row per marker match per genome (the **detailed** table). | -| `_summary.tsv` | always | One row per genome with its major-lineage call and its count of undetermined markers. | +| `.tsv` | always | One row per marker match per genome (the **detailed** table), with the genomes in the order they were given: the rows of the list, the records of the FASTA, or the files. | +| `_summary.tsv` | always | One row per genome, sorted by name, with its major-lineage call and its count of undetermined markers. | | `_undetermined.tsv` | always | One row per marker per genome that could be read neither as present nor as absent. Only the header when every marker was read. | | `.xlsx`, `_summary.xlsx`, `_undetermined.xlsx` | with `--excel` | Excel copies of the three tables. | | `_masked.fasta` | with `--output-masked-fasta` | One file **per input assembly**, marker sites replaced by `N`, written to the prefix's parent directory. Only produced for reference-coordinate sequences (records whose length matches the reference); other inputs are skipped with the reason logged. Two inputs sharing a file stem do not overwrite each other — the second becomes `_2_masked.fasta`. See [classify](classify.md#output). | @@ -123,7 +183,7 @@ Marker-based variant calling on assemblies. Writes a detailed per-marker table, | Column | Description | |---|---| -| `genome` | Genome/sample name (from the input list or FASTA record ID). In `--input-files` mode it is prefixed with `[filename]`. | +| `genome` | With `-i`, the record's whole FASTA header line; with `--input-files`, that line prefixed with `[filename]`; with `-l`, the sample name from the list. | | `k-mer` | The diagnostic marker k-mer matched in the query. | | `k-merPOS` | 1-based start position of that k-mer in the query contig. | | `SNPgenome` | 1-based position of the variant allele within the query contig. | @@ -149,7 +209,7 @@ Marker-based variant calling on assemblies. Writes a detailed per-marker table, | Column | Description | |---|---| | `genome` | Genome/sample name. | -| `lineage:count` | Space-separated `lineage:count` pairs at **every hierarchical level** (each ancestor path prefix is counted), sorted by count descending, then by name. | +| `lineage:count` | Space-separated `lineage:count` pairs at **every hierarchical level** (each ancestor path prefix is counted), sorted by count descending, then by name. With a resistance panel, markers found per drug instead: a catalogue path is not a hierarchy, and its grade has spaces in it. | | `major_lineage` | Final call. For a lineage panel: with `--nested-classification` the deepest fully-supported path wins, otherwise the most abundant lineage. For a WHO resistance catalogue it is the resistance verdict instead, for example `Resistant: INH,RIF`. See [classify](classify.md#resistance-panels). | | `undetermined` | Number of markers that could be read neither way in this genome. | | `undetermined:count` | Those markers as `label:count` pairs under the **first level** of their path only (the drug for a resistance panel, the main lineage for a lineage panel), sorted like `lineage:count`. Empty when every marker was read. | @@ -172,44 +232,161 @@ rows in a resistance panel. | `SNPreference` | 1-based marker position in the reference genome. | | `REF`, `ALT` | Alleles of the marker. | | `lineage` | Lineage (or drug) path of the marker. | -| `Gene`, `mutation` | The marker's own gene and mutation fields; empty when the marker TSV has none. | -| `reason` | `not_found`: nothing of the marker occurs 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 the locus carries. `no_reference_kmer`: the marker has no usable reference k-mer (a reference allele outside A, C, G and T) and the anchors could not read it either. | +| `Gene`, `mutation` | The marker's own gene and mutation annotation columns; empty when the marker TSV has none, which includes WHO-shaped panels, where the gene and mutation are part of the path. | +| `reason` | `not_found`: nothing of the marker occurs 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 the locus carries. `alt_kmer_in_reference`: the reference itself carries this marker's ALT k-mer, so finding it means nothing, and no anchor could tell the real locus from the copy. `ref_kmer_repeated`: the reference carries the window more than once and the genome did not show every copy. `no_reference_kmer`: the marker has no usable reference k-mer (a reference allele outside A, C, G and T) and the anchors could not read it either. | + +### Examples + +On the [example dataset](input-formats.md#example-dataset), +`pathotypr classify -l samples.tsv -r reference.fasta -m lineage_markers.tsv -o lineage` +writes: + +=== "lineage.tsv" + + | genome | k-mer | k-merPOS | SNPgenome | SNPreference | REF | ALT | lineage | Gene | Gene_Start | Gene_End | AA_Pos | AA_Change | alleles_found | evidence | + |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| + | sample_A | ACGGGATCTCGGTGATTGCAATTTTTGCACC | 1088 | 1103 | 1103 | G | T | L2 | | | | | | ALT | kmer | + | sample_A | AGCTAGTACCTTACGTTAACGTGCAGGTTCA | 1489 | 1504 | 1504 | C | T | L2;L2.2 | | | | | | ALT | kmer | + | sample_B | | | | 2105 | G | C | L4;L4.9 | | | | | | ALT | left_anchor | + | sample_B | GCTAGTTTCAAGATCGCTTATTACATCGCCA | 2193 | 2207 | 2207 | CA | C | L4;L4.9 | | | | | | ALT | kmer | + | sample_B | TAAACTCGTGAGGCGGTGAGGTATGGCGATG | 2590 | 2605 | 2606 | A | G | L4 | | | | | | ALT | kmer | + | sample_C | TAAACTCGTGAGGCGGTGAGGTATGGCGATG | 2390 | 2405 | 2606 | A | G | L4 | | | | | | ALT | kmer | + + The marker at 2105 of `sample_B` has no `k-mer`, `k-merPOS` or + `SNPgenome`: the change at 2111 hides its k-mer, and its left anchor read + the allele instead. `SNPgenome` and `SNPreference` part ways after a length + change: the deletion at 2207 moves the 2606 marker of `sample_B` to 2605, + and the 201 bases `sample_C` lost move it to 2405. The list gives a GFF, but + no lineage marker falls in a gene, so the gene columns are empty. No sample + carries an L1 marker, and an absent marker gets no row. + +=== "lineage_summary.tsv" + + | genome | lineage:count | major_lineage | undetermined | undetermined:count | + |---|---|---|---|---| + | sample_A | L2:2 L2;L2.2:1 | L2 | 0 | | + | sample_B | L4:3 L4;L4.9:2 | L4 | 0 | | + | sample_C | L4:1 | L4 | 2 | L4:2 | + + Every marker also counts towards its ancestors, so `sample_B` has three L4 + markers, two of them L4.9, and by default the most abundant level wins: + `L4`. With `--nested-classification` the call is the deepest level with + support: `L2;L2.2` for `sample_A`, `L4;L4.9` for `sample_B`, and still + `L4` for `sample_C`. + +=== "lineage_undetermined.tsv" + + | genome | SNPreference | REF | ALT | lineage | Gene | mutation | reason | + |---|---|---|---|---|---|---|---| + | sample_C | 2105 | G | C | L4;L4.9 | | | not_found | + | sample_C | 2207 | CA | C | L4;L4.9 | | | not_found | + + `sample_C` lost the region of both L4.9 markers, so neither their k-mers + nor their anchors turn up. They are not called absent: they are listed as + undetermined. + +With the resistance panel instead, +`pathotypr classify -l samples.tsv -r reference.fasta -m resistance_markers.tsv -o resistance` +writes: + +=== "resistance.tsv" + + | genome | k-mer | k-merPOS | SNPgenome | SNPreference | REF | ALT | lineage | Gene | Gene_Start | Gene_End | AA_Pos | AA_Change | alleles_found | evidence | + |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| + | sample_A | CATATCATATCATCTTGAATGTATACACTTG | 3134 | 3149 | 3149 | C | T | RIF;RIF-R;geneR_S50L;1) Assoc w R;geneR;S50L | geneR | 3001 | 3600 | 50 | Ser50Leu(TCG>TTG) | ALT | kmer | + | sample_B | CCCCGCCTTGTTGCGTGAGCCGGTATGTCTG | 3193 | 3208 | 3209 | C | T | RIF;RIF-R;geneR_A70V;3) Uncertain significance;geneR;A70V | geneR | 3001 | 3600 | 70 | Ala70Val(GCG>GTG) | ALT | kmer | + | sample_B | TCCGCTCCTGGCTCGGTCAGGATGGCACAAT | 3839 | 3854 | 3855 | C | G | INH;INH-R;geneI_S15T;1) Assoc w R;geneI;S15T | geneI | 3701 | 3898 | 15 | Ser15Thr(AGC>ACC) | ALT | kmer | + | sample_C | GGTTGACGGGATCCATACCTTCCTCCGTGGA | 2770 | 2785 | 2986 | C | T | RIF;RIF-R;geneR_c.-15C>T;5) Not assoc w R;geneR;c.-15C>T | | | | | | ALT | kmer | + + The GFF fills `Gene` to `AA_Change` for the three markers inside a gene, + with the amino acid change read from each sample's own codon. The fourth, + `c.-15C>T`, lies 15 bases before `geneR`, in no gene, so those cells stay + empty. + +=== "resistance_summary.tsv" + + | genome | lineage:count | major_lineage | undetermined | undetermined:count | + |---|---|---|---|---| + | sample_A | RIF:1 | Resistant: RIF | 0 | | + | sample_B | INH:1 RIF:1 | Resistant: INH | 0 | | + | sample_C | RIF:1 | No resistance markers found | 0 | | + + `lineage:count` counts the markers found per drug, whatever their grade, + and the call names only the drugs with a grade 1 or 2 marker. The RIF + marker of `sample_B` is `3) Uncertain significance` and the one of + `sample_C` is `5) Not assoc w R`, so neither makes a call. Every marker was + read, so `resistance_undetermined.tsv` holds only its header. + +### From real runs + +Excerpts of runs on H37Rv and on two samples against the deposited resistance +panel. + +=== "Detailed, lineage panel" + + H37Rv against the lineage panel, with `-i`: the `genome` column is the + record's whole header line. No GFF was given, so the gene and amino-acid + columns are empty. -=== "Detailed" + ```text + genome k-mer k-merPOS SNPgenome SNPreference REF ALT lineage Gene Gene_Start Gene_End AA_Pos AA_Change alleles_found evidence + NC_000962.3 Mycobacterium tuberculosis H37Rv, complete genome CGCGTCGGTGAGTATCGTGCACGCGTGTGCG 15102 15117 15117 G C L4 ALT kmer + NC_000962.3 Mycobacterium tuberculosis H37Rv, complete genome CGTTCGTAGCCGCAGGACGGCGGTGTCCACG 311598 311613 311613 T G L4;L4.9 ALT kmer + ``` + +=== "Detailed, resistance panel with a GFF" + + Two samples from an `--input-list`, against the WHO-shaped resistance panel + and the H37Rv GFF. `double_435` carries both base changes of one codon, so + three catalogue rows fire: the two-base one by its k-mer, and the two + single-base ones by an anchor each, which is why their `k-mer`, `k-merPOS` + and `SNPgenome` cells are empty. All three report the amino acid the + sample's own codon reads. `h37rv` matches nothing, and gets the row with its + name only. ```text genome k-mer k-merPOS SNPgenome SNPreference REF ALT lineage Gene Gene_Start Gene_End AA_Pos AA_Change alleles_found evidence - sampleA ACGT…GTCA 1523 1533 745 C T L2;L2.2 rv0667 759807 763325 450 S450L ALT kmer - sampleA TTGA…CCAG 9021 9031 7362 G A L2 katG 2153889 2156111 315 ALT kmer - sampleA 2155168 C G INH;INH-R;katG_S315T katG 2153889 2156111 315 S315T ALT right_anchor - sampleB + h37rv + double_435 761109 G T RIF;RIF-R;rpoB_D435Y;1) Assoc w R;rpoB;D435Y rpoB 759807 763325 435 Asp435Phe(GAC>TTC) ALT left_anchor + double_435 TGAGCCAATTCATGTTCCAGAACAACCCGCT 761095 761109 761109 GA TT RIF;RIF-R;rpoB_D435F;1) Assoc w R;rpoB;D435F rpoB 759807 763325 435 Asp435Phe(GAC>TTC) ALT kmer + double_435 761110 A T RIF;RIF-R;rpoB_D435V;1) Assoc w R;rpoB;D435V rpoB 759807 763325 435 Asp435Phe(GAC>TTC) ALT right_anchor ``` === "Summary" ```text genome lineage:count major_lineage undetermined undetermined:count - sampleA L2:2 L2;L2.2:1 L2 3 L4:2 L1:1 - sampleB Unclassified 0 + NC_000962.3 Mycobacterium tuberculosis H37Rv, complete genome L4:62 L4;L4.9:6 L4 0 ``` + By default the most abundant level wins, and every marker also counts + towards its ancestors, so H37Rv is called `L4` (62 markers) rather than + `L4.9` (6). With `--nested-classification` the same genome is called + `L4;L4.9`, the deepest level with support. + === "Summary, resistance panel" ```text genome lineage:count major_lineage undetermined undetermined:count - sampleA INH:2 RIF:1 … Resistant: INH,RIF 187 INH:91 RIF:62 EMB:34 - sampleB OTHER:1 No resistance markers found 0 + double_435 RIF:3 Resistant: RIF 23 RIF:23 + h37rv No resistance markers found 0 ``` + With a resistance panel `lineage:count` counts the markers found per drug. + The 23 undetermined markers of `double_435` are indels next to the changed + codon: indels have no anchors, and the change breaks both of their k-mers. + === "Undetermined" ```text genome SNPreference REF ALT lineage Gene mutation reason - sampleA 3836739 A G L4;L4.1 not_found - sampleA 3836741 C T L4;L4.2 ambiguous_both_alleles - sampleA 1834177 A C L1 anchors_disagree + double_435 761095 T TGAG RIF;RIF-R;rpoB_Leu430_Ser431insArg;2) Assoc w R - Interim;rpoB;Leu430_Ser431insArg not_found + double_435 761107 TGGACCA T RIF;RIF-R;rpoB_Asp435_Gln436del;2) Assoc w R - Interim;rpoB;Asp435_Gln436del ref_kmer_repeated ``` + With a WHO-shaped panel the `Gene` and `mutation` cells are empty: the gene + and mutation are levels five and six of the path, not annotation columns. + See also: [Assembly classification](algorithms/assembly-classification.md), [Marker format](marker_format.md). --- @@ -221,10 +398,9 @@ Alignment-free genotyping from FASTQ reads. Writes one detailed table **per samp | File | When | Content | |---|---|---| | `__mutations.tsv` | always | Per-marker calls for one sample (one file per sample). | -| `__undetermined.tsv` | always | Markers the reads could answer neither way, one row each, with a `reason` of `not_found` or `low_depth`. Only the header when every marker was read. See [split-fastq](split-fastq.md#per-sample-undetermined-tsv). | +| `__undetermined.tsv` | always | Markers the reads could answer neither way, one row each, with the `reason`. Only the header when every marker was read. See [split-fastq](split-fastq.md#per-sample-undetermined-tsv). | | `_summary.tsv` | always | One row per sample with its major-lineage call and its count of undetermined markers. | | `__mutations.xlsx`, `__undetermined.xlsx`, `_summary.xlsx` | with `--excel` | Excel copies of the three tables. | -| `__mutations.xlsx`, `_summary.xlsx` | with `--excel` | Excel copies. | !!! note "Sample names in filenames are sanitised" Characters outside `A–Z a–z 0–9 _ - .` become `_`, and leading dots / surrounding underscores are trimmed. If two samples sanitise to the same name, the second gets a `_2` suffix, the third `_3`, and so on. The `genome` column in the summary keeps the **original** sample name. @@ -255,7 +431,8 @@ Only markers meeting `--min-depth` coverage **and** `--min-alt-percent` are writ **Header:** `pos ref_allele alt_allele ref_count alt_count lineage_path reason` One row per marker the reads could answer neither way, with `reason` one of -`not_found`, `low_depth`, `no_unique_anchor` or `anchors_disagree`. A marker +`not_found`, `low_depth`, `no_unique_anchor`, `anchors_disagree`, +`alt_kmer_in_reference` or `ref_kmer_repeated`. A marker read through a neighbour's window, or read from one of its own anchors, is not listed: it was answered. See [split-fastq](split-fastq.md#per-sample-undetermined-tsv). @@ -267,11 +444,92 @@ listed: it was answered. See | Column | Description | |---|---| | `genome` | Original sample name. | -| `lineage:count` | Space-separated `lineage:count` pairs across all hierarchical levels, sorted by count descending, then by name. | +| `lineage:count` | Space-separated `lineage:count` pairs across all hierarchical levels, sorted by count descending, then by name. With a resistance panel, markers found per drug instead. | | `major_lineage` | Final lineage call (`--nested-classification` enables hierarchical path validation; otherwise most-abundant wins). With a WHO drug-resistance panel, the drugs with a grade 1 or 2 marker instead. | | `undetermined` | How many markers the reads could answer neither way. | | `undetermined:count` | Those markers as `label:count` pairs under the first level of their path. Empty when every marker was read. | +### Example + +On the [example dataset](input-formats.md#example-dataset), +`pathotypr split-fastq -l reads.tsv -r reference.fasta -m lineage_markers.tsv -o reads` +writes a mutations table and an undetermined table per sample, and a summary: + +=== "reads_sample_B_mutations.tsv" + + | pos | ref_allele | alt_allele | ref_count | alt_count | alt_fraction | lineage_path | evidence | extra_annotations... | + |---|---|---|---|---|---|---|---|---| + | 2105 | G | C | 0 | 22 | 100.00 | L4;L4.9 | left_anchor | | + | 2606 | A | G | 0 | 16 | 100.00 | L4 | kmer | | + + The change at 2111 hides both k-mers of the marker at 2105, so the 22 + reads on its row are those of its left anchor. The deletion at 2207 has no + row: `split-fastq` skips indels. + +=== "reads_sample_C_undetermined.tsv" + + | pos | ref_allele | alt_allele | ref_count | alt_count | lineage_path | reason | + |---|---|---|---|---|---|---| + | 2105 | G | C | 0 | 0 | L4;L4.9 | not_found | + + No read of `sample_C` covers 2105, so the marker is listed here instead of + being called absent. The undetermined tables of the other two samples hold + only their header. + +=== "reads_summary.tsv" + + | genome | lineage:count | major_lineage | undetermined | undetermined:count | + |---|---|---|---|---| + | sample_A | L2:2 L2;L2.2:1 | L2 | 0 | | + | sample_B | L4:2 L4;L4.9:1 | L4 | 0 | | + | sample_C | L4:1 | L4 | 1 | L4:1 | + + The same calls as `classify`, with one L4.9 marker fewer for `sample_B` + and one undetermined marker fewer for `sample_C`: the deletion is not in + the FASTQ panel. + +### From real runs + +Excerpts of a real run of two samples against the resistance panel. Both carry +the same rifampicin variant; in the second, another change seven bases away +hides both of its k-mers, and the marker is read from its left anchor instead. + +=== "Mutations" + + ```text + pos ref_allele alt_allele ref_count alt_count alt_fraction lineage_path evidence extra_annotations... + 761155 C T 0 119 100.00 RIF;RIF-R;rpoB_S450L;1) Assoc w R;rpoB;S450L kmer + ``` + + ```text + pos ref_allele alt_allele ref_count alt_count alt_fraction lineage_path evidence extra_annotations... + 761155 C T 0 112 100.00 RIF;RIF-R;rpoB_S450L;1) Assoc w R;rpoB;S450L left_anchor + ``` + + The header always ends in `extra_annotations...`; the cells only appear + when the panel has annotation columns after an empty separator, which the + WHO-shaped panel does not. + +=== "Undetermined" + + ```text + pos ref_allele alt_allele ref_count alt_count lineage_path reason + 759545 TA CG 0 0 RIF;RIF-R;rpoB_c.-261A>G;5) Not assoc w R;rpoB;c.-261A>G not_found + 759546 A G 0 0 RIF;RIF-R;rpoB_c.-261A>G;5) Not assoc w R;rpoB;c.-261A>G not_found + ``` + + These reads cover a single region, so most of the panel is listed here as + `not_found`: nothing read it. A whole-genome run lists only the markers + something actually hid. + +=== "Summary" + + ```text + genome lineage:count major_lineage undetermined undetermined:count + variant_and_neighbour RIF:1 Resistant: RIF 87049 EMB:13401 OTHER:11171 RIF:9525 INH:9014 … + variant_only RIF:1 Resistant: RIF 87059 EMB:13401 OTHER:11171 RIF:9535 INH:9014 … + ``` + !!! warning "No indels in FASTQ mode" `split-fastq` calls SNPs/MNVs only. Insertions and deletions are detected reliably via the assembly-based [`classify`](classify.md) workflow. @@ -288,20 +546,40 @@ Finds the single best-matching reference for a set of FASTQ reads. All input rea | `` | when `-o` is given (otherwise printed to **stdout**) | Best-match report. | | `` | with `--excel` **and** `-o` | Excel copy. | -**Header:** `Query_Files Best_Match_Reference Shared_Kmer_Fraction` +**Header:** `Query_Files Best_Match_Reference Shared_Kmer_Fraction Query_Kmers` | Column | Description | |---|---| | `Query_Files` | Comma-separated list of all input FASTQ paths that were pooled into the query. | | `Best_Match_Reference` | Header of the top-scoring reference genome. | | `Shared_Kmer_Fraction` | Weighted k-mer containment score, `0`–`1` (4 decimals). | +| `Query_Kmers` | The denominator: k-mer occurrences kept from the query after `--min-kmer-count`. | + +On the [example dataset](input-formats.md#example-dataset), +`pathotypr match -i reads/sample_B.fastq -r references.fasta -o match.tsv` +writes: + +| Query_Files | Best_Match_Reference | Shared_Kmer_Fraction | Query_Kmers | +|---|---|---|---| +| reads/sample_B.fastq | ref_L4 invented L4 representative | 0.9677 | 83930 | + +The 1,199 reads of `sample_B` are 100 bp long and give 70 k-mers each +(100 - 31 + 1), 83,930 in all; 96.77% of them occur in `ref_L4`, and the rest +cover the changes `sample_B` has and `ref_L4` does not. `ref_L1` and `ref_L2` +scored 0.7198 and 0.7205, and are not reported. `Best_Match_Reference` is the +whole header line. ```text -Query_Files Best_Match_Reference Shared_Kmer_Fraction -reads_R1.fastq.gz,reads_R2.fastq.gz NC_000962.3 H37Rv 0.9873 +Query_Files Best_Match_Reference Shared_Kmer_Fraction Query_Kmers +sample_reads.fastq reference_A 0.8886 101500 ``` -!!! note "No match, no data row" +A real run: 1,450 reads at 0.15x against two references 250 SNPs apart. The +score is the share of the query's 101,500 k-mer occurrences that `reference_A` +contains; `reference_B` scored 0.8812 and is not reported, since only the best +match is. A whole genome gives far more, since every read of length L adds L - 30 of them with k = 31: about 35 million at 10x with 150 bp reads, and 106 million at 30x. + +!!! note "No shared k-mers still gives a row" If no reference shares any k-mers with the query, the first reference is still reported with a `Shared_Kmer_Fraction` of `0.0000` — read a near-zero score as "no usable match". Only an empty reference FASTA yields a header-only report. Because the Excel writer needs the resolved output path, `--excel` produces a file **only when `-o` is also set** — with stdout output, no `.xlsx` is created. See also: [Reference matching](algorithms/reference-matching.md). diff --git a/docs/predict.md b/docs/predict.md index 49ba672..095d7fc 100644 --- a/docs/predict.md +++ b/docs/predict.md @@ -22,7 +22,7 @@ pathotypr predict -i -m -o ### Requirements - [x] The model must be a **current-format bundle**. An incompatible format version is a hard error and the model has to be retrained. A bundle written by a different pathotypr version only warns. -- [x] Records **shorter than the model's k** are skipped with a warning: no k-mer can be extracted from them. +- [x] Records that yield **no k-mer**, because they are shorter than the model's k or carry no long enough window of A, C, G and T, are reported as `Undetermined` with `Kmers_Used` zero rather than dropped. - [x] No labels are needed or read. The **full header** is carried through to the output. !!! warning "The model dictates k, not you" @@ -31,10 +31,12 @@ pathotypr predict -i -m -o `k=21`. This is also why the minimum usable sequence length depends on the model rather than on the query file. -!!! info "Every record gets a call" - There is no "unknown" class and no confidence threshold. A query from a - lineage absent from the training set still receives the closest label the - forest can find, distinguishable only by a **low confidence and margin**. +!!! info "Any record with k-mers gets a call" + A record that yields no k-mer is `Undetermined`. Every other record gets a + label, because there is no "unknown" class and no confidence threshold: a + query from a lineage absent from the training set still receives the closest + label the forest can find, distinguishable only by a **low confidence and + margin**, and by `Kmers_Used` when it rests on very few k-mers. Read those two columns before acting on a call: see [Output](#predictionstsv-always-written) for what they mean. @@ -70,7 +72,7 @@ These are available on every `pathotypr` subcommand: 6. **Score** each record with a confidence and a confidence margin, then write results immediately and free the batch. !!! warning "Short sequences are skipped" - Any record shorter than the model's k-mer length yields no k-mers and is skipped with a warning; it will not appear in the output. If every record is skipped or the file is empty, the command exits with an error and removes the partial output. + A record that yields no k-mer is reported as `Undetermined` with `Kmers_Used` zero, and the run says at the end how many came out that way. It is not dropped: a sample missing from the output is a sample nobody notices is missing. This covers records shorter than the model's k and, less obviously, N-masked consensus sequences, which are long but hold no window of A, C, G and T: one `N` destroys every k-mer overlapping it, so at k=21 an `N` every twenty bases leaves nothing to read. Those used to come out with an ordinary-looking lineage and confidence, because a tree sends a missing feature down the same branch every time and all the trees then agree. Only a file with no records at all is an error. ## Examples @@ -117,17 +119,19 @@ A tab-separated file with a header row and one row per classified record. Column | Column | Description | |---|---| | `Header` | The input record's full FASTA header line — everything after `>`, description included. | -| `Predicted_Lineage` | Majority-vote lineage label. A record on which no tree cast a usable vote still gets a label, but with a `Confidence` at or near zero — read low confidence, not a special value, as "unresolved". | +| `Predicted_Lineage` | Majority-vote lineage label, or `Undetermined` when the record yielded no k-mer and the model therefore said nothing about it. A tie between two lineages is settled by the label, so the answer does not depend on the order the training FASTA happened to be in. | | `Confidence` | Fraction of trees voting for the winning lineage, in `0.0000`–`1.0000` (4 decimals). | | `Confidence_Margin` | Winner-minus-runner-up vote fraction, in `0.0000`–`1.0000` (4 decimals). | | `Other_Votes` | Up to the three next-best lineages as `label:fraction` (2 decimals), comma-separated. Empty when there are no alternatives. | +| `Kmers_Used` | How many k-mers the record yielded. Zero is what `Undetermined` rests on, and a handful tells you a call rests on almost nothing, which no confidence figure shows: every tree walks the same branch when a feature is missing, so they agree, and the agreement reads as confidence. | Example: ```text -Header Predicted_Lineage Confidence Confidence_Margin Other_Votes -sample_001 L4 0.9600 0.9300 L2:0.03,L1:0.01 -sample_002 L2 0.5400 0.0800 L4:0.46 +Header Predicted_Lineage Confidence Confidence_Margin Other_Votes Kmers_Used +sample_001 L4 0.9600 0.9300 L2:0.03,L1:0.01 4411512 +sample_002 L2 0.5400 0.0800 L4:0.46 4398877 +masked_003 Undetermined 0 ``` ### `predictions.xlsx` (only with `--excel`) diff --git a/docs/split-fastq.md b/docs/split-fastq.md index 1ae1f9c..b811134 100644 --- a/docs/split-fastq.md +++ b/docs/split-fastq.md @@ -21,7 +21,7 @@ You must supply markers (`-m`), a reference (`-r`), and exactly one input source |---|---|---| | Marker panel | `-m, --markers` | [Marker TSV](marker_format.md), tab-separated | | Reference genome | `-r, --reference` | **Single-record** FASTA the marker positions are numbered against | -| Reads | `-i, --input` or `-l, --input-list` | FASTQ, plain or gzipped | +| Reads | `-i, --input` or `-l, --input-list` | FASTQ, plain or gzipped; a FASTA is read too, wrapped or not, and its sample name keeps the `.fasta` ending | `-i` takes one or more files that together form **one** sample. `-l` takes a [sample list](input-formats.md#sample-list-tsv-split-fastq-and-match-input-list) @@ -107,6 +107,7 @@ The marker database is built once and cached in memory, then reused for every sa | Option | Default | Required | Description | |---|---|---|---| +| `--no-anchor-rescue` | `false` | no | Skip the second pass that reads a marker's locus from its anchors when its k-mers could not. Faster, and those markers are then reported as not determined. | | `-o, --output-prefix ` | `split` | no | Prefix for output files. | | `--excel` | `false` | no | Also write Excel (`.xlsx`) files. | | `-t, --threads ` | all cores | no | Number of CPU threads. | @@ -197,17 +198,25 @@ matched, so only anchors that occur **exactly once** in the reference are used, counting both strands. A marker left with no unique anchor is reported as `no_unique_anchor` rather than guessed at. +For the same reason a marker whose ALT k-mer the reference already carries, or +whose window it carries twice, is never settled on read counts at all: reads +from the other copy count towards it just as well. Five and sixty-seven markers +of the WHO catalogue are in that position, and only their anchors can speak for +them. + !!! example "rpoB S450L behind a neighbour" A sample carrying S450L and a synonymous change seven bases away matches - neither k-mer of the marker: 112 reads cover the position and say the - variant is there, and the k-mers see none of it. The left anchor sits clear - of the neighbour, reads those 112 reads, and the marker is called with - `evidence` = `left_anchor`. + neither k-mer of the marker: 124 reads cover the position, every one of them + showing the variant, and the k-mers see none of it. The left anchor sits + clear of the neighbour, the 112 reads that carry it whole are read, and the + marker is called with `evidence` = `left_anchor`. This costs a second pass over the reads, which `--no-anchor-rescue` turns off. -On a 6x whole-genome read set the run took 1.6 times as long with the pass as -without it, and the pass resolved 15 of the 190 markers the k-mers had left -unread. +On a 6x whole-genome read set made from H37Rv itself, the run took about 1.5 +times as long with the pass, called nothing in either case, and settled all 72 +markers whose words the reference duplicates, which no read count can settle: +262 markers were left unread without the pass and 190 with it, all of those at +the edge of the reads' coverage. ## Output @@ -252,6 +261,8 @@ not answer, with the same columns as the mutations table plus a `reason`. | `low_depth` | The locus was read, by fewer than `--min-depth` reads. | | `no_unique_anchor` | The k-mers matched nothing and every anchor of the marker occurs more than once in the reference, so none of them can say which copy a read came from. | | `anchors_disagree` | The two anchors were both read deeply enough and they do not agree, so neither is believed. | +| `alt_kmer_in_reference` | The reference itself carries this marker's ALT k-mer, so reads matching it say nothing about this locus, and its anchors could not settle it either. | +| `ref_kmer_repeated` | The reference carries this marker's window more than once, so reads matching it may come from the other copy. | The counts in the row are the ones the decision rests on: the k-mer counts when the anchors were not consulted, and the counts from the anchor that answered diff --git a/docs/train.md b/docs/train.md index ec2cd50..1d3d697 100644 --- a/docs/train.md +++ b/docs/train.md @@ -32,7 +32,7 @@ ACGTACGT... → label = "L4.3.4.2" The run **fails** unless all of these hold: - [x] At least **two distinct labels**. One class cannot be trained against nothing. -- [x] At least **two records**, so the train/test split leaves a non-empty training set. With `--test-split 0` a single record is accepted, but the accuracy estimate is then meaningless. +- [x] At least **two records**, so the train/test split leaves a non-empty training set. With `--test-split 0` nothing is held out, and the run reports the accuracy as not evaluated rather than as 0%. - [x] `-k` between **1 and 31**. These are tolerated, with a warning in the log: @@ -65,7 +65,7 @@ These are tolerated, with a warning in the log: | `-t, --threads ` | all cores | no | Number of CPU threads. | | `--cv-folds ` | off | no | Use stratified k-fold cross-validation for accuracy instead of a single split. The final model is always trained on ALL data. | | `--max-depth ` | `20` | no | Maximum tree depth. Lower reduces overfitting on small datasets. | -| `--min-samples-leaf ` | `5` | no | Minimum samples per leaf; higher acts as regularization. | +| `--min-samples-leaf ` | `1` | no | Minimum samples per leaf. A node of `2N` samples or fewer is never split, so a high value keeps the trees too shallow to separate lineages with few genomes, and on a very small panel leaves every tree a single leaf; the run says when trees end up as a single leaf. | ### Global flags @@ -147,8 +147,8 @@ Available on every subcommand: | File | Content | |---|---| | `model.pathotypr.zst` | The trained model bundle: config (pathotypr version, k-mer size, tree count, format version), feature hasher, label encoder, and all 100 trees — serialized with bincode and zstd-compressed (level 3). This is the file you pass to [`pathotypr predict`](predict.md). | -| `model.pathotypr.importance.tsv` | The top 500 most-used feature-hash buckets across the ensemble, with the k-mers that map to each. | -| `model.pathotypr.importance.coords.tsv` | Per-occurrence genomic coordinates of the discriminant k-mers behind those top buckets. | +| `model.pathotypr.importance.tsv` | The top 500 most-used feature buckets across the ensemble, with every k-mer that falls in each. A bucket holds every k-mer sharing its last ten bases, so the list is a set of candidates, not the k-mer a split used; see [feature hashing](algorithms/feature-hashing.md#what-the-buckets-really-are). | +| `model.pathotypr.importance.coords.tsv` | Every occurrence of those candidates in the training sequences, with the bases as they read at that coordinate on the given strand. | !!! note "Accuracy is reported to the terminal, not written to a file" The single-split (or cross-validated) accuracy and the out-of-bag accuracy are logged during the run. Per-fold accuracies print at the default verbosity; `-v` adds further debug detail. diff --git a/frontend/index.html b/frontend/index.html index d348f48..85baafa 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -424,8 +424,8 @@

Parameters

- - + +