Download U_construct_workflow/step3.1_construct_U_pool.py from StarLiu714/MOFinder_PU: direct link, hf CLI and curl.
- Browser
- Download file 30.6 kB
-
https://huggingface.co/datasets/StarLiu714/MOFinder_PU/resolve/main/U_construct_workflow/step3.1_construct_U_pool.py
- Command line
-
hf download hf://datasets/StarLiu714/MOFinder_PU/U_construct_workflow/step3.1_construct_U_pool.py
-
curl -L -o step3.1_construct_U_pool.py https://huggingface.co/datasets/StarLiu714/MOFinder_PU/resolve/main/U_construct_workflow/step3.1_construct_U_pool.py
30.6 kB
| #!/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() | |