Matthew Ford commited on
Commit ·
da6651e
1
Parent(s): 459c5c3
v11.5 enrichment: VP/BP 67→340, structure 1731→1741, eval-pairs newly representable=3, leak-rejected=0, formula/MW-rejected=15
Browse files
artifacts/pimt_v11_5_catalog_enrichment.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
artifacts/pimt_v11_5_catalog_enrichment.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PIMT v11.5 targeted physicochemical enrichment
|
| 2 |
+
|
| 3 |
+
PubChem was queried in evaluation-material, formula-frequency, then long-tail order. PubChem is independent of the Fraterworks and PerfumersWorld answer sources.
|
| 4 |
+
|
| 5 |
+
- Profiles: 5722 -> 5726.
|
| 6 |
+
- Structure: 1731 -> 1741.
|
| 7 |
+
- logP: 1692 -> 1702.
|
| 8 |
+
- **VP/BP: 67 -> 340** (VP 67 -> 212; BP 67 -> 328).
|
| 9 |
+
- Odor text: 3142 -> 3142; taxonomy: 2702 -> 2702 (unchanged by this pipeline).
|
| 10 |
+
- One-to-one pairs independently representable: 25 -> 28 (3 newly representable).
|
| 11 |
+
- Leak-rejected enrichments: 0.
|
| 12 |
+
- Formula/MW-rejected resolutions: 15.
|
| 13 |
+
- Other identity-rejected resolutions: 1.
|
| 14 |
+
- Accepted verified resolutions: 525; accepted unverified resolutions: 11.
|
| 15 |
+
|
| 16 |
+
## Provenance tiers
|
| 17 |
+
|
| 18 |
+
```json
|
| 19 |
+
{
|
| 20 |
+
"boiling_point_k": {
|
| 21 |
+
"legacy-untiered": 67,
|
| 22 |
+
"measured": 261,
|
| 23 |
+
"unverified_identity": 5
|
| 24 |
+
},
|
| 25 |
+
"logp": {
|
| 26 |
+
"computed": 10,
|
| 27 |
+
"legacy-untiered": 1692,
|
| 28 |
+
"unverified_identity": 10
|
| 29 |
+
},
|
| 30 |
+
"smiles": {
|
| 31 |
+
"computed": 10,
|
| 32 |
+
"legacy-untiered": 1731,
|
| 33 |
+
"unverified_identity": 10
|
| 34 |
+
},
|
| 35 |
+
"vapor_pressure_pa": {
|
| 36 |
+
"legacy-untiered": 67,
|
| 37 |
+
"measured": 145,
|
| 38 |
+
"unverified_identity": 3
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
Computed PubChem structure/logP values are never treated as ground truth. PUG View values under Experimental Properties are tagged measured; explicitly estimated/calculated values remain computed. Name-only resolutions without CAS/formula/MW/InChIKey cross-checks are tagged unverified.
|
data/material_profiles_v11_5.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/pubchem_material_catalog_v11_5.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/pimt_v11_5_targeted_enrichment.py
ADDED
|
@@ -0,0 +1,678 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Targeted online PubChem enrichment for the frozen v11.4 catalogue.
|
| 3 |
+
|
| 4 |
+
Priority is evaluation material, then documented formula frequency, then the
|
| 5 |
+
remaining catalogue. PubChem is independent of both supplier sources used by
|
| 6 |
+
the evaluation set. Every accepted resolution is checked against available
|
| 7 |
+
CAS, formula, molecular-weight, and InChIKey evidence before any field is
|
| 8 |
+
attached. Name-only identities without one of those checks remain explicitly
|
| 9 |
+
unverified.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import sys
|
| 19 |
+
import tempfile
|
| 20 |
+
import time
|
| 21 |
+
from collections import Counter, defaultdict
|
| 22 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 23 |
+
from copy import deepcopy
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Any
|
| 26 |
+
from urllib.error import HTTPError, URLError
|
| 27 |
+
from urllib.parse import quote, urlparse
|
| 28 |
+
from urllib.request import Request, urlopen
|
| 29 |
+
|
| 30 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
| 31 |
+
from pino.substitution_v11 import load_jsonl, normalize_name, profile_lookup, write_jsonl
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 35 |
+
DATA = ROOT / "data"
|
| 36 |
+
ARTIFACTS = ROOT / "artifacts"
|
| 37 |
+
INPUT_PROFILES = DATA / "material_profiles_v11_4.jsonl"
|
| 38 |
+
OUTPUT_PROFILES = DATA / "material_profiles_v11_5.jsonl"
|
| 39 |
+
EVAL_SET = DATA / "substitution_eval_set_v11_3.jsonl"
|
| 40 |
+
CACHE = DATA / "pubchem_material_catalog_v11_5.json"
|
| 41 |
+
REPORT_JSON = ARTIFACTS / "pimt_v11_5_catalog_enrichment.json"
|
| 42 |
+
REPORT_MD = ARTIFACTS / "pimt_v11_5_catalog_enrichment.md"
|
| 43 |
+
PUBCHEM_DOMAIN = "pubchem.ncbi.nlm.nih.gov"
|
| 44 |
+
PROPERTIES = (
|
| 45 |
+
"CanonicalSMILES,IsomericSMILES,InChIKey,MolecularFormula,"
|
| 46 |
+
"MolecularWeight,XLogP,Title"
|
| 47 |
+
)
|
| 48 |
+
CAS_RE = re.compile(r"(?<!\d)(\d{2,7}-\d{2}-\d)(?!\d)")
|
| 49 |
+
NUMBER_RE = r"(?:\d+(?:\.\d*)?|\.\d+)(?:\s*(?:[Ee][+-]?\d+|[xX×]\s*10\s*\^?\s*[+-]?\d+))?"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def atomic_json(path: Path, value: Any) -> None:
|
| 53 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 54 |
+
fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
| 55 |
+
try:
|
| 56 |
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
| 57 |
+
json.dump(value, handle, indent=2, sort_keys=True, ensure_ascii=False)
|
| 58 |
+
handle.write("\n")
|
| 59 |
+
os.replace(temporary, path)
|
| 60 |
+
finally:
|
| 61 |
+
if os.path.exists(temporary):
|
| 62 |
+
os.unlink(temporary)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def clean_cas(value: Any) -> str | None:
|
| 66 |
+
text = str(value or "").strip()
|
| 67 |
+
if not re.fullmatch(r"\d{2,7}-\d{2}-\d", text):
|
| 68 |
+
return None
|
| 69 |
+
digits = text.replace("-", "")
|
| 70 |
+
checksum = sum(i * int(d) for i, d in enumerate(reversed(digits[:-1]), 1)) % 10
|
| 71 |
+
return text if checksum == int(digits[-1]) else None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def normalized_formula(value: Any) -> str | None:
|
| 75 |
+
text = re.sub(r"\s+", "", str(value or ""))
|
| 76 |
+
return text or None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def numeric(value: Any) -> float | None:
|
| 80 |
+
try:
|
| 81 |
+
result = float(value)
|
| 82 |
+
except (TypeError, ValueError):
|
| 83 |
+
return None
|
| 84 |
+
return result if math.isfinite(result) else None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def source_domain(row: dict[str, Any]) -> str | None:
|
| 88 |
+
value = str(row.get("source_url") or "")
|
| 89 |
+
return (urlparse(value).hostname or "").lower() or None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def eval_materials(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 93 |
+
observations: dict[tuple[str, str], dict[str, Any]] = {}
|
| 94 |
+
for row in rows:
|
| 95 |
+
materials = [{"name": row.get("target"), "cas": row.get("target_cas"), "role": "target"}]
|
| 96 |
+
materials.extend(
|
| 97 |
+
{"name": item.get("name"), "cas": item.get("cas"), "role": "answer"}
|
| 98 |
+
for item in (row.get("answer") or {}).get("materials") or []
|
| 99 |
+
)
|
| 100 |
+
for item in materials:
|
| 101 |
+
name = str(item.get("name") or "").strip()
|
| 102 |
+
cas = clean_cas(item.get("cas"))
|
| 103 |
+
if not (name or cas):
|
| 104 |
+
continue
|
| 105 |
+
key = (cas or "", normalize_name(name))
|
| 106 |
+
entry = observations.setdefault(
|
| 107 |
+
key,
|
| 108 |
+
{"name": name, "cas": cas, "pair_ids": [], "roles": [], "answer_source_domains": []},
|
| 109 |
+
)
|
| 110 |
+
entry["pair_ids"].append(row["pair_id"])
|
| 111 |
+
entry["roles"].append(item["role"])
|
| 112 |
+
domain = source_domain(row)
|
| 113 |
+
if domain:
|
| 114 |
+
entry["answer_source_domains"].append(domain)
|
| 115 |
+
for entry in observations.values():
|
| 116 |
+
for key in ("pair_ids", "roles", "answer_source_domains"):
|
| 117 |
+
entry[key] = sorted(set(entry[key]))
|
| 118 |
+
return sorted(observations.values(), key=lambda x: (x.get("cas") or "", normalize_name(x["name"])))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def request_json(url: str, retries: int = 5) -> tuple[str, Any]:
|
| 122 |
+
for attempt in range(retries):
|
| 123 |
+
try:
|
| 124 |
+
request = Request(url, headers={"User-Agent": "PINO-research/11.5 (PubChem enrichment)"})
|
| 125 |
+
with urlopen(request, timeout=45) as response:
|
| 126 |
+
return "ok", json.load(response)
|
| 127 |
+
except HTTPError as exc:
|
| 128 |
+
if exc.code in {400, 404}:
|
| 129 |
+
return "not_found", None
|
| 130 |
+
if exc.code not in {429, 500, 502, 503, 504} or attempt + 1 == retries:
|
| 131 |
+
return "error", f"HTTP {exc.code}"
|
| 132 |
+
except (TimeoutError, URLError, json.JSONDecodeError) as exc:
|
| 133 |
+
if attempt + 1 == retries:
|
| 134 |
+
return "error", type(exc).__name__
|
| 135 |
+
time.sleep(min(12.0, 1.5 * (2**attempt)))
|
| 136 |
+
return "error", "retry_exhausted"
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def property_lookup(query: str) -> dict[str, Any]:
|
| 140 |
+
url = (
|
| 141 |
+
"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/"
|
| 142 |
+
f"{quote(query, safe='')}/property/{PROPERTIES}/JSON"
|
| 143 |
+
)
|
| 144 |
+
status, payload = request_json(url)
|
| 145 |
+
if status != "ok":
|
| 146 |
+
return {"status": status, "error": payload if status == "error" else None, "query": query}
|
| 147 |
+
rows = payload.get("PropertyTable", {}).get("Properties", [])
|
| 148 |
+
if not rows:
|
| 149 |
+
return {"status": "not_found", "query": query}
|
| 150 |
+
return {"status": "resolved", "query": query, "property": rows[0]}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def synonyms_lookup(cid: int) -> list[str]:
|
| 154 |
+
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/synonyms/JSON"
|
| 155 |
+
status, payload = request_json(url)
|
| 156 |
+
if status != "ok":
|
| 157 |
+
return []
|
| 158 |
+
rows = payload.get("InformationList", {}).get("Information", [])
|
| 159 |
+
return list(rows[0].get("Synonym") or []) if rows else []
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def heading_lookup(cid: int, heading: str) -> dict[str, Any]:
|
| 163 |
+
url = (
|
| 164 |
+
f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON"
|
| 165 |
+
f"?heading={quote(heading)}"
|
| 166 |
+
)
|
| 167 |
+
status, payload = request_json(url)
|
| 168 |
+
if status != "ok":
|
| 169 |
+
return {"status": status, "error": payload if status == "error" else None}
|
| 170 |
+
return {"status": "resolved", "record": payload.get("Record") or {}}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def complete_resolution(result: dict[str, Any]) -> dict[str, Any]:
|
| 174 |
+
if result.get("status") != "resolved":
|
| 175 |
+
return result
|
| 176 |
+
cid = result["property"].get("CID")
|
| 177 |
+
if not cid:
|
| 178 |
+
return {**result, "status": "error", "error": "missing_cid"}
|
| 179 |
+
result = deepcopy(result)
|
| 180 |
+
result["synonyms"] = synonyms_lookup(int(cid))
|
| 181 |
+
result["vapor_pressure"] = heading_lookup(int(cid), "Vapor Pressure")
|
| 182 |
+
result["boiling_point"] = heading_lookup(int(cid), "Boiling Point")
|
| 183 |
+
return result
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def resolve_one(query: str) -> dict[str, Any]:
|
| 187 |
+
return complete_resolution(property_lookup(query))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def strings_from_value(value: dict[str, Any]) -> list[str]:
|
| 191 |
+
strings = [str(item.get("String")) for item in value.get("StringWithMarkup") or [] if item.get("String")]
|
| 192 |
+
for item in value.get("Number") or []:
|
| 193 |
+
strings.append(f"{item} {value.get('Unit') or ''}".strip())
|
| 194 |
+
return strings
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def information_at_heading(record: dict[str, Any], heading: str) -> list[dict[str, Any]]:
|
| 198 |
+
found: list[dict[str, Any]] = []
|
| 199 |
+
|
| 200 |
+
def visit(section: dict[str, Any]) -> None:
|
| 201 |
+
if section.get("TOCHeading") == heading:
|
| 202 |
+
found.extend(section.get("Information") or [])
|
| 203 |
+
for child in section.get("Section") or []:
|
| 204 |
+
visit(child)
|
| 205 |
+
|
| 206 |
+
for section in record.get("Section") or []:
|
| 207 |
+
visit(section)
|
| 208 |
+
return found
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def parse_number(text: str) -> float | None:
|
| 212 |
+
match = re.search(NUMBER_RE, text.replace(",", ""))
|
| 213 |
+
if not match:
|
| 214 |
+
return None
|
| 215 |
+
token = re.sub(r"\s+", "", match.group(0)).replace("×", "x").replace("X", "x")
|
| 216 |
+
power = re.fullmatch(r"(\d+(?:\.\d*)?|\.\d+)x10\^?([+-]?\d+)", token)
|
| 217 |
+
try:
|
| 218 |
+
return float(power.group(1)) * 10 ** int(power.group(2)) if power else float(token)
|
| 219 |
+
except (ValueError, OverflowError):
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def temperature_k(text: str) -> float | None:
|
| 224 |
+
uncertainty = re.search(
|
| 225 |
+
rf"({NUMBER_RE})\s*(?:\+/-|±)\s*{NUMBER_RE}\s*°?\s*([CFK])\b", text, flags=re.I
|
| 226 |
+
)
|
| 227 |
+
value_range = re.search(
|
| 228 |
+
rf"({NUMBER_RE})\s*(?:to|-)\s*({NUMBER_RE})\s*°?\s*([CFK])\b", text, flags=re.I
|
| 229 |
+
)
|
| 230 |
+
match = uncertainty or value_range or re.search(rf"({NUMBER_RE})\s*°?\s*([CFK])\b", text, flags=re.I)
|
| 231 |
+
if not match:
|
| 232 |
+
return None
|
| 233 |
+
value = parse_number(match.group(1))
|
| 234 |
+
if value is None:
|
| 235 |
+
return None
|
| 236 |
+
if value_range and match is value_range:
|
| 237 |
+
upper = parse_number(match.group(2))
|
| 238 |
+
if upper is None:
|
| 239 |
+
return None
|
| 240 |
+
value = (value + upper) / 2
|
| 241 |
+
unit = match.group(3).upper()
|
| 242 |
+
else:
|
| 243 |
+
unit = match.group(2).upper()
|
| 244 |
+
return value + 273.15 if unit == "C" else (value - 32) * 5 / 9 + 273.15 if unit == "F" else value
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def pressure_pa(text: str) -> float | None:
|
| 248 |
+
match = re.search(
|
| 249 |
+
rf"({NUMBER_RE})\s*(Pa|kPa|hPa|mbar|bar|mm\s*Hg|mmHg|torr|atm|psi)\b",
|
| 250 |
+
text.replace("[", "").replace("]", ""),
|
| 251 |
+
flags=re.I,
|
| 252 |
+
)
|
| 253 |
+
if not match:
|
| 254 |
+
return None
|
| 255 |
+
value = parse_number(match.group(1))
|
| 256 |
+
if value is None or value <= 0:
|
| 257 |
+
return None
|
| 258 |
+
unit = re.sub(r"\s+", "", match.group(2)).lower()
|
| 259 |
+
factors = {"pa": 1, "kpa": 1000, "hpa": 100, "mbar": 100, "bar": 100000,
|
| 260 |
+
"mmhg": 133.322368, "torr": 133.322368, "atm": 101325, "psi": 6894.757}
|
| 261 |
+
return value * factors[unit]
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def experimental_observations(result: dict[str, Any], heading: str) -> list[dict[str, Any]]:
|
| 265 |
+
observations: list[dict[str, Any]] = []
|
| 266 |
+
if result.get("status") != "resolved":
|
| 267 |
+
return observations
|
| 268 |
+
for info in information_at_heading(result.get("record") or {}, heading):
|
| 269 |
+
references = [str(x) for x in info.get("Reference") or []]
|
| 270 |
+
for text in strings_from_value(info.get("Value") or {}):
|
| 271 |
+
lower = text.lower()
|
| 272 |
+
tier = "computed" if any(word in lower for word in ("estimated", "estimate", "calculated", "predicted")) else "measured"
|
| 273 |
+
if heading == "Vapor Pressure":
|
| 274 |
+
value = pressure_pa(text)
|
| 275 |
+
if value is None:
|
| 276 |
+
continue
|
| 277 |
+
observations.append({"value_pa": value, "temperature_k": temperature_k(text), "raw": text,
|
| 278 |
+
"tier": tier, "references": references})
|
| 279 |
+
else:
|
| 280 |
+
value = temperature_k(text)
|
| 281 |
+
if value is None or not 100 <= value <= 1500:
|
| 282 |
+
continue
|
| 283 |
+
observations.append({"value_k": value, "raw": text, "tier": tier, "references": references})
|
| 284 |
+
return observations
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def select_vapor_pressure(observations: list[dict[str, Any]]) -> dict[str, Any] | None:
|
| 288 |
+
if not observations:
|
| 289 |
+
return None
|
| 290 |
+
return min(
|
| 291 |
+
observations,
|
| 292 |
+
key=lambda row: (
|
| 293 |
+
row["tier"] != "measured",
|
| 294 |
+
row.get("temperature_k") is None,
|
| 295 |
+
abs((row.get("temperature_k") or 298.15) - 298.15),
|
| 296 |
+
row["value_pa"],
|
| 297 |
+
),
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def select_boiling_point(observations: list[dict[str, Any]]) -> dict[str, Any] | None:
|
| 302 |
+
if not observations:
|
| 303 |
+
return None
|
| 304 |
+
def score(row: dict[str, Any]) -> tuple[Any, ...]:
|
| 305 |
+
raw = row["raw"].lower()
|
| 306 |
+
atmospheric = "760 mm" in raw or "1 atm" in raw or "101.3 kpa" in raw
|
| 307 |
+
qualified = any(token in raw for token in (" at ", "mmhg", "mm hg", "kpa", "atm"))
|
| 308 |
+
return row["tier"] != "measured", not atmospheric, qualified and not atmospheric, row["value_k"]
|
| 309 |
+
return min(observations, key=score)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def identity_check(profile: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:
|
| 313 |
+
prop = result.get("property") or {}
|
| 314 |
+
synonyms = result.get("synonyms") or []
|
| 315 |
+
expected_cas = clean_cas(profile.get("cas"))
|
| 316 |
+
resolved_cas = sorted({cas for text in synonyms for cas in CAS_RE.findall(text) if clean_cas(cas)})
|
| 317 |
+
checks: list[str] = []
|
| 318 |
+
mismatches: list[str] = []
|
| 319 |
+
if expected_cas:
|
| 320 |
+
checks.append("cas")
|
| 321 |
+
if expected_cas not in resolved_cas:
|
| 322 |
+
mismatches.append("cas")
|
| 323 |
+
expected_formula = normalized_formula(profile.get("molecular_formula"))
|
| 324 |
+
resolved_formula = normalized_formula(prop.get("MolecularFormula"))
|
| 325 |
+
if expected_formula:
|
| 326 |
+
checks.append("formula")
|
| 327 |
+
if expected_formula != resolved_formula:
|
| 328 |
+
mismatches.append("formula")
|
| 329 |
+
expected_mw = numeric(profile.get("molecular_weight"))
|
| 330 |
+
resolved_mw = numeric(prop.get("MolecularWeight"))
|
| 331 |
+
if expected_mw is not None:
|
| 332 |
+
checks.append("molecular_weight")
|
| 333 |
+
tolerance = max(0.5, abs(expected_mw) * 0.005)
|
| 334 |
+
if resolved_mw is None or abs(expected_mw - resolved_mw) > tolerance:
|
| 335 |
+
mismatches.append("molecular_weight")
|
| 336 |
+
expected_key = str(profile.get("inchikey") or profile.get("inchi_key") or "").strip()
|
| 337 |
+
if expected_key:
|
| 338 |
+
checks.append("inchikey")
|
| 339 |
+
if expected_key != prop.get("InChIKey"):
|
| 340 |
+
mismatches.append("inchikey")
|
| 341 |
+
if mismatches:
|
| 342 |
+
reason = "resolution-rejected-formula-mismatch" if set(mismatches) & {"formula", "molecular_weight"} else "resolution-rejected-identity-mismatch"
|
| 343 |
+
status = "rejected"
|
| 344 |
+
else:
|
| 345 |
+
reason = None
|
| 346 |
+
status = "verified" if checks else "unverified"
|
| 347 |
+
return {"status": status, "reason": reason, "checks": checks, "mismatches": mismatches,
|
| 348 |
+
"resolved_cas": resolved_cas, "resolved_inchikey": prop.get("InChIKey"),
|
| 349 |
+
"resolved_formula": resolved_formula, "resolved_molecular_weight": resolved_mw}
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def field_provenance(source_ref: str, tier: str, identity: dict[str, Any], raw: str | None = None) -> dict[str, Any]:
|
| 353 |
+
value = {"source": "PubChem", "source_domain": PUBCHEM_DOMAIN, "source_ref": source_ref,
|
| 354 |
+
"tier": tier, "identity_status": identity["status"], "retrieved_for": "v11.5"}
|
| 355 |
+
if raw:
|
| 356 |
+
value["raw"] = raw
|
| 357 |
+
return value
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def apply_result(profile: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:
|
| 361 |
+
identity = identity_check(profile, result)
|
| 362 |
+
if identity["status"] == "rejected":
|
| 363 |
+
return {"updated": False, "identity": identity, "fields": []}
|
| 364 |
+
prop = result["property"]
|
| 365 |
+
cid = int(prop["CID"])
|
| 366 |
+
source_ref = f"https://pubchem.ncbi.nlm.nih.gov/compound/{cid}"
|
| 367 |
+
profile["pubchem_cid"] = cid
|
| 368 |
+
profile["inchikey"] = profile.get("inchikey") or prop.get("InChIKey")
|
| 369 |
+
profile["molecular_formula"] = profile.get("molecular_formula") or prop.get("MolecularFormula")
|
| 370 |
+
profile["identity_validation_v11_5"] = identity
|
| 371 |
+
profile.setdefault("field_provenance", {})
|
| 372 |
+
added: list[str] = []
|
| 373 |
+
computed = {
|
| 374 |
+
"smiles": prop.get("SMILES") or prop.get("ConnectivitySMILES"),
|
| 375 |
+
"molecular_weight": numeric(prop.get("MolecularWeight")),
|
| 376 |
+
"logp": numeric(prop.get("XLogP")),
|
| 377 |
+
}
|
| 378 |
+
for field, value in computed.items():
|
| 379 |
+
if profile.get(field) is None and value is not None:
|
| 380 |
+
profile[field] = value
|
| 381 |
+
profile["field_provenance"][field] = field_provenance(source_ref, "computed", identity)
|
| 382 |
+
added.append(field)
|
| 383 |
+
vp = select_vapor_pressure(experimental_observations(result.get("vapor_pressure") or {}, "Vapor Pressure"))
|
| 384 |
+
if profile.get("vapor_pressure_pa") is None and vp:
|
| 385 |
+
profile["vapor_pressure_pa"] = vp["value_pa"]
|
| 386 |
+
profile["log10_vapor_pressure_pa"] = math.log10(vp["value_pa"])
|
| 387 |
+
if vp.get("temperature_k") is not None:
|
| 388 |
+
profile["vapor_pressure_temperature_k"] = vp["temperature_k"]
|
| 389 |
+
profile["field_provenance"]["vapor_pressure_pa"] = field_provenance(source_ref, vp["tier"], identity, vp["raw"])
|
| 390 |
+
added.append("vapor_pressure_pa")
|
| 391 |
+
bp = select_boiling_point(experimental_observations(result.get("boiling_point") or {}, "Boiling Point"))
|
| 392 |
+
if profile.get("boiling_point_k") is None and bp:
|
| 393 |
+
profile["boiling_point_k"] = bp["value_k"]
|
| 394 |
+
profile["field_provenance"]["boiling_point_k"] = field_provenance(source_ref, bp["tier"], identity, bp["raw"])
|
| 395 |
+
added.append("boiling_point_k")
|
| 396 |
+
if added:
|
| 397 |
+
profile.setdefault("source_fields", [])
|
| 398 |
+
profile["source_fields"] = sorted(set(profile["source_fields"] + ["PubChem PUG REST/PUG View v11.5"]))
|
| 399 |
+
profile["pimt_version"] = "v11.5"
|
| 400 |
+
return {"updated": bool(added), "identity": identity, "fields": added}
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def coverage(profiles: list[dict[str, Any]]) -> dict[str, int]:
|
| 404 |
+
return {
|
| 405 |
+
"profiles": len(profiles),
|
| 406 |
+
"structure": sum(bool(row.get("smiles")) for row in profiles),
|
| 407 |
+
"logp": sum(row.get("logp") is not None for row in profiles),
|
| 408 |
+
"vapor_pressure": sum(row.get("vapor_pressure_pa") is not None for row in profiles),
|
| 409 |
+
"boiling_point": sum(row.get("boiling_point_k") is not None for row in profiles),
|
| 410 |
+
"vapor_pressure_or_boiling_point": sum(row.get("vapor_pressure_pa") is not None or row.get("boiling_point_k") is not None for row in profiles),
|
| 411 |
+
"odor_text": sum(bool(row.get("odor_descriptions")) for row in profiles),
|
| 412 |
+
"odor_taxonomy": sum(bool(row.get("descriptor_distribution")) for row in profiles),
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def provenance_counts(profiles: list[dict[str, Any]]) -> dict[str, dict[str, int]]:
|
| 417 |
+
fields = ("smiles", "logp", "vapor_pressure_pa", "boiling_point_k")
|
| 418 |
+
result: dict[str, dict[str, int]] = {}
|
| 419 |
+
for field in fields:
|
| 420 |
+
counts: Counter[str] = Counter()
|
| 421 |
+
for row in profiles:
|
| 422 |
+
if row.get(field) is None:
|
| 423 |
+
continue
|
| 424 |
+
provenance = (row.get("field_provenance") or {}).get(field) or {}
|
| 425 |
+
counts[str(provenance.get("tier") or "legacy-untiered")] += 1
|
| 426 |
+
if provenance.get("identity_status") == "unverified":
|
| 427 |
+
counts["unverified_identity"] += 1
|
| 428 |
+
result[field] = dict(sorted(counts.items()))
|
| 429 |
+
return result
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def material_profile(material: dict[str, Any], lookup: dict[str, dict[str, Any]]) -> dict[str, Any] | None:
|
| 433 |
+
cas = clean_cas(material.get("cas"))
|
| 434 |
+
if cas and lookup.get(cas):
|
| 435 |
+
return lookup[cas]
|
| 436 |
+
return lookup.get(normalize_name(material.get("name")))
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def representable_one_to_one(rows: list[dict[str, Any]], profiles: list[dict[str, Any]]) -> set[str]:
|
| 440 |
+
lookup = profile_lookup(profiles)
|
| 441 |
+
represented: set[str] = set()
|
| 442 |
+
for row in rows:
|
| 443 |
+
if row.get("answer_shape") != "one_to_one":
|
| 444 |
+
continue
|
| 445 |
+
target = {"name": row.get("target"), "cas": row.get("target_cas")}
|
| 446 |
+
answers = (row.get("answer") or {}).get("materials") or []
|
| 447 |
+
if material_profile(target, lookup) and answers and all(material_profile(item, lookup) for item in answers):
|
| 448 |
+
represented.add(row["pair_id"])
|
| 449 |
+
return represented
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def new_eval_profile(material: dict[str, Any]) -> dict[str, Any]:
|
| 453 |
+
name = material["name"]
|
| 454 |
+
cas = material.get("cas")
|
| 455 |
+
stable = re.sub(r"[^a-z0-9]+", "_", normalize_name(name)).strip("_")[:60]
|
| 456 |
+
return {
|
| 457 |
+
"profile_id": f"v11_5_eval_pubchem_{cas or stable}", "cas": cas, "name": name, "aliases": [],
|
| 458 |
+
"smiles": None, "molecular_formula": None, "molecular_weight": None, "logp": None,
|
| 459 |
+
"boiling_point_k": None, "vapor_pressure_pa": None, "log10_vapor_pressure_pa": None,
|
| 460 |
+
"functional_groups": {}, "natural_synthetic": "unknown", "descriptor_distribution": {},
|
| 461 |
+
"odor_descriptions": [], "poucher_tier": None, "substantivity_log10_predicted": None,
|
| 462 |
+
"substantivity_model": "missing", "source_fields": [], "pimt_version": "v11.5",
|
| 463 |
+
"substitution_risks": [], "catalogue_admission": "independent PubChem resolution of eval-priority identity",
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def build_tasks(profiles: list[dict[str, Any]], materials: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
| 468 |
+
lookup = profile_lookup(profiles)
|
| 469 |
+
tasks: list[dict[str, Any]] = []
|
| 470 |
+
seen_profiles: set[int] = set()
|
| 471 |
+
missing_eval: list[dict[str, Any]] = []
|
| 472 |
+
for material in materials:
|
| 473 |
+
profile = material_profile(material, lookup)
|
| 474 |
+
if profile is None:
|
| 475 |
+
missing_eval.append(material)
|
| 476 |
+
continue
|
| 477 |
+
if id(profile) in seen_profiles:
|
| 478 |
+
continue
|
| 479 |
+
seen_profiles.add(id(profile))
|
| 480 |
+
tasks.append({"profile": profile, "query": str(profile.get("cas") or profile.get("name")), "priority": 0, "eval": material})
|
| 481 |
+
remaining = [row for row in profiles if id(row) not in seen_profiles]
|
| 482 |
+
remaining.sort(key=lambda row: (-(row.get("documented_formula_usage") or {}).get("observation_count", 0), str(row.get("cas") or ""), normalize_name(row.get("name"))))
|
| 483 |
+
for row in remaining:
|
| 484 |
+
frequency = (row.get("documented_formula_usage") or {}).get("observation_count", 0)
|
| 485 |
+
tasks.append({"profile": row, "query": str(row.get("cas") or row.get("name") or ""), "priority": 1 if frequency else 2, "eval": None})
|
| 486 |
+
return [task for task in tasks if task["query"]], missing_eval
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def resolve_queries(tasks: list[dict[str, Any]], cache: dict[str, Any], workers: int, limit: int | None) -> dict[str, int]:
|
| 490 |
+
unique: list[str] = []
|
| 491 |
+
seen: set[str] = set()
|
| 492 |
+
for task in tasks:
|
| 493 |
+
query = task["query"]
|
| 494 |
+
if query not in seen:
|
| 495 |
+
seen.add(query)
|
| 496 |
+
unique.append(query)
|
| 497 |
+
if limit is not None:
|
| 498 |
+
unique = unique[:limit]
|
| 499 |
+
def cache_complete(result: dict[str, Any]) -> bool:
|
| 500 |
+
if result.get("pipeline_complete") is not True or result.get("status") == "error":
|
| 501 |
+
return False
|
| 502 |
+
if result.get("status") != "resolved":
|
| 503 |
+
return True
|
| 504 |
+
return all((result.get(field) or {}).get("status") != "error" for field in ("vapor_pressure", "boiling_point"))
|
| 505 |
+
|
| 506 |
+
pending = [query for query in unique if not cache_complete(cache.get(query) or {})]
|
| 507 |
+
stats = Counter(total_unique=len(unique), reused=len(unique) - len(pending))
|
| 508 |
+
with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
|
| 509 |
+
futures = {executor.submit(resolve_one, query): query for query in pending}
|
| 510 |
+
completed = 0
|
| 511 |
+
for future in as_completed(futures):
|
| 512 |
+
query = futures[future]
|
| 513 |
+
try:
|
| 514 |
+
result = future.result()
|
| 515 |
+
except Exception as exc: # preserve progress and make unexpected failures auditable
|
| 516 |
+
result = {"status": "error", "query": query, "error": type(exc).__name__}
|
| 517 |
+
result["pipeline_complete"] = True
|
| 518 |
+
result["retrieved_at_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 519 |
+
cache[query] = result
|
| 520 |
+
stats[result.get("status") or "unknown"] += 1
|
| 521 |
+
completed += 1
|
| 522 |
+
if completed % 25 == 0:
|
| 523 |
+
atomic_json(CACHE, cache)
|
| 524 |
+
print(f"completed {completed}/{len(pending)} online queries", file=sys.stderr, flush=True)
|
| 525 |
+
atomic_json(CACHE, cache)
|
| 526 |
+
return dict(stats)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def cache_summary(tasks: list[dict[str, Any]], cache: dict[str, Any], execution_mode: str) -> dict[str, Any]:
|
| 530 |
+
by_query: dict[str, int] = {}
|
| 531 |
+
for task in tasks:
|
| 532 |
+
by_query[task["query"]] = min(task["priority"], by_query.get(task["query"], task["priority"]))
|
| 533 |
+
live = {query: cache.get(query) or {} for query in by_query if (cache.get(query) or {}).get("retrieved_at_utc")}
|
| 534 |
+
priority: dict[str, Any] = {}
|
| 535 |
+
labels = {-1: "eval_missing_profile", 0: "eval_existing_profile", 1: "formula_frequency", 2: "long_tail"}
|
| 536 |
+
for level, label in labels.items():
|
| 537 |
+
queries = {query for query, query_level in by_query.items() if query_level == level}
|
| 538 |
+
priority[label] = {
|
| 539 |
+
"total": len(queries),
|
| 540 |
+
"live_attempted": sum(query in live for query in queries),
|
| 541 |
+
"resolved": sum((live.get(query) or {}).get("status") == "resolved" for query in queries),
|
| 542 |
+
"transient_error": sum((live.get(query) or {}).get("status") == "error" for query in queries),
|
| 543 |
+
}
|
| 544 |
+
return {
|
| 545 |
+
"execution_mode": execution_mode,
|
| 546 |
+
"total_priority_queries": len(by_query),
|
| 547 |
+
"live_attempted": len(live),
|
| 548 |
+
"live_status": dict(sorted(Counter(result.get("status") or "unknown" for result in live.values()).items())),
|
| 549 |
+
"priority_completion": priority,
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def markdown(report: dict[str, Any]) -> str:
|
| 554 |
+
before, after = report["coverage_before"], report["coverage_after"]
|
| 555 |
+
one = report["one_to_one_representability"]
|
| 556 |
+
return "\n".join([
|
| 557 |
+
"# PIMT v11.5 targeted physicochemical enrichment", "",
|
| 558 |
+
"PubChem was queried in evaluation-material, formula-frequency, then long-tail order. PubChem is independent of the Fraterworks and PerfumersWorld answer sources.", "",
|
| 559 |
+
f"- Profiles: {before['profiles']} -> {after['profiles']}.",
|
| 560 |
+
f"- Structure: {before['structure']} -> {after['structure']}.",
|
| 561 |
+
f"- logP: {before['logp']} -> {after['logp']}.",
|
| 562 |
+
f"- **VP/BP: {before['vapor_pressure_or_boiling_point']} -> {after['vapor_pressure_or_boiling_point']}** (VP {before['vapor_pressure']} -> {after['vapor_pressure']}; BP {before['boiling_point']} -> {after['boiling_point']}).",
|
| 563 |
+
f"- Odor text: {before['odor_text']} -> {after['odor_text']}; taxonomy: {before['odor_taxonomy']} -> {after['odor_taxonomy']} (unchanged by this pipeline).",
|
| 564 |
+
f"- One-to-one pairs independently representable: {one['before']} -> {one['after']} ({one['newly_representable']} newly representable).",
|
| 565 |
+
f"- Leak-rejected enrichments: {report['leak_check']['rejected']}.",
|
| 566 |
+
f"- Formula/MW-rejected resolutions: {report['identity_validation']['formula_or_mw_rejected']}.",
|
| 567 |
+
f"- Other identity-rejected resolutions: {report['identity_validation']['other_rejected']}.",
|
| 568 |
+
f"- Accepted verified resolutions: {report['identity_validation']['accepted_verified']}; accepted unverified resolutions: {report['identity_validation']['accepted_unverified']}.",
|
| 569 |
+
"", "## Provenance tiers", "", "```json", json.dumps(report["coverage_by_provenance_tier"], indent=2, sort_keys=True), "```", "",
|
| 570 |
+
"Computed PubChem structure/logP values are never treated as ground truth. PUG View values under Experimental Properties are tagged measured; explicitly estimated/calculated values remain computed. Name-only resolutions without CAS/formula/MW/InChIKey cross-checks are tagged unverified.", "",
|
| 571 |
+
])
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def main() -> None:
|
| 575 |
+
parser = argparse.ArgumentParser()
|
| 576 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 577 |
+
parser.add_argument("--limit", type=int, default=None, help="Development-only cap after priority ordering")
|
| 578 |
+
parser.add_argument("--offline", action="store_true", help="Apply only completed v11.5 cache records")
|
| 579 |
+
args = parser.parse_args()
|
| 580 |
+
profiles = load_jsonl(INPUT_PROFILES)
|
| 581 |
+
original = deepcopy(profiles)
|
| 582 |
+
rows = load_jsonl(EVAL_SET)
|
| 583 |
+
materials = eval_materials(rows)
|
| 584 |
+
tasks, missing_eval = build_tasks(profiles, materials)
|
| 585 |
+
cache = json.loads(CACHE.read_text(encoding="utf-8")) if CACHE.exists() else {}
|
| 586 |
+
query_stats: dict[str, Any] = {}
|
| 587 |
+
if not args.offline:
|
| 588 |
+
resolve_queries(tasks, cache, args.workers, args.limit)
|
| 589 |
+
|
| 590 |
+
application = Counter()
|
| 591 |
+
identity_records: list[dict[str, Any]] = []
|
| 592 |
+
processed_queries = set(list(dict.fromkeys(task["query"] for task in tasks))[:args.limit] if args.limit is not None else [task["query"] for task in tasks])
|
| 593 |
+
for task in tasks:
|
| 594 |
+
if task["query"] not in processed_queries:
|
| 595 |
+
continue
|
| 596 |
+
result = cache.get(task["query"]) or {}
|
| 597 |
+
if result.get("status") != "resolved":
|
| 598 |
+
continue
|
| 599 |
+
applied = apply_result(task["profile"], result)
|
| 600 |
+
identity = applied["identity"]
|
| 601 |
+
application[f"identity_{identity['status']}"] += 1
|
| 602 |
+
application["profiles_updated"] += applied["updated"]
|
| 603 |
+
application.update(f"field_{field}" for field in applied["fields"])
|
| 604 |
+
identity_records.append({"profile_id": task["profile"].get("profile_id"), "query": task["query"], **identity})
|
| 605 |
+
|
| 606 |
+
# Missing eval identities may be admitted only from an independent PubChem
|
| 607 |
+
# resolution. They have no formula/MW check and therefore remain unverified.
|
| 608 |
+
extra_tasks = [{"profile": new_eval_profile(material), "query": str(material.get("cas") or material["name"]), "priority": -1, "eval": material} for material in missing_eval]
|
| 609 |
+
if extra_tasks and not args.offline:
|
| 610 |
+
resolve_queries(extra_tasks, cache, args.workers, None)
|
| 611 |
+
profiles_by_key = {row.get("inchikey"): row for row in profiles if row.get("inchikey")}
|
| 612 |
+
for task in extra_tasks:
|
| 613 |
+
result = cache.get(task["query"]) or {}
|
| 614 |
+
if result.get("status") != "resolved":
|
| 615 |
+
continue
|
| 616 |
+
applied = apply_result(task["profile"], result)
|
| 617 |
+
identity = applied["identity"]
|
| 618 |
+
identity_records.append({"profile_id": task["profile"].get("profile_id"), "query": task["query"], **identity})
|
| 619 |
+
if identity["status"] == "rejected" or not applied["fields"]:
|
| 620 |
+
continue
|
| 621 |
+
key = task["profile"].get("inchikey")
|
| 622 |
+
if key and key in profiles_by_key:
|
| 623 |
+
existing = profiles_by_key[key]
|
| 624 |
+
alias = task["profile"]["name"]
|
| 625 |
+
if normalize_name(alias) != normalize_name(existing.get("name")):
|
| 626 |
+
existing.setdefault("aliases", [])
|
| 627 |
+
existing["aliases"] = sorted(set(existing["aliases"] + [alias]), key=lambda value: (normalize_name(value), value))
|
| 628 |
+
existing.setdefault("alias_provenance", {})[alias] = field_provenance(
|
| 629 |
+
f"https://pubchem.ncbi.nlm.nih.gov/compound/{result['property']['CID']}", "authoritative", identity
|
| 630 |
+
)
|
| 631 |
+
application["eval_aliases_added"] += 1
|
| 632 |
+
continue
|
| 633 |
+
profiles.append(task["profile"])
|
| 634 |
+
if key:
|
| 635 |
+
profiles_by_key[key] = task["profile"]
|
| 636 |
+
application[f"identity_{identity['status']}"] += 1
|
| 637 |
+
application["profiles_updated"] += 1
|
| 638 |
+
application["eval_profiles_admitted"] += 1
|
| 639 |
+
application.update(f"field_{field}" for field in applied["fields"])
|
| 640 |
+
|
| 641 |
+
before_repr = representable_one_to_one(rows, original)
|
| 642 |
+
after_repr = representable_one_to_one(rows, profiles)
|
| 643 |
+
eval_domains = sorted({domain for material in materials for domain in material["answer_source_domains"]})
|
| 644 |
+
leak_rejected = int(PUBCHEM_DOMAIN in eval_domains)
|
| 645 |
+
query_stats = cache_summary(tasks + extra_tasks, cache, "offline-apply-of-live-cache" if args.offline else "live-online")
|
| 646 |
+
report = {
|
| 647 |
+
"version": "v11.5", "input": str(INPUT_PROFILES.relative_to(ROOT)), "output": str(OUTPUT_PROFILES.relative_to(ROOT)),
|
| 648 |
+
"priority_policy": ["eval-pair materials", "documented formula-use frequency", "remaining catalogue"],
|
| 649 |
+
"coverage_before": coverage(original), "coverage_after": coverage(profiles),
|
| 650 |
+
"coverage_by_provenance_tier": provenance_counts(profiles), "online_query": query_stats,
|
| 651 |
+
"application": dict(sorted(application.items())),
|
| 652 |
+
"identity_validation": {
|
| 653 |
+
"accepted_verified": sum(x["status"] == "verified" for x in identity_records),
|
| 654 |
+
"accepted_unverified": sum(x["status"] == "unverified" for x in identity_records),
|
| 655 |
+
"formula_or_mw_rejected": sum(x.get("reason") == "resolution-rejected-formula-mismatch" for x in identity_records),
|
| 656 |
+
"other_rejected": sum(x.get("reason") == "resolution-rejected-identity-mismatch" for x in identity_records),
|
| 657 |
+
"records": identity_records,
|
| 658 |
+
},
|
| 659 |
+
"leak_check": {"enrichment_source_domain": PUBCHEM_DOMAIN, "eval_answer_source_domains": eval_domains,
|
| 660 |
+
"accepted": sum(x["status"] != "rejected" for x in identity_records), "rejected": leak_rejected,
|
| 661 |
+
"policy": "reject per material when enrichment source domain equals that pair's answer-source domain"},
|
| 662 |
+
"one_to_one_representability": {"before": len(before_repr), "after": len(after_repr),
|
| 663 |
+
"newly_representable": len(after_repr - before_repr),
|
| 664 |
+
"new_pair_ids": sorted(after_repr - before_repr)},
|
| 665 |
+
"odor_policy": "not modified", "evaluation_sources_used_as_profile_data": [],
|
| 666 |
+
}
|
| 667 |
+
profiles.sort(key=lambda row: (str(row.get("cas") or ""), normalize_name(row.get("name")), str(row.get("profile_id") or "")))
|
| 668 |
+
write_jsonl(OUTPUT_PROFILES, profiles)
|
| 669 |
+
atomic_json(REPORT_JSON, report)
|
| 670 |
+
REPORT_MD.write_text(markdown(report), encoding="utf-8")
|
| 671 |
+
print(json.dumps({"coverage_before": report["coverage_before"], "coverage_after": report["coverage_after"],
|
| 672 |
+
"one_to_one_representability": report["one_to_one_representability"],
|
| 673 |
+
"identity_validation": {k: v for k, v in report["identity_validation"].items() if k != "records"},
|
| 674 |
+
"leak_check": report["leak_check"]}, indent=2, sort_keys=True))
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
if __name__ == "__main__":
|
| 678 |
+
main()
|
tests/test_pimt_v11_5_targeted_enrichment.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "pimt_v11_5_targeted_enrichment.py"
|
| 8 |
+
SPEC = importlib.util.spec_from_file_location("pimt_v11_5_targeted_enrichment", SCRIPT)
|
| 9 |
+
MODULE = importlib.util.module_from_spec(SPEC)
|
| 10 |
+
assert SPEC.loader
|
| 11 |
+
SPEC.loader.exec_module(MODULE)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_identity_rejects_molecular_weight_mismatch():
|
| 15 |
+
profile = {"cas": "121-33-5", "molecular_weight": 999.0}
|
| 16 |
+
result = {
|
| 17 |
+
"property": {"InChIKey": "KEY", "MolecularFormula": "C8H8O3", "MolecularWeight": "152.15"},
|
| 18 |
+
"synonyms": ["Vanillin", "121-33-5"],
|
| 19 |
+
}
|
| 20 |
+
checked = MODULE.identity_check(profile, result)
|
| 21 |
+
assert checked["status"] == "rejected"
|
| 22 |
+
assert checked["reason"] == "resolution-rejected-formula-mismatch"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_identity_accepts_cas_and_weight_match():
|
| 26 |
+
profile = {"cas": "121-33-5", "molecular_weight": 152.15}
|
| 27 |
+
result = {
|
| 28 |
+
"property": {"InChIKey": "KEY", "MolecularFormula": "C8H8O3", "MolecularWeight": "152.15"},
|
| 29 |
+
"synonyms": ["Vanillin", "121-33-5"],
|
| 30 |
+
}
|
| 31 |
+
checked = MODULE.identity_check(profile, result)
|
| 32 |
+
assert checked["status"] == "verified"
|
| 33 |
+
assert checked["checks"] == ["cas", "molecular_weight"]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_name_only_identity_is_unverified():
|
| 37 |
+
checked = MODULE.identity_check(
|
| 38 |
+
{"name": "vanillin"},
|
| 39 |
+
{"property": {"InChIKey": "KEY", "MolecularFormula": "C8H8O3", "MolecularWeight": "152.15"}, "synonyms": ["vanillin"]},
|
| 40 |
+
)
|
| 41 |
+
assert checked["status"] == "unverified"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_parse_vapor_pressure_units_and_scientific_notation():
|
| 45 |
+
assert abs(MODULE.pressure_pa("1.5 mm Hg at 25 °C") - 199.983552) < 1e-6
|
| 46 |
+
assert abs(MODULE.pressure_pa("1.2 x 10^-3 kPa") - 1.2) < 1e-9
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_parse_boiling_point_temperature_units():
|
| 50 |
+
assert abs(MODULE.temperature_k("545 °F at 760 mmHg") - 558.15) < 1e-6
|
| 51 |
+
assert abs(MODULE.temperature_k("285 °C") - 558.15) < 1e-6
|
| 52 |
+
assert abs(MODULE.temperature_k("326 +/- 4 °C") - 599.15) < 1e-6
|
| 53 |
+
assert abs(MODULE.temperature_k("70 to 72 °C") - 344.15) < 1e-6
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_experimental_records_preserve_measured_vs_computed_tier():
|
| 57 |
+
result = {
|
| 58 |
+
"status": "resolved",
|
| 59 |
+
"record": {"Section": [{"TOCHeading": "Vapor Pressure", "Information": [
|
| 60 |
+
{"Value": {"StringWithMarkup": [{"String": "0.1 mmHg at 25 °C"}]}},
|
| 61 |
+
{"Value": {"StringWithMarkup": [{"String": "estimated 0.2 mmHg at 25 °C"}]}},
|
| 62 |
+
]}]},
|
| 63 |
+
}
|
| 64 |
+
rows = MODULE.experimental_observations(result, "Vapor Pressure")
|
| 65 |
+
assert [row["tier"] for row in rows] == ["measured", "computed"]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_eval_source_domain_is_not_pubchem():
|
| 69 |
+
rows = [{
|
| 70 |
+
"pair_id": "p1", "target": "A", "target_cas": None,
|
| 71 |
+
"answer": {"materials": [{"name": "B", "cas": None}]},
|
| 72 |
+
"source_url": "https://fraterworks.com/products/example",
|
| 73 |
+
}]
|
| 74 |
+
materials = MODULE.eval_materials(rows)
|
| 75 |
+
assert {domain for row in materials for domain in row["answer_source_domains"]} == {"fraterworks.com"}
|
| 76 |
+
assert MODULE.PUBCHEM_DOMAIN not in {domain for row in materials for domain in row["answer_source_domains"]}
|