"""Lightweight shared helpers for the PU data construction scripts.""" from __future__ import annotations from collections import Counter import hashlib import json import math from pathlib import Path import re from typing import Any, Iterable, Mapping import unicodedata FIELDS = ( "metal_precursor", "organic_linker", "modulator", "solvent", "metal_concentration_mM", "M_L_ratio", "temperature_C", "time_h", ) TEXT_FIELDS = FIELDS[:4] NUMERIC_FIELDS = FIELDS[4:] SIX_FIELDS = FIELDS[2:] SYSTEM_PREFIX = ( "Act as an expert in reticular chemistry. You will receive reaction conditions as a JSON object with the fields:\n" " metal_precursor, organic_linker, modulator, solvent, metal_concentration_mM, M_L_ratio, temperature_C, and time_h.\n" " Based on these inputs, output exactly one uppercase label: 'P' if the conditions are likely to yield a crystalline\n" ) PN_PROMPT = SYSTEM_PREFIX + " metal-organic framework under experimental conditions, or 'N' if not." PU_PROMPT = ( SYSTEM_PREFIX + " metal-organic framework under experimental conditions, or 'U' if the outcome should be treated as unlabeled/unknown\n" " under the positive-unlabeled learning setup." ) EMPTY = { "", "nan", "none", "null", "", "na", "n/a", "not_reported", "not reported", "not-report", "unknown", } METAL_NAMES = dict( zip( "lithium sodium potassium rubidium cesium caesium beryllium magnesium calcium strontium barium " "scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc yttrium zirconium " "niobium molybdenum technetium ruthenium rhodium palladium silver cadmium hafnium tantalum tungsten " "rhenium osmium iridium platinum gold mercury aluminium aluminum gallium indium tin thallium lead " "bismuth lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium terbium " "dysprosium holmium erbium thulium ytterbium lutetium thorium uranium".split(), "Li Na K Rb Cs Cs Be Mg Ca Sr Ba Sc Ti V Cr Mn Fe Co Ni Cu Zn Y Zr Nb Mo Tc Ru Rh Pd Ag Cd Hf Ta W " "Re Os Ir Pt Au Hg Al Al Ga In Sn Tl Pb Bi La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Th U".split(), ) ) S_BLOCK = set("Li Na K Rb Cs Be Mg Ca Sr Ba".split()) P_BLOCK = set("Al Ga In Sn Tl Pb Bi".split()) F_BLOCK = set("La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Th U".split()) METALS = set(METAL_NAMES.values()) def digest(value: Any) -> str: return hashlib.blake2b(str(value).encode("utf-8"), digest_size=32).hexdigest() def compact(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) def is_missing(value: Any) -> bool: return value is None or (isinstance(value, float) and math.isnan(value)) def source_text(value: Any) -> str | None: if is_missing(value): return None text = str(value).strip() for old, new in [ ("′", "'"), ("’", "'"), ("‘", "'"), ("“", '"'), ("”", '"'), ("–", "-"), ("—", "-"), ]: text = text.replace(old, new) text = " ".join(text.strip('"').strip("'").split()) return None if text.casefold() in EMPTY else text def clean_text(value: Any) -> str | None: if is_missing(value): return None text = unicodedata.normalize("NFKC", str(value)).strip().replace("’", "'").replace("′", "'") text = re.sub(r"\s+", " ", text) return None if text.casefold() in EMPTY else text def parse_number(value: Any) -> float | None: text = source_text(value) if text is None: return None match = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", text) if not match: return None parsed = float(match.group()) return parsed if math.isfinite(parsed) else None def parse_ratio(value: Any) -> float | None: text = source_text(value) if text is None: return None try: parsed = float(text) return parsed if math.isfinite(parsed) else None except ValueError: pass parts = [parse_number(part) for part in re.split(r"[:/]", text)] if any(part is None for part in parts): return None if len(parts) == 1: return parts[0] denominator = sum(parts[1:]) return parts[0] / denominator if denominator else None def payload(row: Mapping[str, Any]) -> dict[str, Any]: result: dict[str, Any] = {field: clean_text(row.get(field)) for field in TEXT_FIELDS} for field in NUMERIC_FIELDS: value = row.get(field) if is_missing(value): result[field] = None continue parsed = float(value) result[field] = parsed if math.isfinite(parsed) else None return result def condition_key(row: Mapping[str, Any]) -> str: """Digest key compatible with the compact eight-field builder key.""" clean = payload(row) canonical = {field: (clean[field] or "").casefold() or None for field in TEXT_FIELDS} for field in NUMERIC_FIELDS: value = clean[field] canonical[field] = format(float(value), ".10g") if value is not None else None return digest(compact(canonical)) def identity_text(value: str) -> str: text = unicodedata.normalize("NFKC", value).strip() text = text.replace("′", "'").replace("’", "'").replace("‘", "'").replace("–", "-").replace("—", "-") text = re.sub(r"\s+", " ", text).casefold() text = re.sub(r"\s*([,()\[\]])\s*", r"\1", text) return text def metal_identity(value: str) -> str: text = unicodedata.normalize("NFKC", value).strip().replace("∙", "·").replace("⋅", "·") text = re.sub(r"\.(?=(?:\d+(?:/\d+)?|n)?H2O\b)", "·", text) text = re.sub(r"\(([A-Z][A-Za-z0-9]*)\)(?![0-9A-Za-z])", r"\1", text) if not re.search(r"\s", text): return identity_text(text) if re.fullmatch(r"[A-Z][A-Za-z0-9()\[\]·./+\-\s]*", text) and not re.search(r"[a-z]{3,}", text): text = re.sub(r"\s+", "", text) return identity_text(text) def mixture_identity(value: str | None) -> str | None: if value is None: return None return compact(sorted({identity_text(part) for part in re.split(r"\s+and\s+", value, flags=re.I)})) def linker_identity(value: str, components: list[str] | None = None) -> str: parts = components if components is not None else re.split(r"\s+and\s+", value, flags=re.I) return compact(sorted({identity_text(part) for part in parts})) def pair_key(row: Mapping[str, Any], linker_aliases: Mapping[str, str] | None = None) -> str: linker = row["organic_linker"] linker_key = (linker_aliases or {}).get(identity_text(linker), linker_identity(linker)) return digest(compact([metal_identity(row["metal_precursor"]), linker_key])) def normalized_condition_key(row: Mapping[str, Any], linker_aliases: Mapping[str, str] | None = None) -> str: clean = payload(row) result = { "pair": pair_key(clean, linker_aliases), "modulator": mixture_identity(clean["modulator"]), "solvent": mixture_identity(clean["solvent"]), } for field in NUMERIC_FIELDS: value = clean[field] result[field] = None if value is None else format(float(value), ".10g") return digest(compact(result)) def family_key(row: Mapping[str, Any], linker_aliases: Mapping[str, str] | None = None) -> str: clean = payload(row) return digest(compact([pair_key(clean, linker_aliases), mixture_identity(clean["solvent"])])) def metal_category(value: str) -> tuple[str, list[str], str | None]: text = unicodedata.normalize("NFKC", value) stack = [] for char in text: if char in "([": stack.append(char) elif char in ")]": if not stack or (stack.pop(), char) not in [("(", ")"), ("[", "]")]: return ("unresolved", [], "unbalanced_formula_brackets") if stack: return ("unresolved", [], "unbalanced_formula_brackets") words = re.findall(r"\b[a-z]+\b", text.casefold()) names = {METAL_NAMES[word] for word in words if word in METAL_NAMES} if names: if re.fullmatch(r"[A-Za-z]+\s*(?:\([IVX]+\))?", text): return ("unresolved", sorted(names), "metal_name_without_precursor_identity") metals = names else: metals = set(re.findall(r"[A-Z][a-z]?", text)) & METALS if not metals: return ("unresolved", [], "unresolved_metal_identity") if len(metals) > 1: category = "mixed_metal" else: metal = next(iter(metals)) category = "s_block" if metal in S_BLOCK else "p_block" if metal in P_BLOCK else "f_block" if metal in F_BLOCK else "d_block" return (category, sorted(metals), None) def donor_rule_failures(row: Mapping[str, Any], config: Mapping[str, Any]) -> list[str]: reasons = [] clean = payload(row) if not clean.get("solvent"): reasons.append("missing_solvent") if clean.get("modulator") is None and not config["allow_null_modulator"]: reasons.append("missing_modulator") for field, limits in config["numeric_donor_rules"].items(): value = clean.get(field) if not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(value): reasons.append("missing_or_nonfinite_" + field) continue for rule, bound in limits.items(): passed = { "min_exclusive": value > bound, "min_inclusive": value >= bound, "max_exclusive": value < bound, "max_inclusive": value <= bound, }[rule] if not passed: reasons.append("out_of_bounds_" + field) break return reasons def reagents(raw: Mapping[str, Any], stem: str, count: int) -> list[str]: result = [] seen = set() for index in range(1, count + 1): value = source_text(raw.get(f"{stem}_{index}")) or source_text(raw.get(f"{stem}_{index}_abbr")) key = value.casefold().replace("·", ".") if value is not None else None if value is not None and key not in seen: seen.add(key) result.append(value) return result def raw_payload(raw: Mapping[str, Any]) -> dict[str, Any]: solvents = [] for key in ["solvent_main", "solvent_secondary"]: value = source_text(raw.get(key)) or source_text(raw.get(key + "_abbr")) if value and value.casefold() not in {item.casefold() for item in solvents}: solvents.append(value) return payload( { "metal_precursor": source_text(raw.get("metal_1")) or source_text(raw.get("metal_1_abbr")), "organic_linker": " and ".join(reagents(raw, "linker", 3)) or None, "modulator": " and ".join(reagents(raw, "modulator", 2)) or None, "solvent": " and ".join(solvents) or None, "metal_concentration_mM": parse_number(raw.get("metel_concnertation")), "M_L_ratio": parse_ratio(raw.get("M_L_ratio")), "temperature_C": parse_number(raw.get("temperature_c")), "time_h": parse_number(raw.get("time_h")), } ) def p_only_norm_text(value: Any) -> str | None: text = source_text(value) if text is None: return None text = text.casefold().replace("·", ".") text = " ".join(text.split()).strip() return text or None def p_only_condition_key(row: Mapping[str, Any]) -> str: """JSON key compatible with step1_csv_preprocess_only_P.py.""" clean = payload(row) canonical: dict[str, Any] = {} for field in TEXT_FIELDS: canonical[field] = p_only_norm_text(clean.get(field)) for field in NUMERIC_FIELDS: value = clean.get(field) canonical[field] = None if value is None else round(float(value), 8) return json.dumps(canonical, sort_keys=True, ensure_ascii=False) def p_only_family_key(row: Mapping[str, Any]) -> str: clean = payload(row) parts = [ f"metal={p_only_norm_text(clean.get('metal_precursor')) or 'unknown'}", f"linker={p_only_norm_text(clean.get('organic_linker')) or 'unknown'}", f"solvent={p_only_norm_text(clean.get('solvent')) or 'unknown'}", ] return "|".join(parts) def read_jsonl(path: Path) -> list[dict[str, Any]]: records = [] with path.open(encoding="utf-8") as stream: for line_number, line in enumerate(stream, 1): text = line.strip() if not text: continue try: records.append(json.loads(text)) except json.JSONDecodeError as exc: raise ValueError(f"Invalid JSONL at {path}:{line_number}: {exc}") from exc return records def write_json(path: Path, value: Mapping[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 write_jsonl(path: Path, rows: Iterable[Mapping[str, Any]]) -> dict[str, int]: path.parent.mkdir(parents=True, exist_ok=True) count = 0 with path.open("w", encoding="utf-8", newline="\n") as stream: for row in rows: stream.write(json.dumps(row, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n") count += 1 return {"rows": count, "bytes": path.stat().st_size} write_rows = write_jsonl def message_payload_and_label(record: Mapping[str, Any]) -> tuple[dict[str, Any], str]: messages = record.get("messages") if not isinstance(messages, list) or len(messages) < 3: raise ValueError("Message JSONL record must contain at least system/user/assistant messages.") user_content = messages[1].get("content") assistant_content = messages[2].get("content") if not isinstance(user_content, str) or not isinstance(assistant_content, str): raise ValueError("Message JSONL record has non-string user or assistant content.") payload_record = json.loads(user_content) return payload(payload_record), assistant_content.strip() def record_payload_and_label(record: Mapping[str, Any]) -> tuple[dict[str, Any], str | None]: if "messages" in record: return message_payload_and_label(record) return payload(record), record.get("label") def condition_keys_for_record(record: Mapping[str, Any]) -> set[str]: row, _ = record_payload_and_label(record) keys = {condition_key(row), p_only_condition_key(row)} stored = record.get("condition_key") if isinstance(stored, str) and stored: keys.add(stored) return keys def write_messages( path: Path, rows: Iterable[Mapping[str, Any]], kind: str, override_nonpositive: str | None = None, ) -> dict[str, Any]: path.parent.mkdir(parents=True, exist_ok=True) labels: Counter[str] = Counter() with path.open("w", encoding="utf-8", newline="\n") as stream: for row in rows: label = str(row["label"]) if override_nonpositive and label != "P": label = override_nonpositive if label not in ({"P", "N"} if kind == "PN" else {"P", "U"}): raise ValueError(f"Bad {kind} label {label}") messages = [ {"role": "system", "content": PN_PROMPT if kind == "PN" else PU_PROMPT}, {"role": "user", "content": json.dumps(payload(row), ensure_ascii=False, allow_nan=False)}, {"role": "assistant", "content": label}, ] stream.write(json.dumps({"messages": messages}, ensure_ascii=False, allow_nan=False) + "\n") labels[label] += 1 return {"rows": sum(labels.values()), "labels": dict(labels), "bytes": path.stat().st_size}