File size: 30,635 Bytes
dee9871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Construct the global U pool from the finalized P pool."""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
import csv
import json
import math
import random
from pathlib import Path
from typing import Any, Iterable, Mapping

import common


ROOT = Path(__file__).resolve().parent
DEFAULT_WORK_DIR = ROOT.parent / "wf-tmp"
DEFAULT_P_POOL = DEFAULT_WORK_DIR / "02_exclude_dev_holdout" / "P_pool.jsonl"
DEFAULT_OUTPUT = DEFAULT_WORK_DIR / "03_construct_U"
DEFAULT_INPUT = ROOT.parent if (ROOT.parent / "processed_positive.csv").is_file() else ROOT.parent / "csv_before_assembly"
if not (DEFAULT_INPUT / "processed_positive.csv").is_file() and (ROOT / "processed_positive.csv").is_file():
    DEFAULT_INPUT = ROOT
if not (DEFAULT_INPUT / "processed_positive.csv").is_file() and (ROOT / "csv_before_assembly" / "processed_positive.csv").is_file():
    DEFAULT_INPUT = ROOT / "csv_before_assembly"
# Source CSVs were not retained in the reorganized delivery dataset.
ARCHIVED_INPUT = ROOT.parents[2] / "1007/PU_runs/datasets/csv_before_assembly"
if not (DEFAULT_INPUT / "processed_positive.csv").is_file() and (ARCHIVED_INPUT / "processed_positive.csv").is_file():
    DEFAULT_INPUT = ARCHIVED_INPUT

DEFAULT_RATIOS = (1, 10, 50)
DEFAULT_RATIO_LIMITS = {
    1: {"metals": 100, "linkers": 400},
    10: {"metals": 321, "linkers": 718},
    50: {"metals": 100, "linkers": 400},
}
DEFAULT_CONDITIONS_PER_PAIR = {
    10: 37,
    50: 14,
}
DEFAULT_SIX_FIELD_LIMITS = {
    "modulator": 793,
    "solvent": 39,
    "metal_concentration_mM": 193,
    "M_L_ratio": 273,
    "temperature_C": 23,
    "time_h": 35,
}
DEFAULT_NUMERIC_DONOR_RULES = {
    "metal_concentration_mM": {"min_exclusive": 0, "max_inclusive": 10000},
    "M_L_ratio": {"min_exclusive": 0, "max_inclusive": 100},
    "temperature_C": {"min_inclusive": -80, "max_inclusive": 300},
    "time_h": {"min_exclusive": 0, "max_inclusive": 2160},
}


def parse_ratios(text: str) -> list[int]:
    ratios = sorted({int(part.strip().removesuffix("x")) for part in text.split(",") if part.strip()})
    if not ratios or not set(ratios) <= {1, 10, 50}:
        raise ValueError("Ratios must be selected from 1, 10, 50.")
    return ratios


def parse_ratio_limits(text: str) -> dict[int, dict[str, int]]:
    limits: dict[int, dict[str, int]] = {}
    for chunk in text.split(","):
        chunk = chunk.strip()
        if not chunk:
            continue
        ratio, metals, linkers = chunk.replace("x", "").replace("=", ":").split(":")
        limits[int(ratio)] = {"metals": int(metals), "linkers": int(linkers)}
    return limits


def parse_six_field_limits(text: str) -> dict[str, int]:
    limits: dict[str, int] = {}
    for chunk in text.split(","):
        chunk = chunk.strip()
        if not chunk:
            continue
        field, value = chunk.replace("=", ":").split(":", 1)
        if field not in common.SIX_FIELDS:
            raise ValueError(f"Unknown six-field limit: {field}")
        limits[field] = int(value)
    missing = [field for field in common.SIX_FIELDS if field not in limits]
    if missing:
        raise ValueError(f"Missing six-field limits: {missing}")
    return limits


def config_from_args(args: argparse.Namespace, ratios: list[int]) -> dict[str, Any]:
    ratio_limits = parse_ratio_limits(args.ratio_limits)
    missing = [ratio for ratio in ratios if ratio not in ratio_limits]
    if missing:
        raise ValueError(f"Missing metal/linker limits for ratios: {missing}")
    six_field_limits = parse_six_field_limits(args.six_field_limits)
    return {
        "seed": args.seed,
        "ratios": ratios,
        "ratio_limits": {ratio: ratio_limits[ratio] for ratio in ratios},
        "minimum_identity_frequency": args.minimum_identity_frequency,
        "numeric_donor_rules": DEFAULT_NUMERIC_DONOR_RULES,
        "allow_null_modulator": args.allow_null_modulator,
        "six_field_limits": six_field_limits,
        "conditions_per_pair": DEFAULT_CONDITIONS_PER_PAIR,
    }


def managed_outputs(output_dir: Path, ratios: Iterable[int]) -> list[Path]:
    paths = [
        output_dir / "pools" / "U_master.jsonl",
        output_dir / "audit" / "metal_inventory.json",
        output_dir / "audit" / "linker_inventory.json",
        output_dir / "audit" / "standard_condition_space.json",
        output_dir / "audit" / "donor_exclusions.jsonl",
        output_dir / "audit" / "metal_linker_pairs.jsonl",
        output_dir / "step3.1_audit.json",
    ]
    for ratio in ratios:
        paths.append(output_dir / "pools" / f"U_{ratio}x.jsonl")
        paths.append(output_dir / "audit" / f"metal_linker_pairs_{ratio}x.jsonl")
    return paths


def prepare_output_dir(output_dir: Path, ratios: Iterable[int], replace: bool) -> None:
    occupied = [path for path in managed_outputs(output_dir, ratios) if path.exists()]
    if occupied and not replace:
        names = [str(path.relative_to(output_dir)) for path in occupied]
        raise FileExistsError(f"Step 3.1 outputs already exist: {names}; use --replace")
    output_dir.mkdir(parents=True, exist_ok=True)
    if replace:
        for path in occupied:
            path.unlink()


def public_generated(row: Mapping[str, Any]) -> dict[str, Any]:
    return {**common.payload(row), **{key: value for key, value in row.items() if key not in common.FIELDS}}


def load_positive_pool(path: Path) -> list[dict[str, Any]]:
    records = []
    for index, raw in enumerate(common.read_jsonl(path), 1):
        row = {**raw, **common.payload(raw)}
        label = row.get("label", "P")
        if label != "P":
            raise ValueError(f"Expected a P-only pool, found label={label!r} in {path}")
        row["label"] = "P"
        row.setdefault("record_id", f"PSTEP31:{index:08d}")
        row["condition_key"] = common.normalized_condition_key(row)
        row["metal_linker_pair_key"] = common.pair_key(row)
        row["chemistry_family_id"] = common.family_key(row)
        row.setdefault("doi_parent_group_id", "SOURCE_GROUP:" + row["record_id"])
        records.append(row)
    if not records:
        raise ValueError(f"No P rows found in {path}")
    return records


def load_known_from_input_dir(input_dir: Path | None) -> set[str]:
    if input_dir is None:
        return set()
    keys: set[str] = set()
    for filename in ["processed_positive.csv", "processed_negative.csv"]:
        path = input_dir / filename
        if not path.is_file():
            continue
        with path.open(encoding="utf-8-sig", newline="") as stream:
            for raw in csv.DictReader(stream):
                row = common.raw_payload(raw)
                if row["metal_precursor"] and row["organic_linker"]:
                    keys.add(common.normalized_condition_key(row))
    return keys


def load_known_from_jsonl(paths: Iterable[Path]) -> set[str]:
    keys: set[str] = set()
    for path in paths:
        if not path.is_file():
            raise FileNotFoundError(f"Missing known-condition JSONL: {path}")
        for record in common.read_jsonl(path):
            row, _ = common.record_payload_and_label(record)
            if row["metal_precursor"] and row["organic_linker"]:
                keys.add(common.normalized_condition_key(row))
    return keys


def load_reserved_pairs(paths: Iterable[Path]) -> set[str]:
    pairs: set[str] = set()
    for path in paths:
        if not path.is_file():
            raise FileNotFoundError(f"Missing reserved-pair JSONL: {path}")
        for record in common.read_jsonl(path):
            stored = record.get("metal_linker_pair_key")
            if isinstance(stored, str) and stored:
                pairs.add(stored)
                continue
            row, _ = common.record_payload_and_label(record)
            if row["metal_precursor"] and row["organic_linker"]:
                pairs.add(common.pair_key(row))
    return pairs


def inventory(positives: list[dict[str, Any]], config: Mapping[str, Any], kind: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
    field = "metal_precursor" if kind == "metal" else "organic_linker"
    for row in positives:
        value = row[field]
        identity = common.metal_identity(value) if kind == "metal" else common.linker_identity(value)
        grouped[identity].append(row)

    items = []
    eligible = []
    for identity, rows in sorted(grouped.items()):
        values = Counter(row[field] for row in rows)
        representative = min(values, key=lambda value: (-values[value], value))
        source = min((row for row in rows if row[field] == representative), key=lambda row: row["record_id"])
        reason = None
        category = None
        elements: list[str] = []
        if kind == "metal":
            category, elements, reason = common.metal_category(representative)
        else:
            parts = set(json.loads(identity))
            if len(identity) < 5 or parts & {"l", "l1", "l2", "l3", "h2l", "h3l", "h4l", "ligand", "linker", "organic linker"}:
                reason = "unresolved_linker_placeholder"
        if len(rows) < config["minimum_identity_frequency"]:
            reason = "frequency_below_minimum"
        item = {
            "identity_id": ("M:" if kind == "metal" else "L:") + common.digest(identity)[:20],
            "identity_key": identity,
            "representative": representative,
            "frequency": len(rows),
            "surface_forms": dict(sorted(values.items())),
            "eligible": reason is None,
            "exclusion_reason": reason,
            "representative_source_record_id": source["record_id"],
        }
        if kind == "metal":
            item.update(category=category, metal_elements=elements)
        items.append(item)
        if reason is None:
            eligible.append(item)
    return items, eligible


def rank_eligible(items: list[dict[str, Any]], seed: int, kind: str) -> list[dict[str, Any]]:
    ranked = sorted(
        (dict(item) for item in items),
        key=lambda item: (-item["frequency"], common.digest(f"{seed}|{kind}-rank|{item['identity_id']}")),
    )
    for index, item in enumerate(ranked, 1):
        item["frequency_rank"] = index
    return ranked


def build_pair_pool(
    metals: list[dict[str, Any]],
    linkers: list[dict[str, Any]],
    positives: list[dict[str, Any]],
    reserved_pairs: set[str],
    config: Mapping[str, Any],
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
    ratios = config["ratios"]
    ratio_limits = config["ratio_limits"]
    ratio_order = {ratio: index for index, ratio in enumerate(ratios)}

    metal_by_identity = {item["identity_key"]: item for item in metals}
    linker_by_identity = {item["identity_key"]: item for item in linkers}
    observed: Counter[str] = Counter()
    pair_identities: dict[str, tuple[str, str]] = {}
    observed_rows = 0
    for row in positives:
        metal_identity = common.metal_identity(row["metal_precursor"])
        linker_identity = common.linker_identity(row["organic_linker"])
        if metal_identity not in metal_by_identity or linker_identity not in linker_by_identity:
            continue
        key = common.digest(common.compact([metal_identity, linker_identity]))
        observed[key] += 1
        observed_rows += 1
        pair_identities[key] = (metal_identity, linker_identity)

    top_limits = ratio_limits.get(50) or ratio_limits.get(1) or {"metals": 100, "linkers": 400}
    top_metals = metals[: top_limits["metals"]]
    top_linkers = linkers[: top_limits["linkers"]]
    top_pair_keys = set()
    for metal in top_metals:
        for linker in top_linkers:
            key = common.digest(common.compact([metal["identity_key"], linker["identity_key"]]))
            top_pair_keys.add(key)
            pair_identities[key] = (metal["identity_key"], linker["identity_key"])

    observed_pair_keys = set(observed)
    raw_ratio_pair_keys: dict[int, set[str]] = {}
    for ratio in ratios:
        if ratio == 1:
            raw_ratio_pair_keys[ratio] = top_pair_keys & observed_pair_keys
        elif ratio == 10:
            raw_ratio_pair_keys[ratio] = set(observed_pair_keys)
        elif ratio == 50:
            raw_ratio_pair_keys[ratio] = top_pair_keys | observed_pair_keys
        else:
            limits = ratio_limits[ratio]
            limited_metals = metals[: limits["metals"]]
            limited_linkers = linkers[: limits["linkers"]]
            ratio_keys = set()
            for metal in limited_metals:
                for linker in limited_linkers:
                    key = common.digest(common.compact([metal["identity_key"], linker["identity_key"]]))
                    ratio_keys.add(key)
                    pair_identities[key] = (metal["identity_key"], linker["identity_key"])
            raw_ratio_pair_keys[ratio] = ratio_keys

    ratio_pair_keys = {
        ratio: keys - reserved_pairs
        for ratio, keys in raw_ratio_pair_keys.items()
    }

    eligible_ratios_by_key: dict[str, list[int]] = defaultdict(list)
    for ratio, keys in ratio_pair_keys.items():
        for key in keys:
            eligible_ratios_by_key[key].append(ratio)

    pairs = []
    for key, eligible_ratios in eligible_ratios_by_key.items():
        metal_identity, linker_identity = pair_identities[key]
        metal = metal_by_identity[metal_identity]
        linker = linker_by_identity[linker_identity]
        min_ratio = min(eligible_ratios, key=lambda ratio: ratio_order[ratio])
        pairs.append(
            {
                "pair_id": "ML:" + key[:24],
                "pair_key": key,
                "metal_identity_id": metal["identity_id"],
                "linker_identity_id": linker["identity_id"],
                "metal_precursor": metal["representative"],
                "organic_linker": linker["representative"],
                "metal_category": metal["category"],
                "metal_rank": metal["frequency_rank"],
                "linker_rank": linker["frequency_rank"],
                "min_ratio": min_ratio,
                "eligible_ratios": sorted(eligible_ratios, key=lambda ratio: ratio_order[ratio]),
                "observed_in_train_P": key in observed,
                "observed_frequency": observed[key],
                "metal_source_record_id": metal["representative_source_record_id"],
                "linker_source_record_id": linker["representative_source_record_id"],
            }
        )

    pairs.sort(
        key=lambda item: (
            ratio_order[item["min_ratio"]],
            not item["observed_in_train_P"],
            -item["observed_frequency"],
            common.digest(f"{config['seed']}|pair-round-order|{item['pair_key']}"),
        )
    )
    audit = {
        "eligible_metals": len(metals),
        "eligible_linker_systems": len(linkers),
        "eligible_train_P_rows_with_ML": observed_rows,
        "eligible_observed_train_pairs": len(observed_pair_keys),
        "selected_top_metals": len(top_metals),
        "selected_top_linkers": len(top_linkers),
        "top_cartesian_pairs": len(top_pair_keys),
        "top_cartesian_observed_intersection_pairs": len(top_pair_keys & observed_pair_keys),
        "top_cartesian_observed_union_pairs": len(top_pair_keys | observed_pair_keys),
        "raw_pairs_by_ratio_before_reserved_exclusion": {
            str(ratio): len(raw_ratio_pair_keys[ratio])
            for ratio in ratios
        },
        "reserved_pairs_excluded_by_ratio": {
            str(ratio): len(raw_ratio_pair_keys[ratio] & reserved_pairs)
            for ratio in ratios
        },
        "reserved_pairs_excluded_total_union": len(set().union(*raw_ratio_pair_keys.values()) & reserved_pairs),
        "selected_pairs": len(pairs),
        "selected_pairs_by_ratio": {
            str(ratio): sum(ratio in item["eligible_ratios"] for item in pairs)
            for ratio in ratios
        },
        "observed_train_pairs": sum(item["observed_in_train_P"] for item in pairs),
        "recombined_pairs": sum(not item["observed_in_train_P"] for item in pairs),
        "pair_categories": dict(Counter(item["metal_category"] for item in pairs)),
        "pairs_by_min_ratio": dict(Counter(str(item["min_ratio"]) for item in pairs)),
    }
    return pairs, audit




def standard_condition_space(
    positives: list[dict[str, Any]],
    config: Mapping[str, Any],
) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, Any]]:
    joint_conditions: dict[str, dict[str, Any]] = {}
    exclusions = []
    reasons: Counter[str] = Counter()
    valid_rows = 0

    for row in positives:
        failures = common.donor_rule_failures(row, config)
        if failures:
            reasons.update(failures)
            exclusions.append({"record_id": row["record_id"], "reasons": failures})
            continue
        clean = common.payload(row)
        valid_rows += 1
        joint_key = common.compact({field: clean[field] for field in common.SIX_FIELDS})
        joint_conditions[joint_key] = json.loads(joint_key)

    field_counts = {
        field: Counter(common.compact(conditions[field]) for conditions in joint_conditions.values())
        for field in common.SIX_FIELDS
    }
    six_field_limits = config["six_field_limits"]
    field_values = {}
    field_value_frequencies = {}
    field_unique_counts = {}
    field_selected_counts = {}
    for field in common.SIX_FIELDS:
        counter = field_counts[field]
        if not counter:
            raise ValueError(f"No valid donor values for {field}.")
        selected_count = min(len(counter), max(1, int(six_field_limits[field])))
        selected = sorted(counter.items(), key=lambda item: (-item[1], item[0]))[:selected_count]
        field_values[field] = [json.loads(key) for key, _ in selected]
        field_value_frequencies[field] = [
            {"value": json.loads(key), "frequency": frequency}
            for key, frequency in selected
        ]
        field_unique_counts[field] = len(counter)
        field_selected_counts[field] = len(selected)

    space_size = math.prod(field_selected_counts.values())
    selected_value_keys = {
        field: {common.compact(value) for value in values}
        for field, values in field_values.items()
    }
    observed_joint_in_standard_space = sum(
        all(common.compact(conditions[field]) in selected_value_keys[field] for field in common.SIX_FIELDS)
        for conditions in joint_conditions.values()
    )
    space = {
        "mode": "standard_independent_field_top_counts",
        "six_field_limits": dict(six_field_limits),
        "field_values": field_values,
        "field_value_frequencies": field_value_frequencies,
        "field_unique_counts": field_unique_counts,
        "field_selected_counts": field_selected_counts,
        "independent_six_field_space_size": space_size,
        "observed_joint_six_field_conditions_total": len(joint_conditions),
        "observed_joint_six_field_conditions_in_standard_space": observed_joint_in_standard_space,
    }
    audit = {
        "mode": space["mode"],
        "valid_donor_P_rows": valid_rows,
        "excluded_P_rows": len(exclusions),
        "failure_reason_counts_nonexclusive": dict(reasons),
        "six_field_limits": dict(six_field_limits),
        "field_unique_counts": field_unique_counts,
        "selected_field_counts": field_selected_counts,
        "independent_six_field_space_size": space_size,
        "observed_joint_six_field_conditions_total": len(joint_conditions),
        "observed_joint_six_field_conditions_in_standard_space": observed_joint_in_standard_space,
        "null_modulator_is_unknown": config["allow_null_modulator"],
        "null_modulator_selected": any(value is None for value in field_values["modulator"]),
    }
    return space, exclusions, audit


def decode_standard_condition(index: int, field_values: Mapping[str, list[Any]]) -> dict[str, Any]:
    conditions = {}
    for field in common.SIX_FIELDS:
        values = field_values[field]
        conditions[field] = values[index % len(values)]
        index //= len(values)
    return conditions


def generate_u_master_standard(
    pairs: list[dict[str, Any]],
    condition_space: Mapping[str, Any],
    known: set[str],
    count: int,
    config: Mapping[str, Any],
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
    if not pairs:
        raise ValueError("No metal-linker pairs are available for U generation.")
    field_values = condition_space["field_values"]
    space_size = int(condition_space["independent_six_field_space_size"])
    states = [
        {
            "rng": random.Random(int(common.digest(f"{config['seed']}|standard-six-field|{pair['pair_id']}"), 16)),
            "used": set(),
            "accepted": 0,
        }
        for pair in pairs
    ]
    accepted = []
    rejected: Counter[str] = Counter()
    used_keys = set()
    attempts = 0

    while len(accepted) < count:
        position = len(accepted) % len(pairs)
        pair = pairs[position]
        state = states[position]
        while True:
            if len(state["used"]) == space_size:
                raise RuntimeError(f"Exhausted standard condition space for {pair['pair_id']}")
            index = state["rng"].randrange(space_size)
            attempts += 1
            if index in state["used"]:
                rejected["already_drawn_condition_for_pair"] += 1
                continue
            state["used"].add(index)
            conditions = decode_standard_condition(index, field_values)
            row = common.payload(
                {
                    "metal_precursor": pair["metal_precursor"],
                    "organic_linker": pair["organic_linker"],
                    **conditions,
                }
            )
            key = common.normalized_condition_key(row)
            if key in known:
                rejected["known_P_or_N_condition"] += 1
                continue
            if key in used_keys:
                rejected["normalized_duplicate_candidate"] += 1
                continue

            condition_id = "C6STD:" + common.digest(common.compact(conditions))[:24]
            state["accepted"] += 1
            row.update(
                {
                    "label": "U",
                    "record_id": "U1002:" + key[:24],
                    "condition_key": key,
                    "pair_id": pair["pair_id"],
                    "condition_id": condition_id,
                    "candidate_index": len(accepted) + 1,
                    "condition_number_for_pair": state["accepted"],
                    "condition_donor_record_id": "STANDARD_TOP_FIELD_POOL",
                    "doi_parent_group_id": "SOURCE_GROUP:STANDARD_TOP_FIELD_POOL",
                    "metal_source_record_id": pair["metal_source_record_id"],
                    "linker_source_record_id": pair["linker_source_record_id"],
                    "chemistry_family_id": common.family_key(row),
                    "metal_linker_pair_key": pair["pair_key"],
                    "min_ratio": pair["min_ratio"],
                    "metal_rank": pair["metal_rank"],
                    "linker_rank": pair["linker_rank"],
                }
            )
            used_keys.add(key)
            accepted.append(row)
            break
    audit = {
        "requested_rows": count,
        "accepted_rows": len(accepted),
        "attempts": attempts,
        "rejections": dict(rejected),
        "sampling_order": "nested_ratio_pair_tiers; one_accepted_standard_condition_per_pair_per_round",
    }
    return accepted, audit






def standard_ratio_target_rows(p_count: int, ratio: int, pair_count: int, config: Mapping[str, Any]) -> int:
    if ratio == 1:
        return p_count
    per_pair = config.get("conditions_per_pair", {}).get(ratio)
    if per_pair is None:
        return p_count * ratio
    return pair_count * int(per_pair)






def pairs_for_ratio(pairs: list[dict[str, Any]], ratio: int, config: Mapping[str, Any]) -> list[dict[str, Any]]:
    return [
        pair
        for pair in pairs
        if ratio in pair.get("eligible_ratios", [])
    ]


def build_step31(
    p_pool_path: Path,
    output_dir: Path,
    config: Mapping[str, Any],
    *,
    known_input_dir: Path | None = DEFAULT_INPUT,
    known_jsonl: Iterable[Path] = (),
    reserved_jsonl: Iterable[Path] = (),
    replace: bool = False,
) -> dict[str, Any]:
    p_pool_path = p_pool_path.resolve()
    output_dir = output_dir.resolve()
    if not p_pool_path.is_file():
        raise FileNotFoundError(f"Missing Step 2 P pool: {p_pool_path}")
    prepare_output_dir(output_dir, config["ratios"], replace)

    positives = load_positive_pool(p_pool_path)
    known = {row["condition_key"] for row in positives}
    known |= load_known_from_input_dir(known_input_dir.resolve() if known_input_dir else None)
    known |= load_known_from_jsonl(known_jsonl)
    reserved_pairs = load_reserved_pairs(reserved_jsonl)

    metal_inventory, eligible_metals = inventory(positives, config, "metal")
    linker_inventory, eligible_linkers = inventory(positives, config, "linker")
    ranked_metals = rank_eligible(eligible_metals, config["seed"], "metal")
    ranked_linkers = rank_eligible(eligible_linkers, config["seed"], "linker")
    pairs, pair_audit = build_pair_pool(ranked_metals, ranked_linkers, positives, reserved_pairs, config)
    condition_space, donor_exclusions, library_audit = standard_condition_space(positives, config)

    files = {
        "audit/metal_inventory.json": common.write_json(output_dir / "audit" / "metal_inventory.json", metal_inventory),
        "audit/linker_inventory.json": common.write_json(output_dir / "audit" / "linker_inventory.json", linker_inventory),
        "audit/standard_condition_space.json": common.write_json(output_dir / "audit" / "standard_condition_space.json", condition_space),
        "audit/donor_exclusions.jsonl": common.write_jsonl(output_dir / "audit" / "donor_exclusions.jsonl", donor_exclusions),
        "audit/metal_linker_pairs.jsonl": common.write_jsonl(output_dir / "audit" / "metal_linker_pairs.jsonl", pairs),
    }

    ratio_outputs = {}
    standard_rows_by_ratio: dict[int, list[dict[str, Any]]] = {}
    generation_by_ratio = {}
    for ratio in config["ratios"]:
        ratio_pairs = pairs_for_ratio(pairs, ratio, config)
        ratio_target = standard_ratio_target_rows(len(positives), ratio, len(ratio_pairs), config)
        selected, ratio_generation_audit = generate_u_master_standard(
            ratio_pairs,
            condition_space,
            known,
            ratio_target,
            config,
        )
        standard_rows_by_ratio[ratio] = selected
        generation_by_ratio[str(ratio)] = ratio_generation_audit
        files[f"audit/metal_linker_pairs_{ratio}x.jsonl"] = common.write_jsonl(
            output_dir / "audit" / f"metal_linker_pairs_{ratio}x.jsonl", ratio_pairs
        )
        ratio_summary = {
            "rows": len(selected),
            "target_rows": ratio_target,
            "pair_rows_available_for_ratio": len(ratio_pairs),
            "conditions_per_pair": None if ratio == 1 else config["conditions_per_pair"].get(ratio),
        }
        files[f"pools/U_{ratio}x.jsonl"] = common.write_jsonl(
            output_dir / "pools" / f"U_{ratio}x.jsonl", map(public_generated, selected)
        )
        ratio_outputs[str(ratio)] = ratio_summary

    master_rows_by_key = {}
    for ratio in config["ratios"]:
        for row in standard_rows_by_ratio[ratio]:
            master_rows_by_key.setdefault(row["condition_key"], row)
    files["pools/U_master.jsonl"] = common.write_jsonl(
        output_dir / "pools" / "U_master.jsonl",
        map(public_generated, master_rows_by_key.values()),
    )
    generation_audit = {
        "mode": "ratio_specific_cartesian_six_field_generation",
        "standard_output_ratios": list(config["ratios"]),
        "ratio_generation": generation_by_ratio,
        "standard_master_unique_rows": len(master_rows_by_key),
    }


    audit = {
        "construction": "P_pool_to_global_U_pool",
        "input_p_pool": str(p_pool_path),
        "input_p_rows": len(positives),
        "known_condition_keys": len(known),
        "reserved_pair_keys": len(reserved_pairs),
        "config": dict(config),
        "identity_inventory": {
            "metals_total": len(metal_inventory),
            "metals_eligible": len(eligible_metals),
            "linkers_total": len(linker_inventory),
            "linkers_eligible": len(eligible_linkers),
        },
        "pair_selection": pair_audit,
        "condition_library": library_audit,
        "generation": generation_audit,
        "ratio_outputs": ratio_outputs,
        "files": files,
    }
    files["step3.1_audit.json"] = common.write_json(output_dir / "step3.1_audit.json", audit)
    return audit


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--p-pool", type=Path, default=DEFAULT_P_POOL)
    parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--ratios", default=",".join(map(str, DEFAULT_RATIOS)))
    parser.add_argument("--ratio-limits", default="1:100:400,10:321:718,50:100:400")
    parser.add_argument("--seed", type=int, default=1234)
    parser.add_argument("--minimum-identity-frequency", type=int, default=3)
    parser.add_argument(
        "--six-field-limits",
        default=",".join(f"{field}:{DEFAULT_SIX_FIELD_LIMITS[field]}" for field in common.SIX_FIELDS),
    )
    parser.add_argument("--known-input-dir", type=Path, default=DEFAULT_INPUT)
    parser.add_argument("--no-known-input-dir", action="store_true")
    parser.add_argument("--known-jsonl", type=Path, action="append", default=[])
    parser.add_argument("--reserved-jsonl", type=Path, action="append", default=[])
    parser.add_argument("--disallow-null-modulator", dest="allow_null_modulator", action="store_false")
    parser.add_argument("--replace", action="store_true")
    parser.set_defaults(allow_null_modulator=True)
    args = parser.parse_args()

    ratios = parse_ratios(args.ratios)
    config = config_from_args(args, ratios)
    known_input_dir = None if args.no_known_input_dir else args.known_input_dir
    build_step31(
        args.p_pool,
        args.output_dir,
        config,
        known_input_dir=known_input_dir,
        known_jsonl=args.known_jsonl,
        reserved_jsonl=args.reserved_jsonl,
        replace=args.replace,
    )


if __name__ == "__main__":
    main()