from __future__ import annotations import csv import gzip import hashlib import io import json from collections import Counter, defaultdict from pathlib import Path from typing import Any, Iterable from pyfaidx import Fasta EXPORT_ROOT = Path(__file__).resolve().parent WORKSPACE = Path(__file__).resolve().parents[3] DATA_DIR = EXPORT_ROOT / "data" PROVENANCE_DIR = EXPORT_ROOT / "provenance" RUN_ROOT = ( WORKSPACE / "outputs" / "runs" / "multiscale_pseudosnp_transfer" / "20260808T003427Z_multiscale_pseudosnp_svd_344bbf0cca5b" ) SUPERVISED_SOURCE = RUN_ROOT / "oof_predictions_pip_ge_0.30.tsv" PSEUDO_COORDINATES = RUN_ROOT / "pseudo_snp_coordinates.tsv" PRETRAINING_RECEIPT = RUN_ROOT / "pretraining_receipt.json" PRETRAINING_EXCLUSION_RECEIPT = RUN_ROOT / "pretraining_exclusion_receipt.json" HG38_FASTA = WORKSPACE / "data" / "reference" / "hg38.fa" SEQUENCE_LENGTH = 3_000 MUTATION_INDEX = 1_500 PSEUDO_SHARDS = 4 EXPECTED = { "supervised_source_sha256": "fc5a1621a994340b37759ea4e12a28d970f8435515fee92452691eab4b4f9521", "governed_development_sha256": "f3d29d9397509f7162d31bb9cc3f9e41e08e2507bceb14123a9a05c988017eb0", "pseudo_coordinate_sha256": "c1f1f561000ed551a859a5a21ed855e0f2fad98b81d2b3ebc995084c00fc0e60", "pseudo_feature_csr_sha256": "a9ce199b9a6e7c6185cd3945ef468e0051f89fc813277e86ab4c8ce23cdbc858", "hg38_fasta_sha256": "5be01555d98347fdb3714dc84c6f77c9d8bc774adcf32c6f7a8fa06f5baf5e51", "fold_assignment_sha256": "b0acffb900e897160599de1269fe3b27e70cff90bd37c557417a2ffa86389da4", } SCORE_COLUMNS = { "transfer_fixed_raw_score", "scratch_fixed_raw_score", "transfer_tuned_raw_score", "scratch_tuned_raw_score", "transfer_fixed_fold_rank_score", "scratch_fixed_fold_rank_score", "transfer_tuned_fold_rank_score", "scratch_tuned_fold_rank_score", } def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def atomic_json(path: Path, payload: Any) -> None: temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text( json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n", ) temporary.replace(path) def deterministic_gzip_text(path: Path): raw = path.open("wb") compressed = gzip.GzipFile(filename="", mode="wb", fileobj=raw, compresslevel=9, mtime=0) return raw, compressed, io.TextIOWrapper(compressed, encoding="utf-8", newline="\n") def close_gzip_text(handles: tuple[Any, Any, Any]) -> None: raw, compressed, text = handles text.flush() text.detach() compressed.close() raw.close() def json_line(record: dict[str, Any]) -> str: return json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n" def optional_float(value: str) -> float | None: return None if value == "" else float(value) def build_supervised() -> dict[str, Any]: if sha256_file(SUPERVISED_SOURCE) != EXPECTED["supervised_source_sha256"]: raise RuntimeError("locked supervised source hash changed") with SUPERVISED_SOURCE.open("r", encoding="utf-8", newline="") as handle: reader = csv.DictReader(handle, delimiter="\t") source_fields = list(reader.fieldnames or []) if not source_fields or not SCORE_COLUMNS.issubset(source_fields): raise RuntimeError("supervised source schema changed") raw_fields = [field for field in source_fields if field not in SCORE_COLUMNS] rows = list(reader) label_counts = Counter(int(row["label"]) for row in rows) fold_counts = Counter(int(row["outer_fold"]) for row in rows) group_counts = Counter(row["split_group_id"] for row in rows) matched: dict[str, list[dict[str, str]]] = defaultdict(list) for row in rows: matched[row["matched_set_id"]].append(row) reference = row["sequence_ref"].upper() alternate = row["sequence_alt"].upper() if len(reference) != SEQUENCE_LENGTH or len(alternate) != SEQUENCE_LENGTH: raise RuntimeError("supervised sequence length changed") differences = [index for index, (a, b) in enumerate(zip(reference, alternate)) if a != b] if differences != [MUTATION_INDEX]: raise RuntimeError("supervised sequence pair is not a centered single-base substitution") if reference[MUTATION_INDEX] != row["ref"].upper(): raise RuntimeError("supervised REF is not centered") if alternate[MUTATION_INDEX] != row["alt"].upper(): raise RuntimeError("supervised ALT is not centered") if len(rows) != 168 or label_counts != Counter({0: 112, 1: 56}): raise RuntimeError("supervised cohort inventory changed") if fold_counts != Counter({0: 39, 1: 30, 2: 45, 3: 27, 4: 27}): raise RuntimeError("supervised fold inventory changed") if len(group_counts) != 49 or len(matched) != 56: raise RuntimeError("supervised grouping inventory changed") if set(row["source"] for row in rows) != {"oa2025_st9"}: raise RuntimeError("supervised source boundary changed") for triplet in matched.values(): if len(triplet) != 3 or sum(int(row["label"]) for row in triplet) != 1: raise RuntimeError("supervised matched triplet changed") folds = {int(row["outer_fold"]) for row in triplet} if len(folds) != 1: raise RuntimeError("matched triplet crosses outer folds") exact_path = DATA_DIR / "supervised_full_metadata.tsv.gz" exact_handles = deterministic_gzip_text(exact_path) exact_writer = csv.DictWriter( exact_handles[2], fieldnames=raw_fields, delimiter="\t", lineterminator="\n" ) exact_writer.writeheader() for row in rows: exact_writer.writerow({field: row[field] for field in raw_fields}) close_gzip_text(exact_handles) model_path = DATA_DIR / "supervised_model_input.jsonl.gz" model_handles = deterministic_gzip_text(model_path) for row in rows: record = { "example_id": row["example_id"], "matched_set_id": row["matched_set_id"], "matched_positive_id": row["matched_positive_id"], "label": int(row["label"]), "label_role": row["label_role"], "outer_fold": int(row["outer_fold"]), "split_group_id": row["split_group_id"], "chrom": row["chrom"], "pos": int(row["pos"]), "ref": row["ref"], "alt": row["alt"], "sequence_ref": row["sequence_ref"], "sequence_alt": row["sequence_alt"], "source": row["source"], "phenotype": row["phenotype"], "source_variant_key": row["source_variant_key"], "label_evidence_kind": row["label_evidence_kind"], "pip": optional_float(row["PIP"]), "analysis_positive_pip": optional_float(row["analysis_positive_pip"]), "maf": optional_float(row["maf"]), "alt_eaf": optional_float(row["alt_eaf"]), "credible_set_purity": optional_float(row["credible_set_purity"]), } model_handles[2].write(json_line(record)) close_gzip_text(model_handles) return { "rows": len(rows), "positives": label_counts[1], "controls": label_counts[0], "matched_sets": len(matched), "guarded_components": len(group_counts), "fold_counts": {str(key): fold_counts[key] for key in sorted(fold_counts)}, "sequence_length": SEQUENCE_LENGTH, "mutation_index_zero_based": MUTATION_INDEX, "source": "oa2025_st9", "files": [exact_path, model_path], } def build_pretraining() -> dict[str, Any]: if sha256_file(PSEUDO_COORDINATES) != EXPECTED["pseudo_coordinate_sha256"]: raise RuntimeError("locked pseudo-SNP coordinate hash changed") with PSEUDO_COORDINATES.open("r", encoding="utf-8", newline="") as handle: rows = list(csv.DictReader(handle, delimiter="\t")) if len(rows) != 20_000: raise RuntimeError("pseudo-SNP inventory changed") shard_size = (len(rows) + PSEUDO_SHARDS - 1) // PSEUDO_SHARDS shard_paths = [ DATA_DIR / f"pretraining-{index:05d}-of-{PSEUDO_SHARDS:05d}.jsonl.gz" for index in range(PSEUDO_SHARDS) ] shard_handles = [deterministic_gzip_text(path) for path in shard_paths] seen: set[tuple[str, int]] = set() fasta = Fasta(str(HG38_FASTA), as_raw=True, sequence_always_upper=True, rebuild=False) try: for index, row in enumerate(rows): pseudo_index = int(row["pseudo_index"]) chrom = row["chrom"].removeprefix("chr") pos = int(row["pos"]) ref = row["ref"].upper() alt = row["alt"].upper() if pseudo_index != index or (chrom, pos) in seen or ref == alt: raise RuntimeError("pseudo-SNP coordinate order or identity changed") seen.add((chrom, pos)) key = f"chr{chrom}" if f"chr{chrom}" in fasta else chrom start = pos - 1 - MUTATION_INDEX reference = str(fasta[key][start : start + SEQUENCE_LENGTH]).upper() if len(reference) != SEQUENCE_LENGTH or reference[MUTATION_INDEX] != ref: raise RuntimeError("pseudo-SNP reference sequence mismatch") alternate = reference[:MUTATION_INDEX] + alt + reference[MUTATION_INDEX + 1 :] record = { "pseudo_index": pseudo_index, "chrom": chrom, "pos": pos, "ref": ref, "alt": alt, "sequence_ref": reference, "sequence_alt": alternate, } shard_index = min(index // shard_size, PSEUDO_SHARDS - 1) shard_handles[shard_index][2].write(json_line(record)) finally: fasta.close() for handles in shard_handles: close_gzip_text(handles) coordinates_copy = DATA_DIR / "pseudo_snp_coordinates.tsv" coordinates_copy.write_bytes(PSEUDO_COORDINATES.read_bytes()) return { "rows": len(rows), "sequence_length": SEQUENCE_LENGTH, "mutation_index_zero_based": MUTATION_INDEX, "label_free": True, "seed": 20260808, "files": [*shard_paths, coordinates_copy], } def copy_receipts() -> list[Path]: outputs: list[Path] = [] for source, name in ( (PRETRAINING_RECEIPT, "pretraining_receipt.json"), (PRETRAINING_EXCLUSION_RECEIPT, "pretraining_exclusion_receipt.json"), ): target = PROVENANCE_DIR / name payload = json.loads(source.read_text(encoding="utf-8")) atomic_json(target, payload) outputs.append(target) return outputs def inventory(paths: Iterable[Path]) -> list[dict[str, Any]]: result = [] for path in sorted(set(paths)): result.append( { "path": path.relative_to(EXPORT_ROOT).as_posix(), "bytes": path.stat().st_size, "sha256": sha256_file(path), } ) return result def main() -> None: DATA_DIR.mkdir(parents=True, exist_ok=True) PROVENANCE_DIR.mkdir(parents=True, exist_ok=True) supervised = build_supervised() pretraining = build_pretraining() receipts = copy_receipts() data_files = [*supervised.pop("files"), *pretraining.pop("files"), *receipts] provenance = { "schema_version": "cembra-hf-private-training-dataset.v1", "claim_scope": "exact_model_ready_training_examples_for_private_research_reproduction", "model_repo": "https://huggingface.co/zzhaobz/cembra", "supervised": supervised, "pretraining": pretraining, "source_records": { "oa2025": { "title": "Translational genomics of osteoarthritis in 1,962,069 individuals", "doi": "10.1038/s41586-025-08771-z", "pmcid": "PMC12119359", "license": "CC BY 4.0", "source_table": "Supplementary Table 9", }, "reference": { "name": "UCSC hg38 FASTA", "url": "https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.fa.gz", "fasta_sha256": EXPECTED["hg38_fasta_sha256"], }, }, "locked_hashes": EXPECTED, "privacy": { "contains_individual_level_genotypes": False, "contains_individual_level_phenotypes": False, "contains_direct_person_identifiers": False, "unit": "variant-level reference/alternate sequence pair", }, "excluded_upstream_files": [ "full OA GWAS summary-statistics archives", "the full 3.2 GB hg38 FASTA", "individual-level UK Biobank or arcOGEN genotype/phenotype data", "model predictions and trained weights", ], "files": inventory(data_files), } manifest_path = EXPORT_ROOT / "DATASET_MANIFEST.json" atomic_json(manifest_path, provenance) package_files = [ path for path in EXPORT_ROOT.rglob("*") if path.is_file() and path.name != "SHA256SUMS" and not path.name.endswith(".tmp") ] sums = "".join( f"{sha256_file(path)} {path.relative_to(EXPORT_ROOT).as_posix()}\n" for path in sorted(package_files) ) (EXPORT_ROOT / "SHA256SUMS").write_text(sums, encoding="ascii", newline="\n") print(json.dumps({"files": len(package_files) + 1, "manifest": provenance}, indent=2)) if __name__ == "__main__": main()