""" Preprocess the positive CSV into the initial P pool. """ from __future__ import annotations import argparse from collections import Counter import hashlib import json import math from pathlib import Path from typing import Any, Mapping import re import unicodedata import pandas as pd ROOT = Path(__file__).resolve().parent DEFAULT_WORK_DIR = ROOT.parent / "wf-tmp" 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_OUTPUT = DEFAULT_WORK_DIR / "01_csv_preprocess" POSITIVE_FILE = "processed_positive.csv" TEXT_FIELDS = ( "metal_precursor", "organic_linker", "modulator", "solvent") NUMERIC_FIELDS = ( "metal_concentration_mM", "M_L_ratio", "temperature_C", "time_h") FIELDS = TEXT_FIELDS + NUMERIC_FIELDS EMPTY_TOKENS = { "", "nan", "none", "null", "na", "n/a", "not_reported", "not reported", "not-report", "unknown"} def digest(value: Any) -> str: return hashlib.blake2b(str(value).encode("utf-8"), digest_size=32).hexdigest() def clean_str(value: Any) -> str | None: try: if pd.isna(value): return None except (TypeError, ValueError): pass text = str(value).strip() text = ( text.replace("′", "'") .replace("’", "'") .replace("‘", "'") .replace("“", '"') .replace("”", '"') .replace("–", "-") .replace("—", "-") ) text = " ".join(text.strip('"').strip("'").split()) return None if text.casefold() in EMPTY_TOKENS else text def norm_for_key(value: Any) -> str | None: text = clean_str(value) if text is None: return None text = text.casefold().replace("·", ".") text = " ".join(text.split()).strip() return text or None def to_float(value: Any) -> float | None: if clean_str(value) is None: return None matches = re.findall(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", str(value)) if not matches: return None try: parsed = float(matches[0]) except ValueError: return None return parsed if math.isfinite(parsed) else None def parse_ml_ratio(value: Any) -> float | None: text = clean_str(value) if text is None: return None try: parsed = float(text) return parsed if math.isfinite(parsed) else None except ValueError: pass numbers = [] for part in re.split(r"[:/]", text): number = to_float(part) if number is None: return None numbers.append(number) if len(numbers) == 1: return numbers[0] linker_sum = sum(numbers[1:]) return numbers[0] / linker_sum if linker_sum else None def display_value(name: Any, abbr: Any = None) -> str | None: return clean_str(name) or clean_str(abbr) def unique_preserve_order(values: Any) -> list[str]: result = [] seen = set() for value in values: text = clean_str(value) if not text: continue key = norm_for_key(text) if key not in seen: result.append(text) seen.add(key) return result def join_with_and(values: Any) -> str | None: values = unique_preserve_order(values) return " and ".join(values) if values else None def collect_numbered_reagents(row: Mapping[str, Any], stem: str, max_n: int = 3) -> list[str]: return unique_preserve_order( display_value(row.get(f"{stem}_{index}"), row.get(f"{stem}_{index}_abbr")) for index in range(1, max_n + 1) ) def collect_solvents(row: Mapping[str, Any]) -> list[str]: return unique_preserve_order( [ display_value(row.get("solvent_main"), row.get("solvent_main_abbr")), display_value(row.get("solvent_secondary"), row.get("solvent_secondary_abbr")), ] ) def has_any(row: Mapping[str, Any], columns: list[str]) -> bool: return any(clean_str(row.get(column)) is not None for column in columns) def row_to_conditions(row: Mapping[str, Any]) -> dict[str, Any]: return { "metal_precursor": display_value(row.get("metal_1"), row.get("metal_1_abbr")), "organic_linker": join_with_and(collect_numbered_reagents(row, "linker", 3)), "modulator": join_with_and(collect_numbered_reagents(row, "modulator", 2)), "solvent": join_with_and(collect_solvents(row)), "metal_concentration_mM": to_float(row.get("metel_concnertation")), "M_L_ratio": parse_ml_ratio(row.get("M_L_ratio")), "temperature_C": to_float(row.get("temperature_c")), "time_h": to_float(row.get("time_h")), } def condition_key_from_conditions(conditions: Mapping[str, Any]) -> str: key = {} for name, value in conditions.items(): if isinstance(value, (float, int)): key[name] = None if pd.isna(value) else round(float(value), 8) elif value is None: key[name] = None else: key[name] = norm_for_key(value) return json.dumps(key, sort_keys=True, ensure_ascii=False) def canonical_set_key(values: Any) -> str: values = sorted({norm_for_key(value) for value in values if norm_for_key(value)}) return " + ".join(values) if values else "unknown" def cluster_key(row: Mapping[str, Any]) -> str: return "|".join( [ f"metal={norm_for_key(display_value(row.get('metal_1'), row.get('metal_1_abbr'))) or 'unknown'}", f"linker={canonical_set_key(collect_numbered_reagents(row, 'linker', 3))}", f"solvent={canonical_set_key(collect_solvents(row))}", ] ) def payload_from_conditions(conditions: Mapping[str, Any]) -> dict[str, Any]: payload = {} for field in TEXT_FIELDS: value = conditions[field] payload[field] = None if value is None else unicodedata.normalize("NFKC", str(value)).strip() for field in NUMERIC_FIELDS: value = conditions[field] payload[field] = None if value is None or not math.isfinite(float(value)) else float(value) return payload def required_failures(row: Mapping[str, Any]) -> list[str]: failures = [] if not has_any(row, ["metal_1", "metal_1_abbr"]): failures.append("missing_metal") if not has_any(row, ["linker_1", "linker_1_abbr", "linker_2", "linker_2_abbr", "linker_3", "linker_3_abbr"]): failures.append("missing_linker") if not has_any(row, ["solvent_main", "solvent_main_abbr", "solvent_secondary", "solvent_secondary_abbr"]): failures.append("missing_solvent") numeric_present = [ parse_ml_ratio(row.get("M_L_ratio")) is not None, to_float(row.get("metel_concnertation")) is not None, to_float(row.get("temperature_c")) is not None, ] if sum(numeric_present) < 2: failures.append("fewer_than_two_core_numeric_fields") return failures def pool_record(row: Mapping[str, Any]) -> dict[str, Any]: conditions = row_to_conditions(row) source_row_id = int(row["source_row_id"]) record = payload_from_conditions(conditions) record.update( label="P", record_id=f"PSTEP1:{source_row_id:08d}", source_csv=POSITIVE_FILE, source_line=source_row_id + 2, source_row_id=source_row_id, condition_key=condition_key_from_conditions(conditions), cluster_key=cluster_key(row), ) return record def exclusion_record(row: Mapping[str, Any], reason: str) -> dict[str, Any]: record = { "source_csv": POSITIVE_FILE, "source_line": int(row["source_row_id"]) + 2, "source_row_id": int(row["source_row_id"]), "label": "P", "reason": reason, } failures = required_failures(row) if failures: record["required_failures"] = failures try: record["payload"] = payload_from_conditions(row_to_conditions(row)) record["condition_key"] = condition_key_from_conditions(row_to_conditions(row)) except Exception: pass return record def write_jsonl(path: Path, records: list[dict[str, Any]]) -> dict[str, int]: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8", newline="\n") as stream: for record in records: stream.write(json.dumps(record, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n") return {"rows": len(records), "bytes": path.stat().st_size} def write_json(path: Path, value: dict[str, Any]) -> dict[str, int]: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8") return {"bytes": path.stat().st_size} def prepare_output_dir(output_dir: Path, replace: bool) -> None: managed = [output_dir / name for name in ["P_pool.jsonl", "P_exclusions.jsonl", "P_audit.json"]] occupied = [path for path in managed if path.exists()] if occupied and not replace: names = [str(path.relative_to(output_dir)) for path in occupied] raise FileExistsError(f"P-only outputs already exist: {names}; use --replace") output_dir.mkdir(parents=True, exist_ok=True) if replace: for path in occupied: path.unlink() def preprocess_positive(input_dir: Path, output_dir: Path, target_count: int = 13288, trim_seed: int = 42, replace: bool = False) -> dict[str, Any]: input_dir = input_dir.resolve() output_dir = output_dir.resolve() prepare_output_dir(output_dir, replace) df = pd.read_csv(input_dir / POSITIVE_FILE, low_memory=False) df["source_row_id"] = range(len(df)) required_mask = df.apply(lambda row: not required_failures(row), axis=1) required_df = df[required_mask].copy() excluded = [exclusion_record(row, "required_filter") for _, row in df[~required_mask].iterrows()] required_df["condition_key"] = required_df.apply(lambda row: condition_key_from_conditions(row_to_conditions(row)), axis=1) required_df["cluster_key"] = required_df.apply(cluster_key, axis=1) duplicate_mask = required_df.duplicated(subset=["condition_key"], keep="first") excluded.extend(exclusion_record(row, "exact_duplicate_within_P") for _, row in required_df[duplicate_mask].iterrows()) dedup_df = required_df[~duplicate_mask].copy() if target_count > len(dedup_df): raise ValueError(f"target_count={target_count} exceeds deduplicated P rows={len(dedup_df)}") trim_n = len(dedup_df) - target_count if trim_n: trim_rank = dedup_df.apply( lambda row: digest(f"{trim_seed}|P-only-target-trim|{int(row['source_row_id'])}|{row['condition_key']}"), axis=1, ) trim_index = set(trim_rank.sort_values(ascending=False).head(trim_n).index) trim_df = dedup_df.loc[sorted(trim_index)].copy() excluded.extend(exclusion_record(row, "P_only_target_trim") for _, row in trim_df.iterrows()) pool_df = dedup_df.drop(index=trim_index).copy() else: pool_df = dedup_df pool_df = pool_df.sort_values("source_row_id") pool_records = [pool_record(row) for _, row in pool_df.iterrows()] excluded = sorted(excluded, key=lambda item: (item["reason"], item["source_row_id"])) files = { "P_pool.jsonl": write_jsonl(output_dir / "P_pool.jsonl", pool_records), "P_exclusions.jsonl": write_jsonl(output_dir / "P_exclusions.jsonl", excluded), } audit = { "input_rows": len(df), "after_required_filter": len(required_df), "after_exact_dedup": len(dedup_df), "target_count": target_count, "trim_seed": trim_seed, "output_rows": len(pool_records), "exclusions_by_reason": dict(Counter(item["reason"] for item in excluded)), "files": files, } write_json(output_dir / "P_audit.json", audit) return audit def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--input-dir", "--source-dir", dest="input_dir", type=Path, default=DEFAULT_INPUT) parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT) parser.add_argument("--target-count", type=int, default=13288) parser.add_argument("--trim-seed", type=int, default=123) parser.add_argument("--replace", action="store_true") args = parser.parse_args() preprocess_positive(args.input_dir, args.output_dir, args.target_count, args.trim_seed, args.replace) if __name__ == "__main__": main()