|
| 1 | +"""Add batches of extra shuffles to a saved co-expression null. |
| 2 | +
|
| 3 | +Reads the saved outputs of alzheimers_coexpression_null.py in DIR and every |
| 4 | +batch under DIR/null_batches/ (written with --first-shuffle and --batch-dir), |
| 5 | +checks that each batch refit the same observed panel, then rewrites the |
| 6 | +outputs from all shuffles together. Per-gene p-values get a Benjamini-Hochberg |
| 7 | +adjusted column (p_adj) across the observed panel. |
| 8 | +
|
| 9 | +Usage: |
| 10 | + python alzheimers_coexpression_null_merge.py --out-dir DIR |
| 11 | +
|
| 12 | +Outputs (to DIR, overwritten): |
| 13 | +- alzheimers_coexpression_null_runs.csv |
| 14 | +- alzheimers_coexpression_null_flip_rates.csv |
| 15 | +- alzheimers_coexpression_null_panels.csv |
| 16 | +- alzheimers_coexpression_null_gene_frequency.csv (with p_adj) |
| 17 | +- alzheimers_coexpression_null_pvalues.csv |
| 18 | +- alzheimers_coexpression_null_flip_rates.png / .pdf |
| 19 | +""" |
| 20 | + |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import argparse |
| 24 | +from pathlib import Path |
| 25 | + |
| 26 | +import matplotlib.pyplot as plt |
| 27 | +import pandas as pd |
| 28 | +from scipy.stats import false_discovery_control |
| 29 | + |
| 30 | +import recursieve |
| 31 | +from alzheimers_coexpression_null import plot_flip_rates |
| 32 | + |
| 33 | +PREFIX = "alzheimers_coexpression_null_" |
| 34 | +TABLES = ("runs", "flip_rates", "panels") |
| 35 | + |
| 36 | + |
| 37 | +def read_tables(folder: Path) -> dict: |
| 38 | + return {key: pd.read_csv(folder / f"{PREFIX}{key}.csv") for key in TABLES} |
| 39 | + |
| 40 | + |
| 41 | +def observed_panel(panels: pd.DataFrame) -> list: |
| 42 | + obs = panels[panels["run"] == "observed"].sort_values("rank") |
| 43 | + return obs["gene"].tolist() |
| 44 | + |
| 45 | + |
| 46 | +def main() -> None: |
| 47 | + plt.rcParams.update({"font.family": "Arial", "font.size": 12, |
| 48 | + "pdf.fonttype": 42, "ps.fonttype": 42}) |
| 49 | + parser = argparse.ArgumentParser(description=__doc__) |
| 50 | + parser.add_argument("--out-dir", type=Path, required=True) |
| 51 | + parser.add_argument("--flip-threshold", type=float, default=0.01, |
| 52 | + help="Stop threshold drawn on the flip-rate plot") |
| 53 | + args = parser.parse_args() |
| 54 | + out_dir = args.out_dir |
| 55 | + |
| 56 | + saved = read_tables(out_dir) |
| 57 | + panel = observed_panel(saved["panels"]) |
| 58 | + batches = sorted((out_dir / "null_batches").glob("*/")) |
| 59 | + if not batches: |
| 60 | + raise SystemExit(f"No batches in {out_dir / 'null_batches'}") |
| 61 | + |
| 62 | + merged = {key: [saved[key]] for key in TABLES} |
| 63 | + for batch in batches: |
| 64 | + tables = read_tables(batch) |
| 65 | + if observed_panel(tables["panels"]) != panel: |
| 66 | + raise SystemExit(f"{batch.name}: observed panel differs from the saved one") |
| 67 | + for key in TABLES: |
| 68 | + df = tables[key] |
| 69 | + merged[key].append(df[df["run"] != "observed"]) |
| 70 | + print(f"Added {batch.name}") |
| 71 | + |
| 72 | + # rerunning the merge must not count a shuffle twice |
| 73 | + runs = pd.concat(merged["runs"], ignore_index=True).drop_duplicates("run", keep="first") |
| 74 | + flips = pd.concat(merged["flip_rates"], ignore_index=True).drop_duplicates(["run", "iteration"]) |
| 75 | + panels = pd.concat(merged["panels"], ignore_index=True).drop_duplicates(["run", "rank"]) |
| 76 | + |
| 77 | + freq = recursieve.recursieve._null_gene_frequency(panels) |
| 78 | + freq["p_adj"] = false_discovery_control(freq["p_value"], method="bh") |
| 79 | + pvalues = recursieve.recursieve._null_pvalues(runs) |
| 80 | + |
| 81 | + outputs = {"runs": runs, "flip_rates": flips, "panels": panels, |
| 82 | + "gene_frequency": freq, "pvalues": pvalues} |
| 83 | + for key, df in outputs.items(): |
| 84 | + df.to_csv(out_dir / f"{PREFIX}{key}.csv", index=False) |
| 85 | + plot_flip_rates(flips, args.flip_threshold, out_dir / f"{PREFIX}flip_rates") |
| 86 | + |
| 87 | + n = runs["run"].ne("observed").sum() |
| 88 | + print(f"{n} shuffles; {int((freq['p_adj'] < 0.05).sum())}/{len(freq)} genes with p_adj < 0.05") |
| 89 | + print(pvalues.round(4).to_string(index=False)) |
| 90 | + |
| 91 | + |
| 92 | +if __name__ == "__main__": |
| 93 | + main() |
0 commit comments