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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Create and optionally push a preprocessed Malinois/Gosai MPRA dataset."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import shutil
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from datasets import Dataset, DatasetDict, Features, Value, load_dataset
|
| 15 |
+
from huggingface_hub import HfApi
|
| 16 |
+
|
| 17 |
+
SOURCE_URL = (
|
| 18 |
+
"https://static-content.springer.com/esm/"
|
| 19 |
+
"art%3A10.1038%2Fs41586-024-08070-z/"
|
| 20 |
+
"MediaObjects/41586_2024_8070_MOESM4_ESM.txt"
|
| 21 |
+
)
|
| 22 |
+
DEFAULT_LOCAL_SOURCE = (
|
| 23 |
+
Path(__file__).resolve().parents[3]
|
| 24 |
+
/ "scratch/malinois_regression/data/41586_2024_8070_MOESM4_ESM.txt"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
TARGET_COLUMNS = ("K562_log2FC", "HepG2_log2FC", "SKNSH_log2FC")
|
| 28 |
+
SE_COLUMNS = ("K562_lfcSE", "HepG2_lfcSE", "SKNSH_lfcSE")
|
| 29 |
+
VALIDATION_CHROMOSOMES = ("19", "21", "X")
|
| 30 |
+
TEST_CHROMOSOMES = ("7", "13")
|
| 31 |
+
SE_METRIC_THRESHOLD = 1.0
|
| 32 |
+
HIGH_ACTIVITY_THRESHOLD = 0.5
|
| 33 |
+
|
| 34 |
+
RAW_FEATURES = Features(
|
| 35 |
+
{
|
| 36 |
+
"IDs": Value("string"),
|
| 37 |
+
"chr": Value("string"),
|
| 38 |
+
"data_project": Value("string"),
|
| 39 |
+
"OL": Value("string"),
|
| 40 |
+
"class": Value("string"),
|
| 41 |
+
"K562_log2FC": Value("float64"),
|
| 42 |
+
"HepG2_log2FC": Value("float64"),
|
| 43 |
+
"SKNSH_log2FC": Value("float64"),
|
| 44 |
+
"K562_lfcSE": Value("float64"),
|
| 45 |
+
"HepG2_lfcSE": Value("float64"),
|
| 46 |
+
"SKNSH_lfcSE": Value("float64"),
|
| 47 |
+
"sequence": Value("string"),
|
| 48 |
+
}
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
OUTPUT_FEATURES = Features(
|
| 52 |
+
{
|
| 53 |
+
"id": Value("string"),
|
| 54 |
+
"split": Value("string"),
|
| 55 |
+
"chromosome": Value("string"),
|
| 56 |
+
"data_project": Value("string"),
|
| 57 |
+
"oligo": Value("string"),
|
| 58 |
+
"variant_class": Value("string"),
|
| 59 |
+
"sequence": Value("string"),
|
| 60 |
+
"sequence_length": Value("int32"),
|
| 61 |
+
"reverse_complement": Value("string"),
|
| 62 |
+
"forward_rc_concat": Value("string"),
|
| 63 |
+
"K562_log2FC": Value("float32"),
|
| 64 |
+
"HepG2_log2FC": Value("float32"),
|
| 65 |
+
"SKNSH_log2FC": Value("float32"),
|
| 66 |
+
"K562_lfcSE": Value("float32"),
|
| 67 |
+
"HepG2_lfcSE": Value("float32"),
|
| 68 |
+
"SKNSH_lfcSE": Value("float32"),
|
| 69 |
+
"K562_log2FC_train_zscore": Value("float32"),
|
| 70 |
+
"HepG2_log2FC_train_zscore": Value("float32"),
|
| 71 |
+
"SKNSH_log2FC_train_zscore": Value("float32"),
|
| 72 |
+
"all_se_le_1": Value("bool"),
|
| 73 |
+
"any_log2fc_gt_0_5": Value("bool"),
|
| 74 |
+
}
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def parse_args() -> argparse.Namespace:
|
| 81 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--repo-id",
|
| 84 |
+
default="HuggingFaceBio/malinois-mpra-regression",
|
| 85 |
+
help="Dataset repository to push to.",
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--source",
|
| 89 |
+
default=str(
|
| 90 |
+
DEFAULT_LOCAL_SOURCE if DEFAULT_LOCAL_SOURCE.exists() else SOURCE_URL
|
| 91 |
+
),
|
| 92 |
+
help="Local source TSV path or public source URL.",
|
| 93 |
+
)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--output-dir",
|
| 96 |
+
type=Path,
|
| 97 |
+
default=Path(__file__).resolve().parent / "build",
|
| 98 |
+
help="Directory for generated card, metadata, and optional local save.",
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--cache-dir",
|
| 102 |
+
type=Path,
|
| 103 |
+
default=Path(__file__).resolve().parent / "cache",
|
| 104 |
+
help="Hugging Face datasets cache directory.",
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument("--num-proc", type=int, default=8)
|
| 107 |
+
parser.add_argument("--push", action="store_true", help="Push dataset/card/script.")
|
| 108 |
+
parser.add_argument(
|
| 109 |
+
"--private", action="store_true", help="Create/update as private."
|
| 110 |
+
)
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--save-local",
|
| 113 |
+
action="store_true",
|
| 114 |
+
help="Also save the processed DatasetDict under output-dir/dataset.",
|
| 115 |
+
)
|
| 116 |
+
return parser.parse_args()
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def normalize_chromosome(value: Any) -> str:
|
| 120 |
+
chrom = str(value).strip()
|
| 121 |
+
if chrom.lower().startswith("chr"):
|
| 122 |
+
chrom = chrom[3:]
|
| 123 |
+
if chrom.endswith(".0") and chrom[:-2].isdigit():
|
| 124 |
+
chrom = chrom[:-2]
|
| 125 |
+
return chrom.upper() if chrom.upper() in {"X", "Y", "M", "MT"} else chrom
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def normalize_sequence(value: Any) -> str:
|
| 129 |
+
return str(value).strip().upper()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def reverse_complement(sequence: str) -> str:
|
| 133 |
+
return sequence.translate(COMPLEMENT)[::-1].upper()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def finite_batch(batch: dict[str, list[Any]]) -> list[bool]:
|
| 137 |
+
mask = np.ones(len(batch["sequence"]), dtype=bool)
|
| 138 |
+
for column in (*TARGET_COLUMNS, *SE_COLUMNS):
|
| 139 |
+
mask &= np.isfinite(np.asarray(batch[column], dtype=np.float64))
|
| 140 |
+
mask &= np.asarray([bool(normalize_sequence(seq)) for seq in batch["sequence"]])
|
| 141 |
+
return mask.tolist()
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def split_name_for_chromosome(chromosome: Any) -> str:
|
| 145 |
+
chrom = normalize_chromosome(chromosome)
|
| 146 |
+
if chrom in VALIDATION_CHROMOSOMES:
|
| 147 |
+
return "validation"
|
| 148 |
+
if chrom in TEST_CHROMOSOMES:
|
| 149 |
+
return "test"
|
| 150 |
+
return "train"
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def split_by_chromosome(dataset: Dataset) -> DatasetDict:
|
| 154 |
+
return DatasetDict(
|
| 155 |
+
{
|
| 156 |
+
split: dataset.filter(
|
| 157 |
+
lambda row, split=split: split_name_for_chromosome(row["chr"]) == split,
|
| 158 |
+
desc=f"Selecting {split} split",
|
| 159 |
+
)
|
| 160 |
+
for split in ("train", "validation", "test")
|
| 161 |
+
}
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def preprocess_split(dataset: Dataset, split: str, num_proc: int) -> Dataset:
|
| 166 |
+
def preprocess_batch(batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
|
| 167 |
+
sequences = [normalize_sequence(seq) for seq in batch["sequence"]]
|
| 168 |
+
rc_sequences = [reverse_complement(seq) for seq in sequences]
|
| 169 |
+
output: dict[str, list[Any]] = {
|
| 170 |
+
"id": [str(value) for value in batch["IDs"]],
|
| 171 |
+
"split": [split] * len(sequences),
|
| 172 |
+
"chromosome": [normalize_chromosome(value) for value in batch["chr"]],
|
| 173 |
+
"data_project": [str(value) for value in batch["data_project"]],
|
| 174 |
+
"oligo": [str(value) for value in batch["OL"]],
|
| 175 |
+
"variant_class": [str(value) for value in batch["class"]],
|
| 176 |
+
"sequence": sequences,
|
| 177 |
+
"sequence_length": [len(seq) for seq in sequences],
|
| 178 |
+
"reverse_complement": rc_sequences,
|
| 179 |
+
"forward_rc_concat": [
|
| 180 |
+
f"<dna>{seq}</dna><dna>{rc_seq}</dna>"
|
| 181 |
+
for seq, rc_seq in zip(sequences, rc_sequences)
|
| 182 |
+
],
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
target_arrays = [
|
| 186 |
+
np.asarray(batch[column], dtype=np.float64) for column in TARGET_COLUMNS
|
| 187 |
+
]
|
| 188 |
+
se_arrays = [
|
| 189 |
+
np.asarray(batch[column], dtype=np.float64) for column in SE_COLUMNS
|
| 190 |
+
]
|
| 191 |
+
for column, values in zip(TARGET_COLUMNS, target_arrays):
|
| 192 |
+
output[column] = values.astype(np.float32).tolist()
|
| 193 |
+
for column, values in zip(SE_COLUMNS, se_arrays):
|
| 194 |
+
output[column] = values.astype(np.float32).tolist()
|
| 195 |
+
|
| 196 |
+
all_se_le_1 = np.ones(len(se_arrays[0]), dtype=bool)
|
| 197 |
+
for values in se_arrays:
|
| 198 |
+
all_se_le_1 &= values <= SE_METRIC_THRESHOLD
|
| 199 |
+
high_activity = np.zeros(len(target_arrays[0]), dtype=bool)
|
| 200 |
+
for values in target_arrays:
|
| 201 |
+
high_activity |= values > HIGH_ACTIVITY_THRESHOLD
|
| 202 |
+
output["all_se_le_1"] = all_se_le_1.tolist()
|
| 203 |
+
output["any_log2fc_gt_0_5"] = high_activity.tolist()
|
| 204 |
+
return output
|
| 205 |
+
|
| 206 |
+
map_kwargs: dict[str, Any] = {
|
| 207 |
+
"batched": True,
|
| 208 |
+
"remove_columns": dataset.column_names,
|
| 209 |
+
"desc": f"Preprocessing {split} split",
|
| 210 |
+
}
|
| 211 |
+
if num_proc > 1:
|
| 212 |
+
map_kwargs["num_proc"] = num_proc
|
| 213 |
+
return dataset.map(preprocess_batch, **map_kwargs)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def fit_train_zscore(train: Dataset) -> dict[str, dict[str, float]]:
|
| 217 |
+
stats: dict[str, dict[str, float]] = {}
|
| 218 |
+
for column in TARGET_COLUMNS:
|
| 219 |
+
values = np.asarray(train[column], dtype=np.float64)
|
| 220 |
+
mean = float(np.mean(values))
|
| 221 |
+
std = float(np.std(values))
|
| 222 |
+
if not math.isfinite(std) or std <= 0.0:
|
| 223 |
+
raise ValueError(f"Cannot z-score {column}: std={std}")
|
| 224 |
+
stats[column] = {"mean": mean, "std": std}
|
| 225 |
+
return stats
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def add_train_zscores(dataset: Dataset, stats: dict[str, dict[str, float]]) -> Dataset:
|
| 229 |
+
def add_batch(batch: dict[str, list[Any]]) -> dict[str, list[float]]:
|
| 230 |
+
output = {}
|
| 231 |
+
for column in TARGET_COLUMNS:
|
| 232 |
+
values = np.asarray(batch[column], dtype=np.float64)
|
| 233 |
+
spec = stats[column]
|
| 234 |
+
output[f"{column}_train_zscore"] = (
|
| 235 |
+
((values - spec["mean"]) / spec["std"]).astype(np.float32).tolist()
|
| 236 |
+
)
|
| 237 |
+
return output
|
| 238 |
+
|
| 239 |
+
return dataset.map(
|
| 240 |
+
add_batch, batched=True, desc=f"Adding z-scores to {dataset[0]['split']}"
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def load_source_dataset(args: argparse.Namespace) -> Dataset:
|
| 245 |
+
dataset = load_dataset(
|
| 246 |
+
"csv",
|
| 247 |
+
data_files=args.source,
|
| 248 |
+
delimiter="\t",
|
| 249 |
+
split="train",
|
| 250 |
+
features=RAW_FEATURES,
|
| 251 |
+
cache_dir=str(args.cache_dir),
|
| 252 |
+
)
|
| 253 |
+
return dataset.filter(
|
| 254 |
+
finite_batch,
|
| 255 |
+
batched=True,
|
| 256 |
+
desc="Filtering finite labels, SEs, and nonempty sequences",
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def build_dataset(args: argparse.Namespace) -> tuple[DatasetDict, dict[str, Any]]:
|
| 261 |
+
raw = load_source_dataset(args)
|
| 262 |
+
raw_splits = split_by_chromosome(raw)
|
| 263 |
+
processed = DatasetDict(
|
| 264 |
+
{
|
| 265 |
+
split: preprocess_split(raw_splits[split], split, args.num_proc)
|
| 266 |
+
for split in ("train", "validation", "test")
|
| 267 |
+
}
|
| 268 |
+
)
|
| 269 |
+
zscore_stats = fit_train_zscore(processed["train"])
|
| 270 |
+
processed = DatasetDict(
|
| 271 |
+
{
|
| 272 |
+
split: add_train_zscores(processed[split], zscore_stats)
|
| 273 |
+
for split in ("train", "validation", "test")
|
| 274 |
+
}
|
| 275 |
+
)
|
| 276 |
+
processed = DatasetDict(
|
| 277 |
+
{
|
| 278 |
+
split: processed[split].cast(OUTPUT_FEATURES)
|
| 279 |
+
for split in ("train", "validation", "test")
|
| 280 |
+
}
|
| 281 |
+
)
|
| 282 |
+
metadata = collect_metadata(processed, zscore_stats, args)
|
| 283 |
+
return processed, metadata
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def collect_metadata(
|
| 287 |
+
dataset: DatasetDict,
|
| 288 |
+
zscore_stats: dict[str, dict[str, float]],
|
| 289 |
+
args: argparse.Namespace,
|
| 290 |
+
) -> dict[str, Any]:
|
| 291 |
+
split_stats: dict[str, dict[str, Any]] = {}
|
| 292 |
+
for split, split_dataset in dataset.items():
|
| 293 |
+
lengths = np.asarray(split_dataset["sequence_length"], dtype=np.float64)
|
| 294 |
+
all_se = np.asarray(split_dataset["all_se_le_1"], dtype=bool)
|
| 295 |
+
high = np.asarray(split_dataset["any_log2fc_gt_0_5"], dtype=bool)
|
| 296 |
+
split_stats[split] = {
|
| 297 |
+
"num_rows": len(split_dataset),
|
| 298 |
+
"all_se_le_1_rows": int(all_se.sum()),
|
| 299 |
+
"any_log2fc_gt_0_5_rows": int(high.sum()),
|
| 300 |
+
"sequence_length_min": int(lengths.min()),
|
| 301 |
+
"sequence_length_mean": float(lengths.mean()),
|
| 302 |
+
"sequence_length_max": int(lengths.max()),
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
return {
|
| 306 |
+
"source": args.source,
|
| 307 |
+
"source_url": SOURCE_URL,
|
| 308 |
+
"repo_id": args.repo_id,
|
| 309 |
+
"target_columns": list(TARGET_COLUMNS),
|
| 310 |
+
"standard_error_columns": list(SE_COLUMNS),
|
| 311 |
+
"validation_chromosomes": list(VALIDATION_CHROMOSOMES),
|
| 312 |
+
"test_chromosomes": list(TEST_CHROMOSOMES),
|
| 313 |
+
"metric_se_threshold": SE_METRIC_THRESHOLD,
|
| 314 |
+
"high_activity_threshold": HIGH_ACTIVITY_THRESHOLD,
|
| 315 |
+
"train_zscore_stats": zscore_stats,
|
| 316 |
+
"splits": split_stats,
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def metric_rows(dataset: DatasetDict) -> dict[str, int]:
|
| 321 |
+
return {
|
| 322 |
+
split: int(np.asarray(split_dataset["all_se_le_1"], dtype=bool).sum())
|
| 323 |
+
for split, split_dataset in dataset.items()
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def render_card(metadata: dict[str, Any]) -> str:
|
| 328 |
+
train = metadata["splits"]["train"]
|
| 329 |
+
validation = metadata["splits"]["validation"]
|
| 330 |
+
test = metadata["splits"]["test"]
|
| 331 |
+
zstats = metadata["train_zscore_stats"]
|
| 332 |
+
total_rows = sum(split["num_rows"] for split in metadata["splits"].values())
|
| 333 |
+
return f"""---
|
| 334 |
+
pretty_name: Malinois/Gosai MPRA Regression
|
| 335 |
+
task_categories:
|
| 336 |
+
- tabular-regression
|
| 337 |
+
tags:
|
| 338 |
+
- biology
|
| 339 |
+
- genomics
|
| 340 |
+
- dna
|
| 341 |
+
- mpra
|
| 342 |
+
- carbon
|
| 343 |
+
size_categories:
|
| 344 |
+
- 100K<n<1M
|
| 345 |
+
---
|
| 346 |
+
|
| 347 |
+
# Malinois/Gosai MPRA Regression
|
| 348 |
+
|
| 349 |
+
This dataset preprocesses the Gosai et al. 2024 supplementary MPRA table used by the
|
| 350 |
+
Malinois benchmark for supervised DNA-to-activity regression. Each row contains a DNA
|
| 351 |
+
sequence and three cell-type-specific activity targets: `K562_log2FC`,
|
| 352 |
+
`HepG2_log2FC`, and `SKNSH_log2FC`.
|
| 353 |
+
|
| 354 |
+
No new license is asserted by this preprocessing. Users should follow the terms of
|
| 355 |
+
the source publication and supplementary data.
|
| 356 |
+
|
| 357 |
+
## Source
|
| 358 |
+
|
| 359 |
+
- Publication: Gosai et al., *Machine-guided design of cell-type-targeting
|
| 360 |
+
cis-regulatory elements*, Nature 2024.
|
| 361 |
+
- Source table: `41586_2024_8070_MOESM4_ESM.txt`.
|
| 362 |
+
- Source URL: `{metadata["source_url"]}`.
|
| 363 |
+
|
| 364 |
+
## Splits
|
| 365 |
+
|
| 366 |
+
Chromosome splits match the Carbon fine-tuning experiments and the public Malinois
|
| 367 |
+
setup we used:
|
| 368 |
+
|
| 369 |
+
| Split | Chromosomes | Rows | Rows with all SE <= 1.0 |
|
| 370 |
+
|---|---:|---:|---:|
|
| 371 |
+
| train | all except validation/test chromosomes | {train["num_rows"]:,} | {train["all_se_le_1_rows"]:,} |
|
| 372 |
+
| validation | 19, 21, X | {validation["num_rows"]:,} | {validation["all_se_le_1_rows"]:,} |
|
| 373 |
+
| test | 7, 13 | {test["num_rows"]:,} | {test["all_se_le_1_rows"]:,} |
|
| 374 |
+
|
| 375 |
+
Total rows after filtering finite targets/standard errors and nonempty sequences:
|
| 376 |
+
{total_rows:,}.
|
| 377 |
+
|
| 378 |
+
## Columns
|
| 379 |
+
|
| 380 |
+
- `id`: original row identifier from the source table.
|
| 381 |
+
- `split`: train, validation, or test.
|
| 382 |
+
- `chromosome`: normalized chromosome label.
|
| 383 |
+
- `data_project`, `oligo`, `variant_class`: source metadata.
|
| 384 |
+
- `sequence`: uppercase DNA sequence.
|
| 385 |
+
- `reverse_complement`: reverse complement of `sequence`.
|
| 386 |
+
- `forward_rc_concat`: `<dna>sequence</dna><dna>reverse_complement</dna>`,
|
| 387 |
+
matching the best Carbon fine-tuning recipe.
|
| 388 |
+
- `K562_log2FC`, `HepG2_log2FC`, `SKNSH_log2FC`: raw regression targets.
|
| 389 |
+
- `K562_lfcSE`, `HepG2_lfcSE`, `SKNSH_lfcSE`: target standard errors.
|
| 390 |
+
- `*_train_zscore`: target standardized using train-split mean/std.
|
| 391 |
+
- `all_se_le_1`: true when all three SE columns are `<= 1.0`; this was the
|
| 392 |
+
main reported validation/test metric filter.
|
| 393 |
+
- `any_log2fc_gt_0_5`: true when any target is greater than `0.5`; this was used
|
| 394 |
+
for optional high-activity training upsampling.
|
| 395 |
+
|
| 396 |
+
Train z-score statistics:
|
| 397 |
+
|
| 398 |
+
| Target | Mean | Std |
|
| 399 |
+
|---|---:|---:|
|
| 400 |
+
| K562_log2FC | {zstats["K562_log2FC"]["mean"]:.8f} | {zstats["K562_log2FC"]["std"]:.8f} |
|
| 401 |
+
| HepG2_log2FC | {zstats["HepG2_log2FC"]["mean"]:.8f} | {zstats["HepG2_log2FC"]["std"]:.8f} |
|
| 402 |
+
| SKNSH_log2FC | {zstats["SKNSH_log2FC"]["mean"]:.8f} | {zstats["SKNSH_log2FC"]["std"]:.8f} |
|
| 403 |
+
|
| 404 |
+
## Usage
|
| 405 |
+
|
| 406 |
+
```py
|
| 407 |
+
from datasets import load_dataset
|
| 408 |
+
|
| 409 |
+
ds = load_dataset("{metadata["repo_id"]}")
|
| 410 |
+
train = ds["train"]
|
| 411 |
+
validation_metric = ds["validation"].filter(lambda row: row["all_se_le_1"])
|
| 412 |
+
|
| 413 |
+
example = train[0]
|
| 414 |
+
sequence = example["forward_rc_concat"]
|
| 415 |
+
labels = [
|
| 416 |
+
example["K562_log2FC_train_zscore"],
|
| 417 |
+
example["HepG2_log2FC_train_zscore"],
|
| 418 |
+
example["SKNSH_log2FC_train_zscore"],
|
| 419 |
+
]
|
| 420 |
+
```
|
| 421 |
+
|
| 422 |
+
To recreate the dataset:
|
| 423 |
+
|
| 424 |
+
```sh
|
| 425 |
+
python create_dataset.py --repo-id {metadata["repo_id"]} --push
|
| 426 |
+
```
|
| 427 |
+
"""
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def write_artifacts(args: argparse.Namespace, metadata: dict[str, Any]) -> None:
|
| 431 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 432 |
+
(args.output_dir / "metadata.json").write_text(
|
| 433 |
+
json.dumps(metadata, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
| 434 |
+
)
|
| 435 |
+
(args.output_dir / "README.md").write_text(render_card(metadata), encoding="utf-8")
|
| 436 |
+
shutil.copy2(Path(__file__), args.output_dir / "create_dataset.py")
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def push_artifacts(args: argparse.Namespace, dataset: DatasetDict) -> None:
|
| 440 |
+
dataset.push_to_hub(args.repo_id, private=args.private)
|
| 441 |
+
api = HfApi()
|
| 442 |
+
api.upload_file(
|
| 443 |
+
path_or_fileobj=str(args.output_dir / "README.md"),
|
| 444 |
+
path_in_repo="README.md",
|
| 445 |
+
repo_id=args.repo_id,
|
| 446 |
+
repo_type="dataset",
|
| 447 |
+
commit_message="Add Malinois MPRA dataset card",
|
| 448 |
+
)
|
| 449 |
+
api.upload_file(
|
| 450 |
+
path_or_fileobj=str(args.output_dir / "create_dataset.py"),
|
| 451 |
+
path_in_repo="create_dataset.py",
|
| 452 |
+
repo_id=args.repo_id,
|
| 453 |
+
repo_type="dataset",
|
| 454 |
+
commit_message="Add dataset creation script",
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def main() -> None:
|
| 459 |
+
args = parse_args()
|
| 460 |
+
dataset, metadata = build_dataset(args)
|
| 461 |
+
write_artifacts(args, metadata)
|
| 462 |
+
|
| 463 |
+
if args.save_local:
|
| 464 |
+
local_path = args.output_dir / "dataset"
|
| 465 |
+
if local_path.exists():
|
| 466 |
+
shutil.rmtree(local_path)
|
| 467 |
+
dataset.save_to_disk(local_path)
|
| 468 |
+
|
| 469 |
+
print(json.dumps(metadata, indent=2, sort_keys=True))
|
| 470 |
+
if args.push:
|
| 471 |
+
push_artifacts(args, dataset)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
if __name__ == "__main__":
|
| 475 |
+
main()
|