Download U_construct_workflow/step2_exclude_dev_holdout.py from StarLiu714/MOFinder_PU: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/datasets/StarLiu714/MOFinder_PU/resolve/main/U_construct_workflow/step2_exclude_dev_holdout.py
- Command line
-
hf download hf://datasets/StarLiu714/MOFinder_PU/U_construct_workflow/step2_exclude_dev_holdout.py
-
curl -L -o step2_exclude_dev_holdout.py https://huggingface.co/datasets/StarLiu714/MOFinder_PU/resolve/main/U_construct_workflow/step2_exclude_dev_holdout.py
14.6 kB
| """ | |
| Step 2: exclude holdout positives, | |
| then split a P-only dev pool. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| from typing import Any, Mapping | |
| import numpy as np | |
| import common | |
| ROOT = Path(__file__).resolve().parent | |
| DEFAULT_WORK_DIR = ROOT.parent / "wf-tmp" | |
| DEFAULT_P_POOL = DEFAULT_WORK_DIR / "01_csv_preprocess" / "P_pool.jsonl" | |
| DEFAULT_OUTPUT = DEFAULT_WORK_DIR / "02_exclude_dev_holdout" | |
| DEFAULT_DEV_FRACTION = 0.05 | |
| DEFAULT_DEV_SEED = 666 | |
| DEFAULT_DEV_TRIALS = 400 | |
| DEFAULT_DEV_SWAPS = 80 | |
| DEFAULT_FINAL_P_COUNT = 11293 | |
| def default_holdout_path() -> Path: | |
| candidates = [ | |
| ROOT.parent / "datasets" / "PN_holdout.jsonl", | |
| ROOT / "PN_holdout.jsonl", | |
| ROOT / "pools" / "holdout_lineage.jsonl", | |
| ROOT / "jsonl_dev" / "holdout_pnpu.jsonl", | |
| ] | |
| for path in candidates: | |
| if path.is_file(): | |
| return path | |
| return candidates[0] | |
| def managed_outputs(output_dir: Path) -> list[Path]: | |
| return [ | |
| output_dir / "P_pool_after_holdout.jsonl", | |
| output_dir / "PU_dev.jsonl", | |
| output_dir / "P_pool.jsonl", | |
| output_dir / "P_exclusions.jsonl", | |
| output_dir / "step2_audit.json", | |
| ] | |
| def prepare_output_dir(output_dir: Path, replace: bool) -> None: | |
| occupied = [path for path in managed_outputs(output_dir) if path.exists()] | |
| if occupied and not replace: | |
| names = [str(path.relative_to(output_dir)) for path in occupied] | |
| raise FileExistsError(f"Step 2 outputs already exist: {names}; use --replace") | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| if replace: | |
| for path in occupied: | |
| path.unlink() | |
| def primary_source_id_for_record(record: Mapping[str, Any]) -> int | None: | |
| source_row_id = record.get("source_row_id") | |
| if source_row_id is not None: | |
| return int(source_row_id) | |
| return None | |
| def load_holdout_positive_reservations(path: Path) -> dict[str, Any]: | |
| source_ids: set[int] = set() | |
| condition_keys: set[str] = set() | |
| family_keys: set[str] = set() | |
| label_counts: Counter[str] = Counter() | |
| positive_rows = 0 | |
| for record in common.read_jsonl(path): | |
| row, label = common.record_payload_and_label(record) | |
| if label is None: | |
| continue | |
| label = str(label) | |
| label_counts[label] += 1 | |
| if label != "P": | |
| continue | |
| positive_rows += 1 | |
| source_row_id = primary_source_id_for_record(record) | |
| if source_row_id is not None: | |
| source_ids.add(source_row_id) | |
| condition_keys.update(common.condition_keys_for_record(record)) | |
| if row["metal_precursor"] and row["organic_linker"]: | |
| family_keys.add(common.family_key(row)) | |
| return { | |
| "path": str(path), | |
| "label_counts": dict(label_counts), | |
| "positive_rows": positive_rows, | |
| "source_ids": source_ids, | |
| "condition_keys": condition_keys, | |
| "family_keys": family_keys, | |
| } | |
| def family_key(row: Mapping[str, Any]) -> str: | |
| value = row.get("cluster_key") | |
| if isinstance(value, str) and value: | |
| return value | |
| return common.p_only_family_key(row) | |
| def holdout_exclusion_reason( | |
| row: Mapping[str, Any], | |
| reservations: Mapping[str, Any], | |
| match_mode: str, | |
| ) -> str | None: | |
| source_ids = reservations["source_ids"] | |
| condition_keys = reservations["condition_keys"] | |
| source_row_id = row.get("source_row_id") | |
| row_keys = common.condition_keys_for_record(row) | |
| if match_mode in {"auto", "source_row_id"} and source_ids and source_row_id is not None: | |
| if int(source_row_id) in source_ids: | |
| return "holdout_source_row_id_overlap" | |
| if match_mode == "source_row_id": | |
| return None | |
| if match_mode in {"auto", "condition_key"} and row_keys & condition_keys: | |
| return "holdout_condition_overlap" | |
| return None | |
| def exclusion_record(row: Mapping[str, Any], reason: str, stage: str) -> dict[str, Any]: | |
| record = { | |
| "reason": reason, | |
| "stage": stage, | |
| "label": row.get("label", "P"), | |
| "record_id": row.get("record_id"), | |
| "source_row_id": row.get("source_row_id"), | |
| "condition_key": row.get("condition_key"), | |
| "cluster_key": row.get("cluster_key"), | |
| "payload": common.payload(row), | |
| } | |
| return {key: value for key, value in record.items() if value is not None} | |
| def mark_split(rows: list[dict[str, Any]], split: str) -> list[dict[str, Any]]: | |
| result = [] | |
| for index, row in enumerate(rows, 1): | |
| item = dict(row) | |
| item["split"] = split | |
| item["split_record_index"] = index | |
| result.append(item) | |
| return result | |
| def split_p_only_dev( | |
| rows: list[dict[str, Any]], | |
| fraction: float, | |
| seed: int, | |
| trials: int, | |
| swaps: int, | |
| ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]: | |
| grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) | |
| for row in rows: | |
| grouped[family_key(row)].append(row) | |
| names = sorted(grouped) | |
| if len(names) < 2: | |
| raise ValueError("At least two P-only families are required for dev splitting.") | |
| sizes = np.array([len(grouped[name]) for name in names], dtype=float) | |
| total_rows = int(sizes.sum()) | |
| target_rows = max(1, int(round(total_rows * fraction))) | |
| family_count = max(1, min(len(names) - 1, int(round(len(names) * fraction)))) | |
| rng = np.random.default_rng(seed) | |
| best_mask: np.ndarray | None = None | |
| best_score = float("inf") | |
| def score(mask: np.ndarray) -> float: | |
| dev_rows = int(sizes[mask].sum()) | |
| train_rows = total_rows - dev_rows | |
| if min(dev_rows, train_rows) <= 0: | |
| return float("inf") | |
| return abs(dev_rows - target_rows) / max(1, target_rows) | |
| for _ in range(trials): | |
| mask = np.zeros(len(names), dtype=bool) | |
| mask[rng.choice(len(names), size=family_count, replace=False)] = True | |
| current = score(mask) | |
| for _ in range(swaps): | |
| trial = mask.copy() | |
| trial[rng.choice(np.flatnonzero(mask))] = False | |
| trial[rng.choice(np.flatnonzero(~mask))] = True | |
| value = score(trial) | |
| if value < current: | |
| mask = trial | |
| current = value | |
| if current < best_score: | |
| best_mask = mask.copy() | |
| best_score = current | |
| if best_mask is None: | |
| raise RuntimeError("P-only dev split search failed.") | |
| dev_families = {names[index] for index in np.flatnonzero(best_mask)} | |
| train = [row for row in rows if family_key(row) not in dev_families] | |
| dev = [row for row in rows if family_key(row) in dev_families] | |
| audit = { | |
| "seed": seed, | |
| "fraction": fraction, | |
| "trials": trials, | |
| "swaps_per_trial": swaps, | |
| "target_rows": target_rows, | |
| "objective": best_score, | |
| "total_families": len(names), | |
| "dev_families": len(dev_families), | |
| } | |
| return train, dev, audit | |
| def train_side_cleanup( | |
| train: list[dict[str, Any]], | |
| dev: list[dict[str, Any]], | |
| holdout_reservations: Mapping[str, Any], | |
| target_count: int, | |
| ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]: | |
| held_condition_keys = set(holdout_reservations["condition_keys"]) | |
| held_family_keys = set(holdout_reservations["family_keys"]) | |
| for row in dev: | |
| held_condition_keys.update(common.condition_keys_for_record(row)) | |
| held_family_keys.add(common.family_key(row)) | |
| kept: list[dict[str, Any]] = [] | |
| exclusions: list[dict[str, Any]] = [] | |
| for row in train: | |
| reason = None | |
| if common.condition_keys_for_record(row) & held_condition_keys: | |
| reason = "dev_or_holdout_condition_overlap" | |
| elif common.family_key(row) in held_family_keys: | |
| reason = "dev_or_holdout_normalized_family_overlap" | |
| if reason is None: | |
| kept.append(row) | |
| else: | |
| exclusions.append(exclusion_record(row, reason, "train_side_cleanup")) | |
| if target_count > len(kept): | |
| raise ValueError(f"target_count={target_count} exceeds Step 2.3 candidate rows={len(kept)}") | |
| duplicate_candidates: list[dict[str, Any]] = [] | |
| seen_clusters: set[str] = set() | |
| for row in sorted(kept, key=lambda item: int(item.get("source_row_id", 0))): | |
| key = family_key(row) | |
| if key in seen_clusters: | |
| duplicate_candidates.append(row) | |
| else: | |
| seen_clusters.add(key) | |
| trim_n = len(kept) - target_count | |
| if trim_n: | |
| if trim_n > len(duplicate_candidates): | |
| raise ValueError(f"Need {trim_n} cluster duplicate rows, found {len(duplicate_candidates)}") | |
| duplicate_ids = {id(row) for row in duplicate_candidates[:trim_n]} | |
| final_rows = [] | |
| for row in kept: | |
| if id(row) in duplicate_ids: | |
| exclusions.append(exclusion_record(row, "cluster_key_duplicate", "train_side_cleanup")) | |
| else: | |
| final_rows.append(row) | |
| else: | |
| final_rows = kept | |
| audit = { | |
| "target_rows": target_count, | |
| "input_rows": len(train), | |
| "after_reserved_overlap_filter": len(kept), | |
| "output_rows": len(final_rows), | |
| "removed_rows": len(train) - len(final_rows), | |
| } | |
| return final_rows, exclusions, audit | |
| def build_step2( | |
| p_pool_path: Path, | |
| holdout_path: Path, | |
| output_dir: Path, | |
| *, | |
| holdout_match: str = "auto", | |
| dev_fraction: float = DEFAULT_DEV_FRACTION, | |
| dev_seed: int = DEFAULT_DEV_SEED, | |
| dev_trials: int = DEFAULT_DEV_TRIALS, | |
| dev_swaps: int = DEFAULT_DEV_SWAPS, | |
| final_p_count: int = DEFAULT_FINAL_P_COUNT, | |
| replace: bool = False, | |
| ) -> dict[str, Any]: | |
| p_pool_path = p_pool_path.resolve() | |
| holdout_path = holdout_path.resolve() | |
| output_dir = output_dir.resolve() | |
| if not p_pool_path.is_file(): | |
| raise FileNotFoundError(f"Missing Step 1 P pool: {p_pool_path}") | |
| if not holdout_path.is_file(): | |
| raise FileNotFoundError(f"Missing holdout JSONL: {holdout_path}") | |
| # Step 2.1: load the Step 1 P pool and the aligned holdout reservations. | |
| prepare_output_dir(output_dir, replace) | |
| p_pool = common.read_jsonl(p_pool_path) | |
| holdout_reservations = load_holdout_positive_reservations(holdout_path) | |
| # Step 2.2: remove P rows that are already used by the holdout split. | |
| after_holdout: list[dict[str, Any]] = [] | |
| exclusions: list[dict[str, Any]] = [] | |
| for row in p_pool: | |
| reason = holdout_exclusion_reason(row, holdout_reservations, holdout_match) | |
| if reason is None: | |
| after_holdout.append(row) | |
| else: | |
| exclusions.append(exclusion_record(row, reason, "holdout_exclusion")) | |
| # Step 2.2: split a seeded P-only dev set from the holdout-cleaned pool. | |
| train, dev, dev_audit = split_p_only_dev(after_holdout, dev_fraction, dev_seed, dev_trials, dev_swaps) | |
| exclusions.extend(exclusion_record(row, "dev_family_split", "dev_split") for row in dev) | |
| # Step 2.3: remove reserved-overlap rows and trim repeated cluster_key rows. | |
| train, cleanup_exclusions, cleanup_audit = train_side_cleanup(train, dev, holdout_reservations, final_p_count) | |
| exclusions.extend(cleanup_exclusions) | |
| after_holdout_rows = mark_split(after_holdout, "after_holdout") | |
| dev_rows = mark_split(dev, "dev") | |
| train_rows = mark_split(train, "train") | |
| files = { | |
| "P_pool_after_holdout.jsonl": common.write_jsonl(output_dir / "P_pool_after_holdout.jsonl", after_holdout_rows), | |
| "PU_dev.jsonl": common.write_jsonl(output_dir / "PU_dev.jsonl", dev_rows), | |
| "P_pool.jsonl": common.write_jsonl(output_dir / "P_pool.jsonl", train_rows), | |
| "P_exclusions.jsonl": common.write_jsonl(output_dir / "P_exclusions.jsonl", exclusions), | |
| } | |
| input_source_ids = {int(row["source_row_id"]) for row in p_pool if row.get("source_row_id") is not None} | |
| holdout_source_ids = holdout_reservations["source_ids"] | |
| missing_holdout_source_ids = sorted(holdout_source_ids - input_source_ids) | |
| audit = { | |
| "construction": "P_only_holdout_exclusion_then_seeded_family_dev_split", | |
| "input_p_pool": str(p_pool_path), | |
| "input_p_rows": len(p_pool), | |
| "holdout": { | |
| "path": holdout_reservations["path"], | |
| "label_counts": holdout_reservations["label_counts"], | |
| "positive_rows": holdout_reservations["positive_rows"], | |
| "match_mode": holdout_match, | |
| "positive_source_ids_available": len(holdout_source_ids), | |
| "positive_source_ids_missing_from_input": len(missing_holdout_source_ids), | |
| "missing_source_row_ids_preview": missing_holdout_source_ids[:20], | |
| }, | |
| "after_holdout_rows": len(after_holdout), | |
| "dev_split": { | |
| **dev_audit, | |
| "dev_rows": len(dev), | |
| "train_rows_before_step2_3": cleanup_audit["input_rows"], | |
| "train_rows": len(train), | |
| }, | |
| "train_side_cleanup": cleanup_audit, | |
| "exclusions_by_reason": dict(Counter(item["reason"] for item in exclusions)), | |
| "files": files, | |
| } | |
| common.write_json(output_dir / "step2_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("--holdout-jsonl", type=Path, default=None) | |
| parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT) | |
| parser.add_argument("--holdout-match", choices=["auto", "source_row_id", "condition_key"], default="auto") | |
| parser.add_argument("--dev-fraction", type=float, default=DEFAULT_DEV_FRACTION) | |
| parser.add_argument("--dev-seed", type=int, default=DEFAULT_DEV_SEED) | |
| parser.add_argument("--dev-trials", type=int, default=DEFAULT_DEV_TRIALS) | |
| parser.add_argument("--dev-swaps", type=int, default=DEFAULT_DEV_SWAPS) | |
| parser.add_argument("--final-p-count", type=int, default=DEFAULT_FINAL_P_COUNT) | |
| parser.add_argument("--replace", action="store_true") | |
| args = parser.parse_args() | |
| holdout_path = args.holdout_jsonl or default_holdout_path() | |
| build_step2( | |
| args.p_pool, | |
| holdout_path, | |
| args.output_dir, | |
| holdout_match=args.holdout_match, | |
| dev_fraction=args.dev_fraction, | |
| dev_seed=args.dev_seed, | |
| dev_trials=args.dev_trials, | |
| dev_swaps=args.dev_swaps, | |
| final_p_count=args.final_p_count, | |
| replace=args.replace, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |