random-promoter-dream-2022 / create_dataset.py
edbeeching's picture
edbeeching HF Staff
Upload create_dataset.py
095ecf8 verified
#!/usr/bin/env python3
"""Convert Random Promoter DREAM 2022 files to Hugging Face datasets.
The script keeps raw downloads under scratch/ by default and publishes several
configs into one dataset repo:
- supervised: train/validation/test sequence-to-activity regression splits
- challenge_test_sequences: unlabeled challenge test sequences
- test_subset_membership: IDs from test_subset_ids.tar.gz
- public_leaderboard_ids: IDs from public_leaderboard_ids.tar.gz
"""
from __future__ import annotations
import argparse
import hashlib
import io
import logging
import shutil
import tarfile
import urllib.request
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from datasets import Dataset
from datasets import DatasetDict
from datasets import Features
from datasets import Value
from datasets import load_dataset
from huggingface_hub import HfApi
ZENODO_RECORD = "10633252"
DEFAULT_HUB_REPO_ID = "HuggingFaceBio/random-promoter-dream-2022"
DEFAULT_RAW_DIR = Path("scratch/promoter_activity_dream/raw")
DEFAULT_OUTPUT_DIR = Path("scratch/promoter_activity_dream/hf_dataset")
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class SourceFile:
filename: str
md5: str
url: str
SOURCE_FILES = {
"train": SourceFile(
filename="train.txt",
md5="b387d6e053f797d80abc8b972d16c355",
url=f"https://zenodo.org/records/{ZENODO_RECORD}/files/train.txt?download=1",
),
"validation": SourceFile(
filename="val.txt",
md5="c0f8d2fc873f194e540586ad51cb5ae6",
url=f"https://zenodo.org/records/{ZENODO_RECORD}/files/val.txt?download=1",
),
"test": SourceFile(
filename="filtered_test_data_with_MAUDE_expression.txt",
md5="d0880059150ddebc900450a9d2a6418d",
url=(
f"https://zenodo.org/records/{ZENODO_RECORD}/files/"
"filtered_test_data_with_MAUDE_expression.txt?download=1"
),
),
"challenge_test_sequences": SourceFile(
filename="test_sequences.txt",
md5="0173024c6f468cc1409e80a1b339609c",
url=(
f"https://zenodo.org/records/{ZENODO_RECORD}/files/"
"test_sequences.txt?download=1"
),
),
"test_subset_ids": SourceFile(
filename="test_subset_ids.tar.gz",
md5="40b56d200273990560b5b1c2def2185a",
url=(
f"https://zenodo.org/records/{ZENODO_RECORD}/files/"
"test_subset_ids.tar.gz?download=1"
),
),
"public_leaderboard_ids": SourceFile(
filename="public_leaderboard_ids.tar.gz",
md5="49ce1bc5118665e6c4382c6b9c470efa",
url=(
f"https://zenodo.org/records/{ZENODO_RECORD}/files/"
"public_leaderboard_ids.tar.gz?download=1"
),
),
}
SUPERVISED_FEATURES = Features(
{
"sequence": Value("string"),
"activity": Value("float32"),
"sequence_length": Value("int32"),
"source_file": Value("string"),
"row_id": Value("int64"),
}
)
SEQUENCE_FEATURES = Features(
{
"sequence": Value("string"),
"sequence_length": Value("int32"),
"source_file": Value("string"),
"row_id": Value("int64"),
}
)
ID_FEATURES = Features(
{
"subset": Value("string"),
"item_id": Value("string"),
"row_id": Value("int64"),
"source_member": Value("string"),
"line_number": Value("int64"),
"raw_line": Value("string"),
}
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Convert Random Promoter DREAM 2022 data to HF datasets."
)
parser.add_argument("--hub-repo-id", default=DEFAULT_HUB_REPO_ID)
parser.add_argument(
"--private", action=argparse.BooleanOptionalAction, default=True
)
parser.add_argument("--push-to-hub", action="store_true")
parser.add_argument("--raw-dir", type=Path, default=DEFAULT_RAW_DIR)
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
parser.add_argument(
"--dataset-cache-dir",
type=Path,
default=None,
help="Optional datasets cache directory. Defaults to the HF cache.",
)
parser.add_argument("--num-proc", type=int, default=8)
parser.add_argument("--max-rows-per-split", type=int, default=None)
parser.add_argument(
"--no-download",
action="store_true",
help="Use existing files in --raw-dir and fail if any are missing.",
)
parser.add_argument("--train-file", type=Path, default=None)
parser.add_argument("--validation-file", type=Path, default=None)
parser.add_argument("--test-file", type=Path, default=None)
parser.add_argument("--test-sequences-file", type=Path, default=None)
parser.add_argument("--test-subset-ids-tar", type=Path, default=None)
parser.add_argument("--public-leaderboard-ids-tar", type=Path, default=None)
return parser.parse_args()
def file_md5(path: Path, chunk_size: int = 1024 * 1024) -> str:
digest = hashlib.md5()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(chunk_size), b""):
digest.update(chunk)
return digest.hexdigest()
def download_file(source: SourceFile, raw_dir: Path, no_download: bool) -> Path:
raw_dir.mkdir(parents=True, exist_ok=True)
path = raw_dir / source.filename
if path.exists():
actual_md5 = file_md5(path)
if actual_md5 != source.md5:
raise ValueError(
f"{path} exists but md5 is {actual_md5}; expected {source.md5}"
)
logger.info("Using cached %s", path)
return path
if no_download:
raise FileNotFoundError(f"Missing {path}; rerun without --no-download")
tmp_path = path.with_suffix(path.suffix + ".tmp")
logger.info("Downloading %s", source.url)
with urllib.request.urlopen(source.url) as response, tmp_path.open("wb") as out:
shutil.copyfileobj(response, out)
actual_md5 = file_md5(tmp_path)
if actual_md5 != source.md5:
tmp_path.unlink(missing_ok=True)
raise ValueError(
f"Downloaded {source.filename} md5 {actual_md5}; expected {source.md5}"
)
tmp_path.replace(path)
return path
def resolve_paths(args: argparse.Namespace) -> dict[str, Path]:
explicit = {
"train": args.train_file,
"validation": args.validation_file,
"test": args.test_file,
"challenge_test_sequences": args.test_sequences_file,
"test_subset_ids": args.test_subset_ids_tar,
"public_leaderboard_ids": args.public_leaderboard_ids_tar,
}
if any(path is not None for path in explicit.values()):
missing = [
name for name in ("train", "validation", "test") if explicit[name] is None
]
if missing:
raise ValueError(
"When using explicit local files, provide train, validation, "
f"and test files. Missing: {missing}"
)
return {name: path for name, path in explicit.items() if path is not None}
return {
name: download_file(source, args.raw_dir, args.no_download)
for name, source in SOURCE_FILES.items()
}
def add_supervised_metadata(
batch: dict[str, list[Any]],
indices: list[int],
source_file: str,
) -> dict[str, list[Any]]:
sequences = [str(sequence).strip().upper() for sequence in batch["sequence"]]
return {
"sequence": sequences,
"activity": [float(value) for value in batch["activity"]],
"sequence_length": [len(sequence) for sequence in sequences],
"source_file": [source_file] * len(sequences),
"row_id": list(indices),
}
def limit_dataset(dataset: Dataset, max_rows: int | None) -> Dataset:
if max_rows is None or max_rows >= len(dataset):
return dataset
return dataset.select(range(max_rows))
def build_supervised_dataset(
paths: dict[str, Path],
*,
max_rows_per_split: int | None,
num_proc: int,
cache_dir: Path | None = None,
) -> DatasetDict:
raw = load_dataset(
"csv",
data_files={
"train": str(paths["train"]),
"validation": str(paths["validation"]),
"test": str(paths["test"]),
},
delimiter="\t",
column_names=["sequence", "activity"],
features=Features({"sequence": Value("string"), "activity": Value("float32")}),
cache_dir=str(cache_dir) if cache_dir is not None else None,
)
processed = {}
for split, dataset in raw.items():
dataset = limit_dataset(dataset, max_rows_per_split)
map_kwargs: dict[str, Any] = {
"with_indices": True,
"fn_kwargs": {"source_file": paths[split].name},
"features": SUPERVISED_FEATURES,
"desc": f"Adding DREAM metadata to {split}",
}
if num_proc and num_proc > 1:
map_kwargs["num_proc"] = num_proc
processed[split] = dataset.map(
add_supervised_metadata, batched=True, **map_kwargs
)
return DatasetDict(processed)
def iter_sequence_file(
path: Path, max_rows: int | None = None
) -> Iterator[dict[str, Any]]:
with path.open("r", encoding="utf-8") as handle:
for row_id, line in enumerate(handle):
if max_rows is not None and row_id >= max_rows:
break
line = line.strip()
if not line:
continue
sequence = line.split("\t", 1)[0].strip().upper()
yield {
"sequence": sequence,
"sequence_length": len(sequence),
"source_file": path.name,
"row_id": row_id,
}
def build_sequence_dataset(
path: Path, max_rows: int | None, cache_dir: Path | None = None
) -> Dataset:
return Dataset.from_generator(
iter_sequence_file,
gen_kwargs={"path": path, "max_rows": max_rows},
features=SEQUENCE_FEATURES,
cache_dir=str(cache_dir) if cache_dir is not None else None,
)
def subset_name_from_member(member_name: str) -> str:
path = Path(member_name)
name = path.name
for suffix in (".txt", ".tsv", ".csv", ".ids"):
if name.endswith(suffix):
name = name[: -len(suffix)]
return name.replace(" ", "_")
def parse_id_line(line: str) -> tuple[str, int]:
item_id = line.split("\t", 1)[0].split(",", 1)[0].strip()
row_id = int(item_id) if item_id.isdigit() else -1
return item_id, row_id
def iter_tar_ids(path: Path, max_rows: int | None = None) -> Iterator[dict[str, Any]]:
emitted = 0
with tarfile.open(path, "r:gz") as tar:
for member in tar:
if not member.isfile():
continue
extracted = tar.extractfile(member)
if extracted is None:
continue
subset = subset_name_from_member(member.name)
with io.TextIOWrapper(extracted, encoding="utf-8") as handle:
for line_number, line in enumerate(handle):
raw_line = line.strip()
if not raw_line:
continue
if max_rows is not None and emitted >= max_rows:
return
item_id, row_id = parse_id_line(raw_line)
yield {
"subset": subset,
"item_id": item_id,
"row_id": row_id,
"source_member": member.name,
"line_number": line_number,
"raw_line": raw_line,
}
emitted += 1
def build_id_dataset(
path: Path, max_rows: int | None, cache_dir: Path | None = None
) -> Dataset:
return Dataset.from_generator(
iter_tar_ids,
gen_kwargs={"path": path, "max_rows": max_rows},
features=ID_FEATURES,
cache_dir=str(cache_dir) if cache_dir is not None else None,
)
def render_dataset_card(hub_repo_id: str) -> str:
return f"""---
license: cc-by-4.0
task_categories:
- text-regression
language:
- en
tags:
- biology
- dna
- genomics
- promoter
- gene-expression
- carbon
---
# Random Promoter DREAM Challenge 2022
This dataset repackages the processed Random Promoter DREAM Challenge 2022
files from Zenodo record `{ZENODO_RECORD}` for use with `datasets`.
The task is sequence-to-expression regression on synthetic yeast promoter
sequences. The canonical supervised config contains random promoter training
examples, validation examples, and labeled designed test promoters.
## Configs
- `supervised`: `train`, `validation`, and `test` splits with promoter
sequences and measured activity.
- `challenge_test_sequences`: unlabeled test sequences for submission-style
prediction workflows.
- `test_subset_membership`: normalized IDs from `test_subset_ids.tar.gz`.
- `public_leaderboard_ids`: normalized IDs from `public_leaderboard_ids.tar.gz`.
## Schema
`supervised`:
- `sequence`: DNA sequence.
- `activity`: measured promoter activity.
- `sequence_length`: sequence length in base pairs.
- `source_file`: source filename.
- `row_id`: zero-based row index within the source split.
ID metadata configs:
- `subset`: subset name inferred from the archive member.
- `item_id`: raw ID token from the source line.
- `row_id`: integer row ID when `item_id` is numeric; otherwise `-1`.
- `source_member`: archive member path.
- `line_number`: line number within the member.
- `raw_line`: unmodified stripped source line.
## Usage
```py
from datasets import load_dataset
ds = load_dataset("{hub_repo_id}", "supervised")
train = ds["train"]
validation = ds["validation"]
test = ds["test"]
subsets = load_dataset("{hub_repo_id}", "test_subset_membership", split="train")
```
## Source
Source: Random Promoter DREAM Challenge 2022, Zenodo DOI
`10.5281/zenodo.10633252`.
The source record is licensed CC BY 4.0. Cite the original DREAM Challenge data
and paper when using this dataset.
## Reproduction
This dataset repo includes `create_dataset.py`, the script used to download,
convert, and upload the configs.
"""
def save_or_push(
*,
dataset: Dataset | DatasetDict,
config_name: str,
args: argparse.Namespace,
api: HfApi | None,
) -> None:
if args.push_to_hub:
dataset.push_to_hub(
args.hub_repo_id,
config_name=config_name,
commit_message=f"Upload {config_name} config",
)
logger.info("Pushed %s to %s", config_name, args.hub_repo_id)
return
output_path = args.output_dir / config_name
dataset.save_to_disk(str(output_path))
logger.info("Saved %s to %s", config_name, output_path)
def upload_dataset_metadata(args: argparse.Namespace, api: HfApi) -> None:
readme_bytes = render_dataset_card(args.hub_repo_id).encode("utf-8")
api.upload_file(
path_or_fileobj=readme_bytes,
path_in_repo="README.md",
repo_id=args.hub_repo_id,
repo_type="dataset",
commit_message="Upload dataset card",
)
api.upload_file(
path_or_fileobj=Path(__file__).read_bytes(),
path_in_repo="create_dataset.py",
repo_id=args.hub_repo_id,
repo_type="dataset",
commit_message="Upload create_dataset.py",
)
def run(args: argparse.Namespace) -> None:
paths = resolve_paths(args)
args.output_dir.mkdir(parents=True, exist_ok=True)
api = None
if args.push_to_hub:
api = HfApi()
api.whoami()
api.create_repo(
repo_id=args.hub_repo_id,
repo_type="dataset",
exist_ok=True,
private=args.private,
)
supervised = build_supervised_dataset(
paths,
max_rows_per_split=args.max_rows_per_split,
num_proc=args.num_proc,
cache_dir=args.dataset_cache_dir,
)
save_or_push(dataset=supervised, config_name="supervised", args=args, api=api)
if "challenge_test_sequences" in paths:
challenge_test = build_sequence_dataset(
paths["challenge_test_sequences"],
args.max_rows_per_split,
cache_dir=args.dataset_cache_dir,
)
save_or_push(
dataset=challenge_test,
config_name="challenge_test_sequences",
args=args,
api=api,
)
if "test_subset_ids" in paths:
subset_ids = build_id_dataset(
paths["test_subset_ids"],
args.max_rows_per_split,
cache_dir=args.dataset_cache_dir,
)
save_or_push(
dataset=subset_ids,
config_name="test_subset_membership",
args=args,
api=api,
)
if "public_leaderboard_ids" in paths:
leaderboard_ids = build_id_dataset(
paths["public_leaderboard_ids"],
args.max_rows_per_split,
cache_dir=args.dataset_cache_dir,
)
save_or_push(
dataset=leaderboard_ids,
config_name="public_leaderboard_ids",
args=args,
api=api,
)
if args.push_to_hub and api is not None:
upload_dataset_metadata(args, api)
logger.info("Uploaded dataset card and create_dataset.py")
else:
(args.output_dir / "README.md").write_text(
render_dataset_card(args.hub_repo_id),
encoding="utf-8",
)
def main() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
run(parse_args())
if __name__ == "__main__":
main()