huggingbahl21 commited on
Commit
1e13ffe
·
verified ·
1 Parent(s): 3040359

Add CausalBench preprocessing script

Browse files

Adds a standalone script to download the inputs and reproduce the K562 and RPE1 tables. Follow-up to #3.

real/causalbench/causalbench_preprocess.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12,<3.13"
3
+ # dependencies = [
4
+ # "anndata==0.13.4", "h5py==3.16.0", "numpy==2.5.3", "openpyxl==3.1.5",
5
+ # "pandas==3.0.6", "scanpy==1.12.4", "scipy==1.18.1", "scikit-learn==1.9.1",
6
+ # ]
7
+ # ///
8
+ """Prepare the K562 and RPE1 datasets using CausalBench preprocessing.
9
+
10
+ Run: uv run causalbench_preprocess.py all
11
+ Use k562 or rpe1 instead of all to prepare one dataset.
12
+
13
+ Downloads go to data/raw/; prepared TSVs go to data/prepared/.
14
+ Both datasets need about 19 GB of downloads and substantial RAM.
15
+ Original data: https://doi.org/10.25452/figshare.plus.20029387.v1
16
+ """
17
+
18
+ # Preprocessing source:
19
+ # https://github.com/causalbench/causalbench/blob/1a2143cffdc85f835b41ce8d52034be1bf903e71/causalscbench/data_access/utils/preprocessing.py
20
+ # Original preprocessing, with download and TSV export helpers added.
21
+ #
22
+ # Copyright (C) 2022, 2023 GlaxoSmithKline plc - Mathieu Chevalley, Yusuf Roohani.
23
+ # Licensed under the Apache License, Version 2.0 (the "License");
24
+ # you may not use this file except in compliance with the License.
25
+ # You may obtain a copy of the License at
26
+ # https://www.apache.org/licenses/LICENSE-2.0
27
+ # Unless required by applicable law or agreed to in writing, software
28
+ # distributed under the License is distributed on an "AS IS" BASIS,
29
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
30
+ # See the License for the specific language governing permissions and
31
+ # limitations under the License.
32
+
33
+ import argparse
34
+ import hashlib
35
+ from pathlib import Path
36
+ import shutil
37
+ from urllib.error import HTTPError
38
+ from urllib.request import urlopen
39
+
40
+ import numpy as np
41
+ import pandas as pd
42
+ import scanpy as sc
43
+
44
+ # 1. Download the original inputs.
45
+ # Figshare names: K562_essential_raw_singlecell_01.h5ad and rpe1_raw_singlecell_01.h5ad.
46
+ DATASETS = {
47
+ "k562": {
48
+ "url": "https://ndownloader.figshare.com/files/35773219",
49
+ "sheet": "TabB_K562_day6_summary_stat",
50
+ "sha256": "3e5a63a9e892b21029bb55fca4e12517a49aad7af6c14133ca63d12cf68c6cee",
51
+ },
52
+ "rpe1": {
53
+ "url": "https://ndownloader.figshare.com/files/35775606",
54
+ "sheet": "TabC_RPE1_summary_statistic",
55
+ "sha256": "9b05ef1f81526216fa008d677e9e0d03dce9a2f7a95499a4fb81e505e9d88ef1",
56
+ },
57
+ }
58
+ # Replogle et al. supplementary workbook, saved locally as summary_stats.xlsx.
59
+
60
+ SUMMARY_URL = "https://ars.els-cdn.com/content/image/1-s2.0-S0092867422005979-mmc2.xlsx"
61
+ # Fallback if the publisher blocks the download; verified against the same checksum.
62
+ SUMMARY_MIRROR = "https://huggingface.co/datasets/huggingbahl21/causalbench/resolve/main/data/raw/summary_stats.xlsx"
63
+ SUMMARY_SHA256 = "364748fe04e9a9cdbcf239d8012c94cd17f72880b43a84817e7505bdb78e7177"
64
+
65
+
66
+ def verify_file(path, expected_sha256):
67
+ """Check the input checksum."""
68
+ with path.open("rb") as stream:
69
+ actual = hashlib.file_digest(stream, "sha256").hexdigest()
70
+ if actual != expected_sha256:
71
+ raise ValueError(f"Checksum mismatch: {path}")
72
+
73
+
74
+ def download(url, path, expected_sha256):
75
+ """Download a file, or reuse it after checking its checksum."""
76
+ if path.exists():
77
+ verify_file(path, expected_sha256)
78
+ return path
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ partial = path.with_name(path.name + ".part")
81
+ print(f"Downloading {url}", flush=True)
82
+ with urlopen(url, timeout=120) as response, partial.open("wb") as stream:
83
+ shutil.copyfileobj(response, stream, length=1024 * 1024)
84
+ verify_file(partial, expected_sha256)
85
+ partial.replace(path)
86
+ return path
87
+
88
+
89
+ # 2. Apply the authors' preprocessing.
90
+ def get_strong_perts(supp):
91
+ filtered = supp[supp['Number of DEGs (anderson-darling)']>50]
92
+ filtered = filtered[filtered['percent knockdown']<=-0.3]
93
+ filtered = filtered[filtered['number of cells (filtered)']>25]
94
+ strong_perts = filtered['genetic perturbation'].values
95
+ strong_perts = [s.split('_')[1] for s in strong_perts]
96
+ return strong_perts
97
+
98
+ def filter_cells_by_pert_effect(adata, k=10):
99
+
100
+ subset_idxs = []
101
+ ctrl_adata = adata[adata.obs['gene'] == 'non-targeting']
102
+
103
+ for itr, g in enumerate(adata.obs['gene'].unique()):
104
+ subset = adata[adata.obs['gene'] == g]
105
+
106
+ if g == 'non-targeting':
107
+ subset_idxs.append(subset.obs.index.values)
108
+ continue
109
+
110
+ try:
111
+ gene_loc = np.where(adata.var.gene_name == g)[0][0]
112
+ thresh = np.percentile(ctrl_adata.X[:,gene_loc],k)
113
+
114
+ subset_idxs.append(subset.obs.index[subset.X[:,gene_loc]<=thresh].values)
115
+ except:
116
+ subset_idxs.append(subset.obs.index.values)
117
+
118
+ subset_idxs = [item for sublist in subset_idxs for item in sublist]
119
+ filtered_adata = adata[subset_idxs,:]
120
+
121
+ return filtered_adata
122
+
123
+
124
+ def preprocess_dataset(dataset_path, summary_stats=None):
125
+ """Return filtered expression values, gene IDs, and intervention labels."""
126
+ data_expr_raw = sc.read(dataset_path)
127
+ if summary_stats is not None:
128
+ # Filter for only strong pertubations
129
+ strong_perts = get_strong_perts(summary_stats) + ['non-targeting']
130
+ idx_to_keep = [v in strong_perts for v in data_expr_raw.obs['gene']]
131
+ pert_filter_k562 = data_expr_raw[idx_to_keep]
132
+ data_expr_raw = filter_cells_by_pert_effect(pert_filter_k562)
133
+
134
+ # Normalize data
135
+ sc.pp.normalize_per_cell(data_expr_raw, key_n_counts='UMI_count')
136
+ sc.pp.log1p(data_expr_raw)
137
+ data_expr_raw_df = data_expr_raw.to_df()
138
+ intervened_genes = list(data_expr_raw.obs["gene_id"])
139
+ gene_to_interventions = dict()
140
+ for i, intervention in enumerate(intervened_genes):
141
+ if intervention in set(data_expr_raw_df.columns.to_list()) or intervention == "non-targeting":
142
+ gene_to_interventions.setdefault(intervention, []).append(i)
143
+ intervened_genes_set = set()
144
+ for gene, cell_indices in gene_to_interventions.items():
145
+ if len(cell_indices) > 100:
146
+ intervened_genes_set.add(gene)
147
+ intervened_genes = ["excluded" if gene not in intervened_genes_set else gene for gene in intervened_genes]
148
+ data_expr_raw_perturbed_only = data_expr_raw_df[data_expr_raw_df.columns[data_expr_raw_df.columns.isin(intervened_genes_set)]]
149
+ gene_ids = data_expr_raw_perturbed_only.columns.to_list()
150
+ return data_expr_raw_perturbed_only.to_numpy(), gene_ids, intervened_genes
151
+
152
+
153
+ # 3. Export expression values and intervention labels.
154
+ def prepare(name, raw_dir, output_dir, summary_path):
155
+ """Prepare one dataset and save it as a gzip TSV."""
156
+ source = DATASETS[name]
157
+ destination = output_dir / f"causalbench_{name}.tsv.gz"
158
+ if destination.exists():
159
+ raise FileExistsError(f"Output already exists: {destination}; choose another --output-dir")
160
+ raw_path = download(source["url"], raw_dir / f"{name}.h5ad", source["sha256"])
161
+ summary = pd.read_excel(summary_path, sheet_name=source["sheet"])
162
+ print(f"Preprocessing {name} with the authors' function", flush=True)
163
+ expression, genes, labels = preprocess_dataset(str(raw_path), summary)
164
+ table = pd.DataFrame(expression, columns=genes)
165
+ table["intervention"] = labels
166
+ output_dir.mkdir(parents=True, exist_ok=True)
167
+ partial = destination.with_name(destination.name + ".part")
168
+ table.to_csv(partial, sep="\t", index=False, compression="gzip")
169
+ partial.replace(destination)
170
+ print(f"Saved {destination}: {len(table):,} cells, {len(genes)} genes", flush=True)
171
+
172
+
173
+ def main():
174
+ parser = argparse.ArgumentParser(
175
+ description=__doc__.split("\n\n", 1)[0],
176
+ epilog="Both datasets require about 19 GB of downloads and substantial RAM to preprocess.",
177
+ )
178
+ parser.add_argument("dataset", choices=["k562", "rpe1", "all"], nargs="?", default="all")
179
+ parser.add_argument("--raw-dir", type=Path, default=Path("data/raw"), help="download folder (default: data/raw)")
180
+ parser.add_argument("--output-dir", type=Path, default=Path("data/prepared"), help="TSV output folder (default: data/prepared)")
181
+ args = parser.parse_args()
182
+ summary_path = args.raw_dir / "summary_stats.xlsx"
183
+ try:
184
+ download(SUMMARY_URL, summary_path, SUMMARY_SHA256)
185
+ except HTTPError as error:
186
+ if error.code not in (403, 404):
187
+ raise
188
+ print("Publisher workbook unavailable; using the checksum-verified mirror", flush=True)
189
+ download(SUMMARY_MIRROR, summary_path, SUMMARY_SHA256)
190
+ names = DATASETS if args.dataset == "all" else [args.dataset]
191
+ for name in names:
192
+ prepare(name, args.raw_dir, args.output_dir, summary_path)
193
+
194
+
195
+ if __name__ == "__main__":
196
+ main()