Download src/cli/build_paper_benchmarks.py from manhngvu/dna_noc: direct link, hf CLI and curl.
- Browser
- Download file 30.5 kB
-
https://huggingface.co/datasets/manhngvu/dna_noc/resolve/main/src/cli/build_paper_benchmarks.py
- Command line
-
hf download hf://datasets/manhngvu/dna_noc/src/cli/build_paper_benchmarks.py
-
curl -L -o build_paper_benchmarks.py https://huggingface.co/datasets/manhngvu/dna_noc/resolve/main/src/cli/build_paper_benchmarks.py
30.5 kB
| """Build paper-strength multi-split benchmark datasets for PROVEDIt.""" | |
| from __future__ import annotations | |
| import csv | |
| import json | |
| import random | |
| import sys | |
| from collections import Counter | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Dict, Iterable, List, Tuple | |
| ROOT = Path(__file__).resolve().parents[2] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from src.cli.build_study_datasets import ( # noqa: E402 | |
| PROCESSED_ROOT, | |
| BenchmarkSpec, | |
| PanelSpec, | |
| SampleMeta, | |
| RD12_SPEC, | |
| RD14_SPEC, | |
| collect_canonical_samples, | |
| load_reference_donors, | |
| normalize_allele, | |
| normalize_marker, | |
| ) | |
| class SplitSpec: | |
| split_id: str | |
| donor_seed: int | |
| partition_seed: int | |
| class PaperBenchmarkSpec: | |
| dataset_id: str | |
| study_id: str | |
| source_mode: str | |
| known_count: int | |
| unknown_count: int | |
| panels: Tuple[PanelSpec, ...] | |
| splits: Tuple[SplitSpec, ...] | |
| primary_task: str | |
| def make_paper_spec(base: BenchmarkSpec, dataset_id: str, primary_task: str) -> PaperBenchmarkSpec: | |
| splits = tuple( | |
| SplitSpec( | |
| split_id=f"split_{idx:02d}", | |
| donor_seed=41 + idx, | |
| partition_seed=1041 + idx, | |
| ) | |
| for idx in range(1, 11) | |
| ) | |
| return PaperBenchmarkSpec( | |
| dataset_id=dataset_id, | |
| study_id=base.study_id, | |
| source_mode=base.source_mode, | |
| known_count=base.known_count, | |
| unknown_count=base.unknown_count, | |
| panels=base.panels, | |
| splits=splits, | |
| primary_task=primary_task, | |
| ) | |
| RD14_PAPER_SPEC = make_paper_spec( | |
| RD14_SPEC, | |
| dataset_id="rd14-fullref-50_multisplit_v2", | |
| primary_task="main benchmark", | |
| ) | |
| RD12_PAPER_SPEC = make_paper_spec( | |
| RD12_SPEC, | |
| dataset_id="rd12-fullref-61_multisplit_v2", | |
| primary_task="secondary benchmark", | |
| ) | |
| def join_ints(values: Iterable[int]) -> str: | |
| return ",".join(str(value) for value in values) | |
| def make_known_unknown_split( | |
| all_ids: List[int], known_count: int, unknown_count: int, seed: int | |
| ) -> Tuple[List[int], List[int]]: | |
| rng = random.Random(seed) | |
| ids = list(all_ids) | |
| rng.shuffle(ids) | |
| unknown_ids = sorted(ids[:unknown_count]) | |
| known_ids = sorted(ids[unknown_count : unknown_count + known_count]) | |
| return known_ids, unknown_ids | |
| def make_partition_map(sample_map: Dict[Tuple[str, str], SampleMeta], seed: int) -> Dict[str, str]: | |
| family_ids = sorted({sample.sample_family_id for sample in sample_map.values()}) | |
| rng = random.Random(seed) | |
| rng.shuffle(family_ids) | |
| n = len(family_ids) | |
| train_cut = int(n * 0.70) | |
| dev_cut = int(n * 0.85) | |
| partition_map: Dict[str, str] = {} | |
| for idx, family_id in enumerate(family_ids): | |
| if idx < train_cut: | |
| partition_map[family_id] = "train" | |
| elif idx < dev_cut: | |
| partition_map[family_id] = "dev" | |
| else: | |
| partition_map[family_id] = "test" | |
| return partition_map | |
| def write_reference_donors(out_dir: Path, reference_rows: List[Dict[str, str]]) -> None: | |
| path = out_dir / "reference_donors.csv" | |
| with path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=["study_id", "panel", "person_id", "marker", "alleles"]) | |
| writer.writeheader() | |
| for row in reference_rows: | |
| writer.writerow(row) | |
| def build_samples_master_rows( | |
| spec: PaperBenchmarkSpec, sample_map: Dict[Tuple[str, str], SampleMeta] | |
| ) -> Dict[Tuple[str, str], Dict[str, str]]: | |
| rows: Dict[Tuple[str, str], Dict[str, str]] = {} | |
| for key, sample in sorted(sample_map.items(), key=lambda item: (item[1].panel, item[1].sample_file)): | |
| rows[key] = { | |
| "benchmark_id": spec.dataset_id, | |
| "study_id": sample.study_id, | |
| "panel": sample.panel, | |
| "source_mode": sample.source_mode, | |
| "sample_file": sample.sample_file, | |
| "source_csv": sample.source_csv, | |
| "sample_family_id": sample.sample_family_id, | |
| "folder_people_label": sample.folder_people_label, | |
| "injection_time": sample.injection_time, | |
| "true_contributors": join_ints(sample.true_contributors), | |
| "total_contributors": str(sample.total_contributors), | |
| "is_active_mixture_sample": str(sample.is_active_mixture_sample), | |
| } | |
| return rows | |
| def write_samples_master(out_dir: Path, rows: Dict[Tuple[str, str], Dict[str, str]]) -> None: | |
| fieldnames = [ | |
| "benchmark_id", | |
| "study_id", | |
| "panel", | |
| "source_mode", | |
| "sample_file", | |
| "source_csv", | |
| "sample_family_id", | |
| "folder_people_label", | |
| "injection_time", | |
| "true_contributors", | |
| "total_contributors", | |
| "is_active_mixture_sample", | |
| ] | |
| path = out_dir / "samples_master.csv" | |
| with path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) | |
| writer.writeheader() | |
| for row in rows.values(): | |
| writer.writerow(row) | |
| def build_sample_label_rows( | |
| spec: PaperBenchmarkSpec, | |
| split: SplitSpec, | |
| sample_map: Dict[Tuple[str, str], SampleMeta], | |
| known_ids: List[int], | |
| unknown_ids: List[int], | |
| partition_map: Dict[str, str], | |
| ) -> Dict[Tuple[str, str], Dict[str, str]]: | |
| known_set = set(known_ids) | |
| unknown_set = set(unknown_ids) | |
| rows: Dict[Tuple[str, str], Dict[str, str]] = {} | |
| for key, sample in sorted(sample_map.items(), key=lambda item: (item[1].panel, item[1].sample_file)): | |
| true_set = set(sample.true_contributors) | |
| known_true = sorted(true_set & known_set) | |
| unknown_true = sorted(true_set & unknown_set) | |
| rows[key] = { | |
| "benchmark_id": spec.dataset_id, | |
| "split_id": split.split_id, | |
| "partition": partition_map[sample.sample_family_id], | |
| "study_id": sample.study_id, | |
| "panel": sample.panel, | |
| "sample_file": sample.sample_file, | |
| "sample_family_id": sample.sample_family_id, | |
| "true_contributors": join_ints(sample.true_contributors), | |
| "known_contributors_true": join_ints(known_true), | |
| "unknown_contributors_true": join_ints(unknown_true), | |
| "num_known_in_sample": str(len(known_true)), | |
| "num_unknown_in_sample": str(len(unknown_true)), | |
| "unknown_present": "1" if unknown_true else "0", | |
| "total_contributors": str(sample.total_contributors), | |
| } | |
| return rows | |
| def write_sample_labels(path: Path, rows: Dict[Tuple[str, str], Dict[str, str]]) -> None: | |
| fieldnames = [ | |
| "benchmark_id", | |
| "split_id", | |
| "partition", | |
| "study_id", | |
| "panel", | |
| "sample_file", | |
| "sample_family_id", | |
| "true_contributors", | |
| "known_contributors_true", | |
| "unknown_contributors_true", | |
| "num_known_in_sample", | |
| "num_unknown_in_sample", | |
| "unknown_present", | |
| "total_contributors", | |
| ] | |
| with path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) | |
| writer.writeheader() | |
| for row in rows.values(): | |
| writer.writerow(row) | |
| def write_sample_labels_all_splits(out_dir: Path, split_rows: List[Dict[str, str]]) -> None: | |
| fieldnames = [ | |
| "benchmark_id", | |
| "split_id", | |
| "partition", | |
| "study_id", | |
| "panel", | |
| "sample_file", | |
| "sample_family_id", | |
| "true_contributors", | |
| "known_contributors_true", | |
| "unknown_contributors_true", | |
| "num_known_in_sample", | |
| "num_unknown_in_sample", | |
| "unknown_present", | |
| "total_contributors", | |
| ] | |
| path = out_dir / "sample_labels_all_splits.csv" | |
| with path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) | |
| writer.writeheader() | |
| for row in split_rows: | |
| writer.writerow(row) | |
| def build_leakage_audit( | |
| spec: PaperBenchmarkSpec, | |
| split: SplitSpec, | |
| sample_rows: Dict[Tuple[str, str], Dict[str, str]], | |
| partition_map: Dict[str, str], | |
| ) -> Dict[str, object]: | |
| family_partitions: Dict[str, set[str]] = {} | |
| sample_partitions: Dict[str, set[str]] = {} | |
| partition_counts = Counter() | |
| unknown_counts = Counter() | |
| for row in sample_rows.values(): | |
| family_id = row["sample_family_id"] | |
| partition = row["partition"] | |
| sample_key = f"{row['panel']}|{row['sample_file']}" | |
| family_partitions.setdefault(family_id, set()).add(partition) | |
| sample_partitions.setdefault(sample_key, set()).add(partition) | |
| partition_counts[partition] += 1 | |
| unknown_counts[row["unknown_present"]] += 1 | |
| families_with_multiple_partitions = sorted( | |
| family_id for family_id, parts in family_partitions.items() if len(parts) > 1 | |
| ) | |
| samples_with_multiple_partitions = sorted( | |
| sample_key for sample_key, parts in sample_partitions.items() if len(parts) > 1 | |
| ) | |
| return { | |
| "benchmark_id": spec.dataset_id, | |
| "split_id": split.split_id, | |
| "study_id": spec.study_id, | |
| "donor_seed": split.donor_seed, | |
| "partition_seed": split.partition_seed, | |
| "num_samples": len(sample_rows), | |
| "num_unique_families": len(partition_map), | |
| "partition_counts": dict(partition_counts), | |
| "unknown_present_counts": { | |
| "0": unknown_counts.get("0", 0), | |
| "1": unknown_counts.get("1", 0), | |
| }, | |
| "families_with_multiple_partitions": families_with_multiple_partitions, | |
| "samples_with_multiple_partitions": samples_with_multiple_partitions, | |
| "family_leakage_detected": bool(families_with_multiple_partitions), | |
| "sample_leakage_detected": bool(samples_with_multiple_partitions), | |
| } | |
| def write_manifest( | |
| split_dir: Path, | |
| spec: PaperBenchmarkSpec, | |
| split: SplitSpec, | |
| known_ids: List[int], | |
| unknown_ids: List[int], | |
| partition_map: Dict[str, str], | |
| ) -> None: | |
| manifest = { | |
| "benchmark_id": spec.dataset_id, | |
| "split_id": split.split_id, | |
| "study_id": spec.study_id, | |
| "source_mode": spec.source_mode, | |
| "known_count": spec.known_count, | |
| "unknown_count": spec.unknown_count, | |
| "donor_seed": split.donor_seed, | |
| "partition_seed": split.partition_seed, | |
| "known_ids": known_ids, | |
| "unknown_ids": unknown_ids, | |
| "family_partition_map": partition_map, | |
| } | |
| (split_dir / "split_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") | |
| def write_json(path: Path, payload: Dict[str, object]) -> None: | |
| path.write_text(json.dumps(payload, indent=2), encoding="utf-8") | |
| def build_marker_and_peak_tables( | |
| out_dir: Path, | |
| spec: PaperBenchmarkSpec, | |
| sample_map: Dict[Tuple[str, str], SampleMeta], | |
| sample_master_rows: Dict[Tuple[str, str], Dict[str, str]], | |
| ) -> None: | |
| peak_fieldnames = [ | |
| "benchmark_id", | |
| "study_id", | |
| "panel", | |
| "sample_file", | |
| "sample_family_id", | |
| "marker", | |
| "dye", | |
| "peak_index", | |
| "allele_label_raw", | |
| "allele_label_norm", | |
| "size", | |
| "height", | |
| "is_ol", | |
| "is_empty", | |
| "total_contributors", | |
| ] | |
| marker_fieldnames = [ | |
| "benchmark_id", | |
| "study_id", | |
| "panel", | |
| "sample_file", | |
| "sample_family_id", | |
| "marker", | |
| "dye", | |
| "peak_count_total", | |
| "peak_count_non_ol", | |
| "observed_alleles_all", | |
| "observed_alleles_non_ol", | |
| "max_height", | |
| "sum_height", | |
| "has_ol", | |
| "total_contributors", | |
| ] | |
| peak_path = out_dir / "peak_table.csv" | |
| marker_path = out_dir / "marker_table.csv" | |
| marker_agg: Dict[Tuple[str, str, str], Dict[str, object]] = {} | |
| sample_to_source = { | |
| (sample.panel, sample.sample_file): ROOT / sample.source_csv for sample in sample_map.values() | |
| } | |
| with peak_path.open("w", newline="", encoding="utf-8") as peak_handle: | |
| peak_writer = csv.DictWriter(peak_handle, fieldnames=peak_fieldnames) | |
| peak_writer.writeheader() | |
| for panel_spec in spec.panels: | |
| for csv_path in sorted(panel_spec.raw_root.rglob("*.csv")): | |
| if "Known Genotypes" in csv_path.name: | |
| continue | |
| with csv_path.open(encoding="utf-8-sig", newline="", errors="replace") as handle: | |
| reader = csv.DictReader(handle) | |
| for row in reader: | |
| sample_file = row["Sample File"].strip() | |
| key = (panel_spec.panel, sample_file) | |
| if key not in sample_master_rows: | |
| continue | |
| if sample_to_source[key] != csv_path: | |
| continue | |
| sample_row = sample_master_rows[key] | |
| marker = normalize_marker(row["Marker"]) | |
| dye = row["Dye"].strip() | |
| marker_key = (panel_spec.panel, sample_file, marker) | |
| if marker_key not in marker_agg: | |
| marker_agg[marker_key] = { | |
| "benchmark_id": sample_row["benchmark_id"], | |
| "study_id": sample_row["study_id"], | |
| "panel": panel_spec.panel, | |
| "sample_file": sample_file, | |
| "sample_family_id": sample_row["sample_family_id"], | |
| "marker": marker, | |
| "dye": set(), | |
| "peak_count_total": 0, | |
| "peak_count_non_ol": 0, | |
| "observed_alleles_all": set(), | |
| "observed_alleles_non_ol": set(), | |
| "max_height": 0.0, | |
| "sum_height": 0.0, | |
| "has_ol": 0, | |
| "total_contributors": sample_row["total_contributors"], | |
| } | |
| agg = marker_agg[marker_key] | |
| agg["dye"].add(dye) | |
| for idx in range(1, 101): | |
| allele_raw = row.get(f"Allele {idx}", "") | |
| size_raw = row.get(f"Size {idx}", "") | |
| height_raw = row.get(f"Height {idx}", "") | |
| if allele_raw is None or str(allele_raw).strip() == "": | |
| continue | |
| allele_raw = str(allele_raw).strip() | |
| allele_norm = normalize_allele(allele_raw) | |
| try: | |
| size = float(size_raw) | |
| except (TypeError, ValueError): | |
| size = "" | |
| try: | |
| height = float(height_raw) | |
| except (TypeError, ValueError): | |
| height = 0.0 | |
| is_ol = 1 if allele_norm.upper() == "OL" else 0 | |
| agg["peak_count_total"] += 1 | |
| agg["observed_alleles_all"].add(allele_norm) | |
| agg["sum_height"] += height | |
| if height > agg["max_height"]: | |
| agg["max_height"] = height | |
| if is_ol: | |
| agg["has_ol"] = 1 | |
| else: | |
| agg["peak_count_non_ol"] += 1 | |
| agg["observed_alleles_non_ol"].add(allele_norm) | |
| peak_writer.writerow( | |
| { | |
| "benchmark_id": sample_row["benchmark_id"], | |
| "study_id": sample_row["study_id"], | |
| "panel": panel_spec.panel, | |
| "sample_file": sample_file, | |
| "sample_family_id": sample_row["sample_family_id"], | |
| "marker": marker, | |
| "dye": dye, | |
| "peak_index": idx, | |
| "allele_label_raw": allele_raw, | |
| "allele_label_norm": allele_norm, | |
| "size": size, | |
| "height": height, | |
| "is_ol": is_ol, | |
| "is_empty": 0, | |
| "total_contributors": sample_row["total_contributors"], | |
| } | |
| ) | |
| with marker_path.open("w", newline="", encoding="utf-8") as marker_handle: | |
| writer = csv.DictWriter(marker_handle, fieldnames=marker_fieldnames) | |
| writer.writeheader() | |
| for _, agg in sorted(marker_agg.items(), key=lambda item: (item[1]["panel"], item[1]["sample_file"], item[1]["marker"])): | |
| writer.writerow( | |
| { | |
| "benchmark_id": agg["benchmark_id"], | |
| "study_id": agg["study_id"], | |
| "panel": agg["panel"], | |
| "sample_file": agg["sample_file"], | |
| "sample_family_id": agg["sample_family_id"], | |
| "marker": agg["marker"], | |
| "dye": "|".join(sorted(agg["dye"])), | |
| "peak_count_total": agg["peak_count_total"], | |
| "peak_count_non_ol": agg["peak_count_non_ol"], | |
| "observed_alleles_all": "|".join(sorted(a for a in agg["observed_alleles_all"] if a)), | |
| "observed_alleles_non_ol": "|".join(sorted(a for a in agg["observed_alleles_non_ol"] if a)), | |
| "max_height": f"{agg['max_height']:.6f}", | |
| "sum_height": f"{agg['sum_height']:.6f}", | |
| "has_ol": agg["has_ol"], | |
| "total_contributors": agg["total_contributors"], | |
| } | |
| ) | |
| def write_docs( | |
| out_dir: Path, | |
| spec: PaperBenchmarkSpec, | |
| universe_size: int, | |
| sample_count: int, | |
| split_count: int, | |
| ) -> None: | |
| readme = f"""# {spec.dataset_id} | |
| Paper-strength frozen benchmark dataset built from PROVEDIt `UnFiltered`. | |
| ## Summary | |
| - study: `{spec.study_id}` | |
| - source_mode: `{spec.source_mode}` | |
| - panels included: {", ".join(panel.panel for panel in spec.panels)} | |
| - reference universe size: `{universe_size}` | |
| - number of samples: `{sample_count}` | |
| - known donors per split: `{spec.known_count}` | |
| - unknown donors per split: `{spec.unknown_count}` | |
| - number of frozen splits: `{split_count}` | |
| - benchmark role: `{spec.primary_task}` | |
| ## Layout | |
| - `reference_donors.csv`: donor-level ground-truth reference alleles | |
| - `samples_master.csv`: split-invariant sample metadata and true contributors | |
| - `sample_labels_all_splits.csv`: sample labels across all frozen splits | |
| - `marker_table.csv`: one row per sample-marker pair | |
| - `peak_table.csv`: one row per peak | |
| - `splits/`: split-specific manifests, labels, and leakage audits | |
| - `SCHEMA.md`: column dictionary for all dataset files | |
| - `PROTOCOL.md`: fixed experimental protocol for the paper | |
| """ | |
| schema = """# Schema | |
| ## reference_donors.csv | |
| - `study_id`: PROVEDIt study ID | |
| - `panel`: STR panel / kit | |
| - `person_id`: donor identifier within the study | |
| - `marker`: marker / locus name | |
| - `alleles`: donor ground-truth alleles at that marker | |
| ## samples_master.csv | |
| - `benchmark_id`: dataset release identifier | |
| - `study_id`: PROVEDIt study ID | |
| - `panel`: STR panel / kit | |
| - `source_mode`: filtered vs unfiltered source flag | |
| - `sample_file`: original sample name from raw CSV | |
| - `source_csv`: raw CSV file from which the sample was kept | |
| - `sample_family_id`: family/group key used to reduce leakage | |
| - `folder_people_label`: original folder label such as `1-Person`, `2-Person` | |
| - `injection_time`: timing label from the raw path, e.g. `5 sec` | |
| - `true_contributors`: comma-separated contributor IDs parsed from the sample name | |
| - `total_contributors`: total contributor count parsed from the sample name | |
| - `is_active_mixture_sample`: 1 if the sample belongs to the active raw study universe | |
| ## sample_labels_all_splits.csv | |
| - `benchmark_id`: dataset release identifier | |
| - `split_id`: split identifier such as `split_01` | |
| - `partition`: train/dev/test assignment | |
| - `study_id`: PROVEDIt study ID | |
| - `panel`: STR panel / kit | |
| - `sample_file`: original sample name | |
| - `sample_family_id`: family/group key used to reduce leakage | |
| - `true_contributors`: comma-separated contributor IDs parsed from the sample name | |
| - `known_contributors_true`: contributor IDs belonging to the known split | |
| - `unknown_contributors_true`: contributor IDs belonging to the unknown split | |
| - `num_known_in_sample`: count of known contributors in the sample | |
| - `num_unknown_in_sample`: count of unknown contributors in the sample | |
| - `unknown_present`: 1 if at least one unknown contributor is present, else 0 | |
| - `total_contributors`: total contributor count parsed from the sample name | |
| ## marker_table.csv | |
| - `benchmark_id`: dataset release identifier | |
| - `study_id`: PROVEDIt study ID | |
| - `panel`: STR panel / kit | |
| - `sample_file`: original sample name | |
| - `sample_family_id`: family/group key used to reduce leakage | |
| - `marker`: marker/locus name | |
| - `dye`: dye channel(s) observed for that sample-marker | |
| - `peak_count_total`: total non-empty peak slots for the marker | |
| - `peak_count_non_ol`: total non-OL peaks for the marker | |
| - `observed_alleles_all`: all observed allele labels joined by `|` | |
| - `observed_alleles_non_ol`: non-OL allele labels joined by `|` | |
| - `max_height`: maximum peak height for the marker | |
| - `sum_height`: sum of peak heights for the marker | |
| - `has_ol`: 1 if at least one OL peak is present, else 0 | |
| - `total_contributors`: inherited split-invariant sample metadata | |
| ## peak_table.csv | |
| - `benchmark_id`: dataset release identifier | |
| - `study_id`: PROVEDIt study ID | |
| - `panel`: STR panel / kit | |
| - `sample_file`: original sample name | |
| - `sample_family_id`: family/group key used to reduce leakage | |
| - `marker`: marker/locus name | |
| - `dye`: dye channel | |
| - `peak_index`: original peak slot index from the raw CSV row | |
| - `allele_label_raw`: raw allele label as stored in the source CSV | |
| - `allele_label_norm`: normalized allele label after whitespace / `.0` cleanup | |
| - `size`: reported fragment size for the peak | |
| - `height`: reported peak height for the peak | |
| - `is_ol`: 1 if the peak label is `OL`, else 0 | |
| - `is_empty`: reserved flag; materialized peaks are written as 0 | |
| - `total_contributors`: inherited split-invariant sample metadata | |
| ## splits/<split_id>/split_manifest.json | |
| - `benchmark_id`: dataset release identifier | |
| - `split_id`: split identifier | |
| - `study_id`: PROVEDIt study ID | |
| - `source_mode`: filtered vs unfiltered source flag | |
| - `known_count`: size of the known donor set | |
| - `unknown_count`: size of the unknown donor set | |
| - `donor_seed`: seed used to sample known vs unknown donors | |
| - `partition_seed`: seed used to assign sample families to train/dev/test | |
| - `known_ids`: donor IDs belonging to the known set | |
| - `unknown_ids`: donor IDs belonging to the unknown set | |
| - `family_partition_map`: mapping from `sample_family_id` to `train`, `dev`, or `test` | |
| ## splits/<split_id>/sample_labels.csv | |
| Same columns as `sample_labels_all_splits.csv`, but restricted to one split. | |
| ## splits/<split_id>/leakage_audit.json | |
| - `partition_counts`: number of samples in train/dev/test | |
| - `unknown_present_counts`: number of samples with and without unknown contributors | |
| - `families_with_multiple_partitions`: family IDs that leaked across partitions | |
| - `samples_with_multiple_partitions`: sample keys that leaked across partitions | |
| - `family_leakage_detected`: boolean leakage flag at family level | |
| - `sample_leakage_detected`: boolean leakage flag at sample level | |
| """ | |
| protocol = f"""# Experimental Protocol | |
| ## Benchmark Role | |
| - dataset: `{spec.dataset_id}` | |
| - study: `{spec.study_id}` | |
| - role: `{spec.primary_task}` | |
| ## Frozen Split Design | |
| - number of donor-level splits: `{split_count}` | |
| - known donors per split: `{spec.known_count}` | |
| - unknown donors per split: `{spec.unknown_count}` | |
| - train/dev/test assignment is done at the `sample_family_id` level | |
| - each split stores both donor IDs and family partition assignments | |
| ## Tasks | |
| Primary tasks: | |
| - identify `known_contributors_true` | |
| - predict `num_known_in_sample` | |
| - detect `unknown_present` | |
| ## Data Usage Rules | |
| - all collaborators must use the same frozen dataset artifacts | |
| - all collaborators must use the provided split manifests | |
| - `samples_master.csv`, `marker_table.csv`, and `peak_table.csv` are split-invariant | |
| - split-specific supervision must come from `sample_labels_all_splits.csv` or `splits/<split_id>/sample_labels.csv` | |
| ## Recommended Reporting | |
| Primary metrics: | |
| - known-contributor precision | |
| - known-contributor recall | |
| - known-contributor F1 | |
| - `num_known_in_sample` accuracy | |
| - `unknown_present` accuracy | |
| - `unknown_present` F1 | |
| Secondary metrics: | |
| - false inclusion rate | |
| - false exclusion rate | |
| - per-NOC breakdown using `total_contributors` | |
| - mean and standard deviation across all frozen splits | |
| ## Suggested Baselines | |
| - sample-level baseline using only `samples_master.csv` + split labels | |
| - marker-level baseline using `marker_table.csv` | |
| - peak-level baseline using `peak_table.csv` | |
| ## Leakage Policy | |
| - family-level leakage across train/dev/test is forbidden | |
| - the canonical leakage check is the JSON audit shipped inside each split folder | |
| """ | |
| (out_dir / "README.md").write_text(readme, encoding="utf-8") | |
| (out_dir / "SCHEMA.md").write_text(schema, encoding="utf-8") | |
| (out_dir / "PROTOCOL.md").write_text(protocol, encoding="utf-8") | |
| def write_summary( | |
| out_dir: Path, | |
| spec: PaperBenchmarkSpec, | |
| universe_size: int, | |
| sample_count: int, | |
| split_audits: List[Dict[str, object]], | |
| ) -> None: | |
| summary = { | |
| "benchmark_id": spec.dataset_id, | |
| "study_id": spec.study_id, | |
| "source_mode": spec.source_mode, | |
| "panels": [panel.panel for panel in spec.panels], | |
| "reference_universe_size": universe_size, | |
| "num_samples": sample_count, | |
| "num_splits": len(spec.splits), | |
| "known_count_per_split": spec.known_count, | |
| "unknown_count_per_split": spec.unknown_count, | |
| "splits": [ | |
| { | |
| "split_id": audit["split_id"], | |
| "donor_seed": audit["donor_seed"], | |
| "partition_seed": audit["partition_seed"], | |
| "family_leakage_detected": audit["family_leakage_detected"], | |
| "sample_leakage_detected": audit["sample_leakage_detected"], | |
| } | |
| for audit in split_audits | |
| ], | |
| } | |
| write_json(out_dir / "benchmark_summary.json", summary) | |
| def build_paper_benchmark(spec: PaperBenchmarkSpec) -> None: | |
| out_dir = PROCESSED_ROOT / spec.dataset_id | |
| splits_dir = out_dir / "splits" | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| splits_dir.mkdir(parents=True, exist_ok=True) | |
| _, reference_rows, all_ids = load_reference_donors(spec.panels) | |
| sample_map = collect_canonical_samples( | |
| BenchmarkSpec( | |
| benchmark_id=spec.dataset_id, | |
| study_id=spec.study_id, | |
| source_mode=spec.source_mode, | |
| seed=0, | |
| known_count=spec.known_count, | |
| unknown_count=spec.unknown_count, | |
| panels=spec.panels, | |
| ) | |
| ) | |
| sample_master_rows = build_samples_master_rows(spec, sample_map) | |
| write_reference_donors(out_dir, reference_rows) | |
| write_samples_master(out_dir, sample_master_rows) | |
| build_marker_and_peak_tables(out_dir, spec, sample_map, sample_master_rows) | |
| split_rows_all: List[Dict[str, str]] = [] | |
| split_audits: List[Dict[str, object]] = [] | |
| for split in spec.splits: | |
| known_ids, unknown_ids = make_known_unknown_split( | |
| all_ids, spec.known_count, spec.unknown_count, split.donor_seed | |
| ) | |
| partition_map = make_partition_map(sample_map, split.partition_seed) | |
| sample_label_rows = build_sample_label_rows( | |
| spec, split, sample_map, known_ids, unknown_ids, partition_map | |
| ) | |
| split_dir = splits_dir / split.split_id | |
| split_dir.mkdir(parents=True, exist_ok=True) | |
| write_manifest(split_dir, spec, split, known_ids, unknown_ids, partition_map) | |
| write_sample_labels(split_dir / "sample_labels.csv", sample_label_rows) | |
| audit = build_leakage_audit(spec, split, sample_label_rows, partition_map) | |
| write_json(split_dir / "leakage_audit.json", audit) | |
| split_audits.append(audit) | |
| split_rows_all.extend(sample_label_rows.values()) | |
| write_sample_labels_all_splits(out_dir, split_rows_all) | |
| write_docs(out_dir, spec, len(all_ids), len(sample_master_rows), len(spec.splits)) | |
| write_summary(out_dir, spec, len(all_ids), len(sample_master_rows), split_audits) | |
| def write_top_level_protocol() -> None: | |
| docs_dir = ROOT / "docs" | |
| docs_dir.mkdir(parents=True, exist_ok=True) | |
| protocol = """# Shared Experimental Protocol | |
| This project uses frozen PROVEDIt benchmark releases for two collaborators who share identical data artifacts and split manifests but may implement different modeling pipelines. | |
| ## Benchmark Order | |
| 1. `rd14-fullref-50_multisplit_v2` | |
| 2. `rd12-fullref-61_multisplit_v2` | |
| ## Shared Rules | |
| - do not rebuild donor splits independently | |
| - do not reshuffle train/dev/test independently | |
| - always join split-specific labels from `sample_labels_all_splits.csv` or `splits/<split_id>/sample_labels.csv` | |
| - always verify leakage status with `splits/<split_id>/leakage_audit.json` | |
| ## Required Reporting | |
| - report primary metrics on every split | |
| - report mean and standard deviation across all splits | |
| - report both collaborator pipelines on the same splits | |
| - keep the dataset release fixed during model comparisons | |
| """ | |
| (docs_dir / "EXPERIMENT_PROTOCOL.md").write_text(protocol, encoding="utf-8") | |
| def main() -> None: | |
| build_paper_benchmark(RD14_PAPER_SPEC) | |
| build_paper_benchmark(RD12_PAPER_SPEC) | |
| write_top_level_protocol() | |
| if __name__ == "__main__": | |
| main() | |