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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
#!/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()