"""Recompute the manuscript's main numerical results from the bundled source tables.""" import argparse import json from pathlib import Path import numpy as np import pandas as pd from scipy import stats from analyze import bh, groups, group_comparison, tissue_effect, TARGETS def close(actual, expected): np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=1e-9) def check_bulk(data): sample_values = pd.read_csv(data / "tissue_sample_values.csv") sample_values["patient"] = sample_values.patient.fillna("") expected = pd.read_csv(data / "tissue_effects.csv").set_index(["accession", "feature"]) summary = {} for accession, samples in sample_values.groupby("accession"): tumors, normals, paired = groups(samples.to_dict(orient="records")) features = expected.loc[accession].index effects = [ tissue_effect(samples[feature].to_numpy(), tumors, normals, paired) | {"feature": feature} for feature in features ] bh(effects) for effect in effects: keys = ["mean_difference", "ci_low", "ci_high", "p", "q", "leave_one_out_min", "leave_one_out_max"] close([effect[key] for key in keys], expected.loc[(accession, effect["feature"]), keys].to_numpy(float)) cip2a = next(effect for effect in effects if effect["feature"] == "CIP2A") assert cip2a["leave_one_out_min"] > 0 if paired: assert cip2a["tumor_higher_pairs"] == 18 summary[accession] = cip2a return summary def check_screens(data): all_scores = pd.read_csv(data / "depmap_model_scores.csv") all_scores = all_scores.loc[~all_scores.reclassified_model] expected = pd.read_csv(data / "depmap_comparison.csv").set_index("gene") rng = np.random.default_rng(149507) comparisons = [] for gene in TARGETS: subset = all_scores.loc[all_scores.gene.eq(gene)] sclc = subset.loc[subset.group.eq("SCLC"), "chronos"].to_numpy() luad = subset.loc[subset.group.eq("LUAD"), "chronos"].to_numpy() comparisons.append({"gene": gene} | group_comparison(sclc, luad, rng)) strict_luad = subset.loc[subset.group.eq("LUAD") & ~subset.model_name.isin(["HCC827 GR5", "MOR/CPR", "NCI-H2286"]), "chronos"] group_comparison(sclc, strict_luad.to_numpy(), rng) bh(comparisons) effect = next(row for row in comparisons if row["gene"] == "CIP2A") keys = ["median_sclc", "median_luad", "median_difference", "bootstrap_low", "bootstrap_high", "p", "q"] close([effect[key] for key in keys], expected.loc["CIP2A", keys].to_numpy(float)) assert (effect["n_sclc"], effect["n_luad"]) == (23, 47) r = pd.read_csv(data / "rnai.csv") assert len(r) == 23 and r.model_id.is_unique close(r.set_index("model_id").chronos.sort_index(), pd.read_csv(data / "chronos.csv").query("group == 'SCLC'").set_index("model_id").chronos.sort_index()) observed = r.dropna(subset=["dependency"]).copy() observed["rank"] = observed.dependency.rank(method="average") close(observed["rank"], observed.within_SCLC_rank) assert len(observed) == 11 top = r.nsmallest(2, "chronos").model_name.tolist() assert top == ["NCI-H211", "DMS 53"] assert observed.set_index("model_name").loc[top, "rank"].tolist() == [1, 3] correlation = stats.spearmanr(observed.chronos, observed.dependency) close(correlation.statistic, 0.27272727272727276) return { "crispr_screen_comparison": effect, "matched_models": len(observed), "spearman_rho": correlation.statistic, "spearman_p": correlation.pvalue, "highlighted_models": observed.loc[observed.model_name.isin(top), ["model_name", "chronos", "dependency", "rank"]].to_dict("records"), } def check_single_cell(data): chan = pd.read_csv(data / "chan_confirmed_primary.csv") external = pd.read_csv(data / "gse281740_cnv_effects.csv") for frame, target in ((chan, "CIP2A"), (external, "cip2a")): close(frame.cpm, frame[target] / frame.umi * 1e6) close(frame.detection, frame.detected / frame.cells) pairs = pd.read_csv(data / "pairs.csv").query("stratum == 'all'").copy() chan = chan.set_index(["patient", "group"]) external = external.query("stratum == 'all'").set_index(["sample", "group"]) for row in pairs.itertuples(): if row.cohort == "Chan": tumor = chan.loc[(row.sample, "malignant")] epithelium = chan.loc[(row.sample, "nonmalignant_epithelial")] else: tumor = external.loc[(row.sample, "CNV_supported_tumour")] epithelium = external.loc[(row.sample, "CNV_low_epithelial")] close([row.cells_malignant, row.cells_nonmalignant_epithelial, row.cpm_malignant, row.cpm_nonmalignant_epithelial], [tumor.cells, epithelium.cells, tumor.cpm, epithelium.cpm]) eligible = pairs[["cells_malignant", "cells_nonmalignant_epithelial"]].min(axis=1).ge(25) assert eligible.equals(pairs.eligible_25) assert pairs.loc[eligible].groupby("cohort").size().to_dict() == {"Chan": 2, "GSE281740": 2} assert pairs.loc[eligible, "delta_cpm"].gt(0).all() sensitivity = pd.read_csv(data / "cip2a_stability_grid.csv") assert sensitivity.groupby(["sample", "stratum"]).size().eq(30).all() and len(sensitivity) == 120 enough = sensitivity[["tumour_cells", "epithelial_cells"]].min(axis=1).ge(25) grid = {} for (sample, stratum), group in sensitivity[enough].groupby(["sample", "stratum"]): matched = group.loc[group.matched_cells.ge(25), "matched_positive"] grid[f"{sample}/{stratum}"] = { "eligible": len(group), "positive": int(group.delta_cpm.gt(0).sum()), "matched_positive_min": matched.min(), "matched_positive_max": matched.max(), } assert [grid[key]["positive"] for key in ("ru1334/all", "ru1449a/all")] == [30, 10] close([grid["ru1334/all"]["matched_positive_min"], grid["ru1449a/all"]["matched_positive_min"]], [1, .982]) low = pd.read_csv(data / "gse281740_cnv_effects.csv").query("stratum == 'low_cycle'") low = low.pivot(index="sample", columns="group", values="cpm") low_difference = low.CNV_supported_tumour - low.CNV_low_epithelial assert low_difference["ru1334"] < 0 < low_difference["ru1449a"] return {"pairs": pairs.to_dict("records"), "sensitivity": grid, "low_marker_delta_cpm": low_difference.to_dict()} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data", type=Path, default=Path("data")) parser.add_argument("--output", type=Path, default=Path("build/key_results.json")) args = parser.parse_args() summary = { "bulk": check_bulk(args.data), "genetic_screens": check_screens(args.data), "single_cell": check_single_cell(args.data), } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(summary, indent=2, allow_nan=False, default=lambda value: value.item()) + "\n", encoding="utf-8") print(f"All comparisons passed. Saved {args.output}.") if __name__ == "__main__": main()