"""Run the DE Results tool itself on each worked example and save what it produces. The pages then show exactly what a visitor gets after clicking "Open in DE Results": the tool's own volcano plot (its SVG export) and its own enrichment results, from the same code and the same pathway libraries the site serves. Nothing here is recomputed in R. python scripts/example_tool_outputs.py [chrome path] Needs Python playwright and Chrome. Serves public/ on a local port, opens /de-results/?example=, and for each library and direction calls the tool's own prepareLib and runEnrich with its default settings. Writes, per example, into public/examples//files/: volcano.svg the tool's "Download SVG" output enrichment.json for every library and direction: settings, release, top gene sets enrichment.txt every gene set with FDR < 0.05, with its overlapping genes """ import asyncio, functools, http.server, json, sys, threading from pathlib import Path from playwright.async_api import async_playwright ROOT = Path(__file__).resolve().parent.parent PUBLIC = ROOT / "public" EXAMPLES = ["gse202069", "gse87340"] TOP = 10 RUN = """async () => { const H = S.manifest.species[S.species], out = {species: S.species, settings: { lfc: S.lfcT, padj: S.pT, min_set: MIN_SET, max_set: MAX_SET, tool: VERSION, up: S.genes.filter(x => x.s === 'up').length, down: S.genes.filter(x => x.s === 'down').length, genes: S.genes.length}, libraries: []}; for (const L of H.libraries) { await pickLib(L.id); const prep = prepareLib(S.genes, S.lib.sets), lib = {id: L.id, name: L.name, source: L.source, version: L.version}; for (const dir of ['up', 'down']) { const r = runEnrich(prep, dir, MIN_SET, MAX_SET); const sig = r.rows.filter(x => x.fdr < 0.05); lib[dir] = {background: r.N, in_direction: r.n, sets_tested: r.tested, significant: sig.length, rows: sig.map(x => ({name: x.name, k: x.k, K: x.K, expected: +x.exp.toFixed(2), fold: +x.fold.toFixed(2), p: +x.p.toPrecision(4), fdr: +x.fdr.toPrecision(4), genes: x.hit}))}; } out.libraries.push(lib); } await pickLib(H.libraries[0].id); return {result: out, svg: volcanoSVG()}; }""" class Quiet(http.server.SimpleHTTPRequestHandler): def log_message(self, *args): pass def serve(): handler = functools.partial(Quiet, directory=str(PUBLIC)) srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=srv.serve_forever, daemon=True).start() return srv def write(i, data): files = PUBLIC / "examples" / i / "files" (files / "volcano.svg").write_text(data["svg"] + "\n") res = data["result"] lines = ["library\tdirection\tgene_set\toverlap\tset_size\texpected\tfold_enrichment\tpvalue\tfdr\tgenes"] for lib in res["libraries"]: for d in ("up", "down"): for r in lib[d]["rows"]: lines.append("\t".join(map(str, [lib["name"], d, r["name"], r["k"], r["K"], r["expected"], r["fold"], r["p"], r["fdr"], ",".join(r["genes"])]))) lib[d]["rows"] = [{**{k: v for k, v in r.items() if k != "genes"}, "genes": r["genes"][:8]} for r in lib[d]["rows"][:TOP]] (files / "enrichment.txt").write_text("\n".join(lines) + "\n") (files / "enrichment.json").write_text(json.dumps(res, indent=1) + "\n") for lib in res["libraries"]: print(i, lib["name"], "up", lib["up"]["significant"], "down", lib["down"]["significant"]) async def main(chrome=None): srv = serve() base = f"http://127.0.0.1:{srv.server_address[1]}" async with async_playwright() as p: browser = await p.chromium.launch(**({"executable_path": chrome} if chrome else {})) page = await browser.new_page(viewport={"width": 1300, "height": 900}) errors = [] page.on("pageerror", lambda e: errors.append(str(e))) for i in EXAMPLES: await page.goto(f"{base}/de-results/?example={i}") await page.wait_for_function( "() => S.manifest && !S.lib.demo && S.src.startsWith('Worked example')", timeout=60000) write(i, await page.evaluate(RUN)) await browser.close() srv.shutdown() if errors: raise SystemExit("page errors: " + "; ".join(errors)) if __name__ == "__main__": asyncio.run(main(*sys.argv[1:]))