File size: 30,480 Bytes
4636192 | 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 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 | """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,
)
@dataclass(frozen=True)
class SplitSpec:
split_id: str
donor_seed: int
partition_seed: int
@dataclass(frozen=True)
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()
|