"""GO/KEGG checks fixed in RULES_go_terms.txt. Data only. Fact-Checked Science ("Our analysis"), https://factchecked.science/planthopper-magnetic-genes/ Data: Xie, W., et al. (2026), Dryad, doi:10.5061/dryad.r4xgxd2vx (CC0); make the input folder with prepare_inputs.py, then pass /dataset (or /field for igrf_route.py) as the script's usage says. Usage: python3 go_terms.py """ import json import os import re import sys import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from xlsx_reader import read_xlsx # noqa: E402 FIG2 = "Raw_data_for_Figure2-Functional enrichment of transcriptional responses under different magnetic field conditions.xlsx" CATS = { "central carbon": ["glycoly", "gluconeogen", "citrate cycle", "tca", "tricarboxylic", "pyruvate", "pentose phosphate", "carbon metabolism", "glucose", "fructose and mannose", "galactose", "starch and sucrose", "glyoxylate"], "amino-acid": ["amino acid", "alanine", "arginine", "asparagine", "aspartate", "cysteine", "glutamate", "glutamine", "glycine", "histidine", "isoleucine", "leucine", "lysine", "methionine", "phenylalanine", "proline", "serine", "threonine", "tryptophan", "tyrosine", "valine", "beta-alanine"], "peroxisomal": ["peroxisom"], "redox": ["oxidoreductase", "oxidation-reduction", "redox", "glutathione", "antioxidant", "peroxidase", "catalase", "superoxide", "reactive oxygen", "nadp", "oxidative stress"], "clock-related": ["circadian", "rhythm", "clock", "entrainment"], } def bh(p): p = np.asarray(p, float) n = len(p) o = np.argsort(p) r = p[o] * n / np.arange(1, n + 1) q = np.minimum.accumulate(r[::-1])[::-1] out = np.empty(n) out[o] = np.minimum(q, 1) return out def table(sheet): rows = sheet["rows"] title = rows[0][0] if rows and rows[0] else None hdr = [str(x) for x in rows[1] if x is not None] recs = [] for r in rows[2:]: if not r or all(x is None for x in r): continue d = {h: (r[i] if i < len(r) else None) for i, h in enumerate(hdr)} recs.append(d) return title, hdr, recs def cats_of(desc): s = str(desc).lower() return [c for c, words in CATS.items() if any(w in s for w in words)] def main(): folder, out_path = sys.argv[1], sys.argv[2] wb = read_xlsx(os.path.join(folder, FIG2)) names = list(wb.keys()) out = {"sheets": names, "per_sheet": {}} for nm in names: title, hdr, recs = table(wb[nm]) p = np.array([float(r["pvalue"]) for r in recs]) pa = np.array([float(r["p.adjust"]) for r in recs]) q = np.array([float(r["qvalue"]) for r in recs]) info = {"title": title, "n_terms": len(recs), "n_padj_lt_0.05": int((pa < 0.05).sum()), "n_q_lt_0.05": int((q < 0.05).sum()), "n_p_lt_0.05": int((p < 0.05).sum()), "max_pvalue_in_sheet": float(p.max()), "min_pvalue": float(p.min())} info["BH_within_sheet_max_abs_diff_vs_padj"] = float(np.max(np.abs(bh(p) - pa))) if "ONTOLOGY" in hdr: per = {} for ont in sorted(set(r["ONTOLOGY"] for r in recs)): idx = [i for i, r in enumerate(recs) if r["ONTOLOGY"] == ont] per[ont] = {"n_terms": len(idx), "n_padj_lt_0.05": int((pa[idx] < 0.05).sum()), "BH_within_ontology_max_abs_diff": float(np.max(np.abs(bh(p[idx]) - pa[idx])))} # added after the fresh review: each ontology's own tests, from padj = p * m / rank within it for ont in per: idx = sorted([i for i, r in enumerate(recs) if r["ONTOLOGY"] == ont], key=lambda i: p[i]) ms = [pa[i] * (k + 1) / p[i] for k, i in enumerate(idx) if pa[i] < 1 and p[i] > 0] per[ont]["implied_tests_lower_bound"] = round(max(ms), 1) if ms else None info["per_ontology"] = per # implied number of tested terms: padj = p * m / rank -> m = padj * rank / p for rows where monotone step holds order = np.argsort(p) ms = [] for rank, i in enumerate(order, 1): if pa[i] < 1 and p[i] > 0: ms.append(pa[i] * rank / p[i]) info["implied_m_from_smallest_p"] = float(ms[0]) if ms else None sig = [{"ID": r.get("ID"), "Description": r.get("Description"), "ONTOLOGY": r.get("ONTOLOGY"), "pvalue": float(r["pvalue"]), "p.adjust": float(r["p.adjust"]), "Count": r.get("Counts", r.get("Count")), "categories": cats_of(r.get("Description"))} for r in recs if float(r["p.adjust"]) < 0.05] info["terms_padj_lt_0.05"] = sig nominal_cat = {} for c in CATS: best = [r for r in recs if c in cats_of(r.get("Description"))] if best: b = min(best, key=lambda r: float(r["pvalue"])) nominal_cat[c] = {"best_term": b.get("Description"), "pvalue": float(b["pvalue"]), "p.adjust": float(b["p.adjust"]), "n_terms_padj_lt_0.05": sum(1 for r in best if float(r["p.adjust"]) < 0.05)} else: nominal_cat[c] = None info["categories"] = nominal_cat out["per_sheet"][nm] = info if nm.replace(" ", "") in ("Fig.2A",): look = {} for want in ["lipid transporter activity", "response to light stimulus", "flavin adenine dinucleotide binding"]: hit = [r for r in recs if str(r.get("Description")).strip().lower() == want] look[want] = [{k: hit[0].get(k) for k in ("ONTOLOGY", "ID", "GeneRatio", "BgRatio", "pvalue", "p.adjust", "qvalue", "geneID", "Counts")}] if hit else [] out["G1_G2_terms"] = look with open(out_path, "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1, default=float) for nm, info in out["per_sheet"].items(): print("==", nm, "|", info["title"]) print(" terms %d | p<0.05 %d | p.adjust<0.05 %d | q<0.05 %d | max p in sheet %.4g | BH-within-sheet diff %.3g | implied m %.1f" % ( info["n_terms"], info["n_p_lt_0.05"], info["n_padj_lt_0.05"], info["n_q_lt_0.05"], info["max_pvalue_in_sheet"], info["BH_within_sheet_max_abs_diff_vs_padj"], info["implied_m_from_smallest_p"] or float("nan"))) if "per_ontology" in info: print(" per ontology:", info["per_ontology"]) for t in info["terms_padj_lt_0.05"]: print(" SIG", t["ONTOLOGY"], t["ID"], t["Description"], "| p %.3g | padj %.3g | n %s | cats %s" % (t["pvalue"], t["p.adjust"], t["Count"], t["categories"])) print(" categories (best term):", json.dumps(info["categories"])) print(json.dumps(out.get("G1_G2_terms"), indent=1)) if __name__ == "__main__": main()