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/12] 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/12] 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/12] 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.

-
-
-
- -
@@ -1561,37 +1550,11 @@

Options

-
- -
- - Advanced speed options (optional) - ?These options are applied only when Strict percentages is disabled. - -
-
-
- - -
- -
- - -
-
- - -
-
- -
-
+
+ +
-
+
If you need strict reproducibility with old reports, keep Strict percentages enabled and leave advanced options untouched. diff --git a/frontend/js/config.js b/frontend/js/config.js index bbbfa75..504d80b 100644 --- a/frontend/js/config.js +++ b/frontend/js/config.js @@ -74,13 +74,7 @@ export const defaultParameters = { match: { 'match-kmer': 21, 'match-threads': '', - 'match-max-ref-freq': 0, - 'match-coarse-top-n': 128, - 'match-coarse-stride': 8, - 'match-early-stop-confidence': 0, - 'match-early-stop-min-kmers': 1000000, - 'match-strict-percentages': true, - 'match-auto-tune': true + 'match-min-kmer-count': 1 } }; diff --git a/frontend/js/forms.js b/frontend/js/forms.js index 31ebb50..98fff7c 100644 --- a/frontend/js/forms.js +++ b/frontend/js/forms.js @@ -338,17 +338,7 @@ async function loadDemoData() { document.getElementById('match-kmer').value = 31; document.getElementById('match-threads').value = 4; - document.getElementById('match-max-ref-freq').value = 0; - // These two controls are optional in the DOM; guard the assignments so a - // missing element does not throw a TypeError and abort the demo loader. - const matchCoarseTopN = document.getElementById('match-coarse-top-n'); - if (matchCoarseTopN) matchCoarseTopN.value = 128; - const matchCoarseStride = document.getElementById('match-coarse-stride'); - if (matchCoarseStride) matchCoarseStride.value = 8; - document.getElementById('match-early-stop-confidence').value = 0; - document.getElementById('match-early-stop-min-kmers').value = 1000000; - document.getElementById('match-strict-percentages').checked = true; - document.getElementById('match-auto-tune').checked = true; + document.getElementById('match-min-kmer-count').value = 1; saveFormState(); @@ -481,13 +471,7 @@ export function saveFormState() { 'splitfq-nested': document.getElementById('splitfq-nested')?.checked, 'match-kmer': document.getElementById('match-kmer')?.value, 'match-threads': document.getElementById('match-threads')?.value, - 'match-max-ref-freq': document.getElementById('match-max-ref-freq')?.value, - 'match-coarse-top-n': document.getElementById('match-coarse-top-n')?.value, - 'match-coarse-stride': document.getElementById('match-coarse-stride')?.value, - 'match-early-stop-confidence': document.getElementById('match-early-stop-confidence')?.value, - 'match-early-stop-min-kmers': document.getElementById('match-early-stop-min-kmers')?.value, - 'match-strict-percentages': document.getElementById('match-strict-percentages')?.checked, - 'match-auto-tune': document.getElementById('match-auto-tune')?.checked + 'match-min-kmer-count': document.getElementById('match-min-kmer-count')?.value }; localStorage.setItem('pathotypr-form-state', JSON.stringify(state)); } @@ -1276,39 +1260,13 @@ async function handleMatchSubmit(e) { min: 1, integer: true }); - const maxRefFreq = parseNumberField('match-max-ref-freq', { - label: 'Max reference k-mer frequency', - fallback: 0, - min: 0, - max: 100 - }); - const coarseTopN = parseNumberField('match-coarse-top-n', { - label: 'Coarse candidate references (top N)', - fallback: 128, - min: 0, - integer: true - }); - const coarseStride = parseNumberField('match-coarse-stride', { - label: 'Coarse scan stride', - fallback: 8, - min: 1, - integer: true - }); - const earlyStopConfidence = parseNumberField('match-early-stop-confidence', { - label: 'Early-stop confidence', - fallback: 0, - min: 0, - max: 1 - }); - const earlyStopMinKmers = parseNumberField('match-early-stop-min-kmers', { - label: 'Early-stop minimum k-mers', - fallback: 1000000, + const minKmerCount = parseNumberField('match-min-kmer-count', { + label: 'Minimum k-mer count', + fallback: 1, min: 1, integer: true }); - const autoTune = document.getElementById('match-auto-tune')?.checked ?? true; - const strictPercentages = document.getElementById('match-strict-percentages')?.checked ?? true; - if (!kmerSize.ok || !threads.ok || !maxRefFreq.ok || !coarseTopN.ok || !coarseStride.ok || !earlyStopConfidence.ok || !earlyStopMinKmers.ok) return; + if (!kmerSize.ok || !threads.ok || !minKmerCount.ok) return; let references = null; let index = null; @@ -1345,13 +1303,7 @@ async function handleMatchSubmit(e) { output, kmer_size: kmerSize.value, threads: threads.value, - max_ref_freq: maxRefFreq.value, - coarse_top_n: coarseTopN.value, - coarse_stride: coarseStride.value, - early_stop_confidence: earlyStopConfidence.value, - early_stop_min_kmers: earlyStopMinKmers.value, - strict_percentages: strictPercentages, - auto_tune: autoTune + min_kmer_count: minKmerCount.value }, onResult: async (result, runId) => handleResultWithModal(result, output, 'match', fastqs, runId) diff --git a/galaxy/tools/pathotypr/pathotypr_match.xml b/galaxy/tools/pathotypr/pathotypr_match.xml index 23af8ea..a3f5dd6 100644 --- a/galaxy/tools/pathotypr/pathotypr_match.xml +++ b/galaxy/tools/pathotypr/pathotypr_match.xml @@ -51,7 +51,7 @@ pathotypr match - + @@ -99,6 +99,7 @@ Column Meaning ``Query_Files`` The read files that went in ``Best_Match_Reference`` The record name of the winning reference ``Shared_Kmer_Fraction`` Fraction of query k-mers contained in it, 0 to 1 +``Query_Kmers`` The denominator: k-mers kept from the query ============================= ================================================ A fraction near 1 means the reads are essentially that reference. A low fraction diff --git a/pathotypr-core/src/match/mod.rs b/pathotypr-core/src/match/mod.rs index 7326c6f..55bdfcd 100644 --- a/pathotypr-core/src/match/mod.rs +++ b/pathotypr-core/src/match/mod.rs @@ -89,10 +89,13 @@ pub struct Args { pub excel: bool, /// Minimum k-mer count to keep when filtering query k-mers. - /// K-mers with fewer occurrences than this are discarded as sequencing noise. - /// Set to 1 to disable singleton filtering (keep all k-mers). - /// Default: 2 (remove singletons). Only applied when total unique k-mers > 100k. - #[arg(long = "min-kmer-count", default_value_t = 2)] + /// K-mers with fewer occurrences than this are discarded as sequencing + /// noise, and both the shared count and the total are then taken over what + /// is left. Default: 1, which keeps every k-mer. Raise it for deep data + /// where singletons really are error, knowing that it lowers every + /// reference's score and that scores from different settings are not + /// comparable. + #[arg(long = "min-kmer-count", default_value_t = 1)] pub min_kmer_count: u32, /// Cancellation token for stopping the task (GUI only, not CLI). @@ -205,7 +208,12 @@ fn count_kmers_from_fastqs( break; } }; - for (_, kmer, _) in seqrec.sequence().bit_kmers(k, true) { + // `sequence()` keeps the newlines a wrapped FASTA has in it, + // and every k-mer window straddling one is then skipped as + // holding an invalid base: the same 1 Mb sequence gave 999,970 + // k-mers on one line and 571,420 wrapped at 70 columns. The + // reference side has always used `seq()`. + for (_, kmer, _) in seqrec.seq().bit_kmers(k, true) { *local_counts.entry(kmer.0).or_insert(0) += 1; kmer_count += 1; @@ -238,20 +246,24 @@ fn count_kmers_from_fastqs( // Filter low-count k-mers (noise reduction). // Only applied when dataset is large enough that singletons are likely errors. + // The filter applies or it does not. 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 nobody can see: on 1 Mb of 0.15x reads, 1,450 of + // them scored 0.8886 and 1,500 of them scored a perfect 1.0000, because + // the second run crossed the threshold, threw away 95% of its k-mers, and + // divided by the remainder. Below a few fold coverage a true k-mer is seen + // once, so dropping singletons there discards the very evidence that tells + // two references apart and leaves repeats, which match both. + let before_count = kmer_counts.len(); + info!(" Unique k-mers in the query: {}", before_count); if min_kmer_count > 1 { - let before_count = kmer_counts.len(); - info!(" Raw k-mer count: {}", before_count); - - if before_count > 100_000 { - let threshold = min_kmer_count; - kmer_counts.retain(|_, &mut count| count >= threshold); - let after_count = kmer_counts.len(); - let reduction = 100.0 * (1.0 - (after_count as f64 / before_count as f64)); - info!( - "📉 Filtered k-mers with count < {} (noise): {} -> {} unique k-mers (reduced by {:.1}%).", - threshold, before_count, after_count, reduction - ); - } + kmer_counts.retain(|_, &mut count| count >= min_kmer_count); + let after_count = kmer_counts.len(); + let reduction = 100.0 * (1.0 - (after_count as f64 / before_count as f64)); + warn!( + "📉 Dropped k-mers seen fewer than {} times: {} -> {} unique ({:.1}% of them). The score below is a fraction of what is left, not of the data, so it cannot be compared with a run at another setting.", + min_kmer_count, before_count, after_count, reduction + ); } Ok(kmer_counts) @@ -326,12 +338,15 @@ pub fn run(args: Args) -> AppResult<()> { ); } // Flatten all files back for processing (Match processes all files together) - detection_result - .samples - .values() - .flatten() - .cloned() - .collect() + { + // The map is a HashMap, whose order varies between processes: + // twenty identical runs printed six different orders of + // Query_Files. Sorting by sample name settles it, as + // classify_split_fastq already does with the same map. + let mut samples: Vec<_> = detection_result.samples.iter().collect(); + samples.sort_by(|(left, _), (right, _)| left.cmp(right)); + samples.into_iter().flat_map(|(_, files)| files.clone()).collect() + } } else { args.fastqs.clone() } @@ -387,14 +402,14 @@ pub fn run(args: Args) -> AppResult<()> { writeln!( writer, - "Query_Files\tBest_Match_Reference\tShared_Kmer_Fraction" + "Query_Files\tBest_Match_Reference\tShared_Kmer_Fraction\tQuery_Kmers" )?; if let Some((best_header, best_score)) = best_match { let query_files_str = fastq_files_to_process.join(","); writeln!( writer, - "{}\t{}\t{:.4}", - query_files_str, best_header, best_score + "{}\t{}\t{:.4}\t{}", + query_files_str, best_header, best_score, total_query_kmers as u64 )?; if args.excel { @@ -403,16 +418,19 @@ pub fn run(args: Args) -> AppResult<()> { "Query_Files", "Best_Match_Reference", "Shared_Kmer_Fraction", + "Query_Kmers", ]; let rows = vec![vec![ query_files_str, best_header, format!("{:.4}", best_score), + (total_query_kmers as u64).to_string(), ]]; - if let Err(e) = crate::common::write_excel_file(path, &headers, &rows) { - warn!("⚠️ Could not write Excel file: {}", e); - } else { - info!("📊 Excel file written to {}", path); + match crate::common::write_excel_file(path, &headers, &rows) { + // The workbook is at the .xlsx path the writer returns, + // not at the .tsv path that was asked for. + Ok(xlsx_path) => info!("📊 Excel file written to {}", xlsx_path), + Err(e) => warn!("⚠️ Could not write Excel file: {}", e), } } } diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index e329c2f..951f200 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -775,7 +775,9 @@ pub async fn run_match( early_stop_confidence: params.early_stop_confidence.unwrap_or(0.0), early_stop_min_kmers: params.early_stop_min_kmers.unwrap_or(1_000_000), strict_percentages: params.strict_percentages.unwrap_or(true), - min_kmer_count: params.min_kmer_count.unwrap_or(2), + // 1, like the CLI: dropping singletons throws away the evidence that + // tells two references apart whenever coverage is low. + min_kmer_count: params.min_kmer_count.unwrap_or(1), excel: params.excel.unwrap_or(true), }; From d1850d7d4612aade567c65f606160364a34378c6 Mon Sep 17 00:00:00 2001 From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:03:01 +0100 Subject: [PATCH 04/12] Hold out the same share of every lineage The single test split was a plain shuffle, so a lineage with few genomes was often left out and the accuracy described only the others. Every lineage with two genomes or more is now tested, and the report adds the mean accuracy per lineage, naming those below 100%. --- pathotypr-core/src/train.rs | 201 +++++++++++++++++++++++++++++++----- 1 file changed, 173 insertions(+), 28 deletions(-) diff --git a/pathotypr-core/src/train.rs b/pathotypr-core/src/train.rs index 931dc2e..b6268e1 100644 --- a/pathotypr-core/src/train.rs +++ b/pathotypr-core/src/train.rs @@ -62,6 +62,10 @@ pub struct TrainReport { /// skipped. Zero would read as a measurement. #[serde(skip_serializing_if = "Option::is_none")] pub accuracy_pct: Option, + /// The accuracy of every lineage averaged with equal weight, on the same + /// test set. Lower than `accuracy_pct` when a rare lineage is missed. + #[serde(skip_serializing_if = "Option::is_none")] + pub macro_accuracy_pct: Option, pub n_training: usize, pub n_test: usize, pub n_classes: usize, @@ -402,6 +406,79 @@ fn compute_oob_accuracy( Some((correct as f64 / evaluated as f64) * 100.0) } +/// Holds out the same share of every lineage, so the test set covers each one. +/// +/// A plain shuffle leaves a lineage of two genomes out of a 20% test set more +/// often than not, and the accuracy then describes only the lineages that +/// happened to land in it: on a panel of two common and four rare lineages, +/// 98.6% of shuffles left at least one lineage untested. Every lineage with two +/// or more genomes now gives at least one to the test set and keeps at least +/// one to learn from. Returns the training and test indices, and how many +/// lineages had too few genomes to be tested at all. +fn stratified_split( + y_data: &[usize], + num_classes: usize, + test_split: f64, + seed: u64, +) -> (Vec, Vec, usize) { + let mut by_class: Vec> = vec![Vec::new(); num_classes]; + for (i, &class) in y_data.iter().enumerate() { + if class < num_classes { + by_class[class].push(i); + } + } + let mut rng = SmallRng::seed_from_u64(seed); + let (mut train, mut test) = (Vec::new(), Vec::new()); + let mut untested = 0usize; + for members in &mut by_class { + if members.is_empty() { + continue; + } + members.shuffle(&mut rng); + let n = members.len(); + let mut held_out = (n as f64 * test_split).round() as usize; + if test_split > 0.0 && n >= 2 { + held_out = held_out.max(1); + } + held_out = held_out.min(n.saturating_sub(1)); + if held_out == 0 { + untested += 1; + } + test.extend_from_slice(&members[..held_out]); + train.extend_from_slice(&members[held_out..]); + } + (train, test, untested) +} + +/// Correct and total per lineage over a test set, voted the way predict votes. +fn per_class_results( + trees: &[SparseDecisionTree], + x_data: &[Vec<(usize, f32)>], + y_data: &[usize], + test_indices: &[usize], + num_classes: usize, + class_names: &[String], +) -> Vec<(usize, usize)> { + let mut results = vec![(0usize, 0usize); num_classes]; + for &idx in test_indices { + let mut vote_counts = vec![0u16; num_classes]; + for tree in trees { + let pred = tree.predict_one(&x_data[idx]); + if pred < num_classes { + vote_counts[pred] += 1; + } + } + let truth = y_data[idx]; + if truth < num_classes { + results[truth].1 += 1; + if most_voted(&vote_counts, class_names) == truth { + results[truth].0 += 1; + } + } + } + results +} + /// Evaluate an ensemble on a test set, returning accuracy percentage. fn evaluate_ensemble( trees: &[SparseDecisionTree], @@ -556,6 +633,7 @@ pub fn run(args: Args) -> AppResult { // 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 mut macro_accuracy_pct: Option = None; let n_training; let n_test; let mut cv_fold_accuracies: Vec = Vec::new(); @@ -596,24 +674,19 @@ pub fn run(args: Args) -> AppResult { n_training = n_total; n_test = 0usize; } else { - // --- Single train/test split (legacy behavior) --- - // Reproduce the same shuffle as split_train_test with seed 42 - let mut all_indices: Vec = (0..n_total).collect(); - let mut rng = SmallRng::seed_from_u64(42); - all_indices.shuffle(&mut rng); - - let mut test_size = (n_total as f64 * args.test_split).round() as usize; - if n_total > 1 { - if test_size == 0 && args.test_split > 0.0 { test_size = 1; } - test_size = test_size.min(n_total - 1); - } else { - test_size = 0; + // --- Single train/test split, stratified by lineage --- + let (train_split, test_split, untested) = + stratified_split(&y_data, num_classes, args.test_split, 42); + if untested > 0 && args.test_split > 0.0 { + warn!( + " ⚠️ {} lineage(s) have a single genome and cannot be tested; the accuracy below does not cover them.", + untested + ); } - - let test_indices = &all_indices[..test_size]; - let train_indices = &all_indices[test_size..]; + let test_indices = &test_split[..]; + let train_indices = &train_split[..]; n_training = train_indices.len(); - n_test = test_size; + n_test = test_indices.len(); if !test_indices.is_empty() { info!("▶ Training evaluation ensemble ({} train, {} test)...", n_training, n_test); @@ -633,18 +706,48 @@ pub fn run(args: Args) -> AppResult { ); 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() + + // The overall figure weighs every genome the same, so a lineage + // with many genomes can carry it while a rare one fails entirely. + // The macro figure weighs every lineage the same, and the + // lineages below 100% are named. + let per_class = per_class_results( + &eval_trees, + &x_data_sparse, + &y_data, + test_indices, + num_classes, + &label_encoder.int_to_label, + ); + let tested: Vec<(usize, (usize, usize))> = per_class + .iter() + .copied() + .enumerate() + .filter(|(_, (_, total))| *total > 0) + .collect(); + if !tested.is_empty() { + let macro_pct = tested + .iter() + .map(|(_, (correct, total))| *correct as f64 / *total as f64) + .sum::() + / tested.len() as f64 + * 100.0; + macro_accuracy_pct = Some(macro_pct); + info!( + " ✅ Mean accuracy per lineage: {:.2}% over {} lineages", + macro_pct, + tested.len() ); + for (class, (correct, total)) in &tested { + if correct < total { + info!( + " {} {}/{} correct", + label_encoder.int_to_label.get(*class).map(String::as_str).unwrap_or("?"), + correct, + total + ); + } + } } } else { info!("▶ Test set is empty, so no accuracy was measured."); @@ -826,6 +929,7 @@ pub fn run(args: Args) -> AppResult { ); Ok(TrainReport { accuracy_pct, // None when nothing was evaluated + macro_accuracy_pct, n_training, n_test, n_classes: num_classes, @@ -844,7 +948,7 @@ pub fn run(args: Args) -> AppResult { #[cfg(test)] mod tests { - use super::split_train_test; + use super::{most_voted, split_train_test, stratified_split}; #[test] fn split_keeps_training_set_non_empty() { @@ -862,4 +966,45 @@ mod tests { let y = vec![]; assert!(split_train_test(&x, &y, 0.2, 42).is_err()); } + /// Every lineage with two or more genomes gives at least one to the test + /// set and keeps at least one to learn from, whatever the proportion. + #[test] + fn the_split_tests_every_lineage_it_can() { + // Two common lineages and four rare ones, the panel where a plain + // shuffle almost always left a rare lineage untested. + let mut y = Vec::new(); + for (class, n) in [(0usize, 20usize), (1, 20), (2, 2), (3, 2), (4, 2), (5, 2)] { + y.extend(std::iter::repeat(class).take(n)); + } + let (train, test, untested) = stratified_split(&y, 6, 0.2, 42); + assert_eq!(untested, 0); + assert_eq!(train.len() + test.len(), y.len()); + for class in 0..6 { + assert!(test.iter().any(|&i| y[i] == class), "lineage {class} must be tested"); + assert!(train.iter().any(|&i| y[i] == class), "lineage {class} must be learnt"); + } + // A lineage of one genome cannot be both, and is reported as untested. + let (_, test, untested) = stratified_split(&[0, 0, 0, 1], 2, 0.2, 42); + assert_eq!(untested, 1); + assert!(!test.iter().any(|&i| i == 3)); + // Even a test share that would take a whole lineage leaves it one + // genome to learn from. + let (train, test, _) = stratified_split(&[0, 0, 1, 1], 2, 0.9, 42); + for class in 0..2 { + assert!(train.iter().any(|&i| [0, 0, 1, 1][i] == class), "lineage {class} must keep a training genome"); + } + assert_eq!(test.len(), 2); + } + + /// Ties go to the label, not to whichever lineage the training FASTA + /// happened to list first. + #[test] + fn a_tie_is_settled_by_the_label() { + let names = vec!["L4".to_string(), "L2".to_string()]; + assert_eq!(most_voted(&[50u16, 50], &names), 1, "L2 sorts before L4"); + let names = vec!["L2".to_string(), "L4".to_string()]; + assert_eq!(most_voted(&[50u16, 50], &names), 0, "the same answer in the other order"); + assert_eq!(most_voted(&[10u16, 90], &names), 1, "and a clear winner still wins"); + } + } From a7f948945d7a93b43863ef3977a984cf88b691e1 Mon Sep 17 00:00:00 2001 From: Paula Ruiz Rodriguez <50167687+Paururo@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:35:58 +0100 Subject: [PATCH 05/12] Default to one sample per leaf, and say what a bucket is A node of twice --min-samples-leaf samples or fewer is never split, and the default of 5 kept the trees too shallow to separate lineages with few genomes; it is now 1 in the CLI, the app and Galaxy, which did better on every panel measured. The documentation now says that a feature bucket is the last ten bases of the canonical k-mer, which a full hash did not improve on, and the coordinates report prints the bases found at each position instead of the canonical k-mer. --- docs/algorithms/feature-hashing.md | 48 +++++++++++++++++++--- docs/algorithms/random-forest.md | 2 +- docs/train.md | 6 +-- frontend/index.html | 4 +- frontend/js/config.js | 2 +- frontend/js/forms.js | 2 +- galaxy/tools/pathotypr/pathotypr_train.xml | 2 +- pathotypr-core/src/train.rs | 17 +++++--- pathotypr-core/src/vectorizer.rs | 15 ++++++- src-tauri/src/commands.rs | 3 +- 10 files changed, 78 insertions(+), 23 deletions(-) diff --git a/docs/algorithms/feature-hashing.md b/docs/algorithms/feature-hashing.md index 73d15b3..db183b6 100644 --- a/docs/algorithms/feature-hashing.md +++ b/docs/algorithms/feature-hashing.md @@ -24,14 +24,52 @@ Sparse vector: [(bucket_42, 3.0), (bucket_1087, 1.0), ...] 1. **K-mer extraction**: Uses [needletail](https://github.com/onecodex/needletail)'s `bit_kmers()` which encodes each k-mer as a 2-bit packed `u64`. This handles canonical k-mers (choosing the lexicographically smaller of forward and reverse complement) automatically. -2. **Hashing**: The bucket index is simply `bitkmer.0 & mask` where `mask = num_buckets - 1`. +2. **Bucketing**: The bucket index is `bitkmer.0 & mask` where `mask = num_buckets - 1`. needletail packs the first base into the high bits, so masking to 20 bits keeps the **last ten bases** of the canonical k-mer. This is not a hash: see [What the buckets really are](#what-the-buckets-really-are) below. 3. **Bucket count**: 2^20 = 1,048,576 buckets. -4. **Sparse representation**: Each sequence produces a `Vec<(usize, f32)>` — only non-zero buckets are stored, sorted by bucket index. This is critical for efficiency: a typical 4.4 Mb genome at k=21 produces ~4.4M k-mers but only ~800K–1M unique bucket entries. - -!!! info "Why no extra hash function is needed" - Since needletail's 2-bit encoding already acts as a hash function (deterministic, uniform for biological sequences), no additional hash function is needed. The power-of-two constraint enables bitmask indexing (`& mask` instead of `% modulus`). +4. **Sparse representation**: Each sequence produces a `Vec<(usize, f32)>` of its non-zero buckets, sorted by bucket index. H37Rv at k=21 produces 4.41M k-mers that fall into 652,008 buckets, 62% of the space. + +## What the buckets really are + +Masking the 2-bit code keeps its last ten bases, so the buckets are the 4^10 +ten-mers, whatever k was asked for. k only decides which strand's ten bases are +kept, through the choice of canonical k-mer: + +| k | buckets occupied by H37Rv (one position in seven) | +|---|---| +| 11 | 27.8% | +| 15 | 28.2% | +| 21 | 28.2% | +| 31 | 28.3% | + +Two k-mers that share their last ten bases always share a bucket: +`AAAAAAAAAAACCCGGGTTTA` and `ACGTACGTAGACCCGGGTTTA` both land in 355068. Across +H37Rv at k=21, 96.0% of k-mer occurrences fall in a bucket shared with another +position, 6.77 of them per occupied bucket on average. + +**It costs no accuracy in what was measured.** Synthetic genomes built on the +MTB ancestor with the lineage panel's own SNPs, six per lineage to train and +four held out to predict: + +| lineages | own SNPs each | these buckets | a full 64-bit hash | +|---|---|---|---| +| L1 to L7 and A4 | 41 to 294 | 32/32 | 32/32 | +| L4.1 to L4.9 | 6 to 8 | 36/36 | 36/36 | +| A4.1 to A4.8 (*M. bovis*) | 2 to 5 | 32/32 | 32/32 | + +The full hash gave slightly more decisive votes (a mean margin of 0.61 against +0.50 on the *M. bovis* sublineages) at twice the training time, and it changes +every feature index, so it would invalidate every model already trained. With no +call to gain, the buckets stay as they are; what changes is that they are +described as what they are. + +!!! warning "Reading the importance reports" + A bucket is not one k-mer. The `kmers` column of `*.importance.tsv` lists + every k-mer of the training data that ends in the same ten bases, and the + one a split actually used is among them without being singled out. Read the + list as candidates, and confirm a candidate on the genomes before treating + it as a marker. ### Why this works diff --git a/docs/algorithms/random-forest.md b/docs/algorithms/random-forest.md index c84105f..1a0613a 100644 --- a/docs/algorithms/random-forest.md +++ b/docs/algorithms/random-forest.md @@ -122,7 +122,7 @@ The top 500 features are exported with: |---|---|---| | `n_trees` | 100 | More trees → smoother predictions, diminishing returns past ~100 | | `max_depth` | 20 | Limits tree complexity; prevents memorization of training noise | -| `min_samples_leaf` | 5 | Regularization — prevents splits that isolate individual samples | +| `min_samples_leaf` | 1 | The usual random-forest value: the bootstrap and the random choice of features already keep trees from memorising samples. It was 5, which forbade every split on panels with a few genomes per lineage. | | `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/train.md b/docs/train.md index ec2cd50..f263368 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 ` | `5` | no | Minimum samples per leaf; higher acts as regularization. | +| `--min-samples-leaf ` | `1` | no | Minimum samples per leaf. A node of `2N` samples or fewer is never split, so a high value with few genomes per lineage trains a forest of stumps; the run says so when it happens. | ### Global flags @@ -147,8 +147,8 @@ Available on every subcommand: | File | Content | |---|---| | `model.pathotypr.zst` | The trained model bundle: config (pathotypr version, k-mer size, tree count, format version), feature hasher, label encoder, and all 100 trees — serialized with bincode and zstd-compressed (level 3). This is the file you pass to [`pathotypr predict`](predict.md). | -| `model.pathotypr.importance.tsv` | The top 500 most-used feature-hash buckets across the ensemble, with the k-mers that map to each. | -| `model.pathotypr.importance.coords.tsv` | Per-occurrence genomic coordinates of the discriminant k-mers behind those top buckets. | +| `model.pathotypr.importance.tsv` | The top 500 most-used feature buckets across the ensemble, with every k-mer that falls in each. A bucket holds every k-mer sharing its last ten bases, so the list is a set of candidates, not the k-mer a split used; see [feature hashing](algorithms/feature-hashing.md#what-the-buckets-really-are). | +| `model.pathotypr.importance.coords.tsv` | Every occurrence of those candidates in the training sequences, with the bases as they read at that coordinate on the given strand. | !!! note "Accuracy is reported to the terminal, not written to a file" The single-split (or cross-validated) accuracy and the out-of-bag accuracy are logged during the run. Per-fold accuracies print at the default verbosity; `-v` adds further debug detail. diff --git a/frontend/index.html b/frontend/index.html index d409dc7..7eb5208 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -424,8 +424,8 @@

Parameters

- - + +