mattbitzesty commited on
Commit
700d58b
·
verified ·
1 Parent(s): ef8e907

Upload scripts/physics_redundancy_probe.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/physics_redundancy_probe.py +108 -0
scripts/physics_redundancy_probe.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """E2 (v2): Physics-redundancy probe — numerically stable.
2
+
3
+ Question: are the engine physics quantities recoverable from the structural
4
+ embeddings (redundant) or do they carry independent information?
5
+
6
+ Fixes vs v1: SVD-truncated ridge (stable under collinearity), per-feature
7
+ standardization, reports MW-only baseline (MW is already in the embedding's
8
+ physical block), and uses the full registry (no OpenPOM requirement) for n.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import sqlite3
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ ROOT = Path(__file__).resolve().parent.parent
19
+ DB = ROOT / "src" / "pino" / "registry.db"
20
+ OUT = ROOT / "artifacts" / "physics_redundancy_probe.json"
21
+
22
+
23
+ def morgan_fp(smiles: str, nbits: int = 2048):
24
+ from rdkit import Chem, RDLogger
25
+ from rdkit.Chem import AllChem
26
+ from rdkit.DataStructs import ConvertToNumpyArray
27
+ RDLogger.DisableLog("rdApp.*")
28
+ if not smiles or smiles.startswith("NATURAL"):
29
+ return None
30
+ m = Chem.MolFromSmiles(smiles)
31
+ if m is None:
32
+ return None
33
+ f = AllChem.GetMorganFingerprintAsBitVect(m, 2, nBits=nbits)
34
+ a = np.zeros(nbits, np.float32)
35
+ ConvertToNumpyArray(f, a)
36
+ return a
37
+
38
+
39
+ def svd_ridge_r2(X, y, folds=5, alpha=1.0, seed=0, rank=None):
40
+ """Stable ridge via truncated SVD; out-of-fold R^2."""
41
+ rng = np.random.default_rng(seed)
42
+ idx = rng.permutation(len(y))
43
+ oof = np.zeros(len(y))
44
+ mu, sd = X.mean(0), X.std(0) + 1e-9
45
+ for te in np.array_split(idx, folds):
46
+ tr = np.setdiff1d(idx, te)
47
+ Xtr = (X[tr] - mu) / sd
48
+ Xte = (X[te] - mu) / sd
49
+ U, S, Vt = np.linalg.svd(Xtr, full_matrices=False)
50
+ # stable ridge: coef = V diag(S/(S^2+alpha)) U^T y (handles any feature count)
51
+ Ut_y = U.T @ y[tr] # (r,)
52
+ coef = Vt.T @ ((S / (S ** 2 + alpha)) * Ut_y)
53
+ oof[te] = Xte @ coef
54
+ ss_res = float(((y - oof) ** 2).sum())
55
+ ss_tot = float(((y - y.mean()) ** 2).sum())
56
+ return 1.0 - ss_res / max(ss_tot, 1e-12)
57
+
58
+
59
+ def main():
60
+ con = sqlite3.connect(DB)
61
+ con.row_factory = sqlite3.Row
62
+ rows = con.execute(
63
+ """SELECT cas, smiles, molecular_weight, boiling_point_k,
64
+ vapor_pressure_pa, odor_threshold_ug_m3, openpom_embedding
65
+ FROM aroma_chemicals
66
+ WHERE vapor_pressure_pa > 0 AND molecular_weight > 0
67
+ AND odor_threshold_ug_m3 > 0"""
68
+ ).fetchall()
69
+ con.close()
70
+
71
+ Xm, Xp, MW, keep_pom = [], [], [], []
72
+ Ypsat, Yoav = [], []
73
+ for i, r in enumerate(rows):
74
+ a = morgan_fp(r["smiles"])
75
+ if a is None:
76
+ continue
77
+ Xm.append(a)
78
+ MW.append([np.log10(r["molecular_weight"])])
79
+ Ypsat.append(np.log10(r["vapor_pressure_pa"]))
80
+ Yoav.append(np.log10(r["vapor_pressure_pa"] / r["odor_threshold_ug_m3"]))
81
+ if r["openpom_embedding"]:
82
+ keep_pom.append(len(Xm) - 1)
83
+ Xp.append(np.array(json.loads(r["openpom_embedding"]), np.float32))
84
+
85
+ Xm = np.array(Xm)
86
+ MW = np.array(MW)
87
+ Xp = np.array(Xp) if Xp else None
88
+ keep_pom = np.array(keep_pom)
89
+ targets = {"log10_P_sat": np.array(Ypsat), "log10_OAV_sat": np.array(Yoav)}
90
+
91
+ print(f"n molecules (Morgan): {len(Xm)} with OpenPOM: {len(keep_pom)}")
92
+ results = {"n_morgan": int(len(Xm)), "n_openpom": int(len(keep_pom)), "readouts": {}}
93
+ for name, y in targets.items():
94
+ r = {"r2_mw_only": round(svd_ridge_r2(MW, y), 4),
95
+ "r2_morgan2048": round(svd_ridge_r2(Xm, y), 4),
96
+ "r2_morgan_plus_mw": round(svd_ridge_r2(np.hstack([Xm, MW]), y), 4)}
97
+ if Xp is not None and len(keep_pom) > 20:
98
+ r["r2_openpom256"] = round(svd_ridge_r2(Xp, y[keep_pom]), 4)
99
+ results["readouts"][name] = r
100
+ print(f"{name:14s} " + " ".join(f"{k.replace('r2_','')}={v:.3f}" for k, v in r.items()))
101
+
102
+ OUT.parent.mkdir(parents=True, exist_ok=True)
103
+ OUT.write_text(json.dumps(results, indent=2))
104
+ print("wrote", OUT)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()