From b0445d44468ee5d8ac93c2ebe55ecde6459d12c6 Mon Sep 17 00:00:00 2001 From: Jason Stajich Date: Sat, 21 Nov 2026 08:37:17 -0800 Subject: [PATCH 1/2] Panel script: offline taxonomy by default, snapshot recorded in the run folder, strict warm-up when offline (#342) Co-Authored-By: Claude Sonnet 5.5 --- scripts/run_clade_panel.slurm | 46 ++++++++++--------- scripts/taxonomy_warmup.py | 75 +++++++++++++++++++++++++++++++ tests/test_clade_panel_warmup.py | 46 +++++++++++++++---- tests/test_taxonomy_warmup.py | 76 ++++++++++++++++++++++++++++++++ 4 files changed, 213 insertions(+), 30 deletions(-) create mode 100644 scripts/taxonomy_warmup.py create mode 100644 tests/test_taxonomy_warmup.py diff --git a/scripts/run_clade_panel.slurm b/scripts/run_clade_panel.slurm index c314eb5d..0fcecd2f 100755 --- a/scripts/run_clade_panel.slurm +++ b/scripts/run_clade_panel.slurm @@ -159,36 +159,38 @@ mv "$WORK/panel.kept.tsv" "$WORK/panel.tsv" # widened routing (one taxid routed three different ways in one pilot, several # genomes ran `exhaustive` at ~30 min each). The cache dir is pinned so every # job shares it regardless of where it was submitted from. +# Offline taxonomy (curator decision 2026-11-12, #342): a campaign never depends on the network for a lookup. MATPREDICT_OFFLINE +# defaults to 1; MATPREDICT_TAXONOMY must then name the table (build it with `matpredict curate-db build-taxonomy`; for example +# /bigdata/stajichlab/jstajich/projects/FungiDB_MATpredict/tools/taxonomy/ncbi_taxonomy.tsv.zst, snapshot 2026-10-01). A taxid that the +# snapshot lacks fails the warm-up and stops the job. MATPREDICT_OFFLINE=0 turns this off for an exploratory run (NCBI E-utilities again). +export MATPREDICT_OFFLINE="${MATPREDICT_OFFLINE:-1}" +if [[ "$MATPREDICT_OFFLINE" =~ ^(1|true|yes)$ ]]; then + if [[ -z "${MATPREDICT_TAXONOMY:-}" || ! -f "$MATPREDICT_TAXONOMY" ]]; then + echo "MATPREDICT_OFFLINE is on but MATPREDICT_TAXONOMY='${MATPREDICT_TAXONOMY:-}' is not a file on $(hostname)" >&2 + echo " set MATPREDICT_TAXONOMY to the taxonomy table, or MATPREDICT_OFFLINE=0 for an exploratory run" >&2 + exit 1 + fi + export MATPREDICT_TAXONOMY + TAXONOMY_WARMUP_STRICT="${TAXONOMY_WARMUP_STRICT:-1}" +else + TAXONOMY_WARMUP_STRICT="${TAXONOMY_WARMUP_STRICT:-0}" +fi +[[ -f "$REPO/scripts/taxonomy_warmup.py" ]] || { echo "$REPO/scripts/taxonomy_warmup.py is missing (pull the repository checkout)" >&2; exit 1; } +"$PY" "$REPO/scripts/taxonomy_warmup.py" --describe > "$OUT_DIR/TAXONOMY.txt" || { echo "could not describe the taxonomy source" >&2; exit 1; } +echo "taxonomy: $(head -1 "$OUT_DIR/TAXONOMY.txt") (record: $OUT_DIR/TAXONOMY.txt)" export MATPREDICT_CACHE_DIR="${MATPREDICT_CACHE_DIR:-$REPO/.matpredict_cache}" # No per-genome report.html in batch runs (the YAML is the result; set MATPREDICT_HTML=1 to keep it). # An env var, not --no-html: an older frozen worktree would reject the flag and ignores the variable. export MATPREDICT_HTML="${MATPREDICT_HTML:-0}" # An EMPTY answer (no lineage and no phylum, no exception) counts as a failure too: on a node without network it is # what a cache miss gives, and it left taxid 5158 (7 C. fimbriata assemblies) not_searched in the v0.9.0 run (#324). -# TAXONOMY_WARMUP_STRICT=1 stops the job when any taxid failed; the default (0) only warns, as before. +# TAXONOMY_WARMUP_STRICT=1 stops the job when any taxid failed. Its default is 1 when the run is offline (the default, #342) and 0 +# with MATPREDICT_OFFLINE=0, where the old behaviour (warn and go on) is kept. warmup_rc=0 -cut -f2 "$WORK/panel.tsv" | sort -u | "$PY" -c ' -import sys, time -from MATPredict.db.taxonomy import (default_genetic_code, default_lineage_phylum_name, - default_lineage_taxids) -bad = 0 -for line in sys.stdin: - t = int(line) - try: - lineage = default_lineage_taxids(t); phylum = default_lineage_phylum_name(t); default_genetic_code(t) - if not lineage and not phylum: - bad += 1 - print(f"taxonomy warm-up: taxid {t} returned no lineage and no phylum (empty answer)", file=sys.stderr) - except Exception as exc: - bad += 1 - print(f"taxonomy warm-up: taxid {t} failed: {exc}", file=sys.stderr) - time.sleep(0.35) -print(f"taxonomy warm-up done, {bad} failed", file=sys.stderr) -sys.exit(3 if bad else 0) -' || warmup_rc=$? +cut -f2 "$WORK/panel.tsv" | sort -u | "$PY" "$REPO/scripts/taxonomy_warmup.py" || warmup_rc=$? if [[ "$warmup_rc" -ne 0 ]]; then - echo "WARNING: taxonomy warm-up left taxids without a lineage (see above); those genomes will be not_searched" >&2 - [[ "${TAXONOMY_WARMUP_STRICT:-0}" == "1" ]] && exit 1 + echo "WARNING: taxonomy warm-up left taxids without a lineage (listed above); those genomes would be not_searched" >&2 + [[ "$TAXONOMY_WARMUP_STRICT" == "1" ]] && exit 1 fi TOTAL=$(wc -l < "$WORK/panel.tsv") diff --git a/scripts/taxonomy_warmup.py b/scripts/taxonomy_warmup.py new file mode 100644 index 00000000..7a7528a0 --- /dev/null +++ b/scripts/taxonomy_warmup.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Taxonomy warm-up and snapshot record for the panel scripts (#324, #342). + +`scripts/run_clade_panel.slurm` runs this before the genomes start: + + cut -f2 panel.tsv | sort -u | python scripts/taxonomy_warmup.py # check every taxid + python scripts/taxonomy_warmup.py --describe > TAXONOMY.txt # what answers lookups + +Check: for each taxid on stdin the lineage, phylum and genetic code are looked up once. A taxid fails when the lookup raises, or +returns an empty answer (no lineage and no phylum), which is what a cache miss gives on a node without network (#324: taxid 5158, +seven *C. fimbriata* assemblies silently not searched). With `$MATPREDICT_OFFLINE=1` and `$MATPREDICT_TAXONOMY` set a taxid that +the snapshot does not hold raises `TaxidNotInSnapshot`, so it fails here instead of being skipped later. Every failing taxid is +listed before the exit code (3 when any failed, else 0), so one run shows them all. + +`--describe` prints one line per fact (source, table path, snapshot date, sha256) for the run folder, so a campaign records which +snapshot it used. Nothing here changes a call. +""" +from __future__ import annotations + +import hashlib +import os +import sys +import time + + +def check(taxids, sleep: float = 0.0, err=sys.stderr) -> list[int]: + """The taxids that fail the lookup (raise, or no lineage and no phylum); each is reported on `err`.""" + from MATPredict.db.taxonomy import default_genetic_code, default_lineage_phylum_name, default_lineage_taxids + + bad: list[int] = [] + for t in taxids: + try: + lineage = default_lineage_taxids(t) + phylum = default_lineage_phylum_name(t) + default_genetic_code(t) + if not lineage and not phylum: + bad.append(t) + print(f"taxonomy warm-up: taxid {t} returned no lineage and no phylum (empty answer)", file=err) + except Exception as exc: # noqa: BLE001 -- reported, never swallowed + bad.append(t) + print(f"taxonomy warm-up: taxid {t} failed: {exc}", file=err) + if sleep: + time.sleep(sleep) + return bad + + +def describe() -> str: + """Lines for TAXONOMY.txt: the lookup source, the table path and snapshot date, the table's sha256.""" + from MATPredict.db import local_taxonomy as lt + + lines = [f"source: {lt.source_label()}", f"offline: {lt.offline()}"] + path = lt.configured_path() + if path is not None: + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + h.update(chunk) + lines += [f"table: {path}", f"snapshot: {lt.get_local().snapshot}", f"sha256: {h.hexdigest()}"] + else: + lines.append("table: none ($MATPREDICT_TAXONOMY unset or missing)") + return "\n".join(lines) + "\n" + + +def main(argv: list[str]) -> int: + if "--describe" in argv: + sys.stdout.write(describe()) + return 0 + taxids = [int(line) for line in sys.stdin if line.strip()] + bad = check(taxids, sleep=float(os.environ.get("TAXONOMY_WARMUP_SLEEP", "0.35"))) + print(f"taxonomy warm-up done, {len(bad)} failed" + (f": {' '.join(map(str, bad))}" if bad else ""), file=sys.stderr) + return 3 if bad else 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/test_clade_panel_warmup.py b/tests/test_clade_panel_warmup.py index cd755982..a4ceb1e9 100644 --- a/tests/test_clade_panel_warmup.py +++ b/tests/test_clade_panel_warmup.py @@ -1,4 +1,4 @@ -"""The panel script's taxonomy warm-up counts an empty answer as a failure and can stop the job (#324).""" +"""The panel script runs offline by default, records the taxonomy snapshot and stops on a taxid with no lineage (#324, #342).""" import subprocess from pathlib import Path @@ -9,14 +9,44 @@ def test_the_script_is_valid_bash(): assert subprocess.run(["bash", "-n", str(SCRIPT)], capture_output=True).returncode == 0 -def test_an_empty_lineage_and_phylum_counts_as_a_failure(): +def test_the_warm_up_is_the_tested_helper(): text = SCRIPT.read_text() - assert "if not lineage and not phylum:" in text - assert "returned no lineage and no phylum" in text - assert "sys.exit(3 if bad else 0)" in text + assert '"$REPO/scripts/taxonomy_warmup.py"' in text # behaviour tested in tests/test_taxonomy_warmup.py + assert "if not lineage and not phylum:" not in text # no second inline copy to drift -def test_strict_mode_is_opt_in_and_defaults_to_a_warning(): +def test_offline_is_the_default_and_needs_the_table(): text = SCRIPT.read_text() - assert 'TAXONOMY_WARMUP_STRICT:-0' in text # default off: the job still runs, with a warning - assert '[[ "${TAXONOMY_WARMUP_STRICT:-0}" == "1" ]] && exit 1' in text + assert 'MATPREDICT_OFFLINE="${MATPREDICT_OFFLINE:-1}"' in text + assert "is not a file on" in text and "exit 1" in text # offline with no table stops the job + + +def test_strict_warm_up_defaults_on_offline_and_off_online(): + text = SCRIPT.read_text() + assert 'TAXONOMY_WARMUP_STRICT="${TAXONOMY_WARMUP_STRICT:-1}"' in text + assert 'TAXONOMY_WARMUP_STRICT="${TAXONOMY_WARMUP_STRICT:-0}"' in text + assert '[[ "$TAXONOMY_WARMUP_STRICT" == "1" ]] && exit 1' in text + + +def test_the_snapshot_is_written_to_the_run_folder(): + text = SCRIPT.read_text() + assert '--describe > "$OUT_DIR/TAXONOMY.txt"' in text + + +def test_the_offline_block_runs_in_bash_and_stops_without_a_table(tmp_path): + """Run the offline block alone: with MATPREDICT_OFFLINE on and no table the script exits 1 with a message.""" + text = SCRIPT.read_text() + start = text.index("export MATPREDICT_OFFLINE=") + end = text.index("[[ -f \"$REPO/scripts/taxonomy_warmup.py\" ]]") + block = text[start:end] + r = subprocess.run(["bash", "-c", block + "\necho passed"], capture_output=True, text=True, + env={"PATH": "/usr/bin:/bin", "MATPREDICT_TAXONOMY": str(tmp_path / "missing.tsv.zst")}) + assert r.returncode == 1 and "is not a file on" in r.stderr and "passed" not in r.stdout + table = tmp_path / "t.tsv.zst" + table.write_text("x") + r = subprocess.run(["bash", "-c", block + '\necho "strict=$TAXONOMY_WARMUP_STRICT"'], capture_output=True, text=True, + env={"PATH": "/usr/bin:/bin", "MATPREDICT_TAXONOMY": str(table)}) + assert r.returncode == 0 and "strict=1" in r.stdout + r = subprocess.run(["bash", "-c", block + '\necho "strict=$TAXONOMY_WARMUP_STRICT"'], capture_output=True, text=True, + env={"PATH": "/usr/bin:/bin", "MATPREDICT_OFFLINE": "0"}) + assert r.returncode == 0 and "strict=0" in r.stdout diff --git a/tests/test_taxonomy_warmup.py b/tests/test_taxonomy_warmup.py new file mode 100644 index 00000000..c133f0fb --- /dev/null +++ b/tests/test_taxonomy_warmup.py @@ -0,0 +1,76 @@ +"""scripts/taxonomy_warmup.py: the panel scripts' taxonomy warm-up and snapshot record (#324, #342). Loaded by path (`scripts/` is not a package).""" +import importlib.util +import io +from pathlib import Path + +import pytest + +from MATPredict.db import local_taxonomy as lt + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "taxonomy_warmup.py" + +# root - cellular - Eukaryota - Fungi - Ascomycota (phylum) - Pachysolen (genus) - P. tannophilus (code 26) +NODES = [(1, 1, "no rank", 1), (131567, 1, "cellular root", 1), (2759, 131567, "domain", 1), (4751, 2759, "kingdom", 1), + (4890, 4751, "phylum", 1), (4917, 4890, "genus", 26), (4918, 4917, "species", 26)] +NAMES = {1: "root", 131567: "cellular organisms", 2759: "Eukaryota", 4751: "Fungi", 4890: "Ascomycota", 4917: "Pachysolen", + 4918: "Pachysolen tannophilus"} + + +def _dmp(rows): + return "".join("\t|\t".join(str(x) for x in r) + "\t|\n" for r in rows) + + +def _load(): + spec = importlib.util.spec_from_file_location("taxonomy_warmup", SCRIPT) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +@pytest.fixture +def offline_table(tmp_path, monkeypatch): + d = tmp_path / "dump" + d.mkdir() + (d / "nodes.dmp").write_text(_dmp([(t, p, r, "", 0, 1, c, 1, 1, 1, 0, 0, "") for t, p, r, c in NODES])) + (d / "names.dmp").write_text(_dmp([(t, n, "", "scientific name") for t, n in NAMES.items()])) + (d / "merged.dmp").write_text(_dmp([(99999, 4918)])) + out = tmp_path / "tax.tsv.zst" + lt.build_table(d, out, snapshot="2026-10-01") + monkeypatch.setenv("MATPREDICT_TAXONOMY", str(out)) + monkeypatch.setenv("MATPREDICT_OFFLINE", "1") + monkeypatch.setenv("TAXONOMY_WARMUP_SLEEP", "0") + return out + + +def test_taxids_in_the_snapshot_pass_including_a_merged_one(offline_table): + err = io.StringIO() + assert _load().check([4918, 99999], err=err) == [] + assert err.getvalue() == "" + + +def test_a_taxid_missing_from_the_snapshot_fails_loudly_offline(offline_table): + err = io.StringIO() + assert _load().check([4918, 123456, 5158], err=err) == [123456, 5158] + assert "taxid 123456 failed" in err.getvalue() and "snapshot 2026-10-01" in err.getvalue() + + +def test_main_exit_code_and_the_list_of_failed_taxids(offline_table, monkeypatch, capsys): + mod = _load() + monkeypatch.setattr("sys.stdin", io.StringIO("4918\n5158\n\n")) + assert mod.main([]) == 3 + assert "1 failed: 5158" in capsys.readouterr().err + monkeypatch.setattr("sys.stdin", io.StringIO("4918\n")) + assert mod.main([]) == 0 + + +def test_describe_records_snapshot_path_and_hash(offline_table): + text = _load().describe() + assert "snapshot 2026-10-01" in text.splitlines()[0] + assert "offline: True" in text and f"table: {offline_table}" in text and "snapshot: 2026-10-01" in text + assert [l for l in text.splitlines() if l.startswith("sha256: ")][0].split()[1].isalnum() + + +def test_describe_says_so_without_a_table(monkeypatch): + monkeypatch.delenv("MATPREDICT_TAXONOMY", raising=False) + monkeypatch.setenv("MATPREDICT_OFFLINE", "1") + assert "table: none" in _load().describe() From a7d9958a52ca2e117b25b297fda0649d9207a9de Mon Sep 17 00:00:00 2001 From: Jason Stajich Date: Sat, 21 Nov 2026 08:38:30 -0800 Subject: [PATCH 2/2] Changelog and CLAUDE.md: offline taxonomy for campaigns (#342) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 2 ++ CLAUDE.md | 1 + 2 files changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d772ce45..a67eb9d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ release completed. ## [Unreleased] +- Panel script `scripts/run_clade_panel.slurm` runs against the offline taxonomy snapshot by default (#342): `MATPREDICT_OFFLINE` defaults to 1 and `MATPREDICT_TAXONOMY` must name the table (the job stops with a message if it does not); the taxonomy source, table path, snapshot date and sha256 are written to `TAXONOMY.txt` in the run folder; the warm-up is now `scripts/taxonomy_warmup.py` (tested) and lists every taxid that fails, and stops the job when offline (`TAXONOMY_WARMUP_STRICT` defaults to 1 offline, 0 with `MATPREDICT_OFFLINE=0`). A taxid missing from the snapshot can no longer leave genomes silently not searched (#324). No change to detection, calls or tiers; v0.9.0 results are not redone. + - `--weak-fragment-cap-policy` (opt-in, in no preset): the "strongest core gene" is now the strongest gene of the CALLED idiomorph (`MAT1-1-*` for a MAT1-1 call, `MAT1-2-*` for MAT1-2), not of every `MAT1-*` gene (#341; curator 2026-11-12). A thin fragment of the other idiomorph no longer lowers a call; a call with no live gene of its own idiomorph is not capped. On the v0.9.0 FungiDB run the three loci the old rule capped (*A. terreus* NIH2624, *C. geophilum* 1.58, *S. schenckii* 1099-18) are kept; on the 11,906 `medium`/`high` `Ascomycota:MAT` loci of the v0.9.0 Ascomycota run the rule matches the same 66 loci either way (one, *Xylaria* XylFL0594, now names MAT1-2-1 rather than MAT1-1-3 as the deciding gene). Default off, so no run changes. `docs/notes/2026-11-19_weak-fragment-cap-idiomorph.md`. - Site: genomes whose recorded name starts with a phylum name or a qualifier (`Ascomycota sp. Antarctolithica obscura`, `uncultured Alectoria`, `cf. Caloplaca sp. 1`) get a genus where the name carries one (`curated_name`, new `name_status` column); 22 genomes move out of "(unassigned)". The results search matches any rank and the recorded name, counts how many genomes matched through another field, and a list shows the genomes with no usable genus. See `docs/notes/2026-11-12_unassigned-species-names.md`. diff --git a/CLAUDE.md b/CLAUDE.md index 995df65a..0ad3e1f5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,6 +24,7 @@ Rules for any agent (or person) working in this repository. They are short on pu - Compute nodes cannot reach GitHub over SSH. Fetch on the login node (`git fetch`, then `git rev-parse FETCH_HEAD`, then `git worktree add --detach`). - Use `--constraint=milan` (EPYC 7713) for timing-sensitive jobs. The `c01`-`c03` Opteron nodes are about 2.15x slower, so never compare timings across node types. - Do not run more than one copy of a submit command. A hung SSH call has once duplicated a job into the same output folder. +- **Campaigns use the offline taxonomy snapshot** (#342): set `MATPREDICT_TAXONOMY` (for example the FungiDB project's `tools/taxonomy/ncbi_taxonomy.tsv.zst`, snapshot 2026-10-01) before `sbatch scripts/run_clade_panel.slurm` or `submit_binned_panel.py`; the script writes `TAXONOMY.txt` (snapshot date, sha256) to the run folder, so copy that into the MANIFEST. A taxid missing from the snapshot stops the job. `MATPREDICT_OFFLINE=0` is for exploratory runs only. - Another session may be running reads work from `run-wave3` and `run-expand300` (jobs named `wave-*`, `genus-*`). Do not move those worktrees. ## Detector rules