"""Build frozen study-level benchmark datasets for PROVEDIt.""" from __future__ import annotations import csv import json import random import re from collections import defaultdict from dataclasses import dataclass from pathlib import Path from typing import Dict, Iterable, List, Tuple from openpyxl import load_workbook ROOT = Path(__file__).resolve().parents[2] DATA_ROOT = ROOT / "data" / "PROVEDIt_1-5-Person CSVs UnFiltered" PROCESSED_ROOT = ROOT / "data" / "processed" @dataclass(frozen=True) class PanelSpec: panel: str raw_root: Path genotype_file: Path @dataclass(frozen=True) class BenchmarkSpec: benchmark_id: str study_id: str source_mode: str seed: int known_count: int unknown_count: int panels: Tuple[PanelSpec, ...] @dataclass class SampleMeta: benchmark_id: str study_id: str panel: str source_mode: str sample_file: str source_csv: str sample_family_id: str folder_people_label: str injection_time: str contributor_token: str ratio_token: str true_contributors: List[int] total_contributors: int is_active_mixture_sample: int RD14_SPEC = BenchmarkSpec( benchmark_id="rd14-fullref-50_seed42_v1", study_id="RD14-0003", source_mode="unfiltered", seed=42, known_count=45, unknown_count=5, panels=( PanelSpec( panel="GF", raw_root=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3500_GF29cycles", genotype_file=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3500_GF29cycles" / "PROVEDIt_RD14-0003 GF Known Genotypes.xlsx", ), PanelSpec( panel="IDPlus", raw_root=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3130_IDPlus28cycles", genotype_file=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3130_IDPlus28cycles" / "PROVEDIt_RD14-0003 IDPlus Known Genotypes.xlsx", ), PanelSpec( panel="F6C", raw_root=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3500_F6C29cycles_hlfrxn", genotype_file=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3500_F6C29cycles_hlfrxn" / "PROVEDIt_RD14-0003 F6C Known Genotypes.csv", ), ), ) RD12_SPEC = BenchmarkSpec( benchmark_id="rd12-fullref-61_seed42_v1", study_id="RD12-0002", source_mode="unfiltered", seed=42, known_count=56, unknown_count=5, panels=( PanelSpec( panel="IDPlus", raw_root=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3500_IDPlus29cycles", genotype_file=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3500_IDPlus29cycles" / "PROVEDIt_RD12-0002 IP Known Genotypes.xlsx", ), PanelSpec( panel="PP16HS", raw_root=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3130_PP16HS32cycles", genotype_file=DATA_ROOT / "PROVEDIt_1-5-Person CSVs UnFiltered_3130_PP16HS32cycles" / "PROVEDIt_RD12-0002 PP16HS Known Genotypes.xlsx", ), ), ) def normalize_marker(marker: str) -> str: marker = marker.strip() return "AMEL" if marker in {"AM", "AMEL"} else marker def normalize_allele(value: str) -> str: token = value.strip() if not token: return "" if token.endswith(".0"): token = token[:-2] return token def load_reference_donors(panel_specs: Iterable[PanelSpec]) -> Tuple[Dict[Tuple[str, int], Dict[str, str]], List[Dict[str, str]], List[int]]: donor_profiles: Dict[Tuple[str, int], Dict[str, str]] = {} reference_rows: List[Dict[str, str]] = [] all_ids = set() for panel_spec in panel_specs: path = panel_spec.genotype_file if path.suffix.lower() == ".xlsx": workbook = load_workbook(path, read_only=True, data_only=True) sheet = workbook[workbook.sheetnames[0]] rows = list(sheet.iter_rows(values_only=True)) else: with path.open(encoding="utf-8-sig", newline="") as handle: rows = list(csv.reader(handle)) header = [str(value).strip() if value is not None else "" for value in rows[0]] sample_idx = header.index("Sample ID") ignore = {"Research ID", "Reseach ID", "Sample ID"} for row in rows[1:]: if not any(value is not None and str(value).strip() for value in row): continue person_raw = row[sample_idx] if person_raw is None or str(person_raw).strip() == "": continue person_id = int(str(person_raw).strip()) all_ids.add(person_id) donor_profiles[(panel_spec.panel, person_id)] = {} for idx, name in enumerate(header): if name in ignore: continue value = row[idx] if idx < len(row) else None if value is None or str(value).strip() == "" or str(value).strip().upper() == "N/A": continue marker = normalize_marker(name) alleles = ",".join(part.strip() for part in str(value).split(",") if part.strip()) donor_profiles[(panel_spec.panel, person_id)][marker] = alleles reference_rows.append( { "study_id": panel_spec.genotype_file.name.split()[0].replace("PROVEDIt_", ""), "panel": panel_spec.panel, "person_id": str(person_id), "marker": marker, "alleles": alleles, } ) return donor_profiles, reference_rows, sorted(all_ids) def parse_sample_metadata(sample_file: str) -> Tuple[str, str, str, List[int]]: study_match = re.search(r"(RD\d{2}-\d{4})-", sample_file) if not study_match: raise ValueError(f"Could not parse sample file: {sample_file}") study_id = study_match.group(1) rest = sample_file[study_match.end() :] parts = rest.split("-", 2) if len(parts) < 2: raise ValueError(f"Could not parse sample file: {sample_file}") contributor_token = parts[0] ratio_token = parts[1].split("_")[0] contributor_ids = [] for part in contributor_token.split("_"): id_match = re.match(r"(\d+)", part) if id_match: contributor_ids.append(int(id_match.group(1))) if not contributor_ids: raise ValueError(f"No contributor IDs found in sample file: {sample_file}") return study_id, contributor_token, ratio_token, contributor_ids def source_priority(path: Path) -> Tuple[int, int, str]: name = path.name has_parentheses = 0 if "(" in name else 1 return (has_parentheses, len(name), name) def collect_canonical_samples(spec: BenchmarkSpec) -> Dict[Tuple[str, str], SampleMeta]: sample_map: Dict[Tuple[str, str], SampleMeta] = {} sample_priority: Dict[Tuple[str, str], Tuple[int, int, str]] = {} 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 rel_parts = csv_path.relative_to(panel_spec.raw_root).parts folder_people_label = rel_parts[0] if len(rel_parts) > 2 else "unknown" injection_time = rel_parts[1] if len(rel_parts) > 2 else "unknown" with csv_path.open(encoding="utf-8-sig", newline="", errors="replace") as handle: reader = csv.DictReader(handle) seen = set() for row in reader: sample_file = row["Sample File"].strip() if sample_file in seen: continue seen.add(sample_file) study_id, contributor_token, ratio_token, contributor_ids = parse_sample_metadata(sample_file) if study_id != spec.study_id: continue key = (panel_spec.panel, sample_file) priority = source_priority(csv_path) if key in sample_map and priority >= sample_priority[key]: continue family_id = f"{study_id}|{contributor_token}|{ratio_token}" sample_map[key] = SampleMeta( benchmark_id=spec.benchmark_id, study_id=study_id, panel=panel_spec.panel, source_mode=spec.source_mode, sample_file=sample_file, source_csv=str(csv_path.relative_to(ROOT)), sample_family_id=family_id, folder_people_label=folder_people_label, injection_time=injection_time, contributor_token=contributor_token, ratio_token=ratio_token, true_contributors=contributor_ids, total_contributors=len(contributor_ids), is_active_mixture_sample=1, ) sample_priority[key] = priority return sample_map 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 = {} 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 join_ints(values: List[int]) -> str: return ",".join(str(v) for v in values) 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_sample_rows( spec: BenchmarkSpec, 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) sample_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) sample_rows[key] = { "benchmark_id": spec.benchmark_id, "split_id": f"seed_{spec.seed}", "partition": partition_map[sample.sample_family_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), "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), "is_active_mixture_sample": str(sample.is_active_mixture_sample), } return sample_rows def write_samples(out_dir: Path, sample_rows: Dict[Tuple[str, str], Dict[str, str]]) -> None: fieldnames = [ "benchmark_id", "split_id", "partition", "study_id", "panel", "source_mode", "sample_file", "source_csv", "sample_family_id", "folder_people_label", "injection_time", "true_contributors", "known_contributors_true", "unknown_contributors_true", "num_known_in_sample", "num_unknown_in_sample", "unknown_present", "total_contributors", "is_active_mixture_sample", ] path = out_dir / "samples.csv" with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in sample_rows.values(): writer.writerow(row) def write_manifest( out_dir: Path, spec: BenchmarkSpec, known_ids: List[int], unknown_ids: List[int], partition_map: Dict[str, str], ) -> None: manifest = { "benchmark_id": spec.benchmark_id, "study_id": spec.study_id, "source_mode": spec.source_mode, "seed": spec.seed, "known_ids": known_ids, "unknown_ids": unknown_ids, "family_partition_map": partition_map, } path = out_dir / "split_manifest.json" path.write_text(json.dumps(manifest, indent=2), encoding="utf-8") def build_marker_and_peak_tables( out_dir: Path, spec: BenchmarkSpec, sample_map: Dict[Tuple[str, str], SampleMeta], sample_rows: Dict[Tuple[str, str], Dict[str, str]], ) -> None: peak_fieldnames = [ "benchmark_id", "split_id", "partition", "study_id", "panel", "sample_file", "sample_family_id", "marker", "dye", "peak_index", "allele_label_raw", "allele_label_norm", "size", "height", "is_ol", "is_empty", "num_known_in_sample", "unknown_present", "total_contributors", ] marker_fieldnames = [ "benchmark_id", "split_id", "partition", "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", "num_known_in_sample", "unknown_present", "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_rows: continue if sample_to_source[key] != csv_path: continue sample_row = sample_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"], "split_id": sample_row["split_id"], "partition": sample_row["partition"], "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, "num_known_in_sample": sample_row["num_known_in_sample"], "unknown_present": sample_row["unknown_present"], "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"], "split_id": sample_row["split_id"], "partition": sample_row["partition"], "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, "num_known_in_sample": sample_row["num_known_in_sample"], "unknown_present": sample_row["unknown_present"], "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"], "split_id": agg["split_id"], "partition": agg["partition"], "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"], "num_known_in_sample": agg["num_known_in_sample"], "unknown_present": agg["unknown_present"], "total_contributors": agg["total_contributors"], } ) def write_docs(out_dir: Path, spec: BenchmarkSpec, universe_size: int) -> None: readme = f"""# {spec.benchmark_id} 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}` - known donors in split: `{spec.known_count}` - unknown donors in split: `{spec.unknown_count}` - split seed: `{spec.seed}` ## Files - `reference_donors.csv`: donor-level ground-truth reference alleles - `samples.csv`: one row per sample with task labels - `marker_table.csv`: one row per sample-marker pair - `peak_table.csv`: one row per peak - `split_manifest.json`: frozen donor split and family partition assignment - `SCHEMA.md`: column dictionary for all dataset files """ schema = """# Schema ## samples.csv - `benchmark_id`: dataset release identifier - `split_id`: split identifier - `partition`: train/dev/test assignment - `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 - `known_contributors_true`: comma-separated contributor IDs belonging to the known split - `unknown_contributors_true`: comma-separated 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 - `is_active_mixture_sample`: 1 for samples that belong to the active raw study universe ## marker_table.csv - `benchmark_id`: dataset release identifier - `split_id`: split identifier - `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 - `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 - `num_known_in_sample`: inherited sample-level label - `unknown_present`: inherited sample-level label - `total_contributors`: inherited sample-level label ## peak_table.csv - `benchmark_id`: dataset release identifier - `split_id`: split identifier - `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 - `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 - `num_known_in_sample`: inherited sample-level label - `unknown_present`: inherited sample-level label - `total_contributors`: inherited sample-level label """ (out_dir / "README.md").write_text(readme, encoding="utf-8") (out_dir / "SCHEMA.md").write_text(schema, encoding="utf-8") def build_benchmark_dataset(spec: BenchmarkSpec) -> None: out_dir = PROCESSED_ROOT / spec.benchmark_id out_dir.mkdir(parents=True, exist_ok=True) _, reference_rows, all_ids = load_reference_donors(spec.panels) sample_map = collect_canonical_samples(spec) known_ids, unknown_ids = make_known_unknown_split(all_ids, spec.known_count, spec.unknown_count, spec.seed) partition_map = make_partition_map(sample_map, spec.seed) sample_rows = build_sample_rows(spec, sample_map, known_ids, unknown_ids, partition_map) write_reference_donors(out_dir, reference_rows) write_samples(out_dir, sample_rows) write_manifest(out_dir, spec, known_ids, unknown_ids, partition_map) build_marker_and_peak_tables(out_dir, spec, sample_map, sample_rows) write_docs(out_dir, spec, len(all_ids)) def main() -> None: build_benchmark_dataset(RD14_SPEC) build_benchmark_dataset(RD12_SPEC) if __name__ == "__main__": main()