diff --git a/scripts/build_cleanrun_tables.py b/scripts/build_cleanrun_tables.py index 46c4eb45..b24287bf 100644 --- a/scripts/build_cleanrun_tables.py +++ b/scripts/build_cleanrun_tables.py @@ -70,6 +70,14 @@ only a core gene at >= 60% identity and >= 80% coverage is listed; the other flagged genes move to `low_confidence_model_genes` (on the v0.8.1 run 18 Wallemia STE3 stops are a splice-junction mis-model, and about 90% of the flagged Boletales HD1 loci are below 50% identity, a divergent gene poorly modelled). + defective_isolates beside `defective_genes` (#291): for each listed defective gene, `gene:k/n`, the number of genomes of the SAME SPECIES + (BFD species, as in genomes.tsv) in which that gene is flagged, over the number of those genomes whose locus of the same family + lists the gene; genes `|`-joined, blank when the locus has no defective gene or the species is unknown. A real pseudogene reads + like `MTLA1:97/97`; an assembly indel like `MTLA2:1/60`. A gene that every isolate models the same wrong way (a splice junction, a low-identity + flank gene) reads like a pseudogene too, so the count tells an assembly indel from a shared feature, not a pseudogene from a + mis-model. A read of the counts, not a call: nothing uses it, tiers are unchanged. + The same counts, one row per species, family and flagged gene, are in `defective_by_species.tsv` (species, family_called, + gene, genomes_with_gene, genomes_flagged, fraction_flagged); for Basidiomycota `k` counts the genes the model check lists. core_reference the matched curated record of each live core gene of the locus (#200, curator 2026-11-07: both core genes are listed): `gene:record_id:identity:bitscore`, genes `|`-joined, one entry per gene (the entry with the highest identity, then the higher bitscore, then the smaller record_id), blank when the locus has no live core gene with a matched record. The @@ -131,7 +139,7 @@ "detection_pass", "genes_found", "verification", "genus", "family", "polished_genes", "idiomorph_margin", "margin_basis", "n_candidates", "baseline_confidence", "tier_note", "label_unsupported", "label_unsupported_reason", "high_basis", "high_basis_outside_scope", - "defective_genes", "low_confidence_model_genes", "core_reference"] + "defective_genes", "low_confidence_model_genes", "core_reference", "defective_isolates"] # ----------------------------------------------------------------------------------------------- reading reports @@ -573,6 +581,37 @@ def build(new, base, listed, samples, mucoro_names, inputs_rows, scope, mucoro=F return G, L, tally +def annotate_defective_isolates(G, L): + """Add `defective_isolates` to each locus row and return the per-species table rows (#291). + + For a species (genomes.tsv), a family and a gene: `genomes_with_gene` is the number of distinct genomes of the species whose locus of that + family lists the gene (`genes_found`, or the gene is flagged), `genomes_flagged` the number with the gene in `defective_genes`. A species + that is blank or `NA` is left out. Rows are sorted by genomes_flagged, then fraction. Report-only; nothing reads the counts.""" + species = {r["genome"]: (r.get("species") or "") for r in G} + seen, flag = defaultdict(set), defaultdict(set) + for x in L: + sp = species.get(x["genome"], "") + if not sp or sp == "NA": + continue + for gn in filter(None, str(x["genes_found"]).split("|")): + seen[(sp, x["family_called"], gn)].add(x["genome"]) + for gn in filter(None, str(x["defective_genes"]).split("|")): + seen[(sp, x["family_called"], gn)].add(x["genome"]) + flag[(sp, x["family_called"], gn)].add(x["genome"]) + for x in L: + sp = species.get(x["genome"], "") + parts = [] + if sp and sp != "NA": + for gn in filter(None, str(x["defective_genes"]).split("|")): + k = (sp, x["family_called"], gn) + parts.append(f"{gn}:{len(flag[k])}/{len(seen[k])}") + x["defective_isolates"] = "|".join(parts) + rows = [[sp, fam, gn, len(seen[(sp, fam, gn)]), len(f), f"{len(f) / len(seen[(sp, fam, gn)]):.3f}"] + for (sp, fam, gn), f in flag.items()] + rows.sort(key=lambda r: (-r[4], -float(r[5]), r[0], r[1], r[2])) + return rows + + def by_rank(G, L, rank): """Per-class (or per-order) table: the v0.6.0 columns, then locus counts for the new columns.""" col = "class_" if rank == "class" else rank @@ -666,6 +705,7 @@ def main(argv=None): G, L, tally = build(new, base, listed, load_samples(a.samples), load_mucoro_names(a.baseline_calls), inputs_rows, scope, a.layout == "mucoro", load_genus_lineage(a.genus_lineage) if a.layout == "mucoro" else None) + sp_rows = annotate_defective_isolates(G, L) os.makedirs(a.out, exist_ok=True) genome_cols, locus_cols = list(GENOME_COLS), list(LOCUS_COLS) if a.layout == "mucoro": # the run folder is SOURCE__id; split it back out for the site @@ -677,6 +717,8 @@ def main(argv=None): locus_cols.insert(0, "source") write_tsv(os.path.join(a.out, "genomes.tsv"), genome_cols, G) write_tsv(os.path.join(a.out, "loci.tsv"), locus_cols, L) + write_tsv(os.path.join(a.out, "defective_by_species.tsv"), + ["species", "family_called", "gene", "genomes_with_gene", "genomes_flagged", "fraction_flagged"], sp_rows) head, rows = by_rank(G, L, a.rank) write_tsv(os.path.join(a.out, f"by_{a.rank}.tsv"), head, rows) diff --git a/tests/test_build_cleanrun_tables_script.py b/tests/test_build_cleanrun_tables_script.py index d63320ac..f3492ae6 100644 --- a/tests/test_build_cleanrun_tables_script.py +++ b/tests/test_build_cleanrun_tables_script.py @@ -280,6 +280,10 @@ def test_end_to_end_tables(tmp_path): assert loci["G5"]["high_basis"] == "" and loci["G5"]["high_basis_outside_scope"] == "tie_break" # defective genes (#151): the locus lists them `|`-joined, the genome counts loci, an intact locus stays blank/zero assert loci["G4"]["defective_genes"] == "GAP1|MAT1-1-1" and G["G4"]["n_defective_loci"] == "1" + # per-species isolate count beside the flag (#291): one genome of the species, so every flagged gene reads 1/1; blank when nothing is flagged + assert loci["G4"]["defective_isolates"] == "GAP1:1/1|MAT1-1-1:1/1" and loci["G1"]["defective_isolates"] == "" + assert [(r["species"], r["gene"], r["genomes_with_gene"], r["genomes_flagged"]) for r in _rows(out / "defective_by_species.tsv")] == [ + ("Curvularia lunata", "GAP1", "1", "1"), ("Curvularia lunata", "MAT1-1-1", "1", "1")] assert all(loci[g]["defective_genes"] == "" for g in ("G1", "G2", "G5")) assert [G[g]["n_defective_loci"] for g in ("G1", "G2", "G3", "G5")] == ["0", "0", "0", "0"] # G3 failed: a count of 0 by = _rows(out / "by_class.tsv") @@ -303,6 +307,35 @@ def test_by_rank_counts_loci_with_a_defective_gene_not_genes(): assert {r[0]: r[-1] for r in rows} == {"C1": 2, "C2": 0} +def _row(genome, family="Ascomycota:MTL", genes="MTLA1|MTLA2", defective=""): + return dict(genome=genome, family_called=family, genes_found=genes, defective_genes=defective) + + +def test_defective_isolates_tells_a_pseudogene_from_an_assembly_indel(): + """#291: `gene:k/n` over the genomes of the same species whose locus of the same family lists the gene.""" + G = [dict(genome=f"P{i}", species="Lodderomyces parapsilosis") for i in range(3)] \ + + [dict(genome=f"A{i}", species="Candidozyma auris") for i in range(4)] + [dict(genome="U1", species="NA"), dict(genome="U2", species="")] + Lr = [_row(f"P{i}", defective="MTLA1") for i in range(3)] # flagged in every isolate: a pseudogene + Lr += [_row("A0", defective="MTLA2")] + [_row(f"A{i}") for i in (1, 2, 3)] # flagged in one of four: an indel + Lr += [_row("U1", defective="MTLA1"), _row("U2", defective="MTLA1")] # unknown species: blank + rows = bct.annotate_defective_isolates(G, Lr) + by = {r["genome"]: r["defective_isolates"] for r in Lr} + assert by["P0"] == "MTLA1:3/3" and by["A0"] == "MTLA2:1/4" and by["A1"] == "" and by["U1"] == "" and by["U2"] == "" + assert rows == [["Lodderomyces parapsilosis", "Ascomycota:MTL", "MTLA1", 3, 3, "1.000"], + ["Candidozyma auris", "Ascomycota:MTL", "MTLA2", 4, 1, "0.250"]] + + +def test_defective_isolates_keeps_families_apart_and_counts_a_flagged_gene_as_present(): + G = [dict(genome="a", species="S x"), dict(genome="b", species="S x"), dict(genome="c", species="S x")] + Lr = [_row("a", family="Ascomycota:MAT", genes="MAT1-1-1", defective="MAT1-1-1"), + _row("b", family="Ascomycota:MAT", genes="MAT1-1-1"), + _row("c", family="Ascomycota:MTL", genes="MTLA1", defective=""), + _row("b", family="Ascomycota:MTL", genes="", defective="MTLA1")] # flagged but not in genes_found: still present + bct.annotate_defective_isolates(G, Lr) + assert Lr[0]["defective_isolates"] == "MAT1-1-1:1/2" # c's MTL locus does not enter the MAT count + assert Lr[3]["defective_isolates"] == "MTLA1:1/2" # b (flagged) and c (lists it): two genomes with the gene in that family + + def test_output_is_deterministic_and_a_tarball_reads_like_the_folder(tmp_path): new, old, samples = _tree(tmp_path) tar = tmp_path / "old.tar.gz" @@ -311,7 +344,7 @@ def test_output_is_deterministic_and_a_tarball_reads_like_the_folder(tmp_path): a, b = tmp_path / "a", tmp_path / "b" bct.main(["--campaign", str(new), "--baseline", str(old), "--samples", str(samples), "--out", str(a)]) bct.main(["--campaign", str(new), "--baseline", str(tar), "--samples", str(samples), "--out", str(b)]) - for f in ("genomes.tsv", "loci.tsv", "by_class.tsv"): + for f in ("genomes.tsv", "loci.tsv", "by_class.tsv", "defective_by_species.tsv"): assert (a / f).read_bytes() == (b / f).read_bytes()