File size: 27,669 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
"""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()