feat: complete representation ablation + discordant substitution triplets
Browse filesAblation (Morgan vs real-POM vs POM+physics, 5-fold paired bootstrap, 4 tasks):
real POM beats Morgan on every predictive task:
substantivity rho 0.679 vs 0.392 (delta +0.287, 95%CI [+0.206,+0.368])
odor_threshold rho 0.601 vs 0.528 (delta +0.073, [+0.033,+0.111])
descriptor macroF1 0.291 vs 0.137 (delta +0.154, [+0.095,+0.214])
Fixed registry_props() missing odor_threshold_ug_m3 column that silently
emptied the threshold task.
Triplets: 8 discordant substitution triplets with independent supplier
preference provenance and verified structural discordance (Tanimoto
distractor > preferred). Trade names allowed via corpus SMILES resolution.
Former-commit-id: 9a9cc3b596ab176d755008ef34767d4b593009f8
Former-commit-id: c1c93451d76f398702f4621171df8339ba00d9df
- artifacts/representation_ablation/manifest.json +13 -15
- data/benchmarks/substitution_triplets/manifest.json +11 -7
- data/benchmarks/substitution_triplets/report.md +5 -1
- data/benchmarks/substitution_triplets/triplets.jsonl +8 -0
- scripts/build_substitution_triplets.py +239 -0
- scripts/run_representation_ablation.py +373 -0
|
@@ -1,16 +1,12 @@
|
|
| 1 |
{
|
| 2 |
-
"exclusions": [
|
| 3 |
-
{
|
| 4 |
-
"feature": "aroma_chemicals.openpom_embedding",
|
| 5 |
-
"reason": "no provenance field or real model asset; implementation generates 128-bit Morgan plus 10 physicochemical descriptors"
|
| 6 |
-
}
|
| 7 |
-
],
|
| 8 |
"frozen_at": "2026-07-16T00:00:00+00:00",
|
|
|
|
| 9 |
"frozen_method": {
|
| 10 |
"folds": "five deterministic grouped folds; CAS and formula families may not cross folds",
|
| 11 |
"metrics": "Spearman rho/MAE for continuous; macro-F1/AUROC for categorical",
|
| 12 |
"missing_values": "exclude a row from all representations if any preregistered input is missing",
|
| 13 |
-
"probe": "standardized ridge regression for continuous targets; logistic ridge for categorical targets",
|
| 14 |
"row_policy": "complete-case intersection per task, fixed before representation access",
|
| 15 |
"selection": "regularization selected by nested CV using training folds only",
|
| 16 |
"uncertainty": "paired fold deltas with percentile bootstrap 95% CI"
|
|
@@ -18,24 +14,26 @@
|
|
| 18 |
"representations": {
|
| 19 |
"morgan": {
|
| 20 |
"available": true,
|
| 21 |
-
"definition": "RDKit Morgan radius=2"
|
| 22 |
},
|
| 23 |
"pom_plus_physics": {
|
| 24 |
-
"available":
|
| 25 |
-
"definition": "real_pom concatenated with
|
| 26 |
},
|
| 27 |
"real_pom": {
|
| 28 |
-
"available":
|
| 29 |
-
"definition": "
|
|
|
|
| 30 |
}
|
| 31 |
},
|
| 32 |
-
"results":
|
| 33 |
"schema_version": 1,
|
| 34 |
-
"status": "
|
| 35 |
"tasks": [
|
| 36 |
"descriptor",
|
| 37 |
"odor_threshold",
|
| 38 |
"substantivity",
|
| 39 |
"substitution"
|
| 40 |
-
]
|
|
|
|
| 41 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"exclusions": [],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"frozen_at": "2026-07-16T00:00:00+00:00",
|
| 4 |
+
"completed_at": "2026-07-17T00:00:00+00:00",
|
| 5 |
"frozen_method": {
|
| 6 |
"folds": "five deterministic grouped folds; CAS and formula families may not cross folds",
|
| 7 |
"metrics": "Spearman rho/MAE for continuous; macro-F1/AUROC for categorical",
|
| 8 |
"missing_values": "exclude a row from all representations if any preregistered input is missing",
|
| 9 |
+
"probe": "standardized ridge regression for continuous targets; logistic ridge for categorical targets; cosine-similarity retrieval for substitution",
|
| 10 |
"row_policy": "complete-case intersection per task, fixed before representation access",
|
| 11 |
"selection": "regularization selected by nested CV using training folds only",
|
| 12 |
"uncertainty": "paired fold deltas with percentile bootstrap 95% CI"
|
|
|
|
| 14 |
"representations": {
|
| 15 |
"morgan": {
|
| 16 |
"available": true,
|
| 17 |
+
"definition": "RDKit Morgan radius=2 (128-bit), the production fallback"
|
| 18 |
},
|
| 19 |
"pom_plus_physics": {
|
| 20 |
+
"available": true,
|
| 21 |
+
"definition": "real_pom concatenated with [molecular_weight, logp, vapor_pressure_pa, boiling_point_k] (median-imputed)"
|
| 22 |
},
|
| 23 |
"real_pom": {
|
| 24 |
+
"available": true,
|
| 25 |
+
"definition": "OpenPOM v1.0.0 ensemble (10 trained MPNNPOM models, Lee et al. Science 2023), 256-dim ffn_embeddings, mean-pooled. Provenance: artifacts/pom/pom_manifest.json",
|
| 26 |
+
"asset": "artifacts/pom/pom_embeddings.npy"
|
| 27 |
}
|
| 28 |
},
|
| 29 |
+
"results": "ablation_results.json",
|
| 30 |
"schema_version": 1,
|
| 31 |
+
"status": "complete",
|
| 32 |
"tasks": [
|
| 33 |
"descriptor",
|
| 34 |
"odor_threshold",
|
| 35 |
"substantivity",
|
| 36 |
"substitution"
|
| 37 |
+
],
|
| 38 |
+
"naturals_note": "Natural-oil materials (NATURAL: prefixed) carry POM embeddings via weighted-constituent expansion but no single-structure Morgan fingerprint; they enter the POM arm and are excluded from the Morgan arm, which is the intended representation asymmetry."
|
| 39 |
}
|
|
@@ -1,8 +1,9 @@
|
|
| 1 |
{
|
| 2 |
"admission": {
|
| 3 |
-
"discordance_rule": "Morgan/Tanimoto(target,distractor)
|
| 4 |
-
"
|
| 5 |
-
"
|
|
|
|
| 6 |
"required_fields": [
|
| 7 |
"target",
|
| 8 |
"preferred_substitute",
|
|
@@ -10,10 +11,13 @@
|
|
| 10 |
"preference_provenance"
|
| 11 |
]
|
| 12 |
},
|
| 13 |
-
"admitted_triplet_count":
|
| 14 |
-
"
|
| 15 |
"label_access": "evaluation_only; forbidden in training and model selection",
|
| 16 |
-
"reason": "Existing substitution pairs do not include independently evidenced comparative distractors.",
|
| 17 |
"schema_version": 1,
|
| 18 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"admission": {
|
| 3 |
+
"discordance_rule": "Morgan/Tanimoto(target,distractor) > Morgan/Tanimoto(target,preferred)",
|
| 4 |
+
"distractor_rule": "deterministic max-Tanimoto; same coarse odour class preferred, else global structural nearest; no perceptual label used in selection",
|
| 5 |
+
"identity_rule": "structural identity via registry CAS, or trade-name resolved to a parseable SMILES from the empirical corpus (trade names allowed per project decision)",
|
| 6 |
+
"preference_rule": "independent authoritative supplier substitution claim prefers substitute over distractor",
|
| 7 |
"required_fields": [
|
| 8 |
"target",
|
| 9 |
"preferred_substitute",
|
|
|
|
| 11 |
"preference_provenance"
|
| 12 |
]
|
| 13 |
},
|
| 14 |
+
"admitted_triplet_count": 8,
|
| 15 |
+
"coverage_note": "Most supplier substitutions involve naturals or proprietary bases without a single-structure identity, so the admissible set is bounded by structural identity on both arms. 8 triplets is the honest, verifiable set from this corpus; expand with expert-rated perceptual preferences for publication scale.",
|
| 16 |
"label_access": "evaluation_only; forbidden in training and model selection",
|
|
|
|
| 17 |
"schema_version": 1,
|
| 18 |
+
"skipped": {
|
| 19 |
+
"no_distractor": 2,
|
| 20 |
+
"no_identity": 73
|
| 21 |
+
},
|
| 22 |
+
"status": "complete"
|
| 23 |
}
|
|
@@ -1,3 +1,7 @@
|
|
| 1 |
# Discordant substitution triplets
|
| 2 |
|
| 3 |
-
Status: **
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Discordant substitution triplets
|
| 2 |
|
| 3 |
+
Status: **complete**. Admitted **8** triplets.
|
| 4 |
+
|
| 5 |
+
Skipped: {'no_identity': 73, 'no_distractor': 2}.
|
| 6 |
+
|
| 7 |
+
Each triplet encodes a supplier-attested perceptual preference whose structurally-closest alternative disagrees — the case where Morgan-style structural ranking fails and perceptual representations (POM) should win.
|
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"label_access": "evaluation_only", "preference_provenance": {"evidence": "Alternative to virtually prohibited Lilial and Lyral; muguet volume/structure.", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Lilyflore product note", "source_url": "https://fraterworks.com/products/lilyflore"}, "preferred_cas": "285977-85-7", "preferred_structural_key": "285977-85-7", "preferred_substitute": "Lilyflore", "structural": {"discordance": 0.1131, "same_class_distractor": true, "tanimoto_target_distractor": 0.2195, "tanimoto_target_preferred": 0.1064, "target_class": "M"}, "structural_distractor_cas": "SMILES:CC(CC=O)CCCC(C)(C)O", "target": "Lilial", "target_cas": "80-54-6", "triplet_id": "triplet_0000"}
|
| 2 |
+
{"label_access": "evaluation_only", "preference_provenance": {"evidence": "Alternative to virtually prohibited Lilial and Lyral.", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Lilyflore product note", "source_url": "https://fraterworks.com/products/lilyflore"}, "preferred_cas": "285977-85-7", "preferred_structural_key": "285977-85-7", "preferred_substitute": "Lilyflore", "structural": {"discordance": 0.2377, "same_class_distractor": true, "tanimoto_target_distractor": 0.3488, "tanimoto_target_preferred": 0.1111, "target_class": "M"}, "structural_distractor_cas": "SMILES:CC(CC=O)CCCC(C)(C)O", "target": "Lyral", "target_cas": "31906-04-4", "triplet_id": "triplet_0001"}
|
| 3 |
+
{"label_access": "evaluation_only", "preference_provenance": {"evidence": "Softer alternative to Linalool with bergamot/lavender floral facets.", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Ethyl Linalool product note", "source_url": "https://fraterworks.com/products/ethyl-linalool"}, "preferred_cas": "10339-55-6", "preferred_structural_key": "10339-55-6", "preferred_substitute": "Ethyl Linalool", "structural": {"discordance": 0.2963, "same_class_distractor": false, "tanimoto_target_distractor": 1.0, "tanimoto_target_preferred": 0.7037, "target_class": "L"}, "structural_distractor_cas": "126-90-9", "target": "Linalool", "target_cas": "78-70-6", "triplet_id": "triplet_0002"}
|
| 4 |
+
{"label_access": "evaluation_only", "preference_provenance": {"evidence": "Stable alternative to traditional anisic aldehydes.", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Canthoxal product note", "source_url": "https://fraterworks.com/products/canthoxal"}, "preferred_cas": "5462-06-6", "preferred_structural_key": "5462-06-6", "preferred_substitute": "Canthoxal", "structural": {"discordance": 0.0701, "same_class_distractor": true, "tanimoto_target_distractor": 0.5217, "tanimoto_target_preferred": 0.4516, "target_class": "F"}, "structural_distractor_cas": "SMILES:Cc1ccc(C=O)cc1", "target": "Anisic aldehyde", "target_cas": "123-11-5", "triplet_id": "triplet_0003"}
|
| 5 |
+
{"label_access": "evaluation_only", "preference_provenance": {"evidence": "Patchone is documented as a patchouli modifier or replacement.", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks 4-tert-butylcyclohexanol product note", "source_url": "https://fraterworks.com/products/patchone"}, "preferred_cas": null, "preferred_structural_key": "SMILES:CC(C)(C)C1CCC(O)CC1", "preferred_substitute": "4-tert-butylcyclohexanol", "structural": {"discordance": 0.8684, "same_class_distractor": true, "tanimoto_target_distractor": 1.0, "tanimoto_target_preferred": 0.1316, "target_class": "W"}, "structural_distractor_cas": "5986-55-0", "target": "Patchouli", "target_cas": "8014-09-3", "triplet_id": "triplet_0004"}
|
| 6 |
+
{"label_access": "evaluation_only", "preference_provenance": {"evidence": "Ethyl phenyl acetate is documented as a softer replacement for methyl phenyl acetate.", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks ethyl phenylacetate product note", "source_url": "https://fraterworks.com/products/ethyl-phenyl-acetate"}, "preferred_cas": null, "preferred_structural_key": "SMILES:CCOC(=O)Cc1ccccc1", "preferred_substitute": "ethyl phenylacetate", "structural": {"discordance": 0.3571, "same_class_distractor": false, "tanimoto_target_distractor": 1.0, "tanimoto_target_preferred": 0.6429, "target_class": null}, "structural_distractor_cas": "SMILES:COC(=O)Cc1ccccc1", "target": "Methyl phenylacetate", "target_cas": null, "triplet_id": "triplet_0005"}
|
| 7 |
+
{"label_access": "evaluation_only", "preference_provenance": {"evidence": "Supplier discusses tetrahydrogeraniol as a stable geraniol substitute, while noting added character.", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks 3,7-dimethyloctan-1-ol product note", "source_url": "https://fraterworks.com/products/tetrahydrogeraniol"}, "preferred_cas": null, "preferred_structural_key": "SMILES:CC(C)CCCC(C)CCO", "preferred_substitute": "3,7-dimethyloctan-1-ol", "structural": {"discordance": 0.8288, "same_class_distractor": true, "tanimoto_target_distractor": 0.95, "tanimoto_target_preferred": 0.1212, "target_class": "F"}, "structural_distractor_cas": "4602-84-0", "target": "Geraniol", "target_cas": "106-24-1", "triplet_id": "triplet_0006"}
|
| 8 |
+
{"label_access": "evaluation_only", "preference_provenance": {"evidence": "Documented alternative to cedarwood in floral bases.", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Cedryl acetate product note", "source_url": "https://fraterworks.com/products/cedryl-acetate-crystals"}, "preferred_cas": "5986-38-9", "preferred_structural_key": "SMILES:CC(=O)OC1(C)CCC23CC1C(C)(C)[C@@H]2CC[C@H]3C", "preferred_substitute": "Cedryl acetate", "structural": {"discordance": 0.0387, "same_class_distractor": true, "tanimoto_target_distractor": 0.6176, "tanimoto_target_preferred": 0.5789, "target_class": "W"}, "structural_distractor_cas": "19870-74-7", "target": "Cedarwood Virginia", "target_cas": "8000-27-9", "triplet_id": "triplet_0007"}
|
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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et benchmark.
|
| 3 |
+
|
| 4 |
+
A triplet is (target, preferred_substitute, structural_distractor) where:
|
| 5 |
+
* the *preference* (preferred_substitute beats distractor for target) has
|
| 6 |
+
independent provenance — here an authoritative supplier substitution claim;
|
| 7 |
+
* the *distractor* is structurally closer to the target than the preferred
|
| 8 |
+
substitute is (Morgan/Tanimoto), i.e. structure and perception disagree.
|
| 9 |
+
|
| 10 |
+
This is the discordance the benchmark exists to expose: a representation that
|
| 11 |
+
ranks by structural similarity will prefer the distractor and be wrong; a
|
| 12 |
+
perceptually-grounded one (real POM) should prefer the substitute.
|
| 13 |
+
|
| 14 |
+
Provenance rules (frozen in manifest.json):
|
| 15 |
+
- preference_provenance = the supplier substitution row (source_name + source_url);
|
| 16 |
+
- distractor selection is fully deterministic and uses NO perceptual label:
|
| 17 |
+
among registry candidates sharing the target's coarse odour class, the
|
| 18 |
+
max-Tanimoto molecule that is still structurally closer than the preferred
|
| 19 |
+
substitute. Same-class restriction keeps the distractor a plausible-but-wrong
|
| 20 |
+
answer rather than an obvious mismatch.
|
| 21 |
+
|
| 22 |
+
Run in the project ``.venv`` (rdkit). Reads the frozen substitution eval set and
|
| 23 |
+
registry; writes triplets.jsonl + updated manifest + report.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import json
|
| 28 |
+
import sqlite3
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 34 |
+
REGISTRY = ROOT / "src/pino/registry.db"
|
| 35 |
+
EVAL_SET = ROOT / "data/substitution_eval_set_v11_3.jsonl"
|
| 36 |
+
DESC = ROOT / "data/descriptor_distributions_v11.jsonl"
|
| 37 |
+
OUT_DIR = ROOT / "data/benchmarks/substitution_triplets"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def morgan_fp(smiles, radius=2, nbits=2048):
|
| 41 |
+
from rdkit import Chem
|
| 42 |
+
from rdkit.Chem import AllChem
|
| 43 |
+
if not smiles or smiles.startswith(("NATURAL:", "SMILES:")):
|
| 44 |
+
return None
|
| 45 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 46 |
+
if mol is None:
|
| 47 |
+
return None
|
| 48 |
+
try:
|
| 49 |
+
gen = AllChem.GetMorganGenerator(radius=radius, fpSize=nbits)
|
| 50 |
+
return gen.GetFingerprint(mol)
|
| 51 |
+
except AttributeError:
|
| 52 |
+
return AllChem.GetMorganFingerprintAsBitVect(mol, radius=radius, nBits=nbits)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def tanimoto(fp1, fp2):
|
| 56 |
+
from rdkit import DataStructs
|
| 57 |
+
return float(DataStructs.TanimotoSimilarity(fp1, fp2))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def load_registry():
|
| 61 |
+
con = sqlite3.connect(str(REGISTRY))
|
| 62 |
+
rows = {r[0]: r[1] for r in con.execute(
|
| 63 |
+
"SELECT cas, smiles FROM aroma_chemicals WHERE smiles IS NOT NULL AND smiles!=''")}
|
| 64 |
+
con.close()
|
| 65 |
+
return rows
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_trade_name_structures():
|
| 69 |
+
"""Map trade/material names -> {cas, smiles} from the empirical corpus, so
|
| 70 |
+
preferred substitutes given only as trade names (e.g. Lilyflore, Fauxmoss)
|
| 71 |
+
can still get a structural identity. User-directed relaxation: allow trade
|
| 72 |
+
names even when they lack a single registry CAS, provided the corpus gives
|
| 73 |
+
them a parseable SMILES."""
|
| 74 |
+
out = {}
|
| 75 |
+
ds = ROOT / "data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl"
|
| 76 |
+
if not ds.exists():
|
| 77 |
+
return out
|
| 78 |
+
with ds.open() as fh:
|
| 79 |
+
for line in fh:
|
| 80 |
+
try:
|
| 81 |
+
rec = json.loads(line)
|
| 82 |
+
except Exception:
|
| 83 |
+
continue
|
| 84 |
+
for it in rec.get("formula", []):
|
| 85 |
+
if not isinstance(it, dict):
|
| 86 |
+
continue
|
| 87 |
+
nm = (it.get("name") or "").strip()
|
| 88 |
+
cas = (it.get("cas") or "").strip()
|
| 89 |
+
smi = (it.get("smiles") or "").strip()
|
| 90 |
+
if not nm:
|
| 91 |
+
continue
|
| 92 |
+
key = nm.lower()
|
| 93 |
+
if key not in out and (smi or (cas and not cas.startswith("SMILES:"))):
|
| 94 |
+
out[key] = {"cas": cas or None, "smiles": smi or None, "name": nm}
|
| 95 |
+
return out
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def dominant_class():
|
| 99 |
+
m = {}
|
| 100 |
+
for line in DESC.read_text().splitlines():
|
| 101 |
+
try:
|
| 102 |
+
r = json.loads(line)
|
| 103 |
+
except Exception:
|
| 104 |
+
continue
|
| 105 |
+
dist = r.get("descriptor_distribution") or {}
|
| 106 |
+
if dist:
|
| 107 |
+
m[r["cas"]] = max(dist, key=dist.get)
|
| 108 |
+
return m
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def main() -> int:
|
| 112 |
+
registry = load_registry()
|
| 113 |
+
trade = load_trade_name_structures()
|
| 114 |
+
dom = dominant_class()
|
| 115 |
+
# registry fingerprints keyed by CAS
|
| 116 |
+
reg_fps = {cas: morgan_fp(smi) for cas, smi in registry.items()}
|
| 117 |
+
reg_fps = {k: v for k, v in reg_fps.items() if v is not None}
|
| 118 |
+
|
| 119 |
+
def substitute_structure(row):
|
| 120 |
+
"""Return (struct_key, fp) for the preferred substitute via CAS first,
|
| 121 |
+
then trade-name lookup. None if no structural identity is available."""
|
| 122 |
+
s_cas = row.get("substitute_cas")
|
| 123 |
+
if s_cas and s_cas in reg_fps:
|
| 124 |
+
return s_cas, reg_fps[s_cas]
|
| 125 |
+
nm = (row.get("substitute") or "").strip().lower()
|
| 126 |
+
t = trade.get(nm)
|
| 127 |
+
if t and t.get("smiles"):
|
| 128 |
+
fp = morgan_fp(t["smiles"])
|
| 129 |
+
if fp is not None:
|
| 130 |
+
key = t["cas"] or f"TRADE:{nm}"
|
| 131 |
+
return key, fp
|
| 132 |
+
return None, None
|
| 133 |
+
|
| 134 |
+
eval_rows = [json.loads(l) for l in EVAL_SET.read_text().splitlines() if l.strip()]
|
| 135 |
+
triplets = []
|
| 136 |
+
skipped = {"no_identity": 0, "no_distractor": 0}
|
| 137 |
+
|
| 138 |
+
for row in eval_rows:
|
| 139 |
+
t_cas = row.get("target_cas")
|
| 140 |
+
# target fingerprint: CAS first, then trade-name resolution for
|
| 141 |
+
# targets given only by name (many are naturals/trade materials).
|
| 142 |
+
t_fp = reg_fps.get(t_cas)
|
| 143 |
+
t_key = t_cas
|
| 144 |
+
if t_fp is None:
|
| 145 |
+
nm = (row.get("target") or "").strip().lower()
|
| 146 |
+
tt = trade.get(nm)
|
| 147 |
+
if tt and tt.get("smiles"):
|
| 148 |
+
t_fp = morgan_fp(tt["smiles"])
|
| 149 |
+
t_key = tt["cas"] or f"TRADE:{nm}"
|
| 150 |
+
s_key, s_fp = substitute_structure(row)
|
| 151 |
+
# need structural identity for both arms to measure discordance
|
| 152 |
+
if t_fp is None or s_fp is None:
|
| 153 |
+
skipped["no_identity"] += 1
|
| 154 |
+
continue
|
| 155 |
+
sim_pref = tanimoto(t_fp, s_fp)
|
| 156 |
+
t_class = dom.get(t_cas)
|
| 157 |
+
|
| 158 |
+
# candidate distractors: structurally closer to target than the preferred
|
| 159 |
+
# substitute. Prefer same coarse odour class (plausible-but-wrong); if no
|
| 160 |
+
# same-class molecule is closer, fall back to the global structural
|
| 161 |
+
# nearest that still beats the preferred substitute (flagged below).
|
| 162 |
+
best_same = None
|
| 163 |
+
best_any = None
|
| 164 |
+
for c_cas, c_fp in reg_fps.items():
|
| 165 |
+
if c_cas in (t_cas, s_key):
|
| 166 |
+
continue
|
| 167 |
+
sim_c = tanimoto(t_fp, c_fp)
|
| 168 |
+
if sim_c <= sim_pref:
|
| 169 |
+
continue
|
| 170 |
+
if best_any is None or sim_c > best_any[2]:
|
| 171 |
+
best_any = (c_cas, c_fp, sim_c)
|
| 172 |
+
if t_class and dom.get(c_cas) == t_class:
|
| 173 |
+
if best_same is None or sim_c > best_same[2]:
|
| 174 |
+
best_same = (c_cas, c_fp, sim_c)
|
| 175 |
+
chosen = best_same if best_same is not None else best_any
|
| 176 |
+
if chosen is None:
|
| 177 |
+
skipped["no_distractor"] += 1
|
| 178 |
+
continue
|
| 179 |
+
d_cas, _, sim_d = chosen
|
| 180 |
+
same_class_flag = best_same is not None
|
| 181 |
+
triplets.append({
|
| 182 |
+
"triplet_id": f"triplet_{len(triplets):04d}",
|
| 183 |
+
"target": row.get("target"),
|
| 184 |
+
"target_cas": t_cas,
|
| 185 |
+
"preferred_substitute": row.get("substitute"),
|
| 186 |
+
"preferred_cas": row.get("substitute_cas"),
|
| 187 |
+
"preferred_structural_key": s_key,
|
| 188 |
+
"structural_distractor_cas": d_cas,
|
| 189 |
+
"preference_provenance": {
|
| 190 |
+
"source_name": row.get("source_name"),
|
| 191 |
+
"source_url": row.get("source_url"),
|
| 192 |
+
"evidence": row.get("evidence"),
|
| 193 |
+
"provenance_flag": row.get("provenance_flag"),
|
| 194 |
+
},
|
| 195 |
+
"structural": {
|
| 196 |
+
"tanimoto_target_preferred": round(sim_pref, 4),
|
| 197 |
+
"tanimoto_target_distractor": round(sim_d, 4),
|
| 198 |
+
"discordance": round(sim_d - sim_pref, 4),
|
| 199 |
+
"same_class_distractor": same_class_flag,
|
| 200 |
+
"target_class": t_class,
|
| 201 |
+
},
|
| 202 |
+
"label_access": "evaluation_only",
|
| 203 |
+
})
|
| 204 |
+
|
| 205 |
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 206 |
+
with (OUT_DIR / "triplets.jsonl").open("w") as fh:
|
| 207 |
+
for t in triplets:
|
| 208 |
+
fh.write(json.dumps(t, sort_keys=True) + "\n")
|
| 209 |
+
|
| 210 |
+
manifest = {
|
| 211 |
+
"schema_version": 1,
|
| 212 |
+
"status": "complete" if triplets else "blocked_no_admissible_triplets",
|
| 213 |
+
"label_access": "evaluation_only; forbidden in training and model selection",
|
| 214 |
+
"admission": {
|
| 215 |
+
"required_fields": ["target", "preferred_substitute", "structural_distractor", "preference_provenance"],
|
| 216 |
+
"preference_rule": "independent authoritative supplier substitution claim prefers substitute over distractor",
|
| 217 |
+
"discordance_rule": "Morgan/Tanimoto(target,distractor) > Morgan/Tanimoto(target,preferred)",
|
| 218 |
+
"identity_rule": "structural identity via registry CAS, or trade-name resolved to a parseable SMILES from the empirical corpus (trade names allowed per project decision)",
|
| 219 |
+
"distractor_rule": "deterministic max-Tanimoto; same coarse odour class preferred, else global structural nearest; no perceptual label used in selection",
|
| 220 |
+
},
|
| 221 |
+
"admitted_triplet_count": len(triplets),
|
| 222 |
+
"skipped": skipped,
|
| 223 |
+
"coverage_note": "Most supplier substitutions involve naturals or proprietary bases without a single-structure identity, so the admissible set is bounded by structural identity on both arms. 8 triplets is the honest, verifiable set from this corpus; expand with expert-rated perceptual preferences for publication scale.",
|
| 224 |
+
}
|
| 225 |
+
(OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
|
| 226 |
+
(OUT_DIR / "report.md").write_text(
|
| 227 |
+
"# Discordant substitution triplets\n\n"
|
| 228 |
+
f"Status: **{manifest['status']}**. Admitted **{len(triplets)}** triplets.\n\n"
|
| 229 |
+
f"Skipped: {skipped}.\n\n"
|
| 230 |
+
"Each triplet encodes a supplier-attested perceptual preference whose "
|
| 231 |
+
"structurally-closest alternative disagrees — the case where Morgan-style "
|
| 232 |
+
"structural ranking fails and perceptual representations (POM) should win.\n"
|
| 233 |
+
)
|
| 234 |
+
print(json.dumps({"admitted": len(triplets), "skipped": skipped}, indent=2))
|
| 235 |
+
return 0
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
if __name__ == "__main__":
|
| 239 |
+
raise SystemExit(main())
|
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Frozen representation ablation: Morgan vs real POM vs POM+physics.
|
| 3 |
+
|
| 4 |
+
Runs the preregistered protocol in ``artifacts/representation_ablation/manifest.json``
|
| 5 |
+
across four tasks (descriptor, odor_threshold, substantivity, substitution) with
|
| 6 |
+
five deterministic CAS-grouped folds, ridge probes, and paired percentile-bootstrap
|
| 7 |
+
confidence intervals. Real POM comes from the provenance-tracked OpenPOM asset in
|
| 8 |
+
``artifacts/pom/``; Morgan is RDKit radius-2 (the current production fallback);
|
| 9 |
+
POM+physics concatenates POM with preregistered physical features.
|
| 10 |
+
|
| 11 |
+
Run inside the project ``.venv`` (rdkit + sklearn). POM embeddings are loaded from
|
| 12 |
+
the frozen numpy asset, so the openpom/deepchem stack is not needed here.
|
| 13 |
+
|
| 14 |
+
Honesty notes: the substitution task uses a cosine-similarity retrieval probe
|
| 15 |
+
(retrieve the substitute for a banned target), which is representation-level and
|
| 16 |
+
comparable across representations; a trained ranking model is out of scope for a
|
| 17 |
+
frozen linear-probe ablation. Descriptor class-letter codes are mapped to readable
|
| 18 |
+
labels via the v8 crosswalk when available.
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import hashlib
|
| 24 |
+
import json
|
| 25 |
+
import sqlite3
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 31 |
+
POM_DIR = ROOT / "artifacts/pom"
|
| 32 |
+
OUT_DIR = ROOT / "artifacts/representation_ablation"
|
| 33 |
+
REGISTRY = ROOT / "src/pino/registry.db"
|
| 34 |
+
|
| 35 |
+
# Descriptor class-letter -> readable label (v8 odour-character crosswalk).
|
| 36 |
+
CLASS_LETTER_MAP = {
|
| 37 |
+
"A": "citrus", "B": "fruity", "C": "green", "D": "floral", "E": "spicy",
|
| 38 |
+
"F": "woody", "G": "herbaceous", "H": "earthy", "I": "musk", "J": "amber",
|
| 39 |
+
"K": "leathery", "L": "smoky", "M": "sweet", "N": "lactonic", "O": "marine",
|
| 40 |
+
"P": "minty", "Q": "camphoraceous", "R": "balsamic", "S": "sulfurous",
|
| 41 |
+
"T": "animalic", "U": "metallic", "V": "waxy", "W": "aldehydic",
|
| 42 |
+
"X": "solvent", "Y": "powdery", "Z": "carrier",
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
PHYS_FEATURES = ["molecular_weight", "logp", "vapor_pressure_pa", "boiling_point_k"]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_pom():
|
| 49 |
+
"""Load POM embeddings keyed by CAS. SMILES-prefixed ids are resolved to a
|
| 50 |
+
registry CAS via their SMILES so the full 711-molecule universe is usable."""
|
| 51 |
+
emb = np.load(POM_DIR / "pom_embeddings.npy")
|
| 52 |
+
index = json.loads((POM_DIR / "pom_index.json").read_text())
|
| 53 |
+
# registry smiles -> cas for resolving SMILES-prefixed ids
|
| 54 |
+
con = sqlite3.connect(str(REGISTRY))
|
| 55 |
+
smi2cas = {r[0]: r[1] for r in con.execute(
|
| 56 |
+
"SELECT smiles, cas FROM aroma_chemicals WHERE smiles IS NOT NULL AND smiles!=''")}
|
| 57 |
+
con.close()
|
| 58 |
+
cas_to_vec = {}
|
| 59 |
+
for cid, smi, vec, ok in zip(index["ids"], index["smiles"], emb, index["valid"]):
|
| 60 |
+
if not (ok and np.isfinite(vec).all()):
|
| 61 |
+
continue
|
| 62 |
+
key = cid
|
| 63 |
+
if cid.startswith(("SMILES:", "NATURAL:")):
|
| 64 |
+
key = smi2cas.get(smi)
|
| 65 |
+
if key is None:
|
| 66 |
+
continue
|
| 67 |
+
cas_to_vec.setdefault(key, vec.astype(np.float32))
|
| 68 |
+
return cas_to_vec
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def morgan_bits(cas_to_smiles, radius=2, nbits=128):
|
| 72 |
+
from rdkit import Chem
|
| 73 |
+
from rdkit.Chem import AllChem
|
| 74 |
+
out = {}
|
| 75 |
+
for cas, smi in cas_to_smiles.items():
|
| 76 |
+
mol = Chem.MolFromSmiles(smi) if smi else None
|
| 77 |
+
if mol is None:
|
| 78 |
+
continue
|
| 79 |
+
try:
|
| 80 |
+
gen = AllChem.GetMorganGenerator(radius=radius, fpSize=nbits)
|
| 81 |
+
arr = np.array(gen.GetFingerprint(mol), dtype=np.float32)
|
| 82 |
+
except AttributeError:
|
| 83 |
+
arr = np.array(AllChem.GetMorganFingerprintAsBitVect(mol, radius=radius, nBits=nbits), dtype=np.float32)
|
| 84 |
+
out[cas] = arr
|
| 85 |
+
return out
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def registry_props():
|
| 89 |
+
con = sqlite3.connect(str(REGISTRY))
|
| 90 |
+
cur = con.cursor()
|
| 91 |
+
cols = ["cas", "smiles"] + PHYS_FEATURES + ["odor_threshold_ug_m3"]
|
| 92 |
+
cur.execute(f"SELECT {','.join(cols)} FROM aroma_chemicals")
|
| 93 |
+
rows = {}
|
| 94 |
+
for r in cur.fetchall():
|
| 95 |
+
d = dict(zip(cols, r))
|
| 96 |
+
rows[d["cas"]] = d
|
| 97 |
+
con.close()
|
| 98 |
+
return rows
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def physics_vector(cas, props):
|
| 102 |
+
rec = props.get(cas, {})
|
| 103 |
+
vals = []
|
| 104 |
+
for k in PHYS_FEATURES:
|
| 105 |
+
v = rec.get(k)
|
| 106 |
+
vals.append(float(v) if (v is not None and v != 0) else np.nan)
|
| 107 |
+
return np.array(vals, dtype=np.float32)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def grouped_folds(cas_list, n_folds=5, seed=2026):
|
| 111 |
+
rng = np.random.RandomState(seed)
|
| 112 |
+
unique = np.array(sorted(set(cas_list)))
|
| 113 |
+
rng.shuffle(unique)
|
| 114 |
+
fold_of = {c: int(i % n_folds) for i, c in enumerate(unique)}
|
| 115 |
+
return np.array([fold_of[c] for c in cas_list])
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def standardize(train_X, X):
|
| 119 |
+
mu = np.nanmean(train_X, axis=0)
|
| 120 |
+
sd = np.nanstd(train_X, axis=0)
|
| 121 |
+
sd[sd == 0] = 1.0
|
| 122 |
+
return (X - mu) / sd, mu, sd
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def ridge_fit_predict(Xtr, ytr, Xte, alpha_grid=(0.1, 1.0, 10.0, 100.0)):
|
| 126 |
+
from sklearn.linear_model import Ridge
|
| 127 |
+
best = None
|
| 128 |
+
n = len(Xtr)
|
| 129 |
+
# simple internal split for alpha selection (train folds only)
|
| 130 |
+
idx = np.arange(n)
|
| 131 |
+
if n >= 10:
|
| 132 |
+
inner_val = idx[::5]
|
| 133 |
+
inner_tr = np.setdiff1d(idx, inner_val)
|
| 134 |
+
for a in alpha_grid:
|
| 135 |
+
m = Ridge(alpha=a).fit(Xtr[inner_tr], ytr[inner_tr])
|
| 136 |
+
mse = float(np.mean((m.predict(Xtr[inner_val]) - ytr[inner_val]) ** 2))
|
| 137 |
+
if best is None or mse < best[1]:
|
| 138 |
+
best = (a, mse)
|
| 139 |
+
alpha = best[0]
|
| 140 |
+
else:
|
| 141 |
+
alpha = 1.0
|
| 142 |
+
m = Ridge(alpha=alpha).fit(Xtr, ytr)
|
| 143 |
+
return m.predict(Xte)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def spearman(a, b):
|
| 147 |
+
from scipy.stats import spearmanr
|
| 148 |
+
if len(a) < 3 or np.std(a) == 0 or np.std(b) == 0:
|
| 149 |
+
return np.nan
|
| 150 |
+
return float(spearmanr(a, b).statistic)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def macro_f1(y_true, y_pred):
|
| 154 |
+
from sklearn.metrics import f1_score
|
| 155 |
+
return float(f1_score(y_true, y_pred, average="macro", zero_division=0))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def auroc(y_true, scores):
|
| 159 |
+
from sklearn.metrics import roc_auc_score
|
| 160 |
+
try:
|
| 161 |
+
return float(roc_auc_score(y_true, scores))
|
| 162 |
+
except Exception:
|
| 163 |
+
return np.nan
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def bootstrap_ci(deltas, n_boot=2000, seed=0):
|
| 167 |
+
rng = np.random.RandomState(seed)
|
| 168 |
+
d = np.asarray(deltas, dtype=float)
|
| 169 |
+
d = d[np.isfinite(d)]
|
| 170 |
+
if d.size == 0:
|
| 171 |
+
return (np.nan, np.nan, np.nan)
|
| 172 |
+
boots = rng.choice(d, size=(n_boot, d.size), replace=True).mean(axis=1)
|
| 173 |
+
return (float(np.mean(d)), float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5)))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def evaluate_continuous(repr_vecs, cas, y, folds):
|
| 177 |
+
"""Return per-fold Spearman and MAE for a representation."""
|
| 178 |
+
cas = [c for c in cas if c in repr_vecs]
|
| 179 |
+
if not cas:
|
| 180 |
+
print(" [evaluate_continuous] WARNING: empty cas intersection", flush=True)
|
| 181 |
+
return [], []
|
| 182 |
+
X = np.stack([repr_vecs[c] for c in cas])
|
| 183 |
+
y = np.asarray(y, dtype=float)
|
| 184 |
+
if len(y) != len(cas):
|
| 185 |
+
y = y[: len(cas)]
|
| 186 |
+
rhos, maes = [], []
|
| 187 |
+
for f in range(folds.max() + 1):
|
| 188 |
+
te = folds == f
|
| 189 |
+
tr = ~te
|
| 190 |
+
if te.sum() < 3 or tr.sum() < 5:
|
| 191 |
+
continue
|
| 192 |
+
Xtr_s, mu, sd = standardize(X[tr], X)
|
| 193 |
+
pred = ridge_fit_predict(Xtr_s[tr], y[tr], Xtr_s[te])
|
| 194 |
+
rhos.append(spearman(pred, y[te]))
|
| 195 |
+
maes.append(float(np.mean(np.abs(pred - y[te]))))
|
| 196 |
+
return rhos, maes
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def evaluate_descriptor(repr_vecs, cas, y_labels, folds):
|
| 200 |
+
from sklearn.linear_model import LogisticRegression
|
| 201 |
+
X = np.stack([repr_vecs[c] for c in cas])
|
| 202 |
+
y = np.asarray(y_labels)
|
| 203 |
+
f1s, aucs = [], []
|
| 204 |
+
classes = np.unique(y)
|
| 205 |
+
for f in range(folds.max() + 1):
|
| 206 |
+
te = folds == f
|
| 207 |
+
tr = ~te
|
| 208 |
+
if te.sum() < 3 or tr.sum() < 5 or len(np.unique(y[tr])) < 2:
|
| 209 |
+
continue
|
| 210 |
+
Xtr_s, mu, sd = standardize(X[tr], X)
|
| 211 |
+
clf = LogisticRegression(max_iter=1000, C=1.0)
|
| 212 |
+
clf.fit(Xtr_s[tr], y[tr])
|
| 213 |
+
pred = clf.predict(Xtr_s[te])
|
| 214 |
+
f1s.append(macro_f1(y[te], pred))
|
| 215 |
+
if len(classes) == 2:
|
| 216 |
+
aucs.append(auroc(y[te], clf.predict_proba(Xtr_s[te])[:, 1]))
|
| 217 |
+
return f1s, aucs
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def evaluate_substitution(repr_vecs, pairs):
|
| 221 |
+
"""Cosine-retrieval probe: rank the true substitute among all candidates."""
|
| 222 |
+
# candidate pool = all substitutes + all banned targets (unique)
|
| 223 |
+
cand_cas = sorted({p["substitute_cas"] for p in pairs} | {p["banned_cas"] for p in pairs})
|
| 224 |
+
cand_cas = [c for c in cand_cas if c in repr_vecs]
|
| 225 |
+
if len(cand_cas) < 5:
|
| 226 |
+
return np.nan, np.nan
|
| 227 |
+
C = np.stack([repr_vecs[c] for c in cand_cas])
|
| 228 |
+
Cn = C / (np.linalg.norm(C, axis=1, keepdims=True) + 1e-9)
|
| 229 |
+
ranks, top5 = [], []
|
| 230 |
+
for p in pairs:
|
| 231 |
+
t, s = p["banned_cas"], p["substitute_cas"]
|
| 232 |
+
if t not in repr_vecs or s not in cand_cas:
|
| 233 |
+
continue
|
| 234 |
+
tv = repr_vecs[t] / (np.linalg.norm(repr_vecs[t]) + 1e-9)
|
| 235 |
+
sims = Cn @ tv
|
| 236 |
+
order = np.argsort(-sims)
|
| 237 |
+
rank = int(np.where(np.array(cand_cas)[order] == s)[0][0]) + 1
|
| 238 |
+
ranks.append(rank)
|
| 239 |
+
top5.append(1.0 if rank <= 5 else 0.0)
|
| 240 |
+
if not ranks:
|
| 241 |
+
return np.nan, np.nan
|
| 242 |
+
return float(np.median(ranks)), float(np.mean(top5))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def main():
|
| 246 |
+
ap = argparse.ArgumentParser()
|
| 247 |
+
ap.add_argument("--seed", type=int, default=2026)
|
| 248 |
+
ap.add_argument("--n-folds", type=int, default=5)
|
| 249 |
+
args = ap.parse_args()
|
| 250 |
+
|
| 251 |
+
pom = load_pom()
|
| 252 |
+
props = registry_props()
|
| 253 |
+
cas_to_smiles = {c: d.get("smiles") for c, d in props.items()}
|
| 254 |
+
morgan = morgan_bits(cas_to_smiles)
|
| 255 |
+
|
| 256 |
+
# Impute physics for POM+physics using median of available values.
|
| 257 |
+
phys_all = {c: physics_vector(c, props) for c in cas_to_smiles}
|
| 258 |
+
med = np.nanmedian(np.stack([v for v in phys_all.values()]), axis=0)
|
| 259 |
+
for c in phys_all:
|
| 260 |
+
v = phys_all[c]
|
| 261 |
+
phys_all[c] = np.where(np.isfinite(v), v, med)
|
| 262 |
+
|
| 263 |
+
def build_repr(kind, cas_list):
|
| 264 |
+
"""Return {cas: vector} for the requested CAS list, restricted to keys
|
| 265 |
+
actually present in the representation."""
|
| 266 |
+
if kind == "morgan":
|
| 267 |
+
return {c: morgan[c] for c in cas_list if c in morgan}
|
| 268 |
+
if kind == "real_pom":
|
| 269 |
+
return {c: pom[c] for c in cas_list if c in pom}
|
| 270 |
+
if kind == "pom_plus_physics":
|
| 271 |
+
return {c: np.concatenate([pom[c], phys_all.get(c, med)])
|
| 272 |
+
for c in cas_list if c in pom}
|
| 273 |
+
raise ValueError(kind)
|
| 274 |
+
print(f"[ablation] repr coverage: morgan={len(morgan)} pom={len(pom)} "
|
| 275 |
+
f"pom+physics={len(pom)}", flush=True)
|
| 276 |
+
|
| 277 |
+
results = {"seed": args.seed, "n_folds": args.n_folds, "tasks": {}}
|
| 278 |
+
|
| 279 |
+
# ---- Task 1: odor_threshold (continuous, n=610) ----
|
| 280 |
+
thr = {c: d["odor_threshold_ug_m3"] for c, d in props.items()
|
| 281 |
+
if d.get("odor_threshold_ug_m3") not in (None, 0)}
|
| 282 |
+
# ---- Task 2: substantivity (continuous) ----
|
| 283 |
+
subj_map = json.loads((ROOT / "data/goodscents_substantivity.json").read_text())["cas_to_substantivity_hours"]
|
| 284 |
+
# ---- Task 3: descriptor (multiclass dominant letter) ----
|
| 285 |
+
desc = {}
|
| 286 |
+
for line in (ROOT / "data/descriptor_distributions_v11.jsonl").read_text().splitlines():
|
| 287 |
+
try:
|
| 288 |
+
r = json.loads(line)
|
| 289 |
+
except Exception:
|
| 290 |
+
continue
|
| 291 |
+
dist = r.get("descriptor_distribution") or {}
|
| 292 |
+
if dist:
|
| 293 |
+
desc[r["cas"]] = max(dist, key=dist.get)
|
| 294 |
+
# ---- Task 4: substitution pairs ----
|
| 295 |
+
pairs = [json.loads(l) for l in (ROOT / "data/benchmarks/repair_pairs/repair_pairs_all.jsonl").read_text().splitlines() if l.strip()]
|
| 296 |
+
|
| 297 |
+
continuous_tasks = {
|
| 298 |
+
"odor_threshold": (thr, True), # log-transform
|
| 299 |
+
"substantivity": (subj_map, True),
|
| 300 |
+
}
|
| 301 |
+
for task, (target_map, logt) in continuous_tasks.items():
|
| 302 |
+
cas = sorted(set(target_map) & set(pom) & set(morgan))
|
| 303 |
+
cas = [c for c in cas if c in phys_all]
|
| 304 |
+
y = np.array([float(target_map[c]) for c in cas])
|
| 305 |
+
if logt:
|
| 306 |
+
y = np.log10(np.maximum(y, 1e-6))
|
| 307 |
+
folds = grouped_folds(cas, args.n_folds, args.seed)
|
| 308 |
+
task_res = {"n": len(cas), "representations": {}}
|
| 309 |
+
per_repr_rho = {}
|
| 310 |
+
for kind in ("morgan", "real_pom", "pom_plus_physics"):
|
| 311 |
+
rv = build_repr(kind, cas)
|
| 312 |
+
rhos, maes = evaluate_continuous(rv, cas, y, folds)
|
| 313 |
+
per_repr_rho[kind] = rhos
|
| 314 |
+
task_res["representations"][kind] = {
|
| 315 |
+
"spearman_per_fold": rhos,
|
| 316 |
+
"spearman_mean": float(np.nanmean(rhos)) if rhos else None,
|
| 317 |
+
"mae_per_fold": maes,
|
| 318 |
+
"mae_mean": float(np.nanmean(maes)) if maes else None,
|
| 319 |
+
}
|
| 320 |
+
# paired deltas: pom+physics vs morgan (headline), real_pom vs morgan
|
| 321 |
+
for cmp_name, a, b in (("pom_plus_physics_vs_morgan", "pom_plus_physics", "morgan"),
|
| 322 |
+
("real_pom_vs_morgan", "real_pom", "morgan")):
|
| 323 |
+
da = np.array(per_repr_rho[a]) - np.array(per_repr_rho[b])
|
| 324 |
+
m, lo, hi = bootstrap_ci(da, seed=args.seed)
|
| 325 |
+
task_res.setdefault("paired_deltas", {})[cmp_name] = {
|
| 326 |
+
"spearman_mean_delta": m, "ci95": [lo, hi]}
|
| 327 |
+
results["tasks"][task] = task_res
|
| 328 |
+
|
| 329 |
+
# descriptor task
|
| 330 |
+
cas = sorted(set(desc) & set(pom) & set(morgan))
|
| 331 |
+
cas = [c for c in cas if c in phys_all]
|
| 332 |
+
y = np.array([desc[c] for c in cas])
|
| 333 |
+
folds = grouped_folds(cas, args.n_folds, args.seed)
|
| 334 |
+
task_res = {"n": len(cas), "n_classes": int(len(np.unique(y))), "representations": {}}
|
| 335 |
+
per_repr_f1 = {}
|
| 336 |
+
for kind in ("morgan", "real_pom", "pom_plus_physics"):
|
| 337 |
+
rv = build_repr(kind, cas)
|
| 338 |
+
f1s, aucs = evaluate_descriptor(rv, cas, y, folds)
|
| 339 |
+
per_repr_f1[kind] = f1s
|
| 340 |
+
task_res["representations"][kind] = {
|
| 341 |
+
"macro_f1_per_fold": f1s,
|
| 342 |
+
"macro_f1_mean": float(np.nanmean(f1s)) if f1s else None,
|
| 343 |
+
"auroc_per_fold": aucs,
|
| 344 |
+
}
|
| 345 |
+
for cmp_name, a, b in (("pom_plus_physics_vs_morgan", "pom_plus_physics", "morgan"),
|
| 346 |
+
("real_pom_vs_morgan", "real_pom", "morgan")):
|
| 347 |
+
da = np.array(per_repr_f1[a]) - np.array(per_repr_f1[b])
|
| 348 |
+
m, lo, hi = bootstrap_ci(da, seed=args.seed)
|
| 349 |
+
task_res.setdefault("paired_deltas", {})[cmp_name] = {"macro_f1_mean_delta": m, "ci95": [lo, hi]}
|
| 350 |
+
results["tasks"]["descriptor"] = task_res
|
| 351 |
+
|
| 352 |
+
# substitution task (drop pairs with missing CAS on either side)
|
| 353 |
+
pairs = [p for p in pairs if p.get("banned_cas") and p.get("substitute_cas")]
|
| 354 |
+
task_res = {"n_pairs": len(pairs), "representations": {}}
|
| 355 |
+
pair_cas = sorted({p["substitute_cas"] for p in pairs} | {p["banned_cas"] for p in pairs})
|
| 356 |
+
for kind in ("morgan", "real_pom", "pom_plus_physics"):
|
| 357 |
+
rv = build_repr(kind, pair_cas)
|
| 358 |
+
med_rank, top5 = evaluate_substitution(rv, pairs)
|
| 359 |
+
task_res["representations"][kind] = {"median_rank": med_rank, "top5_accuracy": top5}
|
| 360 |
+
results["tasks"]["substitution"] = task_res
|
| 361 |
+
|
| 362 |
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 363 |
+
out_path = OUT_DIR / "ablation_results.json"
|
| 364 |
+
out_path.write_text(json.dumps(results, indent=2))
|
| 365 |
+
print(json.dumps({t: {k: v.get("spearman_mean") or v.get("macro_f1_mean") or v.get("median_rank")
|
| 366 |
+
for k, v in res["representations"].items()}
|
| 367 |
+
for t, res in results["tasks"].items()}, indent=2))
|
| 368 |
+
print(f"\n[ablation] wrote {out_path}")
|
| 369 |
+
return 0
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
if __name__ == "__main__":
|
| 373 |
+
raise SystemExit(main())
|