Matthew Ford commited on
Commit ·
3064094
1
Parent(s): f916efb
pimt v10 add line-drawn training assessment runner
Browse filesFormer-commit-id: 20cee51bb4e5d4a3f7d9fee5b0c1bcb8a36dc643
Former-commit-id: ef5bcd69ad69cdf543564ac5b709d59b38030fbe
scripts/pimt_v10_line_drawn_train_assess.py
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""PIMT v10 line-drawn training and quality-assessment run.
|
| 3 |
+
|
| 4 |
+
This script intentionally keeps the two axes separate:
|
| 5 |
+
|
| 6 |
+
* substantivity: measured Poucher coefficients, scaffold-disjoint evaluation
|
| 7 |
+
* character: curated 26-class labels, weak secondary axis only
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import math
|
| 15 |
+
import os
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
from collections import Counter, defaultdict
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any
|
| 22 |
+
|
| 23 |
+
import joblib
|
| 24 |
+
import numpy as np
|
| 25 |
+
from scipy.spatial.distance import jensenshannon
|
| 26 |
+
from scipy.stats import spearmanr
|
| 27 |
+
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
|
| 28 |
+
from sklearn.impute import SimpleImputer
|
| 29 |
+
from sklearn.linear_model import LogisticRegression
|
| 30 |
+
from sklearn.metrics import f1_score, mean_absolute_error, r2_score
|
| 31 |
+
from sklearn.multiclass import OneVsRestClassifier
|
| 32 |
+
from sklearn.pipeline import make_pipeline
|
| 33 |
+
from sklearn.preprocessing import MultiLabelBinarizer, StandardScaler
|
| 34 |
+
|
| 35 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 36 |
+
import train_substantivity as train # noqa: E402
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
VERSION = "v10_line_drawn"
|
| 40 |
+
SEEDS = list(range(20260710, 20260730))
|
| 41 |
+
LOCKED_SEED = 20260710
|
| 42 |
+
TEST_FRACTION = 0.2
|
| 43 |
+
CHARACTER_PATH = Path("data/odour_character_labels_v8_2_clause_guard_dominance.jsonl")
|
| 44 |
+
TIER_PATH = Path("data/substantivity_targets_poucher_tiers_v8.jsonl")
|
| 45 |
+
TIER_TO_LOG10 = {"top": math.log10(2.0), "mid": math.log10(15.0), "base": math.log10(60.0)}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 49 |
+
return [json.loads(line) for line in path.open(encoding="utf-8") if line.strip()]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def sha256_file(path: Path) -> str:
|
| 53 |
+
h = hashlib.sha256()
|
| 54 |
+
with path.open("rb") as f:
|
| 55 |
+
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
| 56 |
+
h.update(chunk)
|
| 57 |
+
return h.hexdigest()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def sha256_files(paths: list[Path]) -> str:
|
| 61 |
+
h = hashlib.sha256()
|
| 62 |
+
for path in sorted(paths, key=lambda p: str(p)):
|
| 63 |
+
h.update(str(path).encode())
|
| 64 |
+
h.update(b"\0")
|
| 65 |
+
h.update(sha256_file(path).encode())
|
| 66 |
+
h.update(b"\0")
|
| 67 |
+
return h.hexdigest()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def git_commit() -> str:
|
| 71 |
+
try:
|
| 72 |
+
return subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
|
| 73 |
+
except Exception:
|
| 74 |
+
return "unknown"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def model_ready_rows(fetch_pubchem: bool) -> list[dict[str, Any]]:
|
| 78 |
+
rows = train.enrich_rows(fetch_pubchem)
|
| 79 |
+
return [
|
| 80 |
+
row
|
| 81 |
+
for row in rows
|
| 82 |
+
if row.get("smiles") or any(row["features"].get(name) is not None for name in train.FEATURE_NAMES)
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def regressor(kind: str, seed: int = 17):
|
| 87 |
+
if kind == "gbm":
|
| 88 |
+
return make_pipeline(
|
| 89 |
+
SimpleImputer(strategy="median"),
|
| 90 |
+
HistGradientBoostingRegressor(
|
| 91 |
+
max_iter=200,
|
| 92 |
+
learning_rate=0.04,
|
| 93 |
+
l2_regularization=0.1,
|
| 94 |
+
random_state=seed,
|
| 95 |
+
),
|
| 96 |
+
)
|
| 97 |
+
if kind == "rf":
|
| 98 |
+
return make_pipeline(
|
| 99 |
+
SimpleImputer(strategy="median"),
|
| 100 |
+
RandomForestRegressor(
|
| 101 |
+
n_estimators=350,
|
| 102 |
+
min_samples_leaf=3,
|
| 103 |
+
random_state=seed,
|
| 104 |
+
n_jobs=-1,
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
raise ValueError(kind)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def regression_metrics(y_true: np.ndarray, pred: np.ndarray) -> dict[str, float]:
|
| 111 |
+
rho, p = spearmanr(y_true, pred)
|
| 112 |
+
return {
|
| 113 |
+
"spearman_rho": float(rho) if rho == rho else float("nan"),
|
| 114 |
+
"spearman_p_value": float(p) if p == p else float("nan"),
|
| 115 |
+
"r2": float(r2_score(y_true, pred)),
|
| 116 |
+
"mae": float(mean_absolute_error(y_true, pred)),
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def eval_substantivity_cv(
|
| 121 |
+
rows: list[dict[str, Any]],
|
| 122 |
+
x: np.ndarray,
|
| 123 |
+
seeds: list[int],
|
| 124 |
+
kind: str = "gbm",
|
| 125 |
+
) -> dict[str, Any]:
|
| 126 |
+
y = np.asarray([r["target_log10"] for r in rows], dtype=float)
|
| 127 |
+
runs = []
|
| 128 |
+
for seed in seeds:
|
| 129 |
+
train_idx, test_idx = train.greedy_scaffold_split(rows, TEST_FRACTION, seed)
|
| 130 |
+
model = regressor(kind, seed=17)
|
| 131 |
+
model.fit(x[train_idx], y[train_idx])
|
| 132 |
+
pred = np.asarray(model.predict(x[test_idx]), dtype=float)
|
| 133 |
+
metrics = regression_metrics(y[test_idx], pred)
|
| 134 |
+
runs.append({
|
| 135 |
+
"seed": seed,
|
| 136 |
+
"n_train": int(len(train_idx)),
|
| 137 |
+
"n_test": int(len(test_idx)),
|
| 138 |
+
"metrics": metrics,
|
| 139 |
+
})
|
| 140 |
+
rho = np.asarray([r["metrics"]["spearman_rho"] for r in runs], dtype=float)
|
| 141 |
+
r2 = np.asarray([r["metrics"]["r2"] for r in runs], dtype=float)
|
| 142 |
+
return {
|
| 143 |
+
"kind": kind,
|
| 144 |
+
"n_runs": len(runs),
|
| 145 |
+
"runs": runs,
|
| 146 |
+
"mean_spearman_rho": float(np.nanmean(rho)),
|
| 147 |
+
"median_spearman_rho": float(np.nanmedian(rho)),
|
| 148 |
+
"mean_r2": float(np.nanmean(r2)),
|
| 149 |
+
"median_r2": float(np.nanmedian(r2)),
|
| 150 |
+
"rho_range": [float(np.nanmin(rho)), float(np.nanmax(rho))],
|
| 151 |
+
"r2_range": [float(np.nanmin(r2)), float(np.nanmax(r2))],
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def fit_locked_model(rows: list[dict[str, Any]], x: np.ndarray) -> dict[str, Any]:
|
| 156 |
+
y = np.asarray([r["target_log10"] for r in rows], dtype=float)
|
| 157 |
+
train_idx, test_idx = train.greedy_scaffold_split(rows, TEST_FRACTION, LOCKED_SEED)
|
| 158 |
+
model = regressor("gbm")
|
| 159 |
+
model.fit(x[train_idx], y[train_idx])
|
| 160 |
+
pred = np.asarray(model.predict(x[test_idx]), dtype=float)
|
| 161 |
+
return {
|
| 162 |
+
"model": model,
|
| 163 |
+
"train_idx": train_idx,
|
| 164 |
+
"test_idx": test_idx,
|
| 165 |
+
"metrics": regression_metrics(y[test_idx], pred),
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def load_character_labels(path: Path) -> dict[str, list[str]]:
|
| 170 |
+
labels: dict[str, set[str]] = defaultdict(set)
|
| 171 |
+
for row in load_jsonl(path):
|
| 172 |
+
cas = str(row.get("cas", "")).strip()
|
| 173 |
+
codes = row.get("class_codes") or [row.get("final_class_or_masked") or row.get("class_code")]
|
| 174 |
+
for code in codes:
|
| 175 |
+
if code:
|
| 176 |
+
labels[cas].add(str(code))
|
| 177 |
+
return {cas: sorted(codes) for cas, codes in labels.items()}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def feature_row_for_cas(cas: str, registry: dict[str, dict[str, Any]], cache: dict[str, dict[str, Any]]) -> dict[str, Any] | None:
|
| 181 |
+
reg = registry.get(cas, {})
|
| 182 |
+
pub = cache.get(cas, {})
|
| 183 |
+
smiles = reg.get("smiles") or pub.get("smiles")
|
| 184 |
+
rdkit_features = train.molecule_features(smiles)
|
| 185 |
+
vp = train.safe_float(reg.get("vapor_pressure_pa") or pub.get("vapor_pressure_pa"))
|
| 186 |
+
features = {
|
| 187 |
+
"log10_vapor_pressure_pa": math.log10(vp) if vp and vp > 0 else None,
|
| 188 |
+
"boiling_point_k": train.safe_float(reg.get("boiling_point_k") or pub.get("boiling_point_k")),
|
| 189 |
+
"molecular_weight": train.safe_float(reg.get("molecular_weight") or pub.get("molecular_weight") or rdkit_features.get("molecular_weight")),
|
| 190 |
+
"logp": train.safe_float(reg.get("logp") or pub.get("logp") or rdkit_features.get("logp")),
|
| 191 |
+
}
|
| 192 |
+
for name in ["heavy_atoms", "h_acceptors", "h_donors", "rotatable_bonds", "tpsa", "fraction_csp3"]:
|
| 193 |
+
features[name] = train.safe_float(rdkit_features.get(name))
|
| 194 |
+
if not smiles and not any(features.get(name) is not None for name in train.FEATURE_NAMES):
|
| 195 |
+
return None
|
| 196 |
+
return {
|
| 197 |
+
"cas": cas,
|
| 198 |
+
"name": reg.get("name") or pub.get("name") or cas,
|
| 199 |
+
"smiles": smiles,
|
| 200 |
+
"target_log10": 0.0,
|
| 201 |
+
"target_raw": 0.0,
|
| 202 |
+
"features": features,
|
| 203 |
+
"scaffold": train.scaffold_key(smiles, cas),
|
| 204 |
+
"source": "odour-character-label",
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def character_feature_rows(labels_by_cas: dict[str, list[str]]) -> list[dict[str, Any]]:
|
| 209 |
+
registry = train.load_registry_rows()
|
| 210 |
+
cache = json.loads((Path("data/pubchem_substantivity_cache.json")).read_text()) if Path("data/pubchem_substantivity_cache.json").exists() else {}
|
| 211 |
+
rows = []
|
| 212 |
+
for cas in sorted(labels_by_cas):
|
| 213 |
+
row = feature_row_for_cas(cas, registry, cache)
|
| 214 |
+
if row is not None:
|
| 215 |
+
rows.append(row)
|
| 216 |
+
return rows
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def eval_character(
|
| 220 |
+
rows: list[dict[str, Any]],
|
| 221 |
+
x: np.ndarray,
|
| 222 |
+
labels_by_cas: dict[str, list[str]],
|
| 223 |
+
class_weight: str | None,
|
| 224 |
+
seeds: list[int],
|
| 225 |
+
) -> dict[str, Any]:
|
| 226 |
+
labelled_rows = [row for row in rows if row["cas"] in labels_by_cas]
|
| 227 |
+
labelled_x = x
|
| 228 |
+
multilabels = [labels_by_cas[row["cas"]] for row in labelled_rows]
|
| 229 |
+
mlb = MultiLabelBinarizer(classes=[chr(ord("A") + i) for i in range(26)])
|
| 230 |
+
y = mlb.fit_transform(multilabels)
|
| 231 |
+
runs = []
|
| 232 |
+
per_class_values: dict[str, list[float]] = {c: [] for c in mlb.classes_}
|
| 233 |
+
for seed in seeds:
|
| 234 |
+
train_idx, test_idx = train.greedy_scaffold_split(labelled_rows, TEST_FRACTION, seed)
|
| 235 |
+
base = LogisticRegression(
|
| 236 |
+
max_iter=2000,
|
| 237 |
+
solver="liblinear",
|
| 238 |
+
class_weight=class_weight,
|
| 239 |
+
random_state=seed,
|
| 240 |
+
)
|
| 241 |
+
clf = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), OneVsRestClassifier(base))
|
| 242 |
+
clf.fit(labelled_x[train_idx], y[train_idx])
|
| 243 |
+
pred = clf.predict(labelled_x[test_idx])
|
| 244 |
+
per_class = f1_score(y[test_idx], pred, average=None, zero_division=0)
|
| 245 |
+
for cls, value in zip(mlb.classes_, per_class, strict=True):
|
| 246 |
+
per_class_values[str(cls)].append(float(value))
|
| 247 |
+
runs.append({
|
| 248 |
+
"seed": seed,
|
| 249 |
+
"n_train": int(len(train_idx)),
|
| 250 |
+
"n_test": int(len(test_idx)),
|
| 251 |
+
"macro_f1": float(f1_score(y[test_idx], pred, average="macro", zero_division=0)),
|
| 252 |
+
"micro_f1": float(f1_score(y[test_idx], pred, average="micro", zero_division=0)),
|
| 253 |
+
"weighted_f1": float(f1_score(y[test_idx], pred, average="weighted", zero_division=0)),
|
| 254 |
+
})
|
| 255 |
+
support = Counter(code for codes in multilabels for code in codes)
|
| 256 |
+
return {
|
| 257 |
+
"n_labelled": len(labelled_rows),
|
| 258 |
+
"n_classes": len(mlb.classes_),
|
| 259 |
+
"class_weight": class_weight,
|
| 260 |
+
"class_support": dict(sorted(support.items())),
|
| 261 |
+
"mean_macro_f1": float(np.mean([r["macro_f1"] for r in runs])),
|
| 262 |
+
"mean_micro_f1": float(np.mean([r["micro_f1"] for r in runs])),
|
| 263 |
+
"mean_weighted_f1": float(np.mean([r["weighted_f1"] for r in runs])),
|
| 264 |
+
"per_class_f1_mean": {
|
| 265 |
+
cls: float(np.mean(vals)) if vals else 0.0
|
| 266 |
+
for cls, vals in sorted(per_class_values.items())
|
| 267 |
+
},
|
| 268 |
+
"rare_class_f1_mean": float(np.mean([
|
| 269 |
+
np.mean(per_class_values[cls])
|
| 270 |
+
for cls, n in support.items()
|
| 271 |
+
if n <= 3 and per_class_values.get(cls)
|
| 272 |
+
])) if any(n <= 3 for n in support.values()) else float("nan"),
|
| 273 |
+
"runs": runs,
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def character_distribution_metric(labels_by_cas: dict[str, list[str]], path: Path) -> dict[str, Any]:
|
| 278 |
+
# The available molecule-level character labels do not have formula genres.
|
| 279 |
+
# Reuse the established v8 diagnostic artifact as the honest discrimination
|
| 280 |
+
# metric for the corpus, and stamp the source in the new v10 report.
|
| 281 |
+
diagnostic_path = Path("artifacts/character_grouping_diagnostic_v8.json")
|
| 282 |
+
if diagnostic_path.exists():
|
| 283 |
+
diagnostic = json.loads(diagnostic_path.read_text(encoding="utf-8"))
|
| 284 |
+
return {
|
| 285 |
+
"source": str(diagnostic_path),
|
| 286 |
+
"source_sha256": sha256_file(diagnostic_path),
|
| 287 |
+
"summary": diagnostic.get("character_verdict", {}),
|
| 288 |
+
"recommendation": diagnostic.get("recommendation"),
|
| 289 |
+
"verdict": "weak_secondary_axis",
|
| 290 |
+
}
|
| 291 |
+
counts = Counter(code for codes in labels_by_cas.values() for code in codes)
|
| 292 |
+
p = np.asarray([counts.get(chr(ord("A") + i), 0) for i in range(26)], dtype=float)
|
| 293 |
+
p = p / max(float(p.sum()), 1.0)
|
| 294 |
+
uniform = np.ones_like(p) / len(p)
|
| 295 |
+
return {
|
| 296 |
+
"source": str(path),
|
| 297 |
+
"source_sha256": sha256_file(path),
|
| 298 |
+
"js_divergence_vs_uniform_bits": float(jensenshannon(p, uniform, base=2.0) ** 2),
|
| 299 |
+
"verdict": "weak_secondary_axis",
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def poucher_tier_auxiliary_rows(measured_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 304 |
+
if not TIER_PATH.exists():
|
| 305 |
+
return []
|
| 306 |
+
measured_cas = {row["cas"] for row in measured_rows}
|
| 307 |
+
registry = train.load_registry_rows()
|
| 308 |
+
cache = json.loads((Path("data/pubchem_substantivity_cache.json")).read_text()) if Path("data/pubchem_substantivity_cache.json").exists() else {}
|
| 309 |
+
out = []
|
| 310 |
+
seen = set()
|
| 311 |
+
for row in load_jsonl(TIER_PATH):
|
| 312 |
+
cas = str(row.get("cas", "")).strip()
|
| 313 |
+
tier = row.get("substantivity_tier")
|
| 314 |
+
if not cas or cas in measured_cas or cas in seen or tier not in TIER_TO_LOG10:
|
| 315 |
+
continue
|
| 316 |
+
reg = registry.get(cas, {})
|
| 317 |
+
pub = cache.get(cas, {})
|
| 318 |
+
smiles = reg.get("smiles") or pub.get("smiles")
|
| 319 |
+
rdkit_features = train.molecule_features(smiles)
|
| 320 |
+
vp = train.safe_float(reg.get("vapor_pressure_pa") or pub.get("vapor_pressure_pa"))
|
| 321 |
+
features = {
|
| 322 |
+
"log10_vapor_pressure_pa": math.log10(vp) if vp and vp > 0 else None,
|
| 323 |
+
"boiling_point_k": train.safe_float(reg.get("boiling_point_k") or pub.get("boiling_point_k")),
|
| 324 |
+
"molecular_weight": train.safe_float(reg.get("molecular_weight") or pub.get("molecular_weight") or rdkit_features.get("molecular_weight")),
|
| 325 |
+
"logp": train.safe_float(reg.get("logp") or pub.get("logp") or rdkit_features.get("logp")),
|
| 326 |
+
}
|
| 327 |
+
for name in ["heavy_atoms", "h_acceptors", "h_donors", "rotatable_bonds", "tpsa", "fraction_csp3"]:
|
| 328 |
+
features[name] = train.safe_float(rdkit_features.get(name))
|
| 329 |
+
if not smiles and not any(features.get(n) is not None for n in train.FEATURE_NAMES):
|
| 330 |
+
continue
|
| 331 |
+
seen.add(cas)
|
| 332 |
+
out.append({
|
| 333 |
+
"cas": cas,
|
| 334 |
+
"name": row.get("name") or cas,
|
| 335 |
+
"smiles": smiles,
|
| 336 |
+
"target_log10": TIER_TO_LOG10[tier],
|
| 337 |
+
"target_raw": 10 ** TIER_TO_LOG10[tier],
|
| 338 |
+
"features": features,
|
| 339 |
+
"scaffold": train.scaffold_key(smiles, cas),
|
| 340 |
+
"source": "poucher-tier",
|
| 341 |
+
"provenance": "poucher-tier",
|
| 342 |
+
"tier": tier,
|
| 343 |
+
})
|
| 344 |
+
return out
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def eval_with_auxiliary_tiers(rows: list[dict[str, Any]], seeds: list[int]) -> dict[str, Any]:
|
| 348 |
+
aux_rows = poucher_tier_auxiliary_rows(rows)
|
| 349 |
+
if not aux_rows:
|
| 350 |
+
return {"status": "reverted", "reason": "no model-ready auxiliary tier rows available", "n_auxiliary": 0}
|
| 351 |
+
y_measured = np.asarray([r["target_log10"] for r in rows], dtype=float)
|
| 352 |
+
runs = []
|
| 353 |
+
for seed in seeds:
|
| 354 |
+
train_idx, test_idx = train.greedy_scaffold_split(rows, TEST_FRACTION, seed)
|
| 355 |
+
train_scaffolds = {rows[int(i)]["scaffold"] for i in train_idx}
|
| 356 |
+
test_scaffolds = {rows[int(i)]["scaffold"] for i in test_idx}
|
| 357 |
+
eligible_aux = [r for r in aux_rows if r["scaffold"] not in test_scaffolds and r["cas"] not in {rows[int(i)]["cas"] for i in test_idx}]
|
| 358 |
+
combined = [rows[int(i)] for i in train_idx] + eligible_aux
|
| 359 |
+
x_combined, _ = train.design_matrix(combined, include_structural=True)
|
| 360 |
+
y_combined = np.asarray([r["target_log10"] for r in combined], dtype=float)
|
| 361 |
+
x_test, _ = train.design_matrix([rows[int(i)] for i in test_idx], include_structural=True)
|
| 362 |
+
model = regressor("gbm")
|
| 363 |
+
model.fit(x_combined, y_combined)
|
| 364 |
+
pred = np.asarray(model.predict(x_test), dtype=float)
|
| 365 |
+
runs.append({
|
| 366 |
+
"seed": seed,
|
| 367 |
+
"n_train_measured": int(len(train_idx)),
|
| 368 |
+
"n_auxiliary_used": int(len(eligible_aux)),
|
| 369 |
+
"train_aux_scaffold_overlap_with_test": sorted(train_scaffolds & test_scaffolds),
|
| 370 |
+
"metrics": regression_metrics(y_measured[test_idx], pred),
|
| 371 |
+
})
|
| 372 |
+
return {
|
| 373 |
+
"status": "measured",
|
| 374 |
+
"n_auxiliary_model_ready": len(aux_rows),
|
| 375 |
+
"provenance": "poucher-tier auxiliary rows; measured targets not overwritten",
|
| 376 |
+
"mean_spearman_rho": float(np.nanmean([r["metrics"]["spearman_rho"] for r in runs])),
|
| 377 |
+
"mean_r2": float(np.nanmean([r["metrics"]["r2"] for r in runs])),
|
| 378 |
+
"runs": runs,
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def eval_vle_augmentation(rows: list[dict[str, Any]], seeds: list[int]) -> dict[str, Any]:
|
| 383 |
+
# VLE augmentation is formula-level in this repo. There is no same-construct
|
| 384 |
+
# molecule-level measured target for perturbed formula masses, so using it
|
| 385 |
+
# here would contaminate the measured-Poucher endpoint.
|
| 386 |
+
return {
|
| 387 |
+
"status": "reverted",
|
| 388 |
+
"reason": "available VLE engine produces formula trajectories, not same-construct molecule-level measured Poucher labels; no change kept without measured improvement",
|
| 389 |
+
"before_metric_source": "measured-only substantivity CV",
|
| 390 |
+
"after_metric": None,
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def write_markdown(report: dict[str, Any], path: Path) -> None:
|
| 395 |
+
sub = report["part1"]["substantivity"]
|
| 396 |
+
char = report["part1"]["character"]
|
| 397 |
+
attempts = report["part2_quality_attempts"]
|
| 398 |
+
lines = [
|
| 399 |
+
f"# PIMT {VERSION} Line-Drawn Assessment",
|
| 400 |
+
"",
|
| 401 |
+
f"- Timestamp UTC: `{report['metadata']['timestamp_utc']}`",
|
| 402 |
+
f"- Git commit: `{report['metadata']['git_commit']}`",
|
| 403 |
+
f"- Dataset SHA256: `{report['metadata']['dataset_sha256']}`",
|
| 404 |
+
f"- Checkpoint SHA256: `{report['metadata']['checkpoint_sha256']}`",
|
| 405 |
+
"",
|
| 406 |
+
"## Per-Axis Verdict",
|
| 407 |
+
"",
|
| 408 |
+
f"- Substantivity: real spine. Mean scaffold-CV rho/R2 = {sub['cv']['mean_spearman_rho']:.3f} / {sub['cv']['mean_r2']:.3f}; locked rho/R2 = {sub['locked_holdout']['spearman_rho']:.3f} / {sub['locked_holdout']['r2']:.3f}.",
|
| 409 |
+
f"- Character: weak secondary axis. n={char['n_labelled']}, mean macro/micro F1 = {char['classifier']['mean_macro_f1']:.3f} / {char['classifier']['mean_micro_f1']:.3f}.",
|
| 410 |
+
"",
|
| 411 |
+
"No aggregate two-axis score is reported.",
|
| 412 |
+
"",
|
| 413 |
+
"## Quality Attempts",
|
| 414 |
+
"",
|
| 415 |
+
"| Attempt | Before | After | Decision |",
|
| 416 |
+
"| --- | ---: | ---: | --- |",
|
| 417 |
+
]
|
| 418 |
+
for item in attempts:
|
| 419 |
+
before = item.get("before")
|
| 420 |
+
after = item.get("after")
|
| 421 |
+
before_s = f"{before:.3f}" if isinstance(before, (int, float)) and math.isfinite(before) else "n/a"
|
| 422 |
+
after_s = f"{after:.3f}" if isinstance(after, (int, float)) and math.isfinite(after) else "n/a"
|
| 423 |
+
lines.append(f"| {item['name']} | {before_s} | {after_s} | {item['decision']} |")
|
| 424 |
+
lines.extend([
|
| 425 |
+
"",
|
| 426 |
+
"## Line Drawn",
|
| 427 |
+
"",
|
| 428 |
+
"No further open-ended character sourcing is started here. Remaining paths are ship the substantivity result, or deliberately revisit character via a trajectory-proportion pivot.",
|
| 429 |
+
"",
|
| 430 |
+
])
|
| 431 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def main() -> None:
|
| 435 |
+
parser = argparse.ArgumentParser()
|
| 436 |
+
parser.add_argument("--fetch-pubchem", action="store_true")
|
| 437 |
+
parser.add_argument("--out-json", default=f"artifacts/{VERSION}_metrics.json")
|
| 438 |
+
parser.add_argument("--out-md", default=f"artifacts/{VERSION}_assessment.md")
|
| 439 |
+
parser.add_argument("--model-dir", default=f"models/pimt_{VERSION}")
|
| 440 |
+
args = parser.parse_args()
|
| 441 |
+
|
| 442 |
+
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 443 |
+
rows = model_ready_rows(args.fetch_pubchem)
|
| 444 |
+
x_base, base_names = train.design_matrix(rows, include_structural=False)
|
| 445 |
+
x_full, full_names = train.design_matrix(rows, include_structural=True)
|
| 446 |
+
|
| 447 |
+
sub_base = eval_substantivity_cv(rows, x_base, SEEDS)
|
| 448 |
+
sub_full = eval_substantivity_cv(rows, x_full, SEEDS)
|
| 449 |
+
sub_rf = eval_substantivity_cv(rows, x_full, SEEDS, kind="rf")
|
| 450 |
+
locked = fit_locked_model(rows, x_full)
|
| 451 |
+
|
| 452 |
+
labels_by_cas = load_character_labels(CHARACTER_PATH)
|
| 453 |
+
character_rows = character_feature_rows(labels_by_cas)
|
| 454 |
+
x_character, _ = train.design_matrix(character_rows, include_structural=True)
|
| 455 |
+
char_baseline = eval_character(character_rows, x_character, labels_by_cas, None, SEEDS)
|
| 456 |
+
char_balanced = eval_character(character_rows, x_character, labels_by_cas, "balanced", SEEDS)
|
| 457 |
+
char_distribution = character_distribution_metric(labels_by_cas, CHARACTER_PATH)
|
| 458 |
+
|
| 459 |
+
aux_tiers = eval_with_auxiliary_tiers(rows, SEEDS)
|
| 460 |
+
vle_aug = eval_vle_augmentation(rows, SEEDS)
|
| 461 |
+
|
| 462 |
+
quality_attempts = [
|
| 463 |
+
{
|
| 464 |
+
"name": "fold D1-cleared auxiliary Poucher tiers",
|
| 465 |
+
"metric": "substantivity mean scaffold-CV Spearman rho",
|
| 466 |
+
"before": sub_full["mean_spearman_rho"],
|
| 467 |
+
"after": aux_tiers.get("mean_spearman_rho"),
|
| 468 |
+
"decision": "kept" if aux_tiers.get("mean_spearman_rho", -999) > sub_full["mean_spearman_rho"] else "reverted",
|
| 469 |
+
"details": aux_tiers,
|
| 470 |
+
},
|
| 471 |
+
{
|
| 472 |
+
"name": "structural feature enrichment",
|
| 473 |
+
"metric": "substantivity mean scaffold-CV Spearman rho",
|
| 474 |
+
"before": sub_base["mean_spearman_rho"],
|
| 475 |
+
"after": sub_full["mean_spearman_rho"],
|
| 476 |
+
"decision": "kept" if sub_full["mean_spearman_rho"] > sub_base["mean_spearman_rho"] else "reverted",
|
| 477 |
+
},
|
| 478 |
+
{
|
| 479 |
+
"name": "data augmentation via VLE engine",
|
| 480 |
+
"metric": "held-out measured substantivity",
|
| 481 |
+
"before": sub_full["mean_spearman_rho"],
|
| 482 |
+
"after": None,
|
| 483 |
+
"decision": "reverted",
|
| 484 |
+
"details": vle_aug,
|
| 485 |
+
},
|
| 486 |
+
{
|
| 487 |
+
"name": "pos_weight / focal-loss analogue for character",
|
| 488 |
+
"metric": "rare-class F1",
|
| 489 |
+
"before": char_baseline["rare_class_f1_mean"],
|
| 490 |
+
"after": char_balanced["rare_class_f1_mean"],
|
| 491 |
+
"decision": "kept" if char_balanced["rare_class_f1_mean"] > char_baseline["rare_class_f1_mean"] else "reverted",
|
| 492 |
+
},
|
| 493 |
+
{
|
| 494 |
+
"name": "distributional character metric as training signal",
|
| 495 |
+
"metric": "character distributional discrimination",
|
| 496 |
+
"before": None,
|
| 497 |
+
"after": None,
|
| 498 |
+
"decision": "reverted",
|
| 499 |
+
"details": {
|
| 500 |
+
"status": "exploratory_not_kept",
|
| 501 |
+
"reason": "no formula-level supervised character target in available measured set; distributional metric is reported as an assessment signal, not optimized as training loss",
|
| 502 |
+
"metric": char_distribution,
|
| 503 |
+
},
|
| 504 |
+
},
|
| 505 |
+
{
|
| 506 |
+
"name": "ensemble / cross-validation on the 170",
|
| 507 |
+
"metric": "substantivity mean scaffold-CV Spearman rho",
|
| 508 |
+
"before": sub_full["mean_spearman_rho"],
|
| 509 |
+
"after": sub_rf["mean_spearman_rho"],
|
| 510 |
+
"decision": "kept" if sub_rf["mean_spearman_rho"] > sub_full["mean_spearman_rho"] else "reverted",
|
| 511 |
+
"details": {"random_forest": sub_rf},
|
| 512 |
+
},
|
| 513 |
+
]
|
| 514 |
+
|
| 515 |
+
model_dir = Path(args.model_dir)
|
| 516 |
+
model_dir.mkdir(parents=True, exist_ok=True)
|
| 517 |
+
checkpoint_path = model_dir / "pimt_v10_line_drawn_substantivity_gbm.joblib"
|
| 518 |
+
joblib.dump({
|
| 519 |
+
"version": VERSION,
|
| 520 |
+
"axis": "substantivity",
|
| 521 |
+
"model": locked["model"],
|
| 522 |
+
"feature_names": full_names,
|
| 523 |
+
"baseline_feature_names": base_names,
|
| 524 |
+
"target": "Poucher measured log10 coefficient only",
|
| 525 |
+
"character_note": "Character labels are evaluated separately as a weak secondary axis; not implied by this checkpoint.",
|
| 526 |
+
}, checkpoint_path)
|
| 527 |
+
checkpoint_sha = sha256_file(checkpoint_path)
|
| 528 |
+
|
| 529 |
+
dataset_paths = [
|
| 530 |
+
Path("data/poucher_substantivity.jsonl"),
|
| 531 |
+
CHARACTER_PATH,
|
| 532 |
+
TIER_PATH,
|
| 533 |
+
Path("data/pubchem_substantivity_cache.json"),
|
| 534 |
+
]
|
| 535 |
+
dataset_paths = [p for p in dataset_paths if p.exists()]
|
| 536 |
+
report = {
|
| 537 |
+
"metadata": {
|
| 538 |
+
"version": VERSION,
|
| 539 |
+
"timestamp_utc": timestamp,
|
| 540 |
+
"git_commit": git_commit(),
|
| 541 |
+
"dataset_paths": [str(p) for p in dataset_paths],
|
| 542 |
+
"dataset_sha256": sha256_files(dataset_paths),
|
| 543 |
+
"checkpoint_path": str(checkpoint_path),
|
| 544 |
+
"checkpoint_sha256": checkpoint_sha,
|
| 545 |
+
},
|
| 546 |
+
"part1": {
|
| 547 |
+
"substantivity": {
|
| 548 |
+
"target": "measured Poucher log10 coefficient only",
|
| 549 |
+
"n_model_ready": len(rows),
|
| 550 |
+
"cv": sub_full,
|
| 551 |
+
"baseline_physical_cv": sub_base,
|
| 552 |
+
"locked_holdout": locked["metrics"],
|
| 553 |
+
},
|
| 554 |
+
"character": {
|
| 555 |
+
"target": "26-class curated molecule labels, masked where absent",
|
| 556 |
+
"n_label_rows_total": len(labels_by_cas),
|
| 557 |
+
"n_labelled": char_baseline["n_labelled"],
|
| 558 |
+
"n_model_ready": len(character_rows),
|
| 559 |
+
"classifier": char_baseline,
|
| 560 |
+
"balanced_classifier": char_balanced,
|
| 561 |
+
"distributional_discrimination": char_distribution,
|
| 562 |
+
"verdict": "weak secondary axis; not co-equal with substantivity",
|
| 563 |
+
},
|
| 564 |
+
},
|
| 565 |
+
"part2_quality_attempts": quality_attempts,
|
| 566 |
+
"part3_assessment": {
|
| 567 |
+
"best_model": "measured-only substantivity GBM" if all(i["decision"] != "kept" or i["name"] == "structural feature enrichment" for i in quality_attempts) else "see kept quality attempts",
|
| 568 |
+
"substantivity_verdict": "real result",
|
| 569 |
+
"character_verdict": "weak and included honestly",
|
| 570 |
+
"line_drawn": "no further open-ended character sourcing; next paths are ship substantivity or deliberate trajectory-proportion pivot",
|
| 571 |
+
},
|
| 572 |
+
}
|
| 573 |
+
|
| 574 |
+
out_json = Path(args.out_json)
|
| 575 |
+
out_md = Path(args.out_md)
|
| 576 |
+
out_json.parent.mkdir(parents=True, exist_ok=True)
|
| 577 |
+
out_json.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
| 578 |
+
write_markdown(report, out_md)
|
| 579 |
+
print(json.dumps({
|
| 580 |
+
"version": VERSION,
|
| 581 |
+
"n_substantivity_model_ready": len(rows),
|
| 582 |
+
"n_character_labelled": char_baseline["n_labelled"],
|
| 583 |
+
"substantivity_locked": locked["metrics"],
|
| 584 |
+
"substantivity_cv_mean_rho": sub_full["mean_spearman_rho"],
|
| 585 |
+
"character_macro_f1": char_baseline["mean_macro_f1"],
|
| 586 |
+
"checkpoint_sha256": checkpoint_sha,
|
| 587 |
+
"metrics": str(out_json),
|
| 588 |
+
"assessment": str(out_md),
|
| 589 |
+
}, indent=2, sort_keys=True))
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
if __name__ == "__main__":
|
| 593 |
+
main()
|