From a2a1179a897179c068f5fab0a1fabbbb796ee8c9 Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 15:26:28 +0100
Subject: [PATCH 01/15] Stop trusting a k-mer the reference itself carries
A k-mer says what it matched, never where, and some markers of the WHO catalogue
have an alternative k-mer the reference already holds elsewhere, or a reference
window it holds twice, so they read the same in every genome whatever the sample
carries. The reference is now read once while the index is built, and those
markers are settled by an anchor unique in the reference as well as in the
genome, or reported as not determined. The app's resistance card also shows the
amino acid the sample's own codon reads when it differs from the catalogue label.
---
docs/algorithms/assembly-classification.md | 8 +-
docs/classify.md | 32 ++++-
docs/output-files.md | 5 +-
docs/split-fastq.md | 8 ++
frontend/js/dr-insights.js | 64 ++++++++-
frontend/js/visualization.js | 11 +-
frontend/styles.css | 10 ++
pathotypr-core/src/classify/markers.rs | 144 +++++++++++++++++++++
pathotypr-core/src/classify/mod.rs | 135 ++++++++++++++++++-
pathotypr-core/src/classify_split_fastq.rs | 23 +++-
pathotypr-core/src/split_kmer.rs | 84 ++++++++++++
11 files changed, 510 insertions(+), 14 deletions(-)
diff --git a/docs/algorithms/assembly-classification.md b/docs/algorithms/assembly-classification.md
index ce40398..d3d35fd 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,9 +75,11 @@ 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` |
A k-mer is an exact match, so another change anywhere in the window (a
diff --git a/docs/classify.md b/docs/classify.md
index 64c1c74..64b0916 100644
--- a/docs/classify.md
+++ b/docs/classify.md
@@ -225,6 +225,30 @@ 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
+
+Five markers of the WHO catalogue have an ALT k-mer that already sits
+elsewhere in H37Rv, two of them in PPE35, and another sixty-seven 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, `ndh c.168C>T` and `PPE35 I417V` read as present in every
+genome tested, the ancestor included.
+
+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 +259,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 +368,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/output-files.md b/docs/output-files.md
index 3f1e812..1d4d349 100644
--- a/docs/output-files.md
+++ b/docs/output-files.md
@@ -173,7 +173,7 @@ rows in a resistance panel.
| `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. |
+| `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. |
=== "Detailed"
@@ -255,7 +255,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).
diff --git a/docs/split-fastq.md b/docs/split-fastq.md
index 1ae1f9c..225f8a9 100644
--- a/docs/split-fastq.md
+++ b/docs/split-fastq.md
@@ -197,6 +197,12 @@ 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
@@ -252,6 +258,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/frontend/js/dr-insights.js b/frontend/js/dr-insights.js
index d241926..5ff56cd 100644
--- a/frontend/js/dr-insights.js
+++ b/frontend/js/dr-insights.js
@@ -120,6 +120,59 @@ function looksLikeGrade(value) {
return /^[1-5]\s*\)/.test(v) || /^unknown$/i.test(v) || /literature/i.test(v);
}
+/** Three-letter amino acid codes to one, as the translation writes them. */
+const AMINO_ACID_LETTER = {
+ ala: 'A', arg: 'R', asn: 'N', asp: 'D', cys: 'C', gln: 'Q', glu: 'E', gly: 'G',
+ his: 'H', ile: 'I', leu: 'L', lys: 'K', met: 'M', phe: 'F', pro: 'P', ser: 'S',
+ thr: 'T', trp: 'W', tyr: 'Y', val: 'V', ter: '*', stp: '*'
+};
+
+/**
+ * The protein change a string names, in one-letter codes, or null when it names
+ * something else: a nucleotide change (`c.168C>T`), a frameshift, a promoter
+ * position.
+ *
+ * Reads both the catalogue's spelling (`D435Y`) and the translation's
+ * (`Asp435Phe(GAC>TTC)`), so the two can be compared.
+ */
+export function proteinChange(text) {
+ const first = String(text || '').split(';')[0].trim();
+ if (!first) return null;
+ const one = /^([A-Z])(\d+)([A-Z*])(?:[^A-Za-z0-9].*)?$/.exec(first);
+ if (one) return { from: one[1], position: Number(one[2]), to: one[3] };
+ const three = /^([A-Za-z]{3})(\d+)([A-Za-z]{3}|\*)(?:[^A-Za-z0-9].*)?$/.exec(first);
+ if (three) {
+ const from = AMINO_ACID_LETTER[three[1].toLowerCase()];
+ const to = three[3] === '*' ? '*' : AMINO_ACID_LETTER[three[3].toLowerCase()];
+ if (from && to) return { from, position: Number(three[2]), to };
+ }
+ return null;
+}
+
+/**
+ * What a marker's label promises against what the sample's codon reads.
+ *
+ * A panel row is one base of a codon, and its label is the amino acid that base
+ * alone would give. The WHO catalogue names rpoB 435 four ways at two
+ * positions, so a sample with two changes in that codon fires a row labelled
+ * D435Y while its codon reads TTC, which is Phe. The row is not wrong: the
+ * label says which catalogue entry matched and the translation says what the
+ * sample has. Shown as one line, though, the label is read as the sample's
+ * change, so where they disagree the sample's reading leads and the label is
+ * named as what it is.
+ */
+export function describeChange(mutation, aaChange) {
+ const label = String(mutation || '').trim();
+ const sample = proteinChange(aaChange);
+ const promised = proteinChange(label);
+ if (!sample || !promised) return { text: label || String(aaChange || '').trim(), label: '' };
+ if (sample.position !== promised.position || sample.to === promised.to) {
+ return { text: label, label: '' };
+ }
+ const read = String(aaChange || '').split(';')[0].trim();
+ return { text: read, label };
+}
+
/**
* Parse one marker's `lineage_path` into its resistance components.
*
@@ -320,8 +373,11 @@ export function buildDrProfile(records) {
if (!byDrug.has(parsed.drug)) {
byDrug.set(parsed.drug, { drug: parsed.drug, mutations: [] });
}
+ const described = describeChange(parsed.mutation, rec?.aaChange);
byDrug.get(parsed.drug).mutations.push({
...parsed,
+ change: described.text,
+ catalogueLabel: described.label,
altFraction: Number.isFinite(rec?.altFraction) ? rec.altFraction : null,
coverage: Number.isFinite(rec?.coverage) ? rec.coverage : null
});
@@ -569,7 +625,7 @@ export function renderDrProfileHtml(profile) {
const cards = profile.map(entry => {
const top = entry.mutations[0];
const detail = top
- ? `${escapeHtml(top.gene || top.markerName || '—')} ${escapeHtml(top.mutation || '')}`.trim()
+ ? `${escapeHtml(top.gene || top.markerName || '—')} ${escapeHtml(top.change || top.mutation || '')}`.trim()
: '';
const extra = entry.mutations.length > 1
? `+${entry.mutations.length - 1} more `
@@ -578,7 +634,11 @@ export function renderDrProfileHtml(profile) {
const rows = entry.mutations.map(m => `
${escapeHtml(m.gene || '—')}
- ${escapeHtml(m.mutation || m.markerName || '—')}
+ ${escapeHtml(m.change || m.mutation || m.markerName || '—')}${
+ m.catalogueLabel
+ ? ` (${escapeHtml(m.catalogueLabel)}) `
+ : ''
+ }
${escapeHtml(m.grade || '—')}
${formatDepth(m.coverage)}
${formatPct(m.altFraction)}
diff --git a/frontend/js/visualization.js b/frontend/js/visualization.js
index bd413bb..ddad137 100644
--- a/frontend/js/visualization.js
+++ b/frontend/js/visualization.js
@@ -1765,6 +1765,9 @@ function buildGenotypingInsightSections(data) {
const fracIdx = findHeaderIndexByTokens(headers, ['alt_fraction', 'alt_percent', 'alt_pct', 'vaf', 'allele_fraction']);
const refIdx = findHeaderIndexByTokens(headers, ['ref_count', 'reference_count', 'ref_reads']);
const altIdx = findHeaderIndexByTokens(headers, ['alt_count', 'alternate_count', 'alt_reads', 'mut_count']);
+ // The amino acid read from the sample's own codon, which a panel label built
+ // from one base of three can contradict.
+ const aaIdx = findHeaderIndexByTokens(headers, ['aa_change', 'amino_acid_change']);
// Summary tables carry no per-marker evidence, only the lineage:count cell.
if (lineageIdx === -1 && lineageCountIdx === -1) return '';
@@ -1784,7 +1787,13 @@ function buildGenotypingInsightSections(data) {
if (altFraction === null && coverage > 0 && altCount !== null) {
altFraction = (altCount / coverage) * 100;
}
- records.push({ sample, lineagePath, altFraction, coverage: coverage > 0 ? coverage : null });
+ records.push({
+ sample,
+ lineagePath,
+ altFraction,
+ coverage: coverage > 0 ? coverage : null,
+ aaChange: aaIdx !== -1 ? normalizeValue(row[aaIdx]) : ''
+ });
if (Number.isFinite(altFraction)) fractions.push(altFraction);
});
}
diff --git a/frontend/styles.css b/frontend/styles.css
index 45fb15e..7bf1694 100644
--- a/frontend/styles.css
+++ b/frontend/styles.css
@@ -6760,6 +6760,16 @@ body.track-expanded-open {
/* Markers that could be read neither way. Warning-coloured because a drug
listed here has not been shown susceptible, which is easy to miss. */
+/* The catalogue entry a marker comes from, shown beside the change the
+ sample's own codon reads when the two disagree: a row labelled D435Y on a
+ codon that reads TTC is Phe, and the label is provenance, not the sample. */
+.dr-mut-label {
+ color: var(--text-muted, #6b7280);
+ font-size: 0.85em;
+ font-weight: 400;
+ white-space: nowrap;
+}
+
.viz-dr-undetermined {
margin: 16px 0 4px;
padding: 14px 16px;
diff --git a/pathotypr-core/src/classify/markers.rs b/pathotypr-core/src/classify/markers.rs
index b9963a5..f6da44f 100644
--- a/pathotypr-core/src/classify/markers.rs
+++ b/pathotypr-core/src/classify/markers.rs
@@ -41,6 +41,17 @@ pub struct MarkerKmerEntry {
/// genome by counting bases from one anchor. See [`AnchorIndex`].
pub left_anchor: Option,
pub right_anchor: Option,
+ /// Whether the reference genome already carries this marker's alternative
+ /// k-mer somewhere. A k-mer says what it matched, never where, so one the
+ /// reference holds is found in every genome and cannot by itself mean the
+ /// marker is present.
+ pub alt_in_reference: bool,
+ /// How many times the reference carries this marker's own window. Above
+ /// one, a reference k-mer hit cannot by itself mean the locus holds the
+ /// reference allele, because the hit may be the other copy. Finding the
+ /// window as often as the reference has it does prove it: every copy was
+ /// read and every one is reference.
+ pub ref_copies: u32,
pub ref_position: usize,
pub lineage: String,
pub ref_allele_len: usize,
@@ -585,6 +596,10 @@ pub fn generate_markerkmer(
ref_kmer,
left_anchor,
right_anchor,
+ // Filled once the whole panel is built, by one pass over the
+ // reference: see mark_reference_copies.
+ alt_in_reference: false,
+ ref_copies: 0,
ref_position: pos,
lineage: marker.lineage.clone(),
ref_allele_len: ref_len,
@@ -629,6 +644,8 @@ pub fn generate_markerkmer(
}
text_index.into_values().collect()
};
+ let mut entries = entries;
+ mark_reference_copies(&mut entries, ref_seq, k);
build_index(entries, use_encoded_index, anchor_len)
}
@@ -719,6 +736,125 @@ fn build_index(mut markers: Vec, encoded: bool, anchor_len: usi
MarkerIndex { markers, alt, reference, marker_site, site_count, site_alleles, anchors }
}
+/// Records which markers have a k-mer the reference genome itself carries.
+///
+/// A marker is recognised by a word, and a word says what it matched and not
+/// where. The WHO catalogue has five markers whose alternative word already
+/// sits elsewhere in H37Rv, two of them in PPE35, so they read as present in
+/// every genome including the ancestor. Another sixty-seven have a second copy
+/// of their reference word, which reads as the reference allele while the real
+/// locus carries the variant.
+///
+/// Knowing this from the reference is what lets a k-mer hit be treated as the
+/// weak evidence it is: those markers are settled by an anchor, which does say
+/// where it matched, or reported as unread. The alternative is to trust the
+/// word and be wrong without noticing.
+fn mark_reference_copies(markers: &mut [MarkerKmerEntry], ref_seq: &str, k: usize) {
+ if k == 0 || ref_seq.len() < k {
+ return;
+ }
+ // Both orientations of every word, because a genome is scanned on both
+ // strands and a copy on the other strand misleads just as much.
+ let mut alt_of: FxHashMap, Vec> = FxHashMap::default();
+ let mut ref_of: FxHashMap, Vec> = FxHashMap::default();
+ for (id, entry) in markers.iter().enumerate() {
+ let rc = crate::classify::reverse_complement_sequence(&entry.kmer);
+ alt_of.entry(entry.kmer.clone().into_bytes()).or_default().push(id);
+ if rc != entry.kmer {
+ alt_of.entry(rc.into_bytes()).or_default().push(id);
+ }
+ if let Some(reference) = entry.ref_kmer.as_deref() {
+ let rc = crate::classify::reverse_complement_sequence(reference);
+ ref_of.entry(reference.as_bytes().to_vec()).or_default().push(id);
+ if rc != reference {
+ ref_of.entry(rc.into_bytes()).or_default().push(id);
+ }
+ }
+ }
+
+ // The anchors too. An anchor is trusted for saying *where* it matched, so
+ // one the reference carries twice is worth nothing even when a genome
+ // happens to hold it once: that single copy can be the other locus, with
+ // the real one broken by the very change the anchor exists to see past.
+ let anchor_len = k - 1;
+ let mut anchor_of: FxHashMap, Vec<(usize, bool)>> = FxHashMap::default();
+ for (id, entry) in markers.iter().enumerate() {
+ for (side, anchor) in [(true, &entry.left_anchor), (false, &entry.right_anchor)] {
+ if let Some(anchor) = anchor.as_deref() {
+ let rc = crate::classify::reverse_complement_sequence(anchor);
+ anchor_of.entry(anchor.as_bytes().to_vec()).or_default().push((id, side));
+ if rc != anchor {
+ anchor_of.entry(rc.into_bytes()).or_default().push((id, side));
+ }
+ }
+ }
+ }
+
+ let mut alt_hits = vec![0u32; markers.len()];
+ let mut ref_hits = vec![0u32; markers.len()];
+ let mut left_hits = vec![0u32; markers.len()];
+ let mut right_hits = vec![0u32; markers.len()];
+ for window in ref_seq.as_bytes().windows(k) {
+ if let Some(ids) = alt_of.get(window) {
+ for &id in ids {
+ alt_hits[id] = alt_hits[id].saturating_add(1);
+ }
+ }
+ if let Some(ids) = ref_of.get(window) {
+ for &id in ids {
+ ref_hits[id] = ref_hits[id].saturating_add(1);
+ }
+ }
+ }
+ if anchor_len > 0 && ref_seq.len() >= anchor_len {
+ for window in ref_seq.as_bytes().windows(anchor_len) {
+ if let Some(ids) = anchor_of.get(window) {
+ for &(id, left) in ids {
+ let hits = if left { &mut left_hits } else { &mut right_hits };
+ hits[id] = hits[id].saturating_add(1);
+ }
+ }
+ }
+ }
+
+ let (mut with_alt_copy, mut with_ref_copy, mut dropped_anchors) = (0usize, 0usize, 0usize);
+ for (id, entry) in markers.iter_mut().enumerate() {
+ entry.alt_in_reference = alt_hits[id] > 0;
+ entry.ref_copies = ref_hits[id];
+ if entry.left_anchor.is_some() && left_hits[id] != 1 {
+ entry.left_anchor = None;
+ dropped_anchors += 1;
+ }
+ if entry.right_anchor.is_some() && right_hits[id] != 1 {
+ entry.right_anchor = None;
+ dropped_anchors += 1;
+ }
+ if entry.alt_in_reference {
+ with_alt_copy += 1;
+ debug!(
+ "The reference already carries the alternative k-mer of the marker at position {} ({}>{}), so it will only be called from an anchor",
+ entry.ref_position, entry.ref_allele, entry.alt_allele
+ );
+ }
+ if entry.ref_copies > 1 {
+ with_ref_copy += 1;
+ debug!(
+ "The reference carries the window of the marker at position {} more than once, so a reference k-mer hit cannot rule it absent",
+ entry.ref_position
+ );
+ }
+ }
+ if dropped_anchors > 0 {
+ debug!("{} anchors occur more than once in the reference and were dropped.", dropped_anchors);
+ }
+ if with_alt_copy > 0 || with_ref_copy > 0 {
+ info!(
+ "{} markers have an alternative k-mer the reference already carries, and {} a repeated reference k-mer. Their anchors settle them, or they are reported as unread; run with -v to list them.",
+ with_alt_copy, with_ref_copy
+ );
+ }
+}
+
/// Collects the anchors of every substitution marker into their own lookups.
fn build_anchor_index(markers: &[MarkerKmerEntry], encoded: bool, anchor_len: usize) -> AnchorIndex {
let mut index = AnchorIndex {
@@ -800,6 +936,10 @@ pub struct MarkerScan {
pub matches: Vec,
/// Sites whose reference k-mer occurs, once each.
pub reference_sites: Vec,
+ /// How many times each site's reference k-mer was found. A window the
+ /// reference carries twice is proved absent by finding it twice: both
+ /// copies were read and both are reference.
+ pub site_hits: Vec,
}
/// Records what one k-mer of the genome turned out to be.
@@ -836,6 +976,10 @@ fn record_hit(
if seen_sites.insert(site) {
scan.reference_sites.push(site);
}
+ if scan.site_hits.len() <= site {
+ scan.site_hits.resize(site + 1, 0);
+ }
+ scan.site_hits[site] = scan.site_hits[site].saturating_add(1);
}
}
diff --git a/pathotypr-core/src/classify/mod.rs b/pathotypr-core/src/classify/mod.rs
index a0fc850..7795379 100644
--- a/pathotypr-core/src/classify/mod.rs
+++ b/pathotypr-core/src/classify/mod.rs
@@ -361,6 +361,11 @@ fn collect_marker_lines<'a>(
// the alternative allele of any marker there. Reading one allele of a
// site rules out the others at the same position.
let mut site_read = vec![false; marker_index.site_count()];
+ // How many times each site's reference window turned up, summed over every
+ // contig and strand. A window the reference carries twice is proved absent
+ // by finding it twice. Overlapping contigs of a draft assembly can inflate
+ // this, which only takes the marker back to being reported absent.
+ let mut site_hit_counts = vec![0u32; marker_index.site_count()];
let mut observed: HashMap = HashMap::new();
for contig_seq in &contigs {
@@ -371,6 +376,9 @@ fn collect_marker_lines<'a>(
reference_found[site] = true;
site_read[site] = true;
}
+ for (site, hits) in scan.site_hits.iter().enumerate() {
+ site_hit_counts[site] = site_hit_counts[site].saturating_add(*hits);
+ }
for m in scan.matches {
if alt_found[m.marker_id] {
continue;
@@ -452,7 +460,13 @@ fn collect_marker_lines<'a>(
AnchorRead::Conflict => "anchors_disagree",
// No anchor could read it, so fall back to what the k-mers saw.
AnchorRead::Unusable => {
- if kmer_alt && !kmer_reference {
+ if entry.alt_in_reference && kmer_alt {
+ // The reference itself carries this alternative k-mer, so
+ // finding it says nothing: every genome has it. Only an
+ // anchor could have told the real locus from the copy, and
+ // none could be read.
+ "alt_kmer_in_reference"
+ } else if kmer_alt && !kmer_reference {
match observed.get(&id) {
Some((m, alt_bases, ctx)) => {
lines.detail.push(format_marker_match(
@@ -466,6 +480,15 @@ fn collect_marker_lines<'a>(
// Both alleles turned up and nothing can say which copy
// this locus is. Reporting it present would be a guess.
"ambiguous_both_alleles"
+ } else if marker_index
+ .site_of(id)
+ .is_some_and(|site| site_read[site] && site_hit_counts[site] < entry.ref_copies)
+ {
+ // The reference holds this window more than once and the
+ // genome did not show every copy, so the hit may be the
+ // other copy and cannot rule the marker out. Showing them
+ // all does rule it out: every copy was read as reference.
+ "ref_kmer_repeated"
} else if marker_index.site_of(id).is_some_and(|site| site_read[site]) {
continue; // read as the reference allele, so absent
} else if marker_index.site_of(id).is_some() {
@@ -1634,6 +1657,116 @@ mod tests {
);
}
+ /// The WHO catalogue has five markers whose alternative k-mer H37Rv itself
+ /// carries, two of them in PPE35, so the word turns up in every genome and
+ /// the marker read as present everywhere, the ancestor included. When no
+ /// anchor can tell the real locus from the copy, the only honest answer is
+ /// that the marker was not read.
+ #[test]
+ fn an_alternative_kmer_the_reference_carries_is_not_evidence() {
+ let base = long_ref();
+ let pos = 300;
+ let alt = other_base(&base[pos - 1..pos]);
+ // A stretch holding the locus with the variant already in it, and both
+ // of the marker's anchors, copied elsewhere in the reference. The
+ // alternative k-mer is now in the reference and neither anchor is
+ // unique, so nothing can say which copy a hit came from.
+ let mut stretch = base[250..350].to_string();
+ stretch.replace_range(pos - 1 - 250..pos - 250, alt);
+ let mut reference = base.clone();
+ reference.replace_range(450..550, &stretch);
+
+ let marker = marker_at(&reference, pos, alt);
+ let k = 31;
+ let index = generate_markerkmer(std::slice::from_ref(&marker), reference.as_str(), k, 10);
+ assert!(
+ index.markers()[0].alt_in_reference,
+ "the fixture needs the copy to be in the reference"
+ );
+
+ // A genome identical to the reference: its locus carries the reference
+ // allele, so the marker is not there.
+ let ref_rc = reverse_complement_sequence(&reference);
+ let lines = analyze_genome_seq("g", &reference, &index, &None, k, &reference, &ref_rc);
+ assert!(
+ !lines.detail.iter().any(|l| l.contains("RIF;RIF-R;test")),
+ "a word the reference carries must not be read as the marker being present: {:?}",
+ lines.detail
+ );
+ assert!(
+ lines.undetermined.iter().any(|l| l.contains("alt_kmer_in_reference")),
+ "and the row must say why it could not be read: {:?}",
+ lines.undetermined
+ );
+ }
+
+ /// Sixty-seven markers of the catalogue have a second copy of their
+ /// reference window. A reference hit may be that copy, so it cannot rule
+ /// the marker out: a genome whose real locus carries the variant behind
+ /// another change used to be reported as not carrying it at all.
+ #[test]
+ fn a_repeated_reference_kmer_cannot_rule_a_marker_out() {
+ let base = long_ref();
+ let pos = 300;
+ let alt = other_base(&base[pos - 1..pos]);
+ // The window and both anchors, copied as they are: the reference word
+ // now occurs twice and no anchor is unique.
+ let mut reference = base.clone();
+ let stretch = base[250..350].to_string();
+ reference.replace_range(450..550, &stretch);
+
+ let marker = marker_at(&reference, pos, alt);
+ let k = 31;
+ let index = generate_markerkmer(std::slice::from_ref(&marker), reference.as_str(), k, 10);
+ assert_eq!(index.markers()[0].ref_copies, 2, "the fixture needs the repeated window");
+ assert!(!index.markers()[0].alt_in_reference, "but not the alternative word");
+
+ // The genome carries the variant, with a second change seven bases
+ // along that hides the alternative k-mer. The reference k-mer still
+ // matches, at the copy.
+ let mut genome = reference.clone();
+ genome.replace_range(pos - 1..pos, alt);
+ let neighbour = other_base(&base[pos + 6..pos + 7]);
+ genome.replace_range(pos + 6..pos + 7, neighbour);
+
+ let ref_rc = reverse_complement_sequence(&reference);
+ let lines = analyze_genome_seq("g", &genome, &index, &None, k, &reference, &ref_rc);
+ assert!(
+ lines.undetermined.iter().any(|l| l.contains("ref_kmer_repeated")),
+ "the copy must not be read as this locus holding the reference allele: {:?}",
+ lines.undetermined
+ );
+
+ // A genome that shows both copies as the reference has proved the
+ // marker absent: there is no third copy for it to be hiding in. This
+ // is the ordinary case, and the one that would drown the undetermined
+ // table if a repeated window were treated as unreadable by itself.
+ let lines = analyze_genome_seq("g", &reference, &index, &None, k, &reference, &ref_rc);
+ assert!(
+ lines.undetermined.is_empty(),
+ "a genome showing every copy as the reference must simply be absent: {:?}",
+ lines.undetermined
+ );
+ assert!(
+ !lines.detail.iter().any(|l| l.contains("RIF;RIF-R;test")),
+ "and nothing is called either: {:?}",
+ lines.detail
+ );
+
+ // The same with the neighbour on the other side, so each anchor in
+ // turn is the one left looking unique while the real copy is broken.
+ let mut genome = reference.clone();
+ genome.replace_range(pos - 1..pos, alt);
+ let neighbour = other_base(&base[pos - 8..pos - 7]);
+ genome.replace_range(pos - 8..pos - 7, neighbour);
+ let lines = analyze_genome_seq("g", &genome, &index, &None, k, &reference, &ref_rc);
+ assert!(
+ lines.undetermined.iter().any(|l| l.contains("ref_kmer_repeated")),
+ "nor with the neighbour on the left: {:?}",
+ lines.undetermined
+ );
+ }
+
#[test]
fn a_paralogous_alt_kmer_does_not_make_the_marker_present() {
// The marker's ALT k-mer also occurs far away, as happens in the
diff --git a/pathotypr-core/src/classify_split_fastq.rs b/pathotypr-core/src/classify_split_fastq.rs
index a39f932..21b5a6e 100644
--- a/pathotypr-core/src/classify_split_fastq.rs
+++ b/pathotypr-core/src/classify_split_fastq.rs
@@ -630,6 +630,9 @@ pub fn run(args: SplitFastqArgs) -> AppResult<()> {
.enumerate()
.filter(|(marker_id, &[ref_count, alt_count])| {
let marker = &markers[*marker_id];
+ if marker.alt_in_reference || marker.ref_repeated {
+ return true; // only an anchor can settle it, whatever the counts
+ }
ref_count + alt_count < args.min_depth
&& !window_covers(
&read_windows,
@@ -1065,7 +1068,11 @@ fn call_marker(
) -> Call {
let [reference, alternate] = kmer_counts;
let coverage = reference + alternate;
- if coverage >= min_depth {
+ // A word the reference carries twice is counted from both copies, so no
+ // depth makes it evidence about this locus. Those markers go straight to
+ // the anchors, which say where they matched.
+ let kmers_can_settle = !marker.alt_in_reference && !marker.ref_repeated;
+ if kmers_can_settle && coverage >= min_depth {
let fraction = (alternate as f32 / coverage as f32) * 100.0;
return if fraction >= min_alt_percent as f32 {
Call::Present { reference, alternate, evidence: "kmer" }
@@ -1074,11 +1081,19 @@ fn call_marker(
};
}
- if window_covers(read_windows, marker.pos, marker.pos + marker.ref_allele.len()) {
+ if kmers_can_settle
+ && window_covers(read_windows, marker.pos, marker.pos + marker.ref_allele.len())
+ {
return Call::Absent;
}
- let depth_reason = if coverage == 0 { "not_found" } else { "low_depth" };
+ let depth_reason = if !kmers_can_settle {
+ if marker.alt_in_reference { "alt_kmer_in_reference" } else { "ref_kmer_repeated" }
+ } else if coverage == 0 {
+ "not_found"
+ } else {
+ "low_depth"
+ };
let Some(anchors) = anchors else {
return Call::Unread { reference, alternate, reason: depth_reason };
};
@@ -1171,6 +1186,8 @@ mod tests {
lineages: vec!["RIF".to_string()],
alt_kmer: Vec::new(),
ref_kmer: Vec::new(),
+ alt_in_reference: false,
+ ref_repeated: false,
kmer_start: pos,
annotations: Vec::new(),
}
diff --git a/pathotypr-core/src/split_kmer.rs b/pathotypr-core/src/split_kmer.rs
index dd862c3..65c3e31 100644
--- a/pathotypr-core/src/split_kmer.rs
+++ b/pathotypr-core/src/split_kmer.rs
@@ -73,6 +73,14 @@ pub struct Marker {
pub lineages: Vec, // e.g., ["L2", "L2.2", "L2.2.1"]
pub alt_kmer: Vec,
pub ref_kmer: Vec,
+ /// Whether the reference genome already carries this marker's ALT k-mer
+ /// somewhere else. Reads from that copy count as the alternate allele, so
+ /// the counts cannot settle the marker: only an anchor can.
+ pub alt_in_reference: bool,
+ /// Whether the reference carries this marker's window more than once.
+ /// Reads from the copy count as the reference allele and drown the real
+ /// locus, so again only an anchor can settle it.
+ pub ref_repeated: bool,
/// 0-based start of the reference window both k-mers were cut from. A read
/// that matches either k-mer matches it exactly, so it reads every base of
/// `kmer_start .. kmer_start + k`.
@@ -307,6 +315,10 @@ pub fn build_markers(
alt_allele: alt_allele_str,
ref_kmer,
alt_kmer,
+ // Filled by one pass over the reference once the panel is
+ // read: see mark_reference_copies.
+ alt_in_reference: false,
+ ref_repeated: false,
kmer_start,
annotations: annotation_cols,
});
@@ -334,6 +346,8 @@ pub fn build_markers(
}
}
+ mark_reference_copies(&mut markers, &ref_seq, kmer_len);
+
info!(
" Built {} diagnostic k-mers from {} marker lines{}.",
markers.len(),
@@ -839,6 +853,74 @@ pub fn scan_fastq_anchors(
Ok(tallies)
}
+/// Records which markers have a k-mer the reference genome itself carries.
+///
+/// A k-mer says what it matched and never where, so reads from a paralogous
+/// copy count towards the wrong marker. Five markers of the WHO catalogue have
+/// an ALT k-mer that already sits elsewhere in H37Rv, two of them in PPE35, and
+/// sixty-seven have a second copy of their reference window. Marking them here
+/// is what lets the caller refuse to settle them on read counts alone and ask
+/// the anchors, which do say where they matched.
+fn mark_reference_copies(markers: &mut [Marker], ref_seq: &[u8], kmer_len: usize) {
+ if kmer_len == 0 || ref_seq.len() < kmer_len || markers.is_empty() {
+ return;
+ }
+ let mut alt_of: FxHashMap> = FxHashMap::default();
+ let mut ref_of: FxHashMap> = FxHashMap::default();
+ for (id, marker) in markers.iter().enumerate() {
+ for (word, map) in [(&marker.alt_kmer, &mut alt_of), (&marker.ref_kmer, &mut ref_of)] {
+ if let Some(hash) = hash_kmer(word) {
+ map.entry(hash).or_default().push(id);
+ }
+ if let Some(hash) = hash_reverse_complement(word) {
+ // A palindrome hashes the same both ways; recording it once
+ // keeps one occurrence from counting as two.
+ let entry = map.entry(hash).or_default();
+ if entry.last() != Some(&id) {
+ entry.push(id);
+ }
+ }
+ }
+ }
+
+ let mut alt_hits = vec![0u32; markers.len()];
+ let mut ref_hits = vec![0u32; markers.len()];
+ for (_, bitkmer, _) in ref_seq.bit_kmers(kmer_len as u8, false) {
+ if let Some(ids) = alt_of.get(&bitkmer.0) {
+ for &id in ids {
+ alt_hits[id] = alt_hits[id].saturating_add(1);
+ }
+ }
+ if let Some(ids) = ref_of.get(&bitkmer.0) {
+ for &id in ids {
+ ref_hits[id] = ref_hits[id].saturating_add(1);
+ }
+ }
+ }
+
+ let (mut with_alt_copy, mut with_ref_copy) = (0usize, 0usize);
+ for (id, marker) in markers.iter_mut().enumerate() {
+ marker.alt_in_reference = alt_hits[id] > 0;
+ marker.ref_repeated = ref_hits[id] > 1;
+ if marker.alt_in_reference {
+ with_alt_copy += 1;
+ debug!(
+ "The reference already carries the ALT k-mer of the marker at pos {} ({}>{}), so only its anchors can settle it",
+ marker.pos + 1, marker.ref_allele, marker.alt_allele
+ );
+ }
+ if marker.ref_repeated {
+ with_ref_copy += 1;
+ }
+ }
+ if with_alt_copy > 0 || with_ref_copy > 0 {
+ info!(
+ " {} markers have an ALT k-mer the reference already carries and {} a repeated reference window; read counts cannot settle those, so their anchors do.",
+ with_alt_copy, with_ref_copy
+ );
+ }
+}
+
pub fn build_marker_index(markers: &[Marker]) -> (MarkerIndex, BloomFilter) {
let mut index: MarkerIndex = FxHashMap::default();
index.reserve(markers.len().saturating_mul(4));
@@ -1184,6 +1266,8 @@ mod tests {
lineages: vec!["RIF".to_string(), "rpoB_X1Y".to_string()],
alt_kmer,
ref_kmer,
+ alt_in_reference: false,
+ ref_repeated: false,
kmer_start,
annotations: Vec::new(),
}
From 567ede5a26a321ba88f080c2f1b9ae44829820b5 Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 15:42:26 +0100
Subject: [PATCH 02/15] Say when predict and train measured nothing
A record with no usable k-mer, such as an N-masked consensus, used to get an
ordinary lineage call and confidence, and is now reported as Undetermined beside
a Kmers_Used count. Train no longer prints an unmeasured accuracy as 0.00%, deals
its cross-validation folds so none comes out empty, warns when trees never split,
and breaks vote ties by label rather than by file order. The Excel writer keeps
sample names as text, and predict's cleanup no longer deletes an earlier run's
workbook.
---
docs/output-files.md | 5 +-
docs/predict.md | 7 +-
frontend/js/visualization.js | 5 +-
galaxy/tools/pathotypr/pathotypr_predict.xml | 9 +-
pathotypr-core/src/excel.rs | 49 ++++++-
pathotypr-core/src/fasta_io.rs | 16 ++-
pathotypr-core/src/predict.rs | 144 ++++++++++++++-----
pathotypr-core/src/train.rs | 124 ++++++++++++----
pathotypr-core/tests/integration.rs | 4 +-
src-tauri/src/commands.rs | 7 +-
10 files changed, 299 insertions(+), 71 deletions(-)
diff --git a/docs/output-files.md b/docs/output-files.md
index 1d4d349..5938e2b 100644
--- a/docs/output-files.md
+++ b/docs/output-files.md
@@ -76,7 +76,7 @@ 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 |
|---|---|
@@ -85,9 +85,10 @@ Writes one predictions table to `--output`, streamed as sequences are classified
| `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. |
+| `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. |
```text
-Header Predicted_Lineage Confidence Confidence_Margin Other_Votes
+Header Predicted_Lineage Confidence Confidence_Margin Other_Votes Kmers_Used
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
```
diff --git a/docs/predict.md b/docs/predict.md
index 49ba672..4d9f3ec 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"
@@ -70,7 +70,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,10 +117,11 @@ 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:
diff --git a/frontend/js/visualization.js b/frontend/js/visualization.js
index ddad137..ad01810 100644
--- a/frontend/js/visualization.js
+++ b/frontend/js/visualization.js
@@ -7541,7 +7541,10 @@ export function renderTrainSummaryCard(toolId, report) {
const isCv = report.cv_mean_accuracy_pct != null;
const accuracyValue = isCv
? `${Number(report.cv_mean_accuracy_pct).toFixed(2)}% ± ${Number(report.cv_std_accuracy_pct || 0).toFixed(2)}%`
- : `${Number(report.accuracy_pct || 0).toFixed(2)}%`;
+ // Absent means no evaluation ran, which is not the same as zero.
+ : (report.accuracy_pct == null
+ ? 'not evaluated'
+ : `${Number(report.accuracy_pct).toFixed(2)}%`);
const accuracySub = isCv
? `${(report.cv_fold_accuracies || []).length}-fold stratified CV`
: `${report.n_test || 0} test samples`;
diff --git a/galaxy/tools/pathotypr/pathotypr_predict.xml b/galaxy/tools/pathotypr/pathotypr_predict.xml
index 164b59d..11c6305 100644
--- a/galaxy/tools/pathotypr/pathotypr_predict.xml
+++ b/galaxy/tools/pathotypr/pathotypr_predict.xml
@@ -47,10 +47,11 @@ The output has one row per input sequence:
Column Meaning
========================= ====================================================
``Header`` The FASTA header of the input sequence, unchanged
-``Predicted_Lineage`` The class the ensemble voted for
+``Predicted_Lineage`` The class the ensemble voted for, or Undetermined
``Confidence`` Fraction of trees that voted for it, 0 to 1
``Confidence_Margin`` The gap to the runner-up
``Other_Votes`` The remaining classes and their shares
+``Kmers_Used`` k-mers the sequence yielded; zero means nothing read
========================= ====================================================
**Reading the confidence**
@@ -61,6 +62,12 @@ the training set will still be assigned to the nearest class it knows, and can
do so confidently. The margin is the more useful number of the two: a high
confidence with a small margin means two classes were nearly tied.
+Read ``Kmers_Used`` beside them. A sequence that yields no k-mer, because it is
+shorter than the model's k or because it is N-masked, comes out as
+``Undetermined`` with zero there; a sequence that yields a handful gets an
+ordinary-looking confidence, because every tree sends a missing feature down the
+same branch and their agreement is what confidence measures.
+
.. class:: warningmark
A model only knows the labels it was trained on, and those come from the first
diff --git a/pathotypr-core/src/excel.rs b/pathotypr-core/src/excel.rs
index d6431eb..08239e8 100644
--- a/pathotypr-core/src/excel.rs
+++ b/pathotypr-core/src/excel.rs
@@ -39,6 +39,28 @@ pub struct ExcelStreamWriter {
next_row: u32,
/// Deferred conditional formatting rules: (col_idx, low_threshold, high_threshold).
conditional_formats: Vec<(u16, f64, f64)>,
+ /// Columns that hold a name rather than a measurement, worked out from the
+ /// header. Their cells stay text whatever they look like.
+ identifier_columns: Vec,
+}
+
+/// Whether a column holds an identifier, judged by its header.
+///
+/// A sample called `0048` parses as a number, and writing it as one turns it
+/// into `48` in the spreadsheet while the TSV keeps `0048`; `1e5` becomes
+/// `100000`. Joining the two files back together by sample then silently
+/// matches the wrong rows, which is worse than either file being wrong on its
+/// own. Measurements are left to be numbers, because that is what makes them
+/// sortable and what the conditional formatting needs.
+fn holds_identifier(header: &str) -> bool {
+ // Matched whole, not by suffix: `SNPgenome` is a coordinate, and making it
+ // text would stop it sorting.
+ const NAMES: [&str; 12] = [
+ "header", "genome", "sample", "sample_name", "sample_id", "isolate", "strain", "file",
+ "filename", "name", "id", "query",
+ ];
+ let header = header.trim().to_ascii_lowercase();
+ NAMES.contains(&header.as_str())
}
impl ExcelStreamWriter {
@@ -76,6 +98,7 @@ impl ExcelStreamWriter {
max_widths,
next_row: 1,
conditional_formats: Vec::new(),
+ identifier_columns: headers.iter().map(|header| holds_identifier(header)).collect(),
})
}
@@ -91,7 +114,9 @@ impl ExcelStreamWriter {
}
self.max_widths[col_idx] = self.max_widths[col_idx].max(cell.len());
- if let Ok(num) = cell.parse::() {
+ let identifier = self.identifier_columns.get(col_idx).copied().unwrap_or(false);
+ let number = if identifier { None } else { cell.parse::().ok() };
+ if let Some(num) = number {
worksheet.write_number_with_format(
self.next_row,
col_idx as u16,
@@ -210,3 +235,25 @@ pub fn parse_tsv_for_excel(tsv_content: &str) -> (Vec<&str>, Vec>) {
(headers, rows)
}
+
+#[cfg(test)]
+mod tests {
+ use super::holds_identifier;
+
+ /// A sample called `0048` must not become 48, and a coordinate must stay a
+ /// number: the rule is read off the header, so this pins which headers of
+ /// this tool's own tables fall on which side.
+ #[test]
+ fn identifier_columns_are_told_from_measurements() {
+ for header in ["Header", "genome", "sample", "Sample_ID", "isolate", "strain", "name", "id"] {
+ assert!(holds_identifier(header), "{header} names a sample");
+ }
+ for header in [
+ "SNPgenome", "SNPreference", "pos", "k-merPOS", "AA_Pos", "Gene_Start", "Gene_End",
+ "ref_count", "alt_count", "alt_fraction", "Confidence", "Kmers_Used", "lineage",
+ "major_lineage", "undetermined", "evidence", "reason",
+ ] {
+ assert!(!holds_identifier(header), "{header} is not a sample name");
+ }
+ }
+}
diff --git a/pathotypr-core/src/fasta_io.rs b/pathotypr-core/src/fasta_io.rs
index 8833b1e..922b265 100644
--- a/pathotypr-core/src/fasta_io.rs
+++ b/pathotypr-core/src/fasta_io.rs
@@ -65,6 +65,7 @@ pub fn read_fasta(path: &str) -> AppResult<(Vec, Vec, Vec AppResult<(Vec, Vec, Vec AppResult<(Vec, Vec, Vec 0 {
+ info!(
+ " Read {} sequences from {} ({} entries skipped for having no sequence)",
+ sequences.len(),
+ path,
+ skipped
+ );
+ } else {
+ info!(" Read {} sequences from {}", sequences.len(), path);
+ }
Ok((sequences, lineages, headers))
}
diff --git a/pathotypr-core/src/predict.rs b/pathotypr-core/src/predict.rs
index 8200da9..2de819f 100644
--- a/pathotypr-core/src/predict.rs
+++ b/pathotypr-core/src/predict.rs
@@ -15,7 +15,7 @@ use crate::errors::{
};
use clap::Parser;
use indicatif::{ProgressBar, ProgressStyle};
-use log::{info, warn};
+use log::{debug, info, warn};
use rayon::prelude::*;
use std::fs::File;
use std::io::{BufWriter, Read, Write};
@@ -82,6 +82,13 @@ pub fn load_model_bundle(path: &str) -> AppResult {
Ok(bundle)
}
+/// Removes the files this run created, and only those.
+///
+/// It used to also remove the .xlsx derived from the output name, whether or
+/// not `--excel` was given. The Excel writer only touches the disk inside
+/// `finish()`, so no partial .xlsx can exist to clean up, and every file that
+/// derivation could delete was one an earlier run had left: `predict -o run.tsv`
+/// over a bad FASTA deleted yesterday's `run.xlsx`.
fn cleanup_generated_outputs(paths: &[String]) {
for out_path in paths {
match std::fs::remove_file(out_path) {
@@ -89,32 +96,61 @@ fn cleanup_generated_outputs(paths: &[String]) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => warn!("Failed to remove partial output {}: {}", out_path, e),
}
+ }
+}
- // Must match the writer's derivation exactly, or cleanup deletes the
- // wrong file and leaves the real partial .xlsx behind.
- let xlsx_path = crate::excel::excel_path_from_tsv(out_path);
- match std::fs::remove_file(&xlsx_path) {
- Ok(_) => {}
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
- Err(e) => warn!(
- "Failed to remove partial output {}: {}",
- xlsx_path,
- e
- ),
+/// What the model says about one record, or that it could not say anything.
+///
+/// A record with no usable k-mer is not a weak prediction, it is no
+/// prediction: every tree walks the "feature absent" branch of every split and
+/// the ensemble agrees on whatever that path leads to. An N-masked consensus,
+/// the ordinary product of a reference-based pipeline, used to come out with
+/// the same lineage and the same confidence as a real genome.
+struct Prediction {
+ label: String,
+ confidence: f32,
+ margin: f32,
+ others: String,
+ /// k-mers the record yielded. Zero means nothing was read: too short for
+ /// k, or no window of A, C, G and T long enough to encode.
+ kmers: u64,
+}
+
+impl Prediction {
+ /// The row for a record the model cannot speak about.
+ fn undetermined() -> Self {
+ Self {
+ label: "Undetermined".to_string(),
+ confidence: f32::NAN,
+ margin: f32::NAN,
+ others: String::new(),
+ kmers: 0,
+ }
+ }
+
+ /// Confidence and margin as written out: empty for an undetermined row,
+ /// because 0.0000 there reads as a measured zero.
+ fn figures(&self) -> (String, String) {
+ if self.kmers == 0 {
+ (String::new(), String::new())
+ } else {
+ (format!("{:.4}", self.confidence), format!("{:.4}", self.margin))
}
}
}
/// Predict a single sparse row against the tree ensemble.
-///
-/// Returns `(predicted_label, confidence, margin, other_votes_str)`.
fn predict_one_record(
sparse_row: &[(usize, f32)],
trees: &[crate::sparse_tree::SparseDecisionTree],
int_to_label: &[String],
n_classes: usize,
total_trees: f32,
-) -> (String, f32, f32, String) {
+) -> Prediction {
+ if sparse_row.is_empty() {
+ return Prediction::undetermined();
+ }
+ let kmers = sparse_row.iter().map(|&(_, count)| count as f64).sum::() as u64;
let mut vote_counts = vec![0u16; n_classes];
for tree in trees {
let pred = tree.predict_one(sparse_row);
@@ -123,8 +159,22 @@ fn predict_one_record(
}
}
- if let Some((best_class_idx, &winner_vote_count)) =
- vote_counts.iter().enumerate().max_by_key(|(_, count)| *count)
+ // `max_by_key` keeps the last of equal keys, and class indices follow the
+ // order labels first appear in the training FASTA, so a tie used to be
+ // broken by where a record sat in that file. The label decides instead, so
+ // the same votes give the same answer whatever the file order was.
+ if let Some((best_class_idx, &winner_vote_count)) = vote_counts
+ .iter()
+ .enumerate()
+ .max_by(|(left, a), (right, b)| {
+ a.cmp(b).then_with(|| {
+ int_to_label
+ .get(*right)
+ .map(String::as_str)
+ .unwrap_or("")
+ .cmp(int_to_label.get(*left).map(String::as_str).unwrap_or(""))
+ })
+ })
{
let mut second_vote_count = 0u16;
for (class_idx, &vote_count) in vote_counts.iter().enumerate() {
@@ -180,9 +230,10 @@ fn predict_one_record(
.collect::>()
.join(",");
- (predicted_label, confidence, margin, other_votes_str)
+ Prediction { label: predicted_label, confidence, margin, others: other_votes_str, kmers }
} else {
- ("Unknown".to_string(), 0.0, 0.0, String::new())
+ // No classes at all, which `load_model_bundle` already refuses.
+ Prediction::undetermined()
}
}
@@ -227,14 +278,19 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
let kmer_size = bundle.config.kmer_size;
// --- Open output files before streaming ---
- let generated_outputs = vec![args.output.clone()];
+ let mut generated_outputs = vec![args.output.clone()];
+ if args.excel {
+ // Written at the end of the run, so cleanup only finds it when this
+ // run got that far.
+ generated_outputs.push(crate::excel::excel_path_from_tsv(&args.output));
+ }
let mut output_file = match File::create(&args.output) {
Ok(f) => BufWriter::new(f),
Err(e) => return Err(AppError::Io(e)),
};
if let Err(e) = writeln!(
output_file,
- "Header\tPredicted_Lineage\tConfidence\tConfidence_Margin\tOther_Votes"
+ "Header\tPredicted_Lineage\tConfidence\tConfidence_Margin\tOther_Votes\tKmers_Used"
) {
drop(output_file);
cleanup_generated_outputs(&generated_outputs);
@@ -247,6 +303,7 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
"Confidence",
"Confidence_Margin",
"Other_Votes",
+ "Kmers_Used",
];
let mut excel_writer = if args.excel {
match crate::common::ExcelStreamWriter::new(&args.output, &excel_headers) {
@@ -294,6 +351,9 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
let cancellation = ParallelCancellation::new(cancel_token);
let mut total_predicted = 0u64;
let mut found_any = false;
+ // Records the model could say nothing about, counted so the run can say so
+ // rather than leaving them to look like ordinary calls.
+ let mut undetermined_records = 0usize;
let mut batch: Vec<(String, String)> = Vec::with_capacity(PREDICT_BATCH_SIZE);
loop {
@@ -319,14 +379,17 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
)));
}
};
+ // A record too short for k, or one made of Ns, yields no
+ // k-mer. It is kept and reported as undetermined rather
+ // than dropped: a sample missing from the output is a
+ // sample nobody notices is missing.
if seq.len() < kmer_size {
- warn!(
- "Skipping entry shorter than k={} ({} bp), no k-mer can be extracted: {}",
- kmer_size,
+ debug!(
+ "No k-mer can be cut from {} ({} bp, k={}); it will be reported as undetermined",
+ header,
seq.len(),
- header
+ kmer_size
);
- continue;
}
batch.push((header, seq));
if batch.len() >= PREDICT_BATCH_SIZE {
@@ -355,11 +418,11 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
let trees = &bundle.trees;
let int_to_label = &bundle.label_encoder.int_to_label;
- let batch_predictions: Vec<(String, f32, f32, String)> = x_sparse
+ let batch_predictions: Vec = x_sparse
.par_iter()
.map(|sparse_row| {
if cancellation.is_cancelled() {
- return (String::new(), 0.0, 0.0, String::new());
+ return Prediction::undetermined();
}
predict_one_record(sparse_row, trees, int_to_label, n_classes, total_trees)
})
@@ -372,11 +435,15 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
// Write batch results immediately
for (i, (header, _)) in batch.iter().enumerate() {
- let (ref pred, conf, margin, ref others) = batch_predictions[i];
+ let prediction = &batch_predictions[i];
+ if prediction.kmers == 0 {
+ undetermined_records += 1;
+ }
+ let (confidence, margin) = prediction.figures();
if let Err(e) = writeln!(
output_file,
- "{}\t{}\t{:.4}\t{:.4}\t{}",
- header, pred, conf, margin, others
+ "{}\t{}\t{}\t{}\t{}\t{}",
+ header, prediction.label, confidence, margin, prediction.others, prediction.kmers
) {
drop(output_file);
cleanup_generated_outputs(&generated_outputs);
@@ -385,10 +452,11 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
let row = vec![
header.clone(),
- pred.clone(),
- format!("{:.4}", conf),
- format!("{:.4}", margin),
- others.clone(),
+ prediction.label.clone(),
+ confidence.clone(),
+ margin.clone(),
+ prediction.others.clone(),
+ prediction.kmers.to_string(),
];
let mut disable_excel = false;
if let Some(writer) = excel_writer.as_mut() {
@@ -416,6 +484,12 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
"No records found in the input FASTA file.".to_string(),
));
}
+ if undetermined_records > 0 {
+ warn!(
+ "⚠️ {} record(s) yielded no k-mer at k={} and are reported as Undetermined: too short, or without a long enough window of A, C, G and T. An N-masked consensus reads this way.",
+ undetermined_records, kmer_size
+ );
+ }
if let Err(e) = output_file.flush() {
drop(output_file);
diff --git a/pathotypr-core/src/train.rs b/pathotypr-core/src/train.rs
index 68ccfa5..931dc2e 100644
--- a/pathotypr-core/src/train.rs
+++ b/pathotypr-core/src/train.rs
@@ -34,9 +34,34 @@ const N_TREES: u16 = 100;
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Structured report returned after a successful training run.
+/// The class with the most votes, ties broken by label rather than by index.
+///
+/// `max_by_key` keeps the last of equal keys and class indices follow the order
+/// labels first appear in the training FASTA, so a tie used to be settled by
+/// where a record sat in that file: reordering the input changed the call.
+fn most_voted(votes: &[C], class_names: &[String]) -> usize {
+ votes
+ .iter()
+ .enumerate()
+ .max_by(|(left, a), (right, b)| {
+ a.cmp(b).then_with(|| {
+ class_names
+ .get(*right)
+ .map(String::as_str)
+ .unwrap_or("")
+ .cmp(class_names.get(*left).map(String::as_str).unwrap_or(""))
+ })
+ })
+ .map(|(class, _)| class)
+ .unwrap_or(0)
+}
+
#[derive(Debug, Clone, Serialize)]
pub struct TrainReport {
- pub accuracy_pct: f64,
+ /// None when no evaluation ran: an empty test set, or every CV fold
+ /// skipped. Zero would read as a measurement.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub accuracy_pct: Option,
pub n_training: usize,
pub n_test: usize,
pub n_classes: usize,
@@ -324,6 +349,7 @@ fn compute_oob_accuracy(
sample_indices: &[usize],
num_classes: usize,
tree_seeds: &[u64],
+ class_names: &[String],
) -> Option {
let n_samples = sample_indices.len();
if n_samples == 0 || trees.is_empty() {
@@ -363,12 +389,7 @@ fn compute_oob_accuracy(
if oob_count[local_idx] == 0 {
continue; // sample was in every bootstrap (very unlikely with 100 trees)
}
- let predicted = oob_votes[local_idx]
- .iter()
- .enumerate()
- .max_by_key(|(_, &c)| c)
- .map(|(cls, _)| cls)
- .unwrap_or(0);
+ let predicted = most_voted(&oob_votes[local_idx], class_names);
if predicted == y_data[sample_indices[local_idx]] {
correct += 1;
}
@@ -388,6 +409,7 @@ fn evaluate_ensemble(
y_data: &[usize],
test_indices: &[usize],
num_classes: usize,
+ class_names: &[String],
) -> f64 {
if test_indices.is_empty() {
return 0.0;
@@ -402,12 +424,7 @@ fn evaluate_ensemble(
vote_counts[pred] += 1;
}
}
- let best_class = vote_counts
- .iter()
- .enumerate()
- .max_by_key(|(_, &c)| c)
- .map(|(idx, _)| idx)
- .unwrap_or(0);
+ let best_class = most_voted(&vote_counts, class_names);
if best_class == y_data[idx] {
correct += 1;
}
@@ -430,6 +447,7 @@ fn stratified_cv(
max_depth: usize,
min_samples_leaf: usize,
cancel_token: &Option,
+ class_names: &[String],
) -> AppResult> {
let n = x_data.len();
@@ -441,13 +459,24 @@ fn stratified_cv(
}
}
- // Shuffle within each class for randomness, then distribute into folds round-robin
+ // Shuffle within each class, then deal into folds round-robin with a
+ // cursor that carries across classes.
+ //
+ // Restarting at fold 0 for every class is what stratified folds are
+ // usually written as, and it is wrong whenever a class is smaller than k:
+ // fold j only ever receives a member of a class with more than j members,
+ // so with 20 lineages of 3 genomes and --cv-folds 10 the folds hold
+ // 20, 20, 20 and then seven empty ones. The empty folds were skipped with
+ // a warning while the summary still said "10-fold", and each of the three
+ // that ran held out a third of the data instead of a tenth.
let mut rng = SmallRng::seed_from_u64(42);
let mut fold_assignments = vec![0usize; n];
+ let mut cursor = 0usize;
for class_group in &mut class_indices {
class_group.shuffle(&mut rng);
- for (i, &idx) in class_group.iter().enumerate() {
- fold_assignments[idx] = i % k;
+ for &idx in class_group.iter() {
+ fold_assignments[idx] = cursor % k;
+ cursor += 1;
}
}
@@ -472,7 +501,7 @@ fn stratified_cv(
cancel_token, false,
)?;
- let acc = evaluate_ensemble(&trees, x_data, y_data, &test_idx, num_classes);
+ let acc = evaluate_ensemble(&trees, x_data, y_data, &test_idx, num_classes, class_names);
info!(" Fold {} accuracy: {:.2}% (train={}, test={})", fold + 1, acc, train_idx.len(), test_idx.len());
fold_accuracies.push(acc);
}
@@ -523,7 +552,10 @@ pub fn run(args: Args) -> AppResult {
let n_total = x_data_sparse.len();
// --- Accuracy estimation: CV or single split ---
- let mut accuracy_pct = 0.0_f64;
+ // None until something is actually evaluated. It used to start at 0.0 and
+ // stay there when the test set was empty, so a successful run reported
+ // "Accuracy: 0.00%", which reads as a measurement.
+ let mut accuracy_pct: Option = None;
let n_training;
let n_test;
let mut cv_fold_accuracies: Vec = Vec::new();
@@ -543,7 +575,7 @@ pub fn run(args: Args) -> AppResult {
&x_data_sparse, &y_data, k,
n_features, num_classes, N_TREES,
args.max_depth, args.min_samples_leaf,
- cancel_token,
+ cancel_token, &label_encoder.int_to_label,
)?;
if !fold_accs.is_empty() {
@@ -554,7 +586,7 @@ pub fn run(args: Args) -> AppResult {
let std_dev = variance.sqrt();
info!(" ✅ {}-fold CV accuracy: {:.2}% ± {:.2}%", k, mean, std_dev);
- accuracy_pct = mean;
+ accuracy_pct = Some(mean);
cv_mean_accuracy_pct = Some(mean);
cv_std_accuracy_pct = Some(std_dev);
cv_fold_accuracies = fold_accs;
@@ -591,10 +623,31 @@ pub fn run(args: Args) -> AppResult {
args.max_depth, args.min_samples_leaf,
cancel_token, false,
)?;
- accuracy_pct = evaluate_ensemble(&eval_trees, &x_data_sparse, &y_data, &test_indices.to_vec(), num_classes);
- info!(" ✅ Test Set Accuracy: {:.2}%", accuracy_pct);
+ let measured = evaluate_ensemble(
+ &eval_trees,
+ &x_data_sparse,
+ &y_data,
+ &test_indices.to_vec(),
+ num_classes,
+ &label_encoder.int_to_label,
+ );
+ accuracy_pct = Some(measured);
+ info!(" ✅ Test Set Accuracy: {:.2}%", measured);
+ // The split is a plain shuffle, so a lineage with few genomes can
+ // land entirely on one side. An accuracy that covers four of six
+ // lineages is not an accuracy for the panel.
+ let covered: std::collections::HashSet =
+ test_indices.iter().map(|&i| y_data[i]).collect();
+ if covered.len() < num_classes {
+ warn!(
+ " ⚠️ The test set covers {} of {} lineages, so that accuracy says nothing about the other {}. Use --cv-folds for a figure that covers every lineage, or read the out-of-bag accuracy below.",
+ covered.len(),
+ num_classes,
+ num_classes - covered.len()
+ );
+ }
} else {
- info!("▶ Test set is empty, skipping evaluation.");
+ info!("▶ Test set is empty, so no accuracy was measured.");
}
}
@@ -620,9 +673,30 @@ pub fn run(args: Args) -> AppResult {
// --- OOB accuracy (free estimate from bootstrap) ---
// Uses the exact seeds from train_ensemble to reproduce bootstrap samples.
+ // A tree that never split predicts one label for everything. It happens by
+ // default: --min-samples-leaf is 5 and a node of 10 samples or fewer is
+ // never divided, so a panel with a few genomes per lineage trains a forest
+ // of stumps and saves it without a word.
+ let stumps = trees.iter().filter(|tree| tree.nodes.len() <= 1).count();
+ if stumps == trees.len() {
+ warn!(
+ "⚠️ Every tree is a single leaf, so this model predicts one lineage for every input. With {} sequences over {} lineages, --min-samples-leaf {} forbids every split: a node of {} samples or fewer is never divided. Lower it, or train on more genomes per lineage.",
+ n_total,
+ num_classes,
+ args.min_samples_leaf,
+ args.min_samples_leaf * 2
+ );
+ } else if stumps > 0 {
+ warn!(
+ "⚠️ {} of the {} trees are a single leaf and give the same vote to every prediction.",
+ stumps,
+ trees.len()
+ );
+ }
+
let oob_accuracy_pct = compute_oob_accuracy(
&trees, &x_data_sparse, &y_data, &all_indices,
- num_classes, &tree_seeds,
+ num_classes, &tree_seeds, &label_encoder.int_to_label,
);
if let Some(oob) = oob_accuracy_pct {
info!(" 🎯 Out-of-bag accuracy: {:.2}%", oob);
@@ -751,7 +825,7 @@ pub fn run(args: Args) -> AppResult {
training_time_secs
);
Ok(TrainReport {
- accuracy_pct,
+ accuracy_pct, // None when nothing was evaluated
n_training,
n_test,
n_classes: num_classes,
diff --git a/pathotypr-core/tests/integration.rs b/pathotypr-core/tests/integration.rs
index cb141cd..a8bd1f1 100644
--- a/pathotypr-core/tests/integration.rs
+++ b/pathotypr-core/tests/integration.rs
@@ -76,7 +76,9 @@ fn end_to_end_train_predict() {
cancel_token: None,
};
let report = pathotypr_core::train::run(train_args).unwrap();
- assert!(report.accuracy_pct >= 80.0, "Accuracy too low: {:.1}%", report.accuracy_pct);
+ // None would mean nothing was evaluated, which this run does do.
+ let accuracy = report.accuracy_pct.expect("the test split was evaluated");
+ assert!(accuracy >= 80.0, "Accuracy too low: {:.1}%", accuracy);
assert_eq!(report.n_classes, 3);
assert_eq!(report.n_trees, 100);
assert!(report.oob_accuracy_pct.is_some());
diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs
index e20fabb..e329c2f 100644
--- a/src-tauri/src/commands.rs
+++ b/src-tauri/src/commands.rs
@@ -77,7 +77,12 @@ pub async fn run_train(
let accuracy_msg = if let (Some(mean), Some(std)) = (report.cv_mean_accuracy_pct, report.cv_std_accuracy_pct) {
format!("CV Accuracy: {:.2}% ± {:.2}%", mean, std)
} else {
- format!("Accuracy: {:.2}%", report.accuracy_pct)
+ match report.accuracy_pct {
+ Some(accuracy) => format!("Accuracy: {:.2}%", accuracy),
+ // Nothing was held out, so there is nothing to report. It
+ // used to say 0.00%, which reads as a measurement.
+ None => "Accuracy: not evaluated".to_string(),
+ }
};
let oob_msg = report.oob_accuracy_pct
.map(|oob| format!(" | OOB: {:.2}%", oob))
From 267897d864535b41aea466e54bf653c4af078971 Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 15:50:09 +0100
Subject: [PATCH 03/15] Give the match score one meaning
The singleton filter switched itself on above 100,000 unique k-mers and the score
was then a fraction of what remained, so 3% more reads could turn 0.8886 into a
perfect 1.0000; it now applies only when asked for, and the report carries the
denominator. Query k-mers are cut after removing the line breaks of a wrapped
FASTA, Query_Files comes out in the same order on every run, and the Excel log
names the file it wrote. The app's five match controls that reached nothing are
replaced by the one that changes the answer.
---
docs/algorithms/reference-matching.md | 8 +--
docs/match.md | 24 +++++--
frontend/index.html | 45 ++----------
frontend/js/config.js | 8 +--
frontend/js/forms.js | 62 ++---------------
galaxy/tools/pathotypr/pathotypr_match.xml | 3 +-
pathotypr-core/src/match/mod.rs | 80 +++++++++++++---------
src-tauri/src/commands.rs | 4 +-
8 files changed, 89 insertions(+), 145 deletions(-)
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/match.md b/docs/match.md
index 0608b0b..ce9585b 100644
--- a/docs/match.md
+++ b/docs/match.md
@@ -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,12 +138,26 @@ 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 left
+ 4.7% of the k-mers and scored the correct reference **1.0000**, a perfect
+ score from almost no data. Keeping them gave 0.8886 against 0.8824 and the
+ right answer.
+
+ 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
+reads_R1.fastq.gz,reads_R2.fastq.gz NC_000962.3 0.9873 4283915
```
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.
diff --git a/frontend/index.html b/frontend/index.html
index d348f48..d409dc7 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1541,18 +1541,7 @@ Output
Options
-
-
Recommended for most runs: keep Strict percentages enabled for results consistent with previous analyses.
-
Use advanced speed options only when you want faster runtime and can accept potential score changes.
-
-
-
-
-
- Advanced speed options (optional)
- ?These options are applied only when Strict percentages is disabled.
-
-
-
+
+ Minimum k-mer count ?Drops query k-mers seen fewer than this many times, as sequencing noise. 1 keeps every k-mer, which is what you want below a few fold coverage: there a real k-mer is usually seen once, and dropping singletons throws away the evidence that tells two references apart. Raising it lowers every score, so scores from different settings cannot be compared.
+
-
+
- Min Leaf Samples ?Minimum samples per leaf node. Higher values prevent overfitting by regularizing the trees. Default: 5.
-
+ Min Leaf Samples ?Minimum samples per leaf node. Default: 1. A node of twice this many samples or fewer is never split, so a high value with few genomes per lineage trains trees that never split at all and predict one lineage for everything.
+
diff --git a/frontend/js/config.js b/frontend/js/config.js
index 504d80b..6679cff 100644
--- a/frontend/js/config.js
+++ b/frontend/js/config.js
@@ -53,7 +53,7 @@ export const defaultParameters = {
'train-threads': '',
'train-cv-folds': '',
'train-max-depth': 20,
- 'train-min-leaf': 5
+ 'train-min-leaf': 1
},
predict: {
'predict-threads': ''
diff --git a/frontend/js/forms.js b/frontend/js/forms.js
index 98fff7c..bd786e9 100644
--- a/frontend/js/forms.js
+++ b/frontend/js/forms.js
@@ -907,7 +907,7 @@ async function handleTrainSubmit(e) {
});
const minLeaf = parseNumberField('train-min-leaf', {
label: 'Min leaf samples',
- fallback: 5,
+ fallback: 1,
min: 1,
max: 100,
integer: true
diff --git a/galaxy/tools/pathotypr/pathotypr_train.xml b/galaxy/tools/pathotypr/pathotypr_train.xml
index 3cca1c3..d101873 100644
--- a/galaxy/tools/pathotypr/pathotypr_train.xml
+++ b/galaxy/tools/pathotypr/pathotypr_train.xml
@@ -36,7 +36,7 @@ pathotypr train
-
+
diff --git a/pathotypr-core/src/train.rs b/pathotypr-core/src/train.rs
index b6268e1..b0c0c7b 100644
--- a/pathotypr-core/src/train.rs
+++ b/pathotypr-core/src/train.rs
@@ -112,10 +112,15 @@ pub struct Args {
/// Default: 20.
#[arg(long, default_value_t = 20)]
pub max_depth: usize,
- /// Minimum number of samples required in a leaf node.
- /// Higher values act as regularization, preventing the tree from memorizing
- /// individual training samples. Default: 5.
- #[arg(long, default_value_t = 5)]
+ /// Minimum number of samples required in a leaf node. Default: 1, the usual
+ /// value for a random forest, where the bootstrap and the random choice of
+ /// features already keep trees from memorising samples.
+ ///
+ /// It used to be 5, and a node of 10 samples or fewer is never split, so a
+ /// panel with a few genomes per lineage trained a forest of stumps: on
+ /// M. bovis sublineages two to five SNPs apart, 5 gave 31 of 32 calls with
+ /// a vote margin of 0.15, and 1 gave 32 of 32 with a margin of 0.50.
+ #[arg(long, default_value_t = 1)]
pub min_samples_leaf: usize,
/// Cancellation token for stopping the task (GUI only, not CLI).
#[arg(skip)]
@@ -777,9 +782,9 @@ pub fn run(args: Args) -> AppResult {
// --- OOB accuracy (free estimate from bootstrap) ---
// Uses the exact seeds from train_ensemble to reproduce bootstrap samples.
// A tree that never split predicts one label for everything. It happens by
- // default: --min-samples-leaf is 5 and a node of 10 samples or fewer is
+ // large --min-samples-leaf: a node of twice that many samples or fewer is
// never divided, so a panel with a few genomes per lineage trains a forest
- // of stumps and saves it without a word.
+ // of stumps and used to save it without a word.
let stumps = trees.iter().filter(|tree| tree.nodes.len() <= 1).count();
if stumps == trees.len() {
warn!(
diff --git a/pathotypr-core/src/vectorizer.rs b/pathotypr-core/src/vectorizer.rs
index 045047d..78debb7 100644
--- a/pathotypr-core/src/vectorizer.rs
+++ b/pathotypr-core/src/vectorizer.rs
@@ -1,6 +1,12 @@
//! Feature hashing vectorizer for k-mer-based ML.
//!
-//! Maps k-mers to fixed-size buckets via bitmask (hashing trick).
+//! Maps k-mers to fixed-size buckets by masking their 2-bit code.
+//!
+//! The mask keeps the low 20 bits, which are the last ten bases of the
+//! canonical k-mer, so the feature space is the 4^10 ten-mers whatever k is:
+//! k only decides which strand's ten bases are kept. That costs no accuracy
+//! in the tests behind docs/algorithms/feature-hashing.md, so it stays, but a
+//! bucket is not one k-mer and the importance reports have to be read that way.
//! Stateless — the same hash function is used at train and predict time.
use log::info;
@@ -140,7 +146,12 @@ impl FeatureHasher {
if target_buckets.contains(&idx) {
hits.push(KmerCoord {
bucket: idx,
- kmer: bitkmer_to_string(bitkmer.0, k),
+ // The bases at `position` as the sequence has
+ // them. The canonical k-mer is the reverse
+ // complement of those for about half of all hits,
+ // which then matched nothing at that coordinate.
+ kmer: String::from_utf8_lossy(&seq_bytes[pos..pos + k])
+ .to_ascii_uppercase(),
seq_index: seq_idx,
position: pos + 1, // 1-based
});
diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs
index 951f200..1df2269 100644
--- a/src-tauri/src/commands.rs
+++ b/src-tauri/src/commands.rs
@@ -53,7 +53,8 @@ pub async fn run_train(
threads: params.threads,
cv_folds: params.cv_folds,
max_depth: params.max_depth.unwrap_or(20),
- min_samples_leaf: params.min_samples_leaf.unwrap_or(5),
+ // 1, like the CLI: 5 turned sublineage panels into forests of stumps.
+ min_samples_leaf: params.min_samples_leaf.unwrap_or(1),
cancel_token: Some(cancel_token),
};
From 2bbc67411c799875e9c1820ed265c90b6a69b25d Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 16:51:10 +0100
Subject: [PATCH 06/15] Make the documentation match what the tools do and what
was measured
Every page was checked against the code and every figure measured again with the
final binary. The fixes cover a missing flag, examples without the new columns,
two pages still describing dropped records, missing undetermined reasons, one
figure that had never been measured, figures from before the paralogue guard, and
counts given to the wrong module.
---
docs/algorithms/assembly-classification.md | 4 ++++
docs/algorithms/marker-genotyping.md | 6 +++++-
docs/algorithms/random-forest.md | 2 +-
docs/classify.md | 14 ++++++++------
docs/getting-started.md | 7 ++++---
docs/match.md | 9 +++++----
docs/output-files.md | 9 +++++----
docs/predict.md | 7 ++++---
docs/split-fastq.md | 17 ++++++++++-------
docs/train.md | 2 +-
frontend/index.html | 2 +-
galaxy/tools/pathotypr/pathotypr_train.xml | 2 +-
pathotypr-core/src/classify/markers.rs | 10 +++++-----
pathotypr-core/src/classify/mod.rs | 7 ++++---
pathotypr-core/src/split_kmer.rs | 7 ++++---
pathotypr-core/src/train.rs | 21 +++++++++++----------
src-tauri/src/commands.rs | 2 +-
17 files changed, 74 insertions(+), 54 deletions(-)
diff --git a/docs/algorithms/assembly-classification.md b/docs/algorithms/assembly-classification.md
index d3d35fd..e15e3a3 100644
--- a/docs/algorithms/assembly-classification.md
+++ b/docs/algorithms/assembly-classification.md
@@ -81,6 +81,10 @@ And when no anchor can read it:
| 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/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 1a0613a..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` | 1 | The usual random-forest value: the bootstrap and the random choice of features already keep trees from memorising samples. It was 5, which forbade every split on panels with a few genomes per lineage. |
+| `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/classify.md b/docs/classify.md
index 64b0916..4ffd620 100644
--- a/docs/classify.md
+++ b/docs/classify.md
@@ -227,12 +227,14 @@ cannot do:
### A k-mer the reference itself carries
-Five markers of the WHO catalogue have an ALT k-mer that already sits
-elsewhere in H37Rv, two of them in PPE35, and another sixty-seven 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, `ndh c.168C>T` and `PPE35 I417V` read as present in every
-genome tested, the ancestor included.
+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:
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/match.md b/docs/match.md
index ce9585b..814f889 100644
--- a/docs/match.md
+++ b/docs/match.md
@@ -143,10 +143,11 @@ Query_Files Best_Match_Reference Shared_Kmer_Fraction Query_Kmers
!!! 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 left
- 4.7% of the k-mers and scored the correct reference **1.0000**, a perfect
- score from almost no data. Keeping them gave 0.8886 against 0.8824 and the
- right answer.
+ 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
diff --git a/docs/output-files.md b/docs/output-files.md
index 5938e2b..6df814d 100644
--- a/docs/output-files.md
+++ b/docs/output-files.md
@@ -81,7 +81,7 @@ Writes one predictions table to `--output`, streamed as sequences are classified
| 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. |
@@ -290,17 +290,18 @@ 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`. |
```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
+reads_R1.fastq.gz,reads_R2.fastq.gz NC_000962.3 H37Rv 0.9873 4283915
```
!!! note "No match, no data row"
diff --git a/docs/predict.md b/docs/predict.md
index 4d9f3ec..58f10fa 100644
--- a/docs/predict.md
+++ b/docs/predict.md
@@ -126,9 +126,10 @@ A tab-separated file with a header row and one row per classified record. Column
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 225f8a9..655ef51 100644
--- a/docs/split-fastq.md
+++ b/docs/split-fastq.md
@@ -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. |
@@ -205,15 +206,17 @@ 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
diff --git a/docs/train.md b/docs/train.md
index f263368..dd5bd2d 100644
--- a/docs/train.md
+++ b/docs/train.md
@@ -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 ` | `1` | no | Minimum samples per leaf. A node of `2N` samples or fewer is never split, so a high value with few genomes per lineage trains a forest of stumps; the run says so when it happens. |
+| `--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
diff --git a/frontend/index.html b/frontend/index.html
index 7eb5208..85baafa 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -424,7 +424,7 @@ Parameters
- Min Leaf Samples ?Minimum samples per leaf node. Default: 1. A node of twice this many samples or fewer is never split, so a high value with few genomes per lineage trains trees that never split at all and predict one lineage for everything.
+ Min Leaf Samples ?Minimum samples per leaf node. Default: 1. A node of twice this many samples or fewer is never split, so a high value keeps the trees from separating lineages with few genomes, and on a very small panel they never split at all.
diff --git a/galaxy/tools/pathotypr/pathotypr_train.xml b/galaxy/tools/pathotypr/pathotypr_train.xml
index d101873..9dd8aed 100644
--- a/galaxy/tools/pathotypr/pathotypr_train.xml
+++ b/galaxy/tools/pathotypr/pathotypr_train.xml
@@ -36,7 +36,7 @@ pathotypr train
-
+
diff --git a/pathotypr-core/src/classify/markers.rs b/pathotypr-core/src/classify/markers.rs
index f6da44f..7ea76d5 100644
--- a/pathotypr-core/src/classify/markers.rs
+++ b/pathotypr-core/src/classify/markers.rs
@@ -739,11 +739,11 @@ fn build_index(mut markers: Vec, encoded: bool, anchor_len: usi
/// Records which markers have a k-mer the reference genome itself carries.
///
/// A marker is recognised by a word, and a word says what it matched and not
-/// where. The WHO catalogue has five markers whose alternative word already
-/// sits elsewhere in H37Rv, two of them in PPE35, so they read as present in
-/// every genome including the ancestor. Another sixty-seven have a second copy
-/// of their reference word, which reads as the reference allele while the real
-/// locus carries the variant.
+/// where. Of the WHO catalogue markers this index holds, two have an
+/// alternative word that already sits elsewhere in H37Rv (ndh c.168C>T and
+/// PPE35 I417V), so they read as present in every genome including the
+/// ancestor, and seventy-one have a second copy of their reference word, which
+/// reads as the reference allele while the real locus carries the variant.
///
/// Knowing this from the reference is what lets a k-mer hit be treated as the
/// weak evidence it is: those markers are settled by an anchor, which does say
diff --git a/pathotypr-core/src/classify/mod.rs b/pathotypr-core/src/classify/mod.rs
index 7795379..8e7f7e9 100644
--- a/pathotypr-core/src/classify/mod.rs
+++ b/pathotypr-core/src/classify/mod.rs
@@ -1657,9 +1657,10 @@ mod tests {
);
}
- /// The WHO catalogue has five markers whose alternative k-mer H37Rv itself
- /// carries, two of them in PPE35, so the word turns up in every genome and
- /// the marker read as present everywhere, the ancestor included. When no
+ /// Two of the WHO catalogue markers classify indexes, ndh c.168C>T and
+ /// PPE35 I417V, have an alternative k-mer H37Rv itself carries, so the word
+ /// turns up in every genome and the marker read as present everywhere, the
+ /// ancestor included. When no
/// anchor can tell the real locus from the copy, the only honest answer is
/// that the marker was not read.
#[test]
diff --git a/pathotypr-core/src/split_kmer.rs b/pathotypr-core/src/split_kmer.rs
index 65c3e31..1d446a3 100644
--- a/pathotypr-core/src/split_kmer.rs
+++ b/pathotypr-core/src/split_kmer.rs
@@ -856,9 +856,10 @@ pub fn scan_fastq_anchors(
/// Records which markers have a k-mer the reference genome itself carries.
///
/// A k-mer says what it matched and never where, so reads from a paralogous
-/// copy count towards the wrong marker. Five markers of the WHO catalogue have
-/// an ALT k-mer that already sits elsewhere in H37Rv, two of them in PPE35, and
-/// sixty-seven have a second copy of their reference window. Marking them here
+/// copy count towards the wrong marker. Of the WHO catalogue markers this
+/// module indexes, five have an ALT k-mer that already sits elsewhere in H37Rv
+/// (three of them in PPE35, one in ndh, one upstream of dnaA), and sixty-seven
+/// have a second copy of their reference window. Marking them here
/// is what lets the caller refuse to settle them on read counts alone and ask
/// the anchors, which do say where they matched.
fn mark_reference_copies(markers: &mut [Marker], ref_seq: &[u8], kmer_len: usize) {
diff --git a/pathotypr-core/src/train.rs b/pathotypr-core/src/train.rs
index b0c0c7b..8cf79f1 100644
--- a/pathotypr-core/src/train.rs
+++ b/pathotypr-core/src/train.rs
@@ -116,10 +116,11 @@ pub struct Args {
/// value for a random forest, where the bootstrap and the random choice of
/// features already keep trees from memorising samples.
///
- /// It used to be 5, and a node of 10 samples or fewer is never split, so a
- /// panel with a few genomes per lineage trained a forest of stumps: on
- /// M. bovis sublineages two to five SNPs apart, 5 gave 31 of 32 calls with
- /// a vote margin of 0.15, and 1 gave 32 of 32 with a margin of 0.50.
+ /// It used to be 5, and a node of 10 samples or fewer is never split, so
+ /// the trees stayed too shallow to separate lineages with few genomes: on
+ /// M. bovis sublineages two to five SNPs apart, with six genomes each, 5
+ /// gave 31 of 32 calls at a vote margin of 0.15 and 1 gave 32 of 32 at
+ /// 0.50. On a panel of ten genomes, 5 leaves every tree a single leaf.
#[arg(long, default_value_t = 1)]
pub min_samples_leaf: usize,
/// Cancellation token for stopping the task (GUI only, not CLI).
@@ -779,12 +780,10 @@ pub fn run(args: Args) -> AppResult {
n_total,
);
- // --- OOB accuracy (free estimate from bootstrap) ---
- // Uses the exact seeds from train_ensemble to reproduce bootstrap samples.
- // A tree that never split predicts one label for everything. It happens by
- // large --min-samples-leaf: a node of twice that many samples or fewer is
- // never divided, so a panel with a few genomes per lineage trains a forest
- // of stumps and used to save it without a word.
+ // A tree that never split predicts one label for everything. A node of twice
+ // --min-samples-leaf samples or fewer is never divided, so a panel small
+ // enough for its setting gets single-leaf trees, all of them on a panel of
+ // ten genomes at 5, and the model used to be saved without a word.
let stumps = trees.iter().filter(|tree| tree.nodes.len() <= 1).count();
if stumps == trees.len() {
warn!(
@@ -802,6 +801,8 @@ pub fn run(args: Args) -> AppResult {
);
}
+ // --- OOB accuracy (free estimate from bootstrap) ---
+ // Uses the exact seeds from train_ensemble to reproduce bootstrap samples.
let oob_accuracy_pct = compute_oob_accuracy(
&trees, &x_data_sparse, &y_data, &all_indices,
num_classes, &tree_seeds, &label_encoder.int_to_label,
diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs
index 1df2269..9875b5d 100644
--- a/src-tauri/src/commands.rs
+++ b/src-tauri/src/commands.rs
@@ -53,7 +53,7 @@ pub async fn run_train(
threads: params.threads,
cv_folds: params.cv_folds,
max_depth: params.max_depth.unwrap_or(20),
- // 1, like the CLI: 5 turned sublineage panels into forests of stumps.
+ // 1, like the CLI: 5 kept trees too shallow to separate lineages with few genomes.
min_samples_leaf: params.min_samples_leaf.unwrap_or(1),
cancel_token: Some(cancel_token),
};
From e00457279962a8922debc923da8152cb72304feb Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 17:17:43 +0100
Subject: [PATCH 07/15] Refuse to write an output over an input
Every command creates its outputs before it has finished reading its inputs, so
an output named after an input destroyed it: a sample list, a FASTA to predict,
the references for match, the marker panel and the training data could all be
truncated or replaced, and three of those runs exited successfully. Each command
now compares its outputs with its inputs once paths are resolved and stops with
a message naming both before anything is written.
---
pathotypr-core/src/classify/mod.rs | 21 ++++++++
pathotypr-core/src/classify_split_fastq.rs | 15 ++++++
pathotypr-core/src/common.rs | 60 ++++++++++++++++++++++
pathotypr-core/src/match/mod.rs | 12 +++++
pathotypr-core/src/predict.rs | 4 ++
pathotypr-core/src/train.rs | 9 ++++
6 files changed, 121 insertions(+)
diff --git a/pathotypr-core/src/classify/mod.rs b/pathotypr-core/src/classify/mod.rs
index 8e7f7e9..88e05cf 100644
--- a/pathotypr-core/src/classify/mod.rs
+++ b/pathotypr-core/src/classify/mod.rs
@@ -1054,6 +1054,27 @@ pub fn run(args: Args) -> AppResult<()> {
let cancel_token = &args.cancel_token;
check_cancelled(cancel_token)?;
check_input_files(&args)?;
+ {
+ let base = args.ofile.strip_suffix(".tsv").unwrap_or(&args.ofile);
+ let mut outputs = vec![
+ if args.ofile.ends_with(".tsv") { args.ofile.clone() } else { format!("{}.tsv", args.ofile) },
+ format!("{}_summary.tsv", base),
+ format!("{}_undetermined.tsv", base),
+ ];
+ if args.excel {
+ let xlsx: Vec = outputs.iter().map(|o| crate::excel::excel_path_from_tsv(o)).collect();
+ outputs.extend(xlsx);
+ }
+ let inputs = [&args.tsv_pos, &args.ref_fasta]
+ .into_iter()
+ .map(String::as_str)
+ .chain(args.tsv_genomes.as_deref())
+ .chain(args.fasta_genomes.as_deref())
+ .chain(args.gff_file.as_deref())
+ .chain(args.fasta_files.iter().flatten().map(String::as_str))
+ .chain(args.gff_files.iter().flatten().map(String::as_str));
+ crate::common::refuse_output_over_input(inputs, &outputs)?;
+ }
let k = crate::common::validate_kmer_size(args.kmer_size)?;
debug!("k-mer size set to: {}", k);
diff --git a/pathotypr-core/src/classify_split_fastq.rs b/pathotypr-core/src/classify_split_fastq.rs
index 21b5a6e..913e2e8 100644
--- a/pathotypr-core/src/classify_split_fastq.rs
+++ b/pathotypr-core/src/classify_split_fastq.rs
@@ -332,6 +332,21 @@ fn check_cancelled_with_cleanup(
}
pub fn run(args: SplitFastqArgs) -> AppResult<()> {
+ {
+ // The per-sample names are only known once the samples are read, but
+ // the summary is fixed, and so are the inputs it could land on.
+ let summary = format!("{}_summary.tsv", args.output_prefix);
+ let inputs = args
+ .input
+ .iter()
+ .map(String::as_str)
+ .chain(args.input_list.as_deref())
+ .chain([args.reference.as_str(), args.markers.as_str()]);
+ crate::common::refuse_output_over_input(
+ inputs,
+ &[summary.clone(), crate::excel::excel_path_from_tsv(&summary)],
+ )?;
+ }
if args.input.is_empty() && args.input_list.is_none() {
return Err(AppError::Generic(
"You must provide an input source: either --input or --input-list.".to_string(),
diff --git a/pathotypr-core/src/common.rs b/pathotypr-core/src/common.rs
index 5315938..3468df9 100644
--- a/pathotypr-core/src/common.rs
+++ b/pathotypr-core/src/common.rs
@@ -9,6 +9,43 @@ pub use crate::excel::{write_excel_file, ExcelStreamWriter};
pub use crate::model::{ModelBundle, MODEL_FORMAT_VERSION};
pub use crate::paired_end::detect_paired_end_files;
+// ---------------------------------------------------------------------------
+// Outputs written over inputs
+// ---------------------------------------------------------------------------
+
+/// Refuses to start when an output would be written over one of the inputs.
+///
+/// Every command creates its outputs before it has finished reading its
+/// inputs, so naming an output after an input destroyed the input: `classify
+/// -l run.tsv -o run` truncated the sample list into its own detail table,
+/// found no sample in it and deleted it while cleaning up, and `match -r
+/// refs.fasta -o refs.fasta`, `train -i data.fasta -o data.fasta` and
+/// `classify -m panel.tsv -o panel` replaced the reference, the training data
+/// and the marker panel with results and exited successfully. Paths are
+/// compared once resolved, so `./run.tsv` or a link to it is the same file.
+pub fn refuse_output_over_input<'a>(
+ inputs: impl IntoIterator- ,
+ outputs: &[String],
+) -> Result<(), crate::errors::AppError> {
+ let inputs: Vec<(&str, std::path::PathBuf)> = inputs
+ .into_iter()
+ .filter_map(|input| std::fs::canonicalize(input).ok().map(|resolved| (input, resolved)))
+ .collect();
+ for output in outputs {
+ // An output that does not exist yet cannot be an existing input.
+ let Ok(resolved) = std::fs::canonicalize(output) else {
+ continue;
+ };
+ if let Some((input, _)) = inputs.iter().find(|(_, path)| *path == resolved) {
+ return Err(crate::errors::AppError::Generic(format!(
+ "The output '{}' is the input '{}'. Writing it would destroy that input; choose another output name.",
+ output, input
+ )));
+ }
+ }
+ Ok(())
+}
+
// ---------------------------------------------------------------------------
// K-mer size validation
// ---------------------------------------------------------------------------
@@ -51,3 +88,26 @@ pub fn configure_thread_pool(num_threads: Option
) {
}
}
}
+
+#[cfg(test)]
+mod output_over_input_tests {
+ use super::refuse_output_over_input;
+
+ /// The case that destroyed a sample list: the output resolves to the input,
+ /// even written another way.
+ #[test]
+ fn an_output_that_is_an_input_is_refused() {
+ let dir = std::env::temp_dir().join(format!("pathotypr-ooi-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let input = dir.join("run.tsv");
+ std::fs::write(&input, "s1\tgenome.fasta\n").unwrap();
+ let input = input.to_str().unwrap().to_string();
+ let same_written_otherwise = format!("{}/./run.tsv", dir.to_str().unwrap());
+ assert!(refuse_output_over_input([input.as_str()], &[input.clone()]).is_err());
+ assert!(refuse_output_over_input([input.as_str()], &[same_written_otherwise]).is_err());
+ // A different file, and one that does not exist yet, are both fine.
+ let other = dir.join("run_summary.tsv").to_str().unwrap().to_string();
+ assert!(refuse_output_over_input([input.as_str()], &[other]).is_ok());
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/pathotypr-core/src/match/mod.rs b/pathotypr-core/src/match/mod.rs
index 55bdfcd..b707a2c 100644
--- a/pathotypr-core/src/match/mod.rs
+++ b/pathotypr-core/src/match/mod.rs
@@ -309,6 +309,18 @@ pub fn run(args: Args) -> AppResult<()> {
let cancel_token = &args.cancel_token;
check_cancelled(cancel_token)?;
+ if let Some(output) = &args.output {
+ let inputs = args
+ .fastqs
+ .iter()
+ .map(String::as_str)
+ .chain(args.input_list.as_deref())
+ .chain(args.references.as_deref());
+ crate::common::refuse_output_over_input(
+ inputs,
+ &[output.clone(), crate::excel::excel_path_from_tsv(output)],
+ )?;
+ }
// Determine fastq files
let fastq_files_to_process = if let Some(list_path) = &args.input_list {
diff --git a/pathotypr-core/src/predict.rs b/pathotypr-core/src/predict.rs
index 2de819f..2f74177 100644
--- a/pathotypr-core/src/predict.rs
+++ b/pathotypr-core/src/predict.rs
@@ -251,6 +251,10 @@ pub fn run(args: PredictArgs) -> AppResult<()> {
let cancel_token = &args.cancel_token;
check_cancelled(cancel_token)?;
+ crate::common::refuse_output_over_input(
+ [args.input.as_str(), args.model.as_str()],
+ &[args.output.clone(), crate::excel::excel_path_from_tsv(&args.output)],
+ )?;
let overall_start = Instant::now();
diff --git a/pathotypr-core/src/train.rs b/pathotypr-core/src/train.rs
index 8cf79f1..85275c0 100644
--- a/pathotypr-core/src/train.rs
+++ b/pathotypr-core/src/train.rs
@@ -594,6 +594,15 @@ fn stratified_cv(
/// Main execution logic for the `train` subcommand.
pub fn run(args: Args) -> AppResult {
+ {
+ let output = std::path::Path::new(&args.output);
+ let outputs = [
+ args.output.clone(),
+ output.with_extension("importance.tsv").to_string_lossy().into_owned(),
+ output.with_extension("importance.coords.tsv").to_string_lossy().into_owned(),
+ ];
+ crate::common::refuse_output_over_input([args.input.as_str()], &outputs)?;
+ }
if !(0.0..1.0).contains(&args.test_split) {
return Err(AppError::Generic(
"--test-split must be between 0.0 and 1.0.".to_string(),
From 14c93a66d2329e781286060c96a801d01c30f1ee Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 17:21:24 +0100
Subject: [PATCH 08/15] Tally a resistance summary per drug
The lineage:count column counts every prefix of a marker's path, which tallies
each level of a lineage hierarchy, but a catalogue path is not a hierarchy and
its prefixes run into the WHO grade, which has spaces in it. The space-separated
pairs then came apart and the column could not be read back; with a resistance
panel it now counts the markers found per drug, as undetermined:count already did.
---
docs/input-formats.md | 60 ++++++++++++++++++++--
pathotypr-core/src/classify/mod.rs | 10 +++-
pathotypr-core/src/classify_split_fastq.rs | 10 +++-
pathotypr-core/src/resistance.rs | 39 ++++++++++++++
4 files changed, 110 insertions(+), 9 deletions(-)
diff --git a/docs/input-formats.md b/docs/input-formats.md
index 0fb1588..23797a4 100644
--- a/docs/input-formats.md
+++ b/docs/input-formats.md
@@ -55,7 +55,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
@@ -81,11 +86,11 @@ Tab-separated. Blank lines and lines beginning with `#` are ignored. A header ro
```text
#pos ref alt level1 level2 gene mutation
- 761155 C T L4 L4.9 gyrA Ser95Thr
- 2155168 G A L2 L2.2 katG Ser315Thr
+ 761155 C T RIF RIF-R rpoB S450L
+ 2155168 C G INH INH-R katG S315T
```
- 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 `rpoB` and its mutation `S450L`. A panel written this way is read as a **lineage** panel, with `RIF` and `INH` as its top levels; to be answered as a resistance panel it has to use the WHO shape below.
=== "Small indel (classify only)"
@@ -105,7 +110,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 +131,51 @@ 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:
+
+```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
+```
+
+These rows are taken from the deposited panel. The path of the first one is
+`RIF;RIF-R;rpoB_S450L;1) Assoc w R;rpoB;S450L`, 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.
+
+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`)
diff --git a/pathotypr-core/src/classify/mod.rs b/pathotypr-core/src/classify/mod.rs
index 88e05cf..a4b878a 100644
--- a/pathotypr-core/src/classify/mod.rs
+++ b/pathotypr-core/src/classify/mod.rs
@@ -1301,7 +1301,13 @@ pub fn run(args: Args) -> AppResult<()> {
// Match the TSV exactly: sorted by count (then name) and space-joined.
// Iterating the HashMap directly made the Excel column disagree with
// its own TSV and vary between otherwise identical runs.
- let lineage_counts_str = format_label_counts(&lineage_map);
+ // A resistance panel is tallied per drug; see resistance::per_drug_counts.
+ let shown_counts = if resistance_panel {
+ crate::resistance::per_drug_counts(&lineage_map)
+ } else {
+ lineage_map.clone()
+ };
+ let lineage_counts_str = format_label_counts(&shown_counts);
let resistance_counts = resistance_panel.then(|| resistance_map.get(&genome)).flatten();
let major_lineage = genome_call(&lineage_map, resistance_counts, args.nested_classification);
let undetermined_counts = undetermined_count_map.get(&genome);
@@ -1322,7 +1328,7 @@ pub fn run(args: Args) -> AppResult<()> {
}
if disable_summary_excel { summary_excel_writer = None; }
- if let Err(e) = write_summary(&mut summary_out, genome.clone(), &lineage_map, undetermined_counts, resistance_counts, args.nested_classification) {
+ if let Err(e) = write_summary(&mut summary_out, genome.clone(), &shown_counts, undetermined_counts, resistance_counts, args.nested_classification) {
drop(summary_out); cleanup_generated_outputs(&generated_outputs); return Err(e);
}
}
diff --git a/pathotypr-core/src/classify_split_fastq.rs b/pathotypr-core/src/classify_split_fastq.rs
index 913e2e8..f05f7a9 100644
--- a/pathotypr-core/src/classify_split_fastq.rs
+++ b/pathotypr-core/src/classify_split_fastq.rs
@@ -907,8 +907,14 @@ pub fn run(args: SplitFastqArgs) -> AppResult<()> {
sample_name, detailed_output_path
);
- // Generate summary line
- let mut sorted_lineages: Vec<(String, usize)> = lineage_counts
+ // Generate summary line. A resistance panel is tallied per drug; see
+ // resistance::per_drug_counts.
+ let shown_counts = if resistance_panel {
+ crate::resistance::per_drug_counts(&lineage_counts)
+ } else {
+ lineage_counts.clone()
+ };
+ let mut sorted_lineages: Vec<(String, usize)> = shown_counts
.iter()
.map(|(k, v)| (k.clone(), *v))
.collect();
diff --git a/pathotypr-core/src/resistance.rs b/pathotypr-core/src/resistance.rs
index 74dcbbd..2866792 100644
--- a/pathotypr-core/src/resistance.rs
+++ b/pathotypr-core/src/resistance.rs
@@ -128,6 +128,23 @@ pub fn fold_marker(per_drug: &mut HashMap, path: &str) {
}
}
+/// The `lineage:count` tally of a resistance run: markers found per drug.
+///
+/// A lineage path's prefixes are its ancestors, so counting every prefix
+/// tallies each level of the hierarchy. A catalogue path is not a hierarchy,
+/// and its prefixes run into the grade, which has spaces in it: the pairs of a
+/// space-separated column came apart as `...;1)`, `Assoc`, `w` and `R:1`, and
+/// the column could not be read back. The count at the drug level is already
+/// there, since every marker counts towards each of its prefixes, so it is the
+/// only one kept.
+pub fn per_drug_counts(prefix_counts: &HashMap) -> HashMap {
+ prefix_counts
+ .iter()
+ .filter(|(path, _)| !path.contains(';'))
+ .map(|(drug, count)| (drug.clone(), *count))
+ .collect()
+}
+
/// The call for one genome: the drugs it carries a grade 1 or 2 marker for.
///
/// Says "found" rather than "none", because a marker that could not be read is
@@ -229,6 +246,28 @@ mod tests {
assert_eq!(call(&per_drug), "No resistance markers found; uncertain: EMB");
}
+ /// The column must split back into the pairs it was made of, so it keeps
+ /// the drugs and drops the prefixes that run into a grade with spaces.
+ #[test]
+ fn a_resistance_tally_counts_markers_per_drug() {
+ let mut prefixes = HashMap::new();
+ for path in [
+ "RIF;RIF-R;rpoB_D435F;1) Assoc w R;rpoB;D435F",
+ "RIF;RIF-R;rpoB_D435V;1) Assoc w R;rpoB;D435V",
+ "INH;INH-R;katG_S315T;1) Assoc w R;katG;S315T",
+ ] {
+ let parts: Vec<&str> = path.split(';').collect();
+ for depth in 1..=parts.len() {
+ *prefixes.entry(parts[..depth].join(";")).or_insert(0usize) += 1;
+ }
+ }
+ let per_drug = per_drug_counts(&prefixes);
+ assert_eq!(per_drug.len(), 2);
+ assert_eq!(per_drug["RIF"], 2);
+ assert_eq!(per_drug["INH"], 1);
+ assert!(per_drug.keys().all(|drug| !drug.contains(' ')));
+ }
+
#[test]
fn a_genome_with_only_ungraded_or_unassociated_markers_claims_nothing() {
let mut per_drug = HashMap::new();
From 8fa5d73f36da0d84c2743670d9bc6db96c9f2f3b Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 17:27:19 +0100
Subject: [PATCH 09/15] Read a wrapped FASTA without losing the k-mers across
its line breaks
split-fastq read each record's sequence with its newlines still in it, so every
k-mer spanning a line break of a wrapped FASTA was skipped as holding an invalid
base, and a variant whose k-mer crossed one was never seen. Both scans now read
the sequence without them; FASTQ reads have none, so their results do not change.
---
pathotypr-core/src/split_kmer.rs | 48 ++++++++++++++++++++++++++++++--
1 file changed, 46 insertions(+), 2 deletions(-)
diff --git a/pathotypr-core/src/split_kmer.rs b/pathotypr-core/src/split_kmer.rs
index 1d446a3..03c2523 100644
--- a/pathotypr-core/src/split_kmer.rs
+++ b/pathotypr-core/src/split_kmer.rs
@@ -768,7 +768,9 @@ pub fn scan_fastq_anchors(
while batch.len() < BATCH_SIZE {
if let Some(record) = rdr.next() {
match record {
- Ok(record) => batch.push(record.sequence()),
+ // seq(), not sequence(): the newlines of a wrapped FASTA
+ // would cut every k-mer that spans one.
+ Ok(record) => batch.push(&record.seq()),
Err(e) => {
let mut first_error =
parse_error.lock().unwrap_or_else(|e| e.into_inner());
@@ -1067,7 +1069,11 @@ pub fn scan_fastq_with_index(
break;
}
};
- batch.push(record.sequence());
+ // seq() drops the line breaks a wrapped FASTA carries inside
+ // its sequence; sequence() keeps them, and every k-mer that
+ // spans one was skipped as holding an invalid base. Reads in
+ // FASTQ have none, so for them nothing changes.
+ batch.push(&record.seq());
record_count += 1;
if record_count & 8191 == 0 {
@@ -1387,6 +1393,44 @@ mod tests {
);
}
+ /// A wrapped FASTA carries newlines inside its sequence. Read raw, every
+ /// k-mer spanning one held an invalid base and was skipped, so a variant
+ /// whose k-mer crossed a line break was never seen.
+ #[test]
+ fn a_kmer_across_a_line_break_of_a_wrapped_fasta_is_counted() {
+ let reference = test_reference();
+ let k = 31;
+ let pos0 = 75;
+ let markers = vec![one_marker(&reference, pos0, "A", k)];
+ let (index, bloom) = build_marker_index(&markers);
+
+ let mut sample = reference.clone();
+ sample[pos0] = b'A';
+ // Lines of 70 bases put the variant at column 76 of the sequence, so
+ // its k-mer starts on the first line and ends on the second.
+ let mut wrapped = b">sample\n".to_vec();
+ for line in sample.chunks(70) {
+ wrapped.extend_from_slice(line);
+ wrapped.push(b'\n');
+ }
+ let dir = std::env::temp_dir().join(format!("pathotypr-wrap-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("wrapped.fasta");
+ std::fs::write(&path, &wrapped).unwrap();
+
+ let counts = scan_fastq_with_index(
+ &[path.to_str().unwrap().to_string()],
+ &index,
+ &bloom,
+ markers.len(),
+ &None,
+ k,
+ )
+ .unwrap();
+ std::fs::remove_dir_all(&dir).ok();
+ assert_eq!(counts[0][1], 1, "the alternate k-mer spans the line break and must be counted");
+ }
+
/// The counts are per allele, so a read carrying neither is neither.
#[test]
fn anchor_depth_adds_up_the_three_outcomes() {
From 1077f8c54c6b249b90700ab58478c0cbe6e20c5e Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 17:27:19 +0100
Subject: [PATCH 10/15] Show real inputs and outputs in the documentation
Every output example is now an excerpt of a real run, and the hand-written ones
they replace were inconsistent: a predict row whose vote shares added up to more
than one, classify rows placing a marker outside the gene it named, and match
counts no real run would produce. The input reference now describes the WHO
resistance panel shape the tools recognise, and several pages that still
described dropped records or the old columns say what the tools do today.
---
docs/input-formats.md | 2 +-
docs/match.md | 8 ++-
docs/output-files.md | 154 +++++++++++++++++++++++++++++++++++-------
docs/predict.md | 10 +--
docs/split-fastq.md | 2 +-
docs/train.md | 2 +-
6 files changed, 143 insertions(+), 35 deletions(-)
diff --git a/docs/input-formats.md b/docs/input-formats.md
index 23797a4..a67a3a6 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
diff --git a/docs/match.md b/docs/match.md
index 814f889..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
@@ -158,9 +158,13 @@ Example:
```text
Query_Files Best_Match_Reference Shared_Kmer_Fraction Query_Kmers
-reads_R1.fastq.gz,reads_R2.fastq.gz NC_000962.3 0.9873 4283915
+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 6df814d..da17c2d 100644
--- a/docs/output-files.md
+++ b/docs/output-files.md
@@ -6,6 +6,7 @@ Every `pathotypr` subcommand writes tab-separated (TSV) result files, and most c
- **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 +47,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 +59,28 @@ 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. |
+
+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).
@@ -89,15 +108,22 @@ Writes one predictions table to `--output`, streamed as sequences are classified
```text
Header Predicted_Lineage Confidence Confidence_Margin Other_Votes Kmers_Used
-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
+sample_A L2.2.1 0.9400 0.9000 L2.2:0.04,L4:0.02 4398877
+sample_B L4.3.4.2 0.7500 0.5500 L4.3:0.20,L4:0.05 4411512
+masked_consensus_02 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`. The last row is from a real run on an
+N-masked sequence: no window of A, C, G and T long enough for the model's k, 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).
@@ -124,7 +150,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. |
@@ -150,7 +176,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. |
@@ -173,44 +199,76 @@ 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. |
+| `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. |
-=== "Detailed"
+Every example below is an excerpt of a real run.
+
+=== "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.
```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
+ 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
+ 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
+ h37rv
```
=== "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).
---
@@ -222,10 +280,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.
@@ -269,11 +326,51 @@ 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. |
+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.
@@ -301,9 +398,14 @@ Finds the single best-matching reference for a set of FASTQ reads. All input rea
```text
Query_Files Best_Match_Reference Shared_Kmer_Fraction Query_Kmers
-reads_R1.fastq.gz,reads_R2.fastq.gz NC_000962.3 H37Rv 0.9873 4283915
+sample_reads.fastq reference_A 0.8886 101500
```
+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 run gives far more: about 35 million k-mer occurrences at 10x with 150 bp reads, and 106 million at 30x.
+
!!! note "No match, no data 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.
diff --git a/docs/predict.md b/docs/predict.md
index 58f10fa..095d7fc 100644
--- a/docs/predict.md
+++ b/docs/predict.md
@@ -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.
diff --git a/docs/split-fastq.md b/docs/split-fastq.md
index 655ef51..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)
diff --git a/docs/train.md b/docs/train.md
index dd5bd2d..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:
From 1ed78a6a0d53060caf6b65687218e27cecca75a2 Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 18:40:59 +0100
Subject: [PATCH 11/15] Keep the order of the classify sample list
The list was read into a hash map, so the detailed table listed the samples in
a different order on every run, and which of two masked FASTA files sharing a
stem got the _2 suffix changed with it. Samples now come out in list order.
---
pathotypr-core/src/classify/mod.rs | 35 +++++++++++++++++++++++++-----
1 file changed, 29 insertions(+), 6 deletions(-)
diff --git a/pathotypr-core/src/classify/mod.rs b/pathotypr-core/src/classify/mod.rs
index a4b878a..3220277 100644
--- a/pathotypr-core/src/classify/mod.rs
+++ b/pathotypr-core/src/classify/mod.rs
@@ -169,13 +169,16 @@ pub fn get_ref(fasta_file: &str) -> AppResult {
// Genome paths from TSV
// ---------------------------------------------------------------------------
-fn get_genomepaths(tsv_file: &str) -> AppResult)>> {
+/// Samples of an input list, in the order the list gives them: the detailed
+/// table and the masked FASTA names follow it, so a run is reproducible.
+fn get_genomepaths(tsv_file: &str) -> AppResult))>> {
let mut rdr = csv::ReaderBuilder::new()
.delimiter(b'\t')
.has_headers(false)
.flexible(true)
.from_path(tsv_file)?;
- let mut genome_paths = HashMap::new();
+ let mut genome_paths = Vec::new();
+ let mut seen_names: HashSet = HashSet::new();
for result in rdr.records() {
let record = result?;
if record.len() < 2 { continue; }
@@ -211,12 +214,13 @@ fn get_genomepaths(tsv_file: &str) -> AppResult))> =
- get_genomepaths(tsv_genomes)?.into_iter().collect();
+ let genome_paths_vec = get_genomepaths(tsv_genomes)?;
debug!("Processing {} genomes from input list.", genome_paths_vec.len());
let pb = ProgressBar::new(genome_paths_vec.len() as u64);
pb.set_style(
@@ -1355,7 +1358,7 @@ pub fn run(args: Args) -> AppResult<()> {
mask_ranges.len(), mask_ranges.iter().map(|(s, e)| e - s).sum::());
let fasta_sources: Vec = if let Some(tsv_genomes) = &args.tsv_genomes {
- get_genomepaths(tsv_genomes)?.into_values().map(|(path, _)| path).collect()
+ get_genomepaths(tsv_genomes)?.into_iter().map(|(_, (path, _))| path).collect()
} else if let Some(fasta_genomes) = &args.fasta_genomes {
vec![fasta_genomes.clone()]
} else if let Some(fasta_files) = &args.fasta_files {
@@ -1423,6 +1426,26 @@ mod tests {
assert_eq!(get_final_lineage_call(&counts), "L1");
}
+ #[test]
+ fn input_list_keeps_the_order_of_the_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let names = ["zeta", "alpha", "mid", "beta", "omega", "delta", "kappa", "eta"];
+ let mut list = String::new();
+ for name in names {
+ let fasta = dir.path().join(format!("{}.fasta", name));
+ std::fs::write(&fasta, ">x\nACGT\n").unwrap();
+ list.push_str(&format!("{}\t{}\n", name, fasta.display()));
+ }
+ let list_path = dir.path().join("samples.tsv");
+ std::fs::write(&list_path, list).unwrap();
+ let read: Vec = super::get_genomepaths(list_path.to_str().unwrap())
+ .unwrap()
+ .into_iter()
+ .map(|(name, _)| name)
+ .collect();
+ assert_eq!(read, names);
+ }
+
#[test]
fn gff_parses_cds_features_correctly() {
let gff_path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../TEST_PATHOTYPR/sequence_L4.gff3");
From 0fff0181c34e4f41d4d2158f6bbbc6b625f827f9 Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 18:40:59 +0100
Subject: [PATCH 12/15] Show every input and output on an invented example
dataset
The input and output pages now run one small invented dataset through every
command and show what pathotypr wrote, with the real-run excerpts kept below.
The pass also fixed examples that disagreed with the code: marker rows whose REF
is not the reference base, the GFF naming rule, the match note and the predict rows.
---
docs/input-formats.md | 167 ++++++++++++++++++++++++++--------
docs/output-files.md | 203 ++++++++++++++++++++++++++++++++++++++----
2 files changed, 317 insertions(+), 53 deletions(-)
diff --git a/docs/input-formats.md b/docs/input-formats.md
index a67a3a6..8cf0dd8 100644
--- a/docs/input-formats.md
+++ b/docs/input-formats.md
@@ -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.
@@ -74,32 +107,43 @@ The same file format carries two kinds of panel, and the tools treat them differ
### 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 RIF RIF-R rpoB S450L
- 2155168 C G INH INH-R katG S315T
+ 3149 C T RIF RIF-R geneR S50L
+ 3855 C G INH INH-R geneI S15T
```
- 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 `rpoB` and its mutation `S450L`. A panel written this way is read as a **lineage** panel, with `RIF` and `INH` as its top levels; to be answered as a resistance panel it has to use the WHO shape below.
+ 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"
@@ -134,7 +178,24 @@ The same file format carries two kinds of panel, and the tools treat them differ
### 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:
+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
@@ -143,13 +204,6 @@ columns after the alleles form the marker's path:
759545 TA CG RIF RIF-R rpoB_c.-261A>G 5) Not assoc w R rpoB c.-261A>G
```
-These rows are taken from the deposited panel. The path of the first one is
-`RIF;RIF-R;rpoB_S450L;1) Assoc w R;rpoB;S450L`, 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.
-
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
@@ -183,11 +237,14 @@ marker, for example `Resistant: INH,RIF`, instead of a lineage; see
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**) | ✅ |
@@ -196,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`"
@@ -209,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 |
@@ -219,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"
@@ -234,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.
@@ -242,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
+ ...
+ ```
---
@@ -250,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
@@ -257,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/output-files.md b/docs/output-files.md
index da17c2d..c29c1ec 100644
--- a/docs/output-files.md
+++ b/docs/output-files.md
@@ -2,6 +2,8 @@
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.
@@ -64,6 +66,29 @@ One row per occurrence of a discriminant k-mer, ordered by bucket rank, then seq
| `lineage` | Class label of that 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
@@ -106,18 +131,26 @@ Writes one predictions table to `--output`, streamed as sequences are classified
| `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. |
| `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. |
-```text
-Header Predicted_Lineage Confidence Confidence_Margin Other_Votes Kmers_Used
-sample_A L2.2.1 0.9400 0.9000 L2.2:0.04,L4:0.02 4398877
-sample_B L4.3.4.2 0.7500 0.5500 L4.3:0.20,L4:0.05 4411512
-masked_consensus_02 Undetermined 0
-```
+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`. The last row is from a real run on an
-N-masked sequence: no window of A, C, G and T long enough for the model's k, so
-no k-mer, no vote, and the row says so instead of carrying a lineage.
+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.
@@ -135,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). |
@@ -202,7 +235,92 @@ rows in a resistance panel.
| `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. |
-Every example below is an excerpt of a real run.
+### 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"
@@ -228,10 +346,10 @@ Every example below is an excerpt of a real run.
```text
genome k-mer k-merPOS SNPgenome SNPreference REF ALT lineage Gene Gene_Start Gene_End AA_Pos AA_Change alleles_found evidence
+ 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
- h37rv
```
=== "Summary"
@@ -331,6 +449,47 @@ listed: it was answered. See
| `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.
@@ -396,6 +555,20 @@ Finds the single best-matching reference for a set of FASTQ reads. All input rea
| `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 Query_Kmers
sample_reads.fastq reference_A 0.8886 101500
@@ -404,9 +577,9 @@ sample_reads.fastq reference_A 0.8886 101500
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 run gives far more: about 35 million k-mer occurrences at 10x with 150 bp reads, and 106 million at 30x.
+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 match, no data row"
+!!! 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).
From b634a3d1af5a5d24e73fe80cb4f769b0f9a5b62f Mon Sep 17 00:00:00 2001
From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com>
Date: Sun, 1 Nov 2026 18:49:24 +0100
Subject: [PATCH 13/15] Bump the version to 1.0.3
The core crate, the app, CITATION.cff, the Galaxy wrapper and the issue templates
move to 1.0.3, and the app screenshots in the docs are rendered again so the
sidebar shows it.
---
.github/DISCUSSION_TEMPLATE/q-a.yml | 2 +-
.../studies-using-pathotypr.yml | 2 +-
.github/ISSUE_TEMPLATE/bug_report.yml | 2 +-
.github/ISSUE_TEMPLATE/unexpected_results.yml | 2 +-
CITATION.cff | 4 ++--
Cargo.lock | 4 ++--
docs/assets/gui/classify.png | Bin 244933 -> 154547 bytes
docs/assets/gui/home.png | Bin 419821 -> 313728 bytes
docs/assets/gui/split-fastq.png | Bin 246752 -> 156464 bytes
frontend/index.html | 2 +-
galaxy/tools/pathotypr/macros.xml | 2 +-
pathotypr-core/Cargo.toml | 2 +-
src-tauri/Cargo.toml | 2 +-
src-tauri/tauri.conf.json | 2 +-
14 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml
index b5610f3..aada30f 100644
--- a/.github/DISCUSSION_TEMPLATE/q-a.yml
+++ b/.github/DISCUSSION_TEMPLATE/q-a.yml
@@ -31,7 +31,7 @@ body:
attributes:
label: Version
description: The output of `pathotypr --version`, or the version the desktop app shows.
- placeholder: "pathotypr 1.0.2"
+ placeholder: "pathotypr 1.0.3"
validations:
required: true
diff --git a/.github/DISCUSSION_TEMPLATE/studies-using-pathotypr.yml b/.github/DISCUSSION_TEMPLATE/studies-using-pathotypr.yml
index 7e554e5..0aba427 100644
--- a/.github/DISCUSSION_TEMPLATE/studies-using-pathotypr.yml
+++ b/.github/DISCUSSION_TEMPLATE/studies-using-pathotypr.yml
@@ -33,7 +33,7 @@ body:
and genomes with no hits were dropped from the summary rather than
reported as unclassified. An analysis run on draft assemblies with 1.0.0
wants reading with that in mind.
- placeholder: pathotypr 1.0.2
+ placeholder: pathotypr 1.0.3
validations:
required: true
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index a025ea3..a94702c 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -19,7 +19,7 @@ body:
attributes:
label: pathotypr version
description: Output of `pathotypr --version`, or the version shown in the desktop app.
- placeholder: "e.g. 1.0.2"
+ placeholder: "e.g. 1.0.3"
validations:
required: true
diff --git a/.github/ISSUE_TEMPLATE/unexpected_results.yml b/.github/ISSUE_TEMPLATE/unexpected_results.yml
index 3ba432f..b24e10b 100644
--- a/.github/ISSUE_TEMPLATE/unexpected_results.yml
+++ b/.github/ISSUE_TEMPLATE/unexpected_results.yml
@@ -17,7 +17,7 @@ body:
id: version
attributes:
label: pathotypr version
- placeholder: "e.g. 1.0.2"
+ placeholder: "e.g. 1.0.3"
validations:
required: true
diff --git a/CITATION.cff b/CITATION.cff
index d6bc0d4..a1ba260 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -11,8 +11,8 @@ authors:
given-names: Mireia
orcid: "https://orcid.org/0000-0003-0752-0538"
affiliation: "Institute for Integrative Systems Biology (I2SysBio), CSIC - University of Valencia"
-version: 1.0.2
-date-released: 2026-08-12
+version: 1.0.3
+date-released: 2026-11-01
license: AGPL-3.0-only
repository-code: "https://github.com/PathoGenOmics-Lab/pathotypr"
url: "https://github.com/PathoGenOmics-Lab/pathotypr"
diff --git a/Cargo.lock b/Cargo.lock
index 8d171fa..7b6dac9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3013,7 +3013,7 @@ checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pathotypr-core"
-version = "1.0.2"
+version = "1.0.3"
dependencies = [
"anyhow",
"bincode",
@@ -3042,7 +3042,7 @@ dependencies = [
[[package]]
name = "pathotypr-gui"
-version = "1.0.2"
+version = "1.0.3"
dependencies = [
"env_logger",
"futures-util",
diff --git a/docs/assets/gui/classify.png b/docs/assets/gui/classify.png
index 277439711b021de6e491ddb43f17934cb45fd7ef..5d6ccab1bd6c18a9f29d5b93291041eb580e4830 100644
GIT binary patch
literal 154547
zcmeFZWk8f&_dTov1|f<90#Z`a($XN^N;lFC(mhB^NOug~okN2nCBo21gVYS&Fy#OE
zJoo+lKEL1J`GO!Y=Q?Mfz1LoAZ9?BGO5tDDw6?pPx^V_b%G#5o)}Ya&sf0kPfGyR1W({dH?l&f8S>q&(J?G
zF{z@9qf_ULHMblsH5*&sbfoa`^OLyEeRD|PzjkM-<*;8^-5v5?KZC%dQ&PI`+>xNB
z=*+we-t9lHEb(EsfBy|W%CbGt{J&4LRMGq}{_j&+uK)i(@BDw-1mllcoRnckcU3S%
zKmOl7!ib(|@?`qwt3hZeYybDCjWkK
zr!OWY2S>PHY>xXx0?8*$8X1w#!i=J)d&0v_P8#Yj%QUOYL<26iU1@}bAQL6N#9UUY
zmHK+{VqV^+5L|LuCHO;J+)Dkn)XYrse;4o`Qv_YT-$85#U+ncH^WZ|87pn7Diou+l
z0d9sOQkavrK%lMt{7-VVu>sRZ*OvKq_k&ov%$NP8&18NFX=yEvYb9MFxS7Jf-^^;&
zO4ZA)CKzmI>R7;2>hv?~+|0x5g~@lvk@^fhcH9mQ4hm@vOI?{h-1)w@kj=c-)>aLD
z50|0zrp;sm=G5DhsZ8vD9#(|@&b?CV#s+GRVPqN=KaTE}w=oECVhtkH
z)jm*SaXYO~k^5fBs3#^>4Vq{AtRo9EF>!Fzdcjuw8DQ=B)3x@qJN~|3yjy%)U1EfZUljjv=Bmhdtl{Zn;6nhp)u-rD~;GZJy=JUF5Shrs3xO;Pyn42^NTj
zD1slVP$?8j*q(2JY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