Download scripts/analyze.py from xuyun/CIP2A: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/datasets/xuyun/CIP2A/resolve/main/scripts/analyze.py
- Command line
-
hf download hf://datasets/xuyun/CIP2A/scripts/analyze.py
-
curl -L -o analyze.py https://huggingface.co/datasets/xuyun/CIP2A/resolve/main/scripts/analyze.py
14.3 kB
| """Replicate SCLC tissue signals and compare target dependencies across lung lineages.""" | |
| import argparse | |
| import csv | |
| import gzip | |
| import hashlib | |
| import json | |
| import re | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| from scipy import stats | |
| TARGETS = ("ANXA2", "CIP2A") | |
| MARKERS = ("BIRC2", "BIRC3") | |
| CONTROL_GENES = ("RPL4", "PSMA1") | |
| NF = "HALLMARK_TNFA_SIGNALING_VIA_NFKB" | |
| AU = "GOBP_MACROAUTOPHAGY" | |
| RECLASSIFIED = {"ACH-000292", "ACH-000530", "ACH-000890"} | |
| def write_csv(path, records): | |
| with path.open("w", encoding="utf-8", newline="") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=records[0]) | |
| writer.writeheader() | |
| writer.writerows(records) | |
| def bh(rows, p_key="p", q_key="q"): | |
| order = sorted(range(len(rows)), key=lambda i: rows[i][p_key]) | |
| previous = 1.0 | |
| for rank, i in reversed(list(enumerate(order, start=1))): | |
| previous = min(previous, rows[i][p_key] * len(rows) / rank) | |
| rows[i][q_key] = previous | |
| def geo_rows(path, delimiter): | |
| with gzip.open(path, "rt", encoding="utf-8-sig") as f: | |
| yield from csv.reader(f, delimiter=delimiter) | |
| def gene_symbol(value): | |
| symbol = value.strip().upper() | |
| return "CIP2A" if symbol == "KIAA1524" else symbol | |
| def read_cohort(folder, accession): | |
| paired = accession == "GSE149507" | |
| key = accession.lower() | |
| meta = {} | |
| for row in geo_rows(folder / f"{key}.meta.gz", "\t"): | |
| if row and row[0] in {"!Sample_title", "!Sample_source_name_ch1", "!Sample_geo_accession"}: | |
| meta[row[0]] = [v.strip() for v in row[1:]] | |
| sample_meta = dict(zip(meta["!Sample_title"], zip(meta["!Sample_source_name_ch1"], | |
| meta["!Sample_geo_accession"], strict=True), strict=True)) | |
| data = geo_rows(folder / (f"{key}.csv.gz" if paired else f"{key}.tsv.gz"), "," if paired else "\t") | |
| offset = 2 if paired else 1 | |
| titles = [v.strip() for v in next(data)[offset:]] | |
| if not paired: | |
| for title in titles: | |
| if title.endswith(".normal"): | |
| assert sample_meta[title.removesuffix(".normal")][0] == "normal" | |
| titles = [title.removesuffix(".normal") for title in titles] | |
| assert len(titles) == len(set(titles)) and set(titles) == set(sample_meta) | |
| samples = [] | |
| for title in titles: | |
| tissue, gsm = sample_meta[title] | |
| assert tissue.lower() in {"tumor", "normal"} | |
| patient = "" | |
| if paired: | |
| patient, suffix = re.fullmatch(r"(SCLC_\d+)_(ca|n)", title).groups() | |
| assert (suffix == "ca") == (tissue.lower() == "tumor") | |
| samples.append(dict(accession=accession, sample=gsm, title=title, tissue=tissue.lower(), patient=patient)) | |
| seen = defaultdict(list) | |
| for row in data: | |
| if not row: | |
| continue | |
| symbol = gene_symbol(row[offset-1]) | |
| if not symbol or symbol in {"NA", "---"}: | |
| continue | |
| assert len(row) == len(titles) + offset | |
| values = np.array([float(x) if x not in ("NA", "") else np.nan for x in row[offset:]]) | |
| if np.all(np.isfinite(values)): | |
| seen[symbol].append(values) | |
| matrix = {name: np.mean(values, axis=0) for name, values in seen.items()} | |
| assert all(g in matrix for g in TARGETS + MARKERS), (key, [g for g in TARGETS + MARKERS if g not in matrix]) | |
| return samples, matrix | |
| def groups(samples): | |
| tumors = [i for i, r in enumerate(samples) if r["tissue"] == "tumor"] | |
| normals = [i for i, r in enumerate(samples) if r["tissue"] == "normal"] | |
| paired = bool(samples[0]["patient"]) | |
| if paired: | |
| indexed = {samples[i]["patient"]: i for i in normals} | |
| assert len(tumors) == len(normals) == len(indexed) == 18 | |
| normals = [indexed[samples[i]["patient"]] for i in tumors] | |
| else: | |
| assert (len(tumors), len(normals)) == (79, 7) | |
| return tumors, normals, paired | |
| def read_sets(folder): | |
| found = {} | |
| for file in ("hallmark.gmt", "macro.gmt"): | |
| for line in (folder / file).read_text(encoding="utf-8-sig").splitlines(): | |
| name, url, *genes = line.rstrip().split("\t") | |
| if name in {NF, AU}: | |
| found[name] = {gene_symbol(g) for g in genes} | |
| assert set(found) == {NF, AU} | |
| return found | |
| def tissue_effect(v, t, n, paired): | |
| a, b = v[t], v[n] | |
| delta = float(a.mean() - b.mean()) | |
| if paired: | |
| diff = a - b | |
| se = float(stats.sem(diff)) | |
| crit = stats.t.ppf(.975, len(diff) - 1) | |
| test = stats.ttest_rel(a, b) | |
| rank_p = stats.wilcoxon(diff).pvalue | |
| sensitivity = [np.delete(diff, i).mean() for i in range(len(diff))] | |
| up = int(np.sum(diff > 0)) | |
| else: | |
| av = a.var(ddof=1) / len(a) | |
| bv = b.var(ddof=1) / len(b) | |
| se = np.sqrt(av + bv) | |
| df = (av+bv)**2 / (av**2/(len(a)-1) + bv**2/(len(b)-1)) | |
| crit = stats.t.ppf(.975, df) | |
| test = stats.ttest_ind(a, b, equal_var=False) | |
| rank_p = stats.mannwhitneyu(a, b, alternative="two-sided").pvalue | |
| sensitivity = [a.mean() - np.delete(b, i).mean() for i in range(len(b))] | |
| up = "" | |
| return dict(n_tumor=len(a), n_normal=len(b), mean_difference=delta, ci_low=delta-crit*se, | |
| ci_high=delta+crit*se, p=float(test.pvalue), rank_p=float(rank_p), tumor_higher_pairs=up, | |
| leave_one_out_min=min(sensitivity), leave_one_out_max=max(sensitivity)) | |
| def tissue_analysis(folder, out): | |
| cohorts = {name: read_cohort(folder, name) for name in ("GSE149507", "GSE60052")} | |
| common = sorted(set.intersection(*(set(matrix) for _, matrix in cohorts.values()))) | |
| gene_sets = read_sets(folder) | |
| included = {name: sorted(members.intersection(common)) for name, members in gene_sets.items()} | |
| assert min(map(len, included.values())) >= 50 | |
| coverage = [dict(pathway=name, reference_genes=len(gene_sets[name]), common_genes=len(genes), | |
| common_rank_background=len(common), members=";".join(genes)) for name, genes in included.items()] | |
| write_csv(out / "pathway_coverage.csv", coverage) | |
| effects, sample_rows, associations, pathway_sensitivity = [], [], [], [] | |
| for accession, (samples, matrix) in cohorts.items(): | |
| ranks = stats.rankdata(np.stack([matrix[g] for g in common]), axis=0) | |
| ranks = (ranks - 0.5) / len(common) * 100 | |
| indices = {g: i for i, g in enumerate(common)} | |
| scores = {name: ranks[[indices[g] for g in genes]].mean(axis=0) | |
| for name, genes in included.items()} | |
| signals = {gene: matrix[gene] for gene in TARGETS + MARKERS} | scores | |
| t, n, paired = groups(samples) | |
| for name, genes in included.items(): | |
| values = np.stack([matrix[g] for g in genes]) | |
| variable = values.std(axis=1, ddof=1) > 0 | |
| score = stats.zscore(values[variable], axis=1, ddof=1).mean(axis=0) | |
| pathway_sensitivity.append(dict(accession=accession, feature=name, genes=int(variable.sum()), | |
| **tissue_effect(score, t, n, paired))) | |
| cohort_effects = [dict(accession=accession, feature=name, | |
| unit="rank percentile points" if name in scores else "published log2 expression", | |
| **tissue_effect(v, t, n, paired)) for name, v in signals.items()] | |
| bh(cohort_effects) | |
| effects.extend(cohort_effects) | |
| for i, sample in enumerate(samples): | |
| sample_rows.append(dict(sample, **{name: values[i] for name, values in signals.items()})) | |
| for gene, pathway in zip(TARGETS, (NF, AU)): | |
| test = stats.spearmanr(signals[gene][t], scores[pathway][t]) | |
| associations.append(dict(accession=accession, target=gene, pathway=pathway, | |
| n_tumor=len(t), rho=test.statistic, nominal_p=test.pvalue)) | |
| write_csv(out / "tissue_effects.csv", effects) | |
| write_csv(out / "tissue_sample_values.csv", sample_rows) | |
| write_csv(out / "tumor_only_target_pathway_correlations.csv", associations) | |
| write_csv(out / "pathway_standardized_sensitivity.csv", pathway_sensitivity) | |
| def cellosaurus_models(folder): | |
| """Join exact ACH IDs and unambiguous NCIt histology in official API exports.""" | |
| lookup = defaultdict(set) | |
| for group, code in (("SCLC", "C4917"), ("LUAD", "C3512")): | |
| stem = f"cello-exact-{group.lower()}" | |
| pages = [folder / f"{stem}.tsv", *sorted(folder.glob(f"{stem}-page*.tsv"))] | |
| rows = [] | |
| for path in pages: | |
| text = path.read_text(encoding="utf-8-sig") | |
| expected = int(re.search(r"response\.numFound: (\d+)", text)[1]) | |
| offset = int(re.search(r"query\.start: (\d+)", text)[1]) | |
| assert offset == len(rows), (path, offset, len(rows)) | |
| rows.extend(csv.DictReader((line for line in text.splitlines() if line and not line.startswith("##")), delimiter="\t")) | |
| assert len(rows) == expected, (group, len(rows), expected) | |
| assert len({r["ac"] for r in rows}) == expected | |
| for row in rows: | |
| disease = {x.split("; ")[1] for x in row["di"].split("|") if x.startswith("NCIt; ")} | |
| if disease != {code}: | |
| continue | |
| for ref in row["dr"].split("|"): | |
| if re.fullmatch(r"DepMap; ACH-\d+", ref): | |
| model = ref.split("; ")[1] | |
| lookup[model].add((group, row["id"], row["ac"])) | |
| return {model: next(iter(assignments)) for model, assignments in lookup.items() if len(assignments) == 1} | |
| def depmap_models(path): | |
| groups = {"SCLC": "SCLC", "LUAD": "LUAD"} | |
| models = {} | |
| with path.open(newline="", encoding="utf-8-sig") as handle: | |
| for row in csv.DictReader(handle): | |
| code = row["OncotreeCode"] | |
| if code in groups and row["OncotreeLineage"] == "Lung": | |
| models[row["ModelID"]] = groups[code], row["CellLineName"], row.get("RRID", "") | |
| return models | |
| def effect_records(effects, models): | |
| records = [] | |
| with effects.open(newline="", encoding="utf-8-sig") as f: | |
| reader = csv.reader(f) | |
| columns = next(reader) | |
| names = {gene_symbol(value.split(" (")[0]): i for i, value in enumerate(columns)} | |
| targets = TARGETS + CONTROL_GENES | |
| for row in reader: | |
| if row[0] not in models: | |
| continue | |
| group, name, source_id = models[row[0]] | |
| for gene in targets: | |
| x = row[names[gene]] | |
| if x and np.isfinite(float(x)): | |
| records.append(dict(model_id=row[0], model_name=name, source_id=source_id, group=group, | |
| gene=gene, chronos=float(x), reclassified_model=row[0] in RECLASSIFIED)) | |
| return records | |
| def group_comparison(a, b, rng): | |
| test = stats.mannwhitneyu(a, b, alternative="two-sided") | |
| median_diff = np.median(a) - np.median(b) | |
| boot = np.median(rng.choice(a, size=(10000, len(a)), replace=True), axis=1) | |
| boot -= np.median(rng.choice(b, size=(10000, len(b)), replace=True), axis=1) | |
| ci = np.quantile(boot, [0.025, .975]) | |
| # Leave-one-model-out effect size can be computed from each model's pairwise wins. | |
| pairwise = np.sign(a[:, None] - b[None, :]) | |
| leave_one = np.r_[(pairwise.sum() - pairwise.sum(axis=1))/((len(a)-1)*len(b)), | |
| (pairwise.sum() - pairwise.sum(axis=0))/(len(a)*(len(b)-1))] | |
| trimmed = stats.mannwhitneyu(np.sort(a)[3:], np.sort(b)[3:], alternative="two-sided") | |
| return dict(n_sclc=len(a), n_luad=len(b), median_sclc=np.median(a), median_luad=np.median(b), | |
| median_difference=median_diff, bootstrap_low=ci[0], bootstrap_high=ci[1], | |
| cliffs_delta=pairwise.mean(), p=test.pvalue, sclc_below_minus_0_5=int(np.sum(a < -.5)), | |
| luad_below_minus_0_5=int(np.sum(b < -.5)), sclc_below_minus_1=int(np.sum(a < -1)), | |
| luad_below_minus_1=int(np.sum(b < -1)), loo_delta_min=min(leave_one), loo_delta_max=max(leave_one), | |
| trimmed_delta=2*trimmed.statistic/((len(a)-3)*(len(b)-3))-1, trimmed_p=trimmed.pvalue) | |
| def dependency_analysis(effects, model_source, out, use_cellosaurus): | |
| models = cellosaurus_models(model_source) if use_cellosaurus else depmap_models(model_source) | |
| records = effect_records(effects, models) | |
| write_csv(out / "depmap_model_scores.csv", records) | |
| rng = np.random.default_rng(149507) | |
| results, sensitivity = [], [] | |
| for gene in TARGETS + CONTROL_GENES: | |
| subset = [r for r in records if r["gene"] == gene and not r["reclassified_model"]] | |
| a = np.array([r["chronos"] for r in subset if r["group"] == "SCLC"]) | |
| b = np.array([r["chronos"] for r in subset if r["group"] == "LUAD"]) | |
| assert len(a) >= 15 and len(b) >= 40, (gene, len(a), len(b)) | |
| results.append(dict(gene=gene, role="candidate" if gene in TARGETS else "essential control", | |
| **group_comparison(a, b, rng), q="")) | |
| if gene in TARGETS: | |
| excluded_names = {"HCC827 GR5", "MOR/CPR", "NCI-H2286"} | |
| stricter_luad = np.array([r["chronos"] for r in subset if r["group"] == "LUAD" | |
| and r["model_name"] not in excluded_names]) | |
| sensitivity.append(dict(gene=gene, excluded_luad_models=";".join(sorted(excluded_names)), | |
| **group_comparison(a, stricter_luad, rng))) | |
| bh([r for r in results if r["gene"] in TARGETS]) | |
| write_csv(out / "depmap_comparison.csv", results) | |
| write_csv(out / "depmap_luad_annotation_sensitivity.csv", sensitivity) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("inputs", type=Path) | |
| parser.add_argument("out", type=Path) | |
| parser.add_argument("--effects", type=Path) | |
| parser.add_argument("--model-source", type=Path) | |
| parser.add_argument("--cellosaurus", action="store_true") | |
| parser.add_argument("--only", choices=("tissue", "dependency")) | |
| args = parser.parse_args() | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| if args.only != "dependency": | |
| tissue_analysis(args.inputs, args.out) | |
| if args.only != "tissue": | |
| dependency_analysis(args.effects, args.model_source, args.out, args.cellosaurus) | |
| if __name__ == "__main__": | |
| main() | |