example_datasets / real /causalbench /causalbench_preprocess.py
huggingbahl21's picture
Add CausalBench preprocessing script
1e13ffe verified
Raw History Blame
8.56 kB
# /// script
# requires-python = ">=3.12,<3.13"
# dependencies = [
# "anndata==0.13.4", "h5py==3.16.0", "numpy==2.5.3", "openpyxl==3.1.5",
# "pandas==3.0.6", "scanpy==1.12.4", "scipy==1.18.1", "scikit-learn==1.9.1",
# ]
# ///
"""Prepare the K562 and RPE1 datasets using CausalBench preprocessing.
Run: uv run causalbench_preprocess.py all
Use k562 or rpe1 instead of all to prepare one dataset.
Downloads go to data/raw/; prepared TSVs go to data/prepared/.
Both datasets need about 19 GB of downloads and substantial RAM.
Original data: https://doi.org/10.25452/figshare.plus.20029387.v1
"""
# Preprocessing source:
# https://github.com/causalbench/causalbench/blob/1a2143cffdc85f835b41ce8d52034be1bf903e71/causalscbench/data_access/utils/preprocessing.py
# Original preprocessing, with download and TSV export helpers added.
#
# Copyright (C) 2022, 2023 GlaxoSmithKline plc - Mathieu Chevalley, Yusuf Roohani.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import hashlib
from pathlib import Path
import shutil
from urllib.error import HTTPError
from urllib.request import urlopen
import numpy as np
import pandas as pd
import scanpy as sc
# 1. Download the original inputs.
# Figshare names: K562_essential_raw_singlecell_01.h5ad and rpe1_raw_singlecell_01.h5ad.
DATASETS = {
"k562": {
"url": "https://ndownloader.figshare.com/files/35773219",
"sheet": "TabB_K562_day6_summary_stat",
"sha256": "3e5a63a9e892b21029bb55fca4e12517a49aad7af6c14133ca63d12cf68c6cee",
},
"rpe1": {
"url": "https://ndownloader.figshare.com/files/35775606",
"sheet": "TabC_RPE1_summary_statistic",
"sha256": "9b05ef1f81526216fa008d677e9e0d03dce9a2f7a95499a4fb81e505e9d88ef1",
},
}
# Replogle et al. supplementary workbook, saved locally as summary_stats.xlsx.
SUMMARY_URL = "https://ars.els-cdn.com/content/image/1-s2.0-S0092867422005979-mmc2.xlsx"
# Fallback if the publisher blocks the download; verified against the same checksum.
SUMMARY_MIRROR = "https://huggingface.co/datasets/huggingbahl21/causalbench/resolve/main/data/raw/summary_stats.xlsx"
SUMMARY_SHA256 = "364748fe04e9a9cdbcf239d8012c94cd17f72880b43a84817e7505bdb78e7177"
def verify_file(path, expected_sha256):
"""Check the input checksum."""
with path.open("rb") as stream:
actual = hashlib.file_digest(stream, "sha256").hexdigest()
if actual != expected_sha256:
raise ValueError(f"Checksum mismatch: {path}")
def download(url, path, expected_sha256):
"""Download a file, or reuse it after checking its checksum."""
if path.exists():
verify_file(path, expected_sha256)
return path
path.parent.mkdir(parents=True, exist_ok=True)
partial = path.with_name(path.name + ".part")
print(f"Downloading {url}", flush=True)
with urlopen(url, timeout=120) as response, partial.open("wb") as stream:
shutil.copyfileobj(response, stream, length=1024 * 1024)
verify_file(partial, expected_sha256)
partial.replace(path)
return path
# 2. Apply the authors' preprocessing.
def get_strong_perts(supp):
filtered = supp[supp['Number of DEGs (anderson-darling)']>50]
filtered = filtered[filtered['percent knockdown']<=-0.3]
filtered = filtered[filtered['number of cells (filtered)']>25]
strong_perts = filtered['genetic perturbation'].values
strong_perts = [s.split('_')[1] for s in strong_perts]
return strong_perts
def filter_cells_by_pert_effect(adata, k=10):
subset_idxs = []
ctrl_adata = adata[adata.obs['gene'] == 'non-targeting']
for itr, g in enumerate(adata.obs['gene'].unique()):
subset = adata[adata.obs['gene'] == g]
if g == 'non-targeting':
subset_idxs.append(subset.obs.index.values)
continue
try:
gene_loc = np.where(adata.var.gene_name == g)[0][0]
thresh = np.percentile(ctrl_adata.X[:,gene_loc],k)
subset_idxs.append(subset.obs.index[subset.X[:,gene_loc]<=thresh].values)
except:
subset_idxs.append(subset.obs.index.values)
subset_idxs = [item for sublist in subset_idxs for item in sublist]
filtered_adata = adata[subset_idxs,:]
return filtered_adata
def preprocess_dataset(dataset_path, summary_stats=None):
"""Return filtered expression values, gene IDs, and intervention labels."""
data_expr_raw = sc.read(dataset_path)
if summary_stats is not None:
# Filter for only strong pertubations
strong_perts = get_strong_perts(summary_stats) + ['non-targeting']
idx_to_keep = [v in strong_perts for v in data_expr_raw.obs['gene']]
pert_filter_k562 = data_expr_raw[idx_to_keep]
data_expr_raw = filter_cells_by_pert_effect(pert_filter_k562)
# Normalize data
sc.pp.normalize_per_cell(data_expr_raw, key_n_counts='UMI_count')
sc.pp.log1p(data_expr_raw)
data_expr_raw_df = data_expr_raw.to_df()
intervened_genes = list(data_expr_raw.obs["gene_id"])
gene_to_interventions = dict()
for i, intervention in enumerate(intervened_genes):
if intervention in set(data_expr_raw_df.columns.to_list()) or intervention == "non-targeting":
gene_to_interventions.setdefault(intervention, []).append(i)
intervened_genes_set = set()
for gene, cell_indices in gene_to_interventions.items():
if len(cell_indices) > 100:
intervened_genes_set.add(gene)
intervened_genes = ["excluded" if gene not in intervened_genes_set else gene for gene in intervened_genes]
data_expr_raw_perturbed_only = data_expr_raw_df[data_expr_raw_df.columns[data_expr_raw_df.columns.isin(intervened_genes_set)]]
gene_ids = data_expr_raw_perturbed_only.columns.to_list()
return data_expr_raw_perturbed_only.to_numpy(), gene_ids, intervened_genes
# 3. Export expression values and intervention labels.
def prepare(name, raw_dir, output_dir, summary_path):
"""Prepare one dataset and save it as a gzip TSV."""
source = DATASETS[name]
destination = output_dir / f"causalbench_{name}.tsv.gz"
if destination.exists():
raise FileExistsError(f"Output already exists: {destination}; choose another --output-dir")
raw_path = download(source["url"], raw_dir / f"{name}.h5ad", source["sha256"])
summary = pd.read_excel(summary_path, sheet_name=source["sheet"])
print(f"Preprocessing {name} with the authors' function", flush=True)
expression, genes, labels = preprocess_dataset(str(raw_path), summary)
table = pd.DataFrame(expression, columns=genes)
table["intervention"] = labels
output_dir.mkdir(parents=True, exist_ok=True)
partial = destination.with_name(destination.name + ".part")
table.to_csv(partial, sep="\t", index=False, compression="gzip")
partial.replace(destination)
print(f"Saved {destination}: {len(table):,} cells, {len(genes)} genes", flush=True)
def main():
parser = argparse.ArgumentParser(
description=__doc__.split("\n\n", 1)[0],
epilog="Both datasets require about 19 GB of downloads and substantial RAM to preprocess.",
)
parser.add_argument("dataset", choices=["k562", "rpe1", "all"], nargs="?", default="all")
parser.add_argument("--raw-dir", type=Path, default=Path("data/raw"), help="download folder (default: data/raw)")
parser.add_argument("--output-dir", type=Path, default=Path("data/prepared"), help="TSV output folder (default: data/prepared)")
args = parser.parse_args()
summary_path = args.raw_dir / "summary_stats.xlsx"
try:
download(SUMMARY_URL, summary_path, SUMMARY_SHA256)
except HTTPError as error:
if error.code not in (403, 404):
raise
print("Publisher workbook unavailable; using the checksum-verified mirror", flush=True)
download(SUMMARY_MIRROR, summary_path, SUMMARY_SHA256)
names = DATASETS if args.dataset == "all" else [args.dataset]
for name in names:
prepare(name, args.raw_dir, args.output_dir, summary_path)
if __name__ == "__main__":
main()