Matthew Ford commited on
Commit
1bb570d
·
1 Parent(s): 371c1ae

feat: v11.6 repair/enrichment scripts + independent-candidate prep + integrity tests

Browse files

Scripts implementing the v11.6 repair chain and corrected-baseline recompute, the
independent-candidate and training-dataset preparation, POM embedding computation,
source-population audit, and frozen genre-output diagnosis. New pytest coverage:
material data integrity, independent-candidate prep, training-dataset prep, source
population.


Former-commit-id: 176362fba0b6e86a533c830ae42bda0f05c91935
Former-commit-id: 3f0e963b225c2fe6d644601e7a427319bdac3b4a

scripts/audit_source_population.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Audit locally available formula/description evidence and emit an AI review queue.
3
+
4
+ The queue contains source text and identity candidates only. It deliberately
5
+ does not generate perceptual labels, assessor outcomes, or chemical identities.
6
+ Those require a separately reviewed, provenance-preserving decision.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+
16
+ ROOT = Path(__file__).resolve().parents[1]
17
+ DATA = ROOT / "data"
18
+
19
+
20
+ def load_jsonl(path: Path) -> list[dict[str, Any]]:
21
+ if not path.exists():
22
+ return []
23
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
24
+
25
+
26
+ def formula_description(row: dict[str, Any]) -> str:
27
+ source = row.get("source") if isinstance(row.get("source"), dict) else {}
28
+ return str(
29
+ row.get("description") or row.get("profile_text") or row.get("overall")
30
+ or source.get("description") or ""
31
+ ).strip()
32
+
33
+
34
+ def main() -> None:
35
+ parser = argparse.ArgumentParser(description=__doc__)
36
+ parser.add_argument("--output", type=Path, default=ROOT / "artifacts/source_population_audit.json")
37
+ parser.add_argument("--ai-review-queue", type=Path, default=ROOT / "artifacts/source_population_ai_review.jsonl")
38
+ args = parser.parse_args()
39
+
40
+ sources = [
41
+ DATA / "wisemoor_free_formulas.sanitized.jsonl",
42
+ DATA / "tgsc_demo_formulas_v2.jsonl",
43
+ DATA / "literature_formulas_poucher_with_profiles.jsonl",
44
+ DATA / "appell_formulas_enriched.jsonl",
45
+ ]
46
+ inventory: list[dict[str, Any]] = []
47
+ review: list[dict[str, Any]] = []
48
+ for path in sources:
49
+ rows = load_jsonl(path)
50
+ described = [(index, row) for index, row in enumerate(rows) if formula_description(row)]
51
+ inventory.append({
52
+ "source": str(path.relative_to(ROOT)),
53
+ "formula_rows": len(rows),
54
+ "rows_with_source_description": len(described),
55
+ })
56
+ for index, row in described:
57
+ source = row.get("source") if isinstance(row.get("source"), dict) else {}
58
+ review.append({
59
+ "review_id": f"{path.stem}:{index}",
60
+ "task": "extract_formula_level_attributes_with_verbatim_source_spans",
61
+ "source_file": str(path.relative_to(ROOT)),
62
+ "source_row_index": index,
63
+ "formula_id": row.get("formula_id") or row.get("id") or row.get("product_id"),
64
+ "formula_name": row.get("name") or source.get("title"),
65
+ "source_text": formula_description(row),
66
+ "allowed_output": ["attribute", "source_span", "confidence", "abstain_reason"],
67
+ "forbidden_output": ["assessor_label", "invented_identity", "invented_metric"],
68
+ "status": "pending_review",
69
+ })
70
+
71
+ tgsc_cache_path = DATA / "tgsc_odor_cache.json"
72
+ tgsc_cache = json.loads(tgsc_cache_path.read_text(encoding="utf-8")) if tgsc_cache_path.exists() else {}
73
+ profiles = load_jsonl(DATA / "material_profiles_v11_5.jsonl")
74
+ report = {
75
+ "schema_version": 1,
76
+ "formula_sources": inventory,
77
+ "formula_rows": sum(item["formula_rows"] for item in inventory),
78
+ "formula_rows_with_source_description": sum(item["rows_with_source_description"] for item in inventory),
79
+ "material_profiles": len(profiles),
80
+ "material_profiles_with_odor_description": sum(bool(row.get("odor_descriptions")) for row in profiles),
81
+ "tgsc_cached_material_pages": len(tgsc_cache),
82
+ "ai_review_rows": len(review),
83
+ "policy": "AI may extract claims only with verbatim source spans; outputs remain proposals until reviewed and are never assessor truth.",
84
+ }
85
+ args.output.parent.mkdir(parents=True, exist_ok=True)
86
+ args.output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
87
+ args.ai_review_queue.parent.mkdir(parents=True, exist_ok=True)
88
+ with args.ai_review_queue.open("w", encoding="utf-8") as handle:
89
+ for row in review:
90
+ handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
91
+ print(json.dumps(report, indent=2, sort_keys=True))
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main()
scripts/diagnose_frozen_genre_outputs.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Post-hoc diagnostics for the frozen genre-representation benchmark.
3
+
4
+ This script never changes the frozen split, embeddings, or preregistered verdict.
5
+ It adds controls, low-data curves, and test-set slices intended to explain a
6
+ negative result. All preprocessing and slice thresholds are fit on train data.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ from collections import Counter
13
+ import json
14
+ import math
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import numpy as np
19
+ from rdkit import Chem
20
+ from rdkit import RDLogger
21
+ from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier
22
+ from sklearn.metrics import accuracy_score, balanced_accuracy_score
23
+ from sklearn.neural_network import MLPClassifier
24
+ from sklearn.pipeline import make_pipeline
25
+ from sklearn.preprocessing import StandardScaler
26
+
27
+ from pino.genre_benchmark import SOLVENTS, composition_features, load_jsonl, nearest_centroid_predict
28
+
29
+
30
+ ELEMENTS = ("C", "H", "N", "O", "F", "P", "S", "Cl", "Br", "I", "B", "Si")
31
+ RDLogger.DisableLog("rdApp.error")
32
+
33
+
34
+ def identity(component: dict[str, Any]) -> str:
35
+ return str(component.get("cas") or component.get("smiles") or component.get("name") or "").strip().lower()
36
+
37
+
38
+ def structural_features(records: list[dict[str, Any]]) -> tuple[np.ndarray, list[dict[str, Any]]]:
39
+ """Weighted element counts plus label-free structural-quality diagnostics."""
40
+ matrix, metadata = [], []
41
+ for row in records:
42
+ elements: Counter[str] = Counter()
43
+ active, parsed, missing, invalid, charged, fragments = 0, 0, 0, 0, 0, 0
44
+ for component in row.get("formula", []):
45
+ if identity(component) in SOLVENTS:
46
+ continue
47
+ active += 1
48
+ smiles = str(component.get("smiles") or "").strip()
49
+ weight = max(float(component.get("weight_fraction", 0.0)), 0.0)
50
+ if not smiles:
51
+ missing += 1
52
+ continue
53
+ mol = Chem.MolFromSmiles(smiles)
54
+ if mol is None:
55
+ invalid += 1
56
+ continue
57
+ parsed += 1
58
+ fragments += int(len(Chem.GetMolFrags(mol)) > 1)
59
+ charged += int(any(atom.GetFormalCharge() for atom in mol.GetAtoms()))
60
+ for atom in mol.GetAtoms():
61
+ elements[atom.GetSymbol()] += weight
62
+ other = sum(value for key, value in elements.items() if key not in ELEMENTS)
63
+ vector = [elements[e] for e in ELEMENTS] + [other, active, parsed, missing, invalid, charged, fragments]
64
+ matrix.append(vector)
65
+ metadata.append({
66
+ "formula_size": active,
67
+ "missing_smiles": missing,
68
+ "invalid_smiles": invalid,
69
+ "charged_components": charged,
70
+ "multifragment_components": fragments,
71
+ "elements": sorted(elements),
72
+ })
73
+ return np.asarray(matrix, dtype=float), metadata
74
+
75
+
76
+ def scores(y: np.ndarray, pred: np.ndarray) -> dict[str, float]:
77
+ return {
78
+ "accuracy": float(accuracy_score(y, pred)),
79
+ "balanced_accuracy": float(balanced_accuracy_score(y, pred)),
80
+ }
81
+
82
+
83
+ def mlp_hidden(input_dim: int, classes: int, budget: int) -> int:
84
+ # (d + 1)h + (h + 1)c; use a common parameter budget across representations.
85
+ return max(1, int(round((budget - classes) / (input_dim + classes + 1))))
86
+
87
+
88
+ def fit_controls(
89
+ train_x: dict[str, np.ndarray], test_x: dict[str, np.ndarray], y_train: np.ndarray, y_test: np.ndarray,
90
+ *, seed: int, parameter_budget: int,
91
+ ) -> tuple[dict[str, Any], dict[str, np.ndarray]]:
92
+ results: dict[str, Any] = {}
93
+ predictions: dict[str, np.ndarray] = {}
94
+ classes = len(np.unique(y_train))
95
+ for name, x_train in train_x.items():
96
+ pred = nearest_centroid_predict(x_train, y_train, test_x[name])
97
+ predictions[f"{name}_nearest_centroid"] = pred
98
+ results[f"{name}_nearest_centroid"] = scores(y_test, pred)
99
+ hidden = mlp_hidden(x_train.shape[1], classes, parameter_budget)
100
+ model = make_pipeline(
101
+ StandardScaler(),
102
+ MLPClassifier(hidden_layer_sizes=(hidden,), max_iter=1000, early_stopping=True,
103
+ validation_fraction=0.15, random_state=seed),
104
+ )
105
+ model.fit(x_train, y_train)
106
+ pred = model.predict(test_x[name])
107
+ predictions[f"{name}_mlp"] = pred
108
+ results[f"{name}_mlp"] = {
109
+ **scores(y_test, pred), "hidden_units": hidden,
110
+ "nominal_parameters": (x_train.shape[1] + 1) * hidden + (hidden + 1) * classes,
111
+ }
112
+ for cls in (ExtraTreesClassifier, RandomForestClassifier):
113
+ model = cls(n_estimators=400, min_samples_leaf=2, class_weight="balanced", n_jobs=-1, random_state=seed)
114
+ model.fit(train_x["composition"], y_train)
115
+ pred = model.predict(test_x["composition"])
116
+ key = f"composition_{cls.__name__.replace('Classifier', '').lower()}"
117
+ predictions[key] = pred
118
+ results[key] = scores(y_test, pred)
119
+ majority = Counter(y_train).most_common(1)[0][0]
120
+ pred = np.repeat(majority, len(y_test))
121
+ predictions["majority"] = pred
122
+ results["majority"] = scores(y_test, pred)
123
+ return results, predictions
124
+
125
+
126
+ def shuffled_control(train: np.ndarray, test: np.ndarray, y_train: np.ndarray, y_test: np.ndarray, seed: int) -> dict[str, float]:
127
+ rng = np.random.default_rng(seed)
128
+ return scores(y_test, nearest_centroid_predict(train[rng.permutation(len(train))], y_train, test[rng.permutation(len(test))]))
129
+
130
+
131
+ def slice_report(y: np.ndarray, predictions: dict[str, np.ndarray], masks: dict[str, np.ndarray]) -> dict[str, Any]:
132
+ report = {}
133
+ for name, mask in masks.items():
134
+ count = int(mask.sum())
135
+ if count < 5:
136
+ continue
137
+ report[name] = {"n": count, "models": {key: scores(y[mask], pred[mask]) for key, pred in predictions.items()}}
138
+ return report
139
+
140
+
141
+ def low_data_curve(x_train: dict[str, np.ndarray], x_test: dict[str, np.ndarray], y_train: np.ndarray,
142
+ y_test: np.ndarray, seed: int) -> list[dict[str, Any]]:
143
+ rng = np.random.default_rng(seed)
144
+ by_label = {label: np.flatnonzero(y_train == label) for label in np.unique(y_train)}
145
+ output = []
146
+ for fraction in (0.1, 0.25, 0.5, 1.0):
147
+ selected = np.concatenate([
148
+ rng.choice(indices, size=max(1, int(math.ceil(len(indices) * fraction))), replace=False)
149
+ for indices in by_label.values()
150
+ ])
151
+ row = {"fraction": fraction, "n_train": int(len(selected)), "models": {}}
152
+ for name in ("learned", "composition", "elements"):
153
+ pred = nearest_centroid_predict(x_train[name][selected], y_train[selected], x_test[name])
154
+ row["models"][name] = scores(y_test, pred)
155
+ output.append(row)
156
+ return output
157
+
158
+
159
+ def diagnose_split(split: dict[str, Any], seed: int, budget: int) -> dict[str, Any]:
160
+ train, test = load_jsonl(split["train_records"]), load_jsonl(split["test_records"])
161
+ learned_train, learned_test = np.load(split["learned_train"]), np.load(split["learned_test"])
162
+ structural_train, train_meta = structural_features(train)
163
+ structural_test, test_meta = structural_features(test)
164
+ train_x = {"learned": learned_train, "composition": composition_features(train), "elements": structural_train}
165
+ test_x = {"learned": learned_test, "composition": composition_features(test), "elements": structural_test}
166
+ y_train, y_test = np.asarray([r["genre"] for r in train]), np.asarray([r["genre"] for r in test])
167
+ controls, predictions = fit_controls(train_x, test_x, y_train, y_test, seed=seed, parameter_budget=budget)
168
+ controls["learned_shuffled_rows"] = shuffled_control(learned_train, learned_test, y_train, y_test, seed)
169
+
170
+ sizes_train = np.asarray([m["formula_size"] for m in train_meta])
171
+ sizes_test = np.asarray([m["formula_size"] for m in test_meta])
172
+ q1, q2 = np.quantile(sizes_train, [1 / 3, 2 / 3])
173
+ element_frequency = Counter(e for meta in train_meta for e in set(meta["elements"]))
174
+ rare = {e for e, count in element_frequency.items() if count < max(5, int(0.01 * len(train)))}
175
+ ood_masks, ood_thresholds = {}, {}
176
+ for feature_name in ("composition", "learned"):
177
+ mean, std = train_x[feature_name].mean(0), train_x[feature_name].std(0)
178
+ std[std == 0] = 1
179
+ train_z = (train_x[feature_name] - mean) / std
180
+ test_z = (test_x[feature_name] - mean) / std
181
+ distance = np.sqrt(np.square(test_z[:, None, :] - train_z[None, :, :]).sum(2).min(1))
182
+ # Select by rank so tied distances (common for singleton formulas) do not
183
+ # silently turn a top-quartile diagnostic into the entire test set.
184
+ top = np.zeros(len(test), dtype=bool)
185
+ top[np.argsort(distance, kind="stable")[-max(1, math.ceil(len(test) / 4)):]] = True
186
+ ood_masks[f"{feature_name}_ood_top_quartile"] = top
187
+ ood_thresholds[feature_name] = float(distance[top].min())
188
+ masks = {
189
+ f"size_small_le_{q1:g}": sizes_test <= q1,
190
+ f"size_medium_{q1:g}_to_{q2:g}": (sizes_test > q1) & (sizes_test <= q2),
191
+ f"size_large_gt_{q2:g}": sizes_test > q2,
192
+ "contains_rare_element": np.asarray([bool(set(m["elements"]) & rare) for m in test_meta]),
193
+ "contains_charged_component": np.asarray([m["charged_components"] > 0 for m in test_meta]),
194
+ "structurally_ambiguous": np.asarray([m["missing_smiles"] + m["invalid_smiles"] + m["multifragment_components"] > 0 for m in test_meta]),
195
+ **ood_masks,
196
+ }
197
+ for label in np.unique(y_test):
198
+ masks[f"genre_{label}"] = y_test == label
199
+ return {
200
+ "name": split.get("name", "split"), "n_train": len(train), "n_test": len(test),
201
+ "controls": controls, "slice_thresholds_fit_on_train": {"size_tertiles": [float(q1), float(q2)],
202
+ "rare_element_record_threshold": max(5, int(0.01 * len(train))), "rare_elements": sorted(rare),
203
+ "ood_top_quartile_min_distance": ood_thresholds},
204
+ "slice_counts": {name: int(mask.sum()) for name, mask in masks.items()},
205
+ "slices": slice_report(y_test, predictions, masks),
206
+ "low_data_curve": low_data_curve(train_x, test_x, y_train, y_test, seed),
207
+ }
208
+
209
+
210
+ def main() -> None:
211
+ parser = argparse.ArgumentParser()
212
+ parser.add_argument("--manifest", required=True)
213
+ parser.add_argument("--output", required=True)
214
+ parser.add_argument("--seed", type=int, default=20260714)
215
+ parser.add_argument("--parameter-budget", type=int, default=4096)
216
+ args = parser.parse_args()
217
+ manifest = json.loads(Path(args.manifest).read_text())
218
+ report = {
219
+ "analysis_status": "post_hoc_diagnostic; does not alter preregistered verdict",
220
+ "parameter_budget": args.parameter_budget,
221
+ "splits": [diagnose_split(split, args.seed + i, args.parameter_budget) for i, split in enumerate(manifest)],
222
+ }
223
+ Path(args.output).write_text(json.dumps(report, indent=2) + "\n")
224
+ print(json.dumps(report, indent=2))
225
+
226
+
227
+ if __name__ == "__main__":
228
+ main()
scripts/freeze_genre_evaluation.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Freeze molecule-disjoint genre splits and export PIMT representations.
3
+
4
+ The prepare phase is label-aware only for the preregistered coverage check. The
5
+ export phase never runs the benchmark and writes embeddings in manifest order.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ from collections import Counter
12
+ import hashlib
13
+ import json
14
+ import random
15
+ import subprocess
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+
21
+ from pino.genre_benchmark import SOLVENTS, active_compounds, formula_fingerprint
22
+
23
+
24
+ def sha256(path: Path) -> str:
25
+ digest = hashlib.sha256()
26
+ with path.open("rb") as handle:
27
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
28
+ digest.update(chunk)
29
+ return digest.hexdigest()
30
+
31
+
32
+ def genre(row: dict[str, Any]) -> str:
33
+ return str(row.get("genre") or row.get("metadata", {}).get("generation_strategy") or "wildcard")
34
+
35
+
36
+ def lean_row(row: dict[str, Any]) -> dict[str, Any]:
37
+ """Retain exactly the fields consumed by the benchmark and row alignment."""
38
+ return {
39
+ "source_index": row["source_index"],
40
+ "formula_id": row.get("formula_id") or row.get("metadata", {}).get("formula_id"),
41
+ "genre": genre(row),
42
+ "formula": row.get("formula", []),
43
+ }
44
+
45
+
46
+ def load_index(dataset: Path) -> tuple[list[dict[str, Any]], list[str]]:
47
+ rows: list[dict[str, Any]] = []
48
+ molecules: set[str] = set()
49
+ with dataset.open(encoding="utf-8") as handle:
50
+ for index, line in enumerate(handle):
51
+ row = json.loads(line)
52
+ row["source_index"] = index
53
+ compounds = active_compounds(row)
54
+ rows.append({
55
+ "source_index": index,
56
+ "genre": genre(row),
57
+ "compounds": compounds,
58
+ "fingerprint": formula_fingerprint(row),
59
+ })
60
+ molecules.update(compounds)
61
+ return rows, sorted(molecules)
62
+
63
+
64
+ def split_indices(rows: list[dict[str, Any]], molecules: list[str], seed: int, train_ratio: float):
65
+ shuffled = molecules.copy()
66
+ random.Random(seed).shuffle(shuffled)
67
+ cut = min(max(int(len(shuffled) * train_ratio), 1), len(shuffled) - 1)
68
+ train_molecules = set(shuffled[:cut])
69
+ test_molecules = set(shuffled[cut:])
70
+ train, test, excluded = [], [], []
71
+ for row in rows:
72
+ compounds = row["compounds"]
73
+ if not compounds:
74
+ excluded.append(row["source_index"])
75
+ elif compounds <= train_molecules:
76
+ train.append(row["source_index"])
77
+ elif compounds <= test_molecules:
78
+ test.append(row["source_index"])
79
+ else:
80
+ excluded.append(row["source_index"])
81
+ return train, test, excluded
82
+
83
+
84
+ def counts(rows_by_index: dict[int, dict[str, Any]], indices: list[int]) -> dict[str, int]:
85
+ return dict(sorted(Counter(rows_by_index[i]["genre"] for i in indices).items()))
86
+
87
+
88
+ def prepare(args: argparse.Namespace) -> None:
89
+ dataset, checkpoint, output = Path(args.dataset), Path(args.checkpoint), Path(args.output_dir)
90
+ output.mkdir(parents=True, exist_ok=True)
91
+ rows, molecules = load_index(dataset)
92
+ by_index = {row["source_index"]: row for row in rows}
93
+ split_specs = []
94
+ wanted: dict[int, tuple[str, str]] = {}
95
+ for seed in args.seeds:
96
+ train, test, excluded = split_indices(rows, molecules, seed, args.train_ratio)
97
+ train_counts, test_counts = counts(by_index, train), counts(by_index, test)
98
+ genres = sorted(set(train_counts) | set(test_counts))
99
+ if any(train_counts.get(g, 0) < args.minimum_per_genre or test_counts.get(g, 0) < args.minimum_per_genre for g in genres):
100
+ raise SystemExit(f"seed {seed} fails minimum-per-genre={args.minimum_per_genre}: train={train_counts}, test={test_counts}")
101
+ name = f"seed_{seed}"
102
+ train_path, test_path = output / f"{name}_train.jsonl", output / f"{name}_test.jsonl"
103
+ for index in train:
104
+ wanted[index] = wanted.get(index, ("", ""))
105
+ split_specs.append((name, seed, train, test, excluded, train_path, test_path, train_counts, test_counts))
106
+
107
+ # Stream the large source once and write compact benchmark records.
108
+ handles = {}
109
+ memberships: dict[int, list[tuple[Path, str]]] = {}
110
+ for _name, _seed, train, test, _excluded, train_path, test_path, _tc, _vc in split_specs:
111
+ handles[train_path] = train_path.open("w", encoding="utf-8")
112
+ handles[test_path] = test_path.open("w", encoding="utf-8")
113
+ for i in train:
114
+ memberships.setdefault(i, []).append((train_path, "train"))
115
+ for i in test:
116
+ memberships.setdefault(i, []).append((test_path, "test"))
117
+ with dataset.open(encoding="utf-8") as source:
118
+ for index, line in enumerate(source):
119
+ if index not in memberships:
120
+ continue
121
+ row = json.loads(line)
122
+ row["source_index"] = index
123
+ encoded = json.dumps(lean_row(row), sort_keys=True, separators=(",", ":")) + "\n"
124
+ for path, _partition in memberships[index]:
125
+ handles[path].write(encoded)
126
+ for handle in handles.values():
127
+ handle.close()
128
+
129
+ manifest, audits = [], []
130
+ for name, seed, train, test, excluded, train_path, test_path, train_counts, test_counts in split_specs:
131
+ manifest.append({
132
+ "name": name,
133
+ "seed": seed,
134
+ "train_records": str(train_path),
135
+ "test_records": str(test_path),
136
+ "learned_train": str(output / f"{name}_train_embeddings.npy"),
137
+ "learned_test": str(output / f"{name}_test_embeddings.npy"),
138
+ })
139
+ audits.append({
140
+ "name": name, "seed": seed, "train_records": len(train), "test_records": len(test),
141
+ "excluded_records": len(excluded), "train_genres": train_counts, "test_genres": test_counts,
142
+ "minimum_per_genre": args.minimum_per_genre, "coverage_passed": True,
143
+ })
144
+ manifest_path = output / "genre_split_manifest.json"
145
+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
146
+ commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
147
+ protocol = {
148
+ "protocol_version": 1,
149
+ "status": "frozen_before_embedding_export_and_benchmark",
150
+ "dataset": {"path": str(dataset), "sha256": sha256(dataset), "records": len(rows)},
151
+ "checkpoint": {"path": str(checkpoint), "sha256": sha256(checkpoint)},
152
+ "git_commit": commit,
153
+ "split": {"method": "active-molecule assignment; mixed-boundary formulas excluded", "train_ratio": args.train_ratio,
154
+ "seeds": args.seeds, "minimum_records_per_genre_per_partition": args.minimum_per_genre},
155
+ "benchmark": {"probe": "training-standardized nearest centroid", "bootstrap_samples": 10000,
156
+ "bootstrap_seed": 8675309, "minimum_valid_splits": 3, "required_margin": 0.0,
157
+ "decision": "support iff every valid split has paired CI95 lower bound > required_margin"},
158
+ "manifest": str(manifest_path),
159
+ "coverage_audit": audits,
160
+ }
161
+ (output / "frozen_protocol.json").write_text(json.dumps(protocol, indent=2) + "\n")
162
+ print(json.dumps(protocol, indent=2))
163
+
164
+
165
+ def pooled_embedding(model, item, torch):
166
+ tokens = item["tokens"].unsqueeze(0)
167
+ states = item["physics"].unsqueeze(0)
168
+ with torch.inference_mode():
169
+ latent = model(tokens, states)
170
+ return latent.mean(dim=(1, 2)).squeeze(0).cpu().numpy().astype(np.float32)
171
+
172
+
173
+ def export(args: argparse.Namespace) -> None:
174
+ import torch
175
+ from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
176
+
177
+ protocol_path = Path(args.protocol)
178
+ protocol = json.loads(protocol_path.read_text())
179
+ dataset, checkpoint = Path(protocol["dataset"]["path"]), Path(protocol["checkpoint"]["path"])
180
+ if sha256(dataset) != protocol["dataset"]["sha256"] or sha256(checkpoint) != protocol["checkpoint"]["sha256"]:
181
+ raise SystemExit("frozen dataset or checkpoint hash mismatch")
182
+ manifest = json.loads(Path(protocol["manifest"]).read_text())
183
+ needed = set()
184
+ for split in manifest:
185
+ for key in ("train_records", "test_records"):
186
+ with Path(split[key]).open() as handle:
187
+ needed.update(json.loads(line)["source_index"] for line in handle if line.strip())
188
+
189
+ state = torch.load(checkpoint, map_location="cpu", weights_only=False)["model_state_dict"]
190
+ hidden = state["input_proj.weight"].shape[0]
191
+ layers = len({key.split(".")[2] for key in state if key.startswith("encoder.layers.")})
192
+ model = PhysicsInformedMixtureTransformer(embedding_dim=151, state_dim=2, hidden_dim=hidden, num_heads=4, num_layers=layers)
193
+ model.load_state_dict(state)
194
+ model.eval()
195
+ embeddings: dict[int, np.ndarray] = {}
196
+ with dataset.open(encoding="utf-8") as source:
197
+ for index, line in enumerate(source):
198
+ if index not in needed:
199
+ continue
200
+ row = json.loads(line)
201
+ ds = FragranceTrajectoryDataset(data_path=None, records=[row], state_dim=2, use_embedding_fallback=True, label_noise=False)
202
+ embeddings[index] = pooled_embedding(model, ds[0], torch)
203
+ if len(embeddings) % 100 == 0:
204
+ print(f"exported {len(embeddings)}/{len(needed)} unique rows", flush=True)
205
+ if embeddings.keys() != needed:
206
+ raise SystemExit(f"missing {len(needed - embeddings.keys())} source rows")
207
+ for split in manifest:
208
+ for partition in ("train", "test"):
209
+ record_path = Path(split[f"{partition}_records"])
210
+ indices = [json.loads(line)["source_index"] for line in record_path.open() if line.strip()]
211
+ np.save(split[f"learned_{partition}"], np.stack([embeddings[i] for i in indices]))
212
+ protocol["status"] = "embeddings_exported_benchmark_not_run"
213
+ protocol["embedding_export"] = {"pooling": "unmasked mean over time and active ingredient tokens", "dimension": hidden,
214
+ "unique_records": len(embeddings)}
215
+ protocol_path.write_text(json.dumps(protocol, indent=2) + "\n")
216
+
217
+
218
+ def main() -> None:
219
+ parser = argparse.ArgumentParser()
220
+ sub = parser.add_subparsers(dest="command", required=True)
221
+ prep = sub.add_parser("prepare")
222
+ prep.add_argument("--dataset", required=True); prep.add_argument("--checkpoint", required=True); prep.add_argument("--output-dir", required=True)
223
+ prep.add_argument("--seeds", type=int, nargs="+", default=[1729, 2718, 3141]); prep.add_argument("--train-ratio", type=float, default=.85)
224
+ prep.add_argument("--minimum-per-genre", type=int, default=5); prep.set_defaults(func=prepare)
225
+ exp = sub.add_parser("export"); exp.add_argument("--protocol", required=True); exp.set_defaults(func=export)
226
+ args = parser.parse_args(); args.func(args)
227
+
228
+
229
+ if __name__ == "__main__":
230
+ main()
scripts/pimt_v11_5_corrected_baseline.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Write the post-review, coverage-stratified v11.5 retrieval baseline."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from collections import Counter
8
+ from pathlib import Path
9
+
10
+ ROOT = Path(__file__).resolve().parents[1]
11
+ sys.path.insert(0, str(ROOT / "src"))
12
+ from pino.substitution_v11 import ( # noqa: E402
13
+ evaluate_retriever, load_jsonl, normalize_name, profile_key, profile_lookup, substitute,
14
+ )
15
+
16
+ OUT_JSON = ROOT / "artifacts/pimt_v11_5_corrected_coverage_baseline.json"
17
+ OUT_MD = ROOT / "artifacts/pimt_v11_5_corrected_coverage_baseline.md"
18
+
19
+
20
+ def overlap(a: dict, b: dict) -> list[str]:
21
+ fields = []
22
+ if a.get("descriptor_distribution") and b.get("descriptor_distribution"): fields.append("odor")
23
+ if a.get("substantivity_log10_predicted") is not None and b.get("substantivity_log10_predicted") is not None: fields.append("substantivity")
24
+ if a.get("log10_vapor_pressure_pa") is not None and b.get("log10_vapor_pressure_pa") is not None: fields.append("volatility")
25
+ return fields
26
+
27
+
28
+ def main() -> None:
29
+ profiles = load_jsonl(ROOT / "data/material_profiles_v11_5.jsonl")
30
+ rows = [row for row in load_jsonl(ROOT / "data/substitution_eval_set_v11_3.jsonl") if row.get("answer_shape") == "one_to_one"]
31
+ result = evaluate_retriever(rows, profiles, top_k=5)
32
+ lookup = profile_lookup(profiles)
33
+ by_id = {row["pair_id"]: row for row in rows}
34
+ details = []
35
+ for item in result["evaluated"]:
36
+ row = by_id[item["pair_id"]]
37
+ target = lookup.get(str(row.get("target_cas") or row.get("target"))) or lookup.get(normalize_name(row.get("target")))
38
+ answer_item = row["answer"]["materials"][0]
39
+ answer = lookup.get(str(answer_item.get("cas") or answer_item.get("name"))) or lookup.get(normalize_name(answer_item.get("name")))
40
+ ranked = substitute(str(row.get("target_cas") or row.get("target")), profiles, mode=row["mode"], top_k=len(profiles))
41
+ answer_key = profile_key(answer)
42
+ rank = next((i for i, candidate in enumerate(ranked, 1) if profile_key(lookup.get(str(candidate.get("candidate_cas"))) or lookup[normalize_name(candidate["candidate"])]) == answer_key), None)
43
+ details.append({"pair_id": item["pair_id"], "mode": row["mode"], "rank": rank, "hit_top_5": bool(rank and rank <= 5), "shared_features": overlap(target, answer), "shared_feature_count": len(overlap(target, answer))})
44
+ strata = {}
45
+ for count in sorted({x["shared_feature_count"] for x in details}):
46
+ subset = [x for x in details if x["shared_feature_count"] == count]
47
+ strata[str(count)] = {"n": len(subset), "top_5_hits": sum(x["hit_top_5"] for x in subset), "median_rank": sorted(x["rank"] for x in subset)[len(subset)//2]}
48
+ report = {
49
+ "status": "not_training_ready", "n_rows": len(rows), "n_rankable": result["n_evaluable"],
50
+ "n_top_5_hits": result["n_hit"], "top_5": result["top_k_hit"],
51
+ "exclusion_reasons": dict(Counter(x["reason"] for x in result["excluded"])),
52
+ "coverage_strata": strata, "evaluated": details, "excluded": result["excluded"],
53
+ "identity_audit": "self-resolved target/answer rows excluded; Neofolione CAS 111-79-5 collision corrected",
54
+ "mode_policy": "cost/regulatory rows are unsupported until independently sourced mode fields exist",
55
+ }
56
+ OUT_JSON.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
57
+ lines = ["# PIMT v11.5 corrected coverage-stratified baseline", "", f"Status: **{report['status']}**", "", f"Rankable one-to-one rows: **{report['n_rankable']}/{report['n_rows']}**; top-5 hits: **{report['n_top_5_hits']}**.", "", "## Exclusions", ""]
58
+ lines += [f"- {reason}: {count}" for reason, count in sorted(report["exclusion_reasons"].items())]
59
+ lines += ["", "## Coverage strata", "", "| Shared observed features | n | Top-5 hits | Median rank |", "|---:|---:|---:|---:|"]
60
+ lines += [f"| {count} | {value['n']} | {value['top_5_hits']} | {value['median_rank']} |" for count, value in strata.items()]
61
+ lines += ["", "Cost and regulatory rows are reported as unsupported, not model misses. No training was run.", ""]
62
+ OUT_MD.write_text("\n".join(lines))
63
+ print(json.dumps({"n_rankable": report["n_rankable"], "top_5_hits": report["n_top_5_hits"], "exclusions": report["exclusion_reasons"]}, indent=2))
64
+
65
+
66
+ if __name__ == "__main__": main()
scripts/pimt_v11_5_pretraining_corrections.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Apply audited identity corrections found by the v11.5 pre-training review."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from rdkit import Chem
9
+ from rdkit.Chem import Descriptors, Lipinski, rdMolDescriptors
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ PROFILES = ROOT / "data/material_profiles_v11_5.jsonl"
13
+ AUDIT = ROOT / "artifacts/pimt_v11_5_pretraining_corrections.json"
14
+ NEOFOLIONE_SMILES = "CCCCCC/C=C/C(=O)OC"
15
+
16
+
17
+ def structure_fields(smiles: str) -> dict:
18
+ mol = Chem.MolFromSmiles(smiles)
19
+ if mol is None:
20
+ raise RuntimeError(f"invalid corrected SMILES: {smiles}")
21
+ return {
22
+ "smiles": smiles,
23
+ "molecular_weight": Descriptors.MolWt(mol),
24
+ "logp": Descriptors.MolLogP(mol),
25
+ "functional_groups": {
26
+ "heavy_atoms": float(mol.GetNumHeavyAtoms()),
27
+ "h_acceptors": float(Lipinski.NumHAcceptors(mol)),
28
+ "h_donors": float(Lipinski.NumHDonors(mol)),
29
+ "rotatable_bonds": float(Lipinski.NumRotatableBonds(mol)),
30
+ "tpsa": rdMolDescriptors.CalcTPSA(mol),
31
+ "fraction_csp3": rdMolDescriptors.CalcFractionCSP3(mol),
32
+ },
33
+ }
34
+
35
+
36
+ def main() -> None:
37
+ rows = [json.loads(line) for line in PROFILES.read_text(encoding="utf-8").splitlines() if line]
38
+ changed = []
39
+ for row in rows:
40
+ if row.get("cas") != "111-79-5":
41
+ continue
42
+ before = {
43
+ "name": row.get("name"), "aliases": row.get("aliases"),
44
+ "smiles": row.get("smiles"), "logp": row.get("logp"),
45
+ "substantivity_log10_predicted": row.get("substantivity_log10_predicted"),
46
+ }
47
+ row["name"] = "Neofolione"
48
+ row["aliases"] = sorted({
49
+ "Neofolione", "Methyl 2-nonenoate", "Methyl non-2-enoate",
50
+ *(alias for alias in row.get("aliases", []) if "habanolide" not in alias.lower()),
51
+ })
52
+ row["identity_correction_v11_5"] = {
53
+ "reason": "CAS 111-79-5 and the verified acyclic C10H18O2 structure are methyl 2-nonenoate (Neofolione), not Habanolide",
54
+ "evidence": [
55
+ "local TGSC exact-CAS cache rw1015351",
56
+ "existing PubChem CID 5368076 identity validation",
57
+ ],
58
+ }
59
+ row.update(structure_fields(NEOFOLIONE_SMILES))
60
+ row["field_provenance"] = {
61
+ **(row.get("field_provenance") or {}),
62
+ "smiles": {"source": "PubChem", "cid": 5368076, "tier": "computed"},
63
+ "molecular_weight": {"source": "RDKit from corrected PubChem SMILES", "tier": "computed"},
64
+ "logp": {"source": "RDKit from corrected PubChem SMILES", "tier": "computed"},
65
+ "functional_groups": {"source": "RDKit from corrected PubChem SMILES", "tier": "computed"},
66
+ }
67
+ # The old prediction used the stale lactone structure. It must not survive
68
+ # the identity repair; a future model rebuild can safely recompute it.
69
+ row["substantivity_log10_predicted"] = None
70
+ row["substantivity_model"] = "pending_recompute_after_identity_correction"
71
+ changed.append({
72
+ "profile_id": row.get("profile_id"), "before": before,
73
+ "after": {
74
+ "name": row["name"], "aliases": row["aliases"],
75
+ "smiles": row["smiles"], "logp": row["logp"],
76
+ "substantivity_log10_predicted": row["substantivity_log10_predicted"],
77
+ },
78
+ })
79
+ if len(changed) != 1:
80
+ raise RuntimeError(f"expected one CAS 111-79-5 profile, found {len(changed)}")
81
+ PROFILES.write_text("".join(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n" for row in rows), encoding="utf-8")
82
+ AUDIT.write_text(json.dumps({"changed_profiles": changed}, indent=2, sort_keys=True) + "\n", encoding="utf-8")
83
+ print(json.dumps({"changed": len(changed), "audit": str(AUDIT.relative_to(ROOT))}))
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
scripts/pimt_v11_6_compliant_repair.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compliant-repair pipeline for formulas containing banned/IFRA-restricted materials.
3
+
4
+ For every formula in the Fraterworks + Appell corpora that contains a material
5
+ on the curated banned list, this:
6
+
7
+ 1. Classifies the banned material (lyral / lilial / musk xylene / musk ketone / oakmoss).
8
+ 2. Selects a compliant substitute from a curated candidate list, using the v11.6
9
+ substitution engine to rank candidates, with a HARD compliance filter:
10
+ - reject any candidate that is itself on the banned list (by name or CAS);
11
+ - reject any candidate in the SAME banned class (no musk-ketone -> musk-xylene);
12
+ - prefer IFRA-unrestricted (listed/None) candidates over IFRA-restricted ones;
13
+ an IFRA-restricted candidate is only used when no unrestricted one ranks,
14
+ and is flagged `compliance_tier="ifra_restricted"`.
15
+ 3. Writes a repaired formula (original + repair) with full provenance.
16
+ 4. Emits a repair-pair substitution benchmark (banned -> compliant, documented).
17
+
18
+ Outputs:
19
+ data/repaired_formulas_v11_6.jsonl original + repaired, paired
20
+ data/benchmarks/repair_pairs/repair_pairs.jsonl substitution benchmark
21
+ artifacts/pimt_v11_6_compliant_repair.json report
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import collections
26
+ import json
27
+ import math
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ ROOT = Path(__file__).resolve().parents[1]
32
+ sys.path.insert(0, str(ROOT / "src"))
33
+ from pino.substitution_v11 import ( # noqa: E402
34
+ normalize_name, profile_lookup, score_candidate, profile_key,
35
+ )
36
+
37
+ PROFILES = ROOT / "data" / "material_profiles_v11_6.jsonl"
38
+ SOURCES = {
39
+ "fraterworks": ROOT / "data" / "fraterworks_free_formulas.jsonl",
40
+ "appell": ROOT / "data" / "appell_formulas_enriched.jsonl",
41
+ }
42
+ OUT_FORMULAS = ROOT / "data" / "repaired_formulas_v11_6.jsonl"
43
+ OUT_BENCH_DIR = ROOT / "data" / "benchmarks" / "repair_pairs"
44
+ OUT_BENCH = OUT_BENCH_DIR / "repair_pairs.jsonl"
45
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_compliant_repair.json"
46
+
47
+ # ---- Curated banned list: name-aliases -> class, with CAS where known ----
48
+ BANNED = {
49
+ "lyral": {"aliases": ["lyral", "hydroxyisohexyl 3-cyclohexene carboxaldehyde", "hicc", "hmpcc"], "cas": {"31906-04-4"}},
50
+ "lilial": {"aliases": ["lilial", "butylphenyl methylpropional", "bmhca", "lysmeral"], "cas": {"80-54-6"}},
51
+ "musk xylene": {"aliases": ["musk xylene", "musk xylol"], "cas": {"81-15-2"}},
52
+ "musk ketone": {"aliases": ["musk ketone"], "cas": {"81-14-1"}},
53
+ "oakmoss": {"aliases": ["oakmoss", "evernia prunastri", "atranol", "chloroatranol"], "cas": {"90028-68-5"}},
54
+ }
55
+ BANNED_CAS = {c for v in BANNED.values() for c in v["cas"]}
56
+ BANNED_ALIAS = {a: cls for cls, v in BANNED.items() for a in v["aliases"]}
57
+
58
+ # ---- Curated compliant candidates per banned class (preference order) ----
59
+ # IFRA-unrestricted (status listed/None) preferred; restricted ones are fallback.
60
+ CANDIDATES = {
61
+ "lyral": ["hydroxycitronellal", "cyclamen aldehyde", "florhydral", "bourgeonal", "muguet aldehyde"],
62
+ "lilial": ["hydroxycitronellal", "cyclamen aldehyde", "florhydral", "bourgeonal", "lilyflore"],
63
+ "musk xylene": ["galaxolide", "ethylene brassylate", "habanolide", "ambrettolide", "muscone", "exaltolide"],
64
+ "musk ketone": ["galaxolide", "ethylene brassylate", "habanolide", "ambrettolide", "muscone", "celestolide"],
65
+ "oakmoss": ["fauxmoss", "evernyl"],
66
+ }
67
+
68
+
69
+ def base_cas(value):
70
+ import re
71
+ m = re.match(r"\s*(\d{2,7}-\d{2}-\d)", str(value or ""))
72
+ return m.group(1) if m else None
73
+
74
+
75
+ def banned_class_of(name, cas):
76
+ k = normalize_name(name)
77
+ for alias, cls in BANNED_ALIAS.items():
78
+ if alias in k:
79
+ return cls
80
+ bc = base_cas(cas)
81
+ if bc and bc in BANNED_CAS:
82
+ for cls, v in BANNED.items():
83
+ if bc in v["cas"]:
84
+ return cls
85
+ return None
86
+
87
+
88
+ def is_banned(profile, own_class=None):
89
+ """Hard filter: True if the candidate is itself banned (any class), and
90
+ specifically if it falls in the same banned class as the target."""
91
+ name_k = normalize_name(profile.get("name"))
92
+ cas = base_cas(profile.get("cas"))
93
+ cand_cls = banned_class_of(profile.get("name"), profile.get("cas"))
94
+ if cand_cls is None and cas:
95
+ cand_cls = banned_class_of("", cas)
96
+ if cand_cls is None:
97
+ # also check aliases on the profile
98
+ for a in (profile.get("aliases") or []):
99
+ cand_cls = banned_class_of(a, None)
100
+ if cand_cls:
101
+ break
102
+ if cand_cls is None:
103
+ return False, None
104
+ # banned outright; always reject. own_class tracked for the report.
105
+ return True, cand_cls
106
+
107
+
108
+ def pick_substitute(target_profile, banned_cls, lookup, profiles):
109
+ """Rank curated candidates with the engine, apply compliance filter, prefer
110
+ IFRA-unrestricted. Returns (profile, tier, score) or (None, None, None)."""
111
+ scored = []
112
+ for cand_name in CANDIDATES.get(banned_cls, []):
113
+ cand = lookup.get(normalize_name(cand_name))
114
+ if cand is None:
115
+ continue
116
+ banned, cand_cls = is_banned(cand, banned_cls)
117
+ if banned:
118
+ continue # hard reject: never substitute a banned material
119
+ if profile_key(cand) == profile_key(target_profile):
120
+ continue
121
+ s = score_candidate(target_profile, cand, mode="regulatory_match")
122
+ if s["score"] < 0:
123
+ continue
124
+ ifra = (cand.get("ifra_restrictions") or {}).get("category_4_limit_percent")
125
+ tier = "ifra_unrestricted" if ifra is None else "ifra_restricted"
126
+ scored.append({"profile": cand, "tier": tier, "score": s["score"], "ifra": ifra})
127
+ if not scored:
128
+ return None, None, None
129
+ # prefer unrestricted tier, then by score
130
+ scored.sort(key=lambda x: (0 if x["tier"] == "ifra_unrestricted" else 1, -x["score"],
131
+ str(x["profile"].get("cas") or "")))
132
+ best = scored[0]
133
+ return best["profile"], best["tier"], best["score"]
134
+
135
+
136
+ def main() -> int:
137
+ profiles = [json.loads(l) for l in PROFILES.open(encoding="utf-8")]
138
+ lookup = profile_lookup(profiles)
139
+
140
+ stats = collections.Counter()
141
+ repair_pairs = []
142
+ out_formulas = []
143
+ per_banned = collections.Counter()
144
+
145
+ for src, path in SOURCES.items():
146
+ if not path.exists():
147
+ continue
148
+ for line in path.open(encoding="utf-8"):
149
+ try:
150
+ rec = json.loads(line)
151
+ except json.JSONDecodeError:
152
+ continue
153
+ formula = rec.get("formula") or rec.get("ingredients") or []
154
+ if not formula:
155
+ continue
156
+ banned_hits = []
157
+ for idx, ing in enumerate(formula):
158
+ cls = banned_class_of(ing.get("name"), ing.get("cas"))
159
+ if cls:
160
+ banned_hits.append((idx, cls, ing))
161
+ stats[f"formulas_scanned_{src}"] += 1
162
+ if not banned_hits:
163
+ continue
164
+ stats[f"formulas_with_banned_{src}"] += 1
165
+
166
+ repaired_formula = [dict(ing) for ing in formula]
167
+ repairs = []
168
+ all_ok = True
169
+ for idx, cls, ing in banned_hits:
170
+ per_banned[cls] += 1
171
+ target = lookup.get(str(ing.get("cas"))) or lookup.get(normalize_name(ing.get("name")))
172
+ if target is None:
173
+ all_ok = False
174
+ repairs.append({"banned": ing.get("name"), "class": cls, "status": "target_not_in_profiles"})
175
+ stats["repair_target_missing"] += 1
176
+ continue
177
+ # Distinguish a genuine substitution from an identity correction:
178
+ # if the banned row's NAME resolves to a compliant profile whose CAS
179
+ # differs from the row's banned CAS, the source record is a mislabeled
180
+ # CAS (known supplier-data collision, e.g. "Veramoss" stored under
181
+ # oakmoss CAS 90028-68-5). Repair = keep the name, fix identity,
182
+ # substitute only if the compliant-named profile itself is unusable.
183
+ # Resolve the row's NAME to a COMPLIANT profile. The primary name
184
+ # lookup can land on a banned-CAS profile because of cross-identity
185
+ # alias pollution (e.g. "Veramoss" listed as an alias of Oakmoss
186
+ # absolute). When that happens, prefer a same-named alternative whose
187
+ # CAS is NOT banned — that is the compliant material the source meant.
188
+ name_profile = None
189
+ row_cas = base_cas(ing.get("cas"))
190
+ candidates_by_name = [
191
+ p for p in profiles
192
+ if normalize_name(p.get("name")) == normalize_name(ing.get("name"))
193
+ or normalize_name(ing.get("name")) in {normalize_name(a) for a in (p.get("aliases") or [])}
194
+ ]
195
+ # prefer same-named profile with a compliant CAS
196
+ for p in candidates_by_name:
197
+ p_cas = base_cas(p.get("cas"))
198
+ if p_cas and p_cas not in BANNED_CAS:
199
+ name_profile = p
200
+ break
201
+ if name_profile is None and candidates_by_name:
202
+ name_profile = candidates_by_name[0]
203
+ name_cas = base_cas(name_profile.get("cas")) if name_profile else None
204
+ is_identity_correction = bool(
205
+ name_profile is not None
206
+ and row_cas and row_cas in BANNED_CAS
207
+ and name_cas and name_cas not in BANNED_CAS
208
+ and name_cas != row_cas
209
+ )
210
+ repair_kind = "identity_correction" if is_identity_correction else "substitution"
211
+ sub, tier, score = pick_substitute(target, cls, lookup, profiles)
212
+ if sub is None:
213
+ all_ok = False
214
+ repairs.append({"banned": ing.get("name"), "class": cls, "status": "no_compliant_substitute"})
215
+ stats["repair_no_substitute"] += 1
216
+ continue
217
+ # apply repair. For identity corrections the compliant substitute IS
218
+ # the correctly-identified material (name kept, CAS corrected); for
219
+ # true substitutions it is the ranked compliant alternative.
220
+ final_cas = name_cas if is_identity_correction else sub.get("cas")
221
+ final_name = (name_profile.get("name") if (is_identity_correction and name_profile is not None) else sub.get("name"))
222
+ repaired_formula[idx] = {
223
+ "name": final_name,
224
+ "cas": final_cas,
225
+ "weight_fraction": ing.get("weight_fraction"),
226
+ "replaces": ing.get("name"),
227
+ }
228
+ repairs.append({
229
+ "banned": ing.get("name"), "banned_cas": ing.get("cas"), "class": cls,
230
+ "repair_kind": repair_kind,
231
+ "substitute": final_name, "substitute_cas": final_cas,
232
+ "compliance_tier": tier, "engine_score": score,
233
+ "weight_fraction": ing.get("weight_fraction"), "status": "repaired",
234
+ })
235
+ stats["repaired"] += 1
236
+ stats[f"repaired_{repair_kind}"] += 1
237
+ repair_pairs.append({
238
+ "pair_id": f"repair_{src}_{stats['repaired']:04d}",
239
+ "source": src,
240
+ "banned_material": ing.get("name"),
241
+ "banned_cas": ing.get("cas"),
242
+ "banned_class": cls,
243
+ "repair_kind": repair_kind,
244
+ "substitute": final_name,
245
+ "substitute_cas": final_cas,
246
+ "compliance_tier": tier,
247
+ "weight_fraction": ing.get("weight_fraction"),
248
+ "rationale": (
249
+ f"{cls}: source CAS {ing.get('cas')} mislabels compliant material; "
250
+ f"identity corrected to {final_name} (CAS {final_cas})"
251
+ if is_identity_correction else
252
+ f"{cls} banned/IFRA-restricted; replaced with compliant {final_name}"
253
+ ),
254
+ "provenance": "compliant-repair-v11.6",
255
+ "eval_only": True,
256
+ })
257
+
258
+ out_formulas.append({
259
+ "source": src,
260
+ "original_formula": formula,
261
+ "repaired_formula": repaired_formula,
262
+ "repairs": repairs,
263
+ "fully_repaired": all_ok and all(r["status"] == "repaired" for r in repairs),
264
+ "banned_classes": sorted({cls for _, cls, _ in banned_hits}),
265
+ "declared_profile": rec.get("declared_profile"),
266
+ "provenance": "compliant-repair-v11.6",
267
+ })
268
+
269
+ OUT_BENCH_DIR.mkdir(parents=True, exist_ok=True)
270
+ with OUT_FORMULAS.open("w", encoding="utf-8") as fh:
271
+ for r in out_formulas:
272
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
273
+ with OUT_BENCH.open("w", encoding="utf-8") as fh:
274
+ for r in repair_pairs:
275
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
276
+
277
+ # compliance self-check: assert no substitute is itself banned. Validate by the
278
+ # substitute's CAS (authoritative), falling back to name only when CAS is absent.
279
+ # Name-only lookup can false-positive on cross-identity alias pollution (e.g.
280
+ # "Veramoss IFF" CAS 4707-47-5 = compliant Evernyl, but "Veramoss" is also an
281
+ # alias of Oakmoss absolute) — the CAS check is the correct arbiter.
282
+ violations = []
283
+ for rp in repair_pairs:
284
+ sub_cas = base_cas(rp.get("substitute_cas"))
285
+ if sub_cas:
286
+ if sub_cas in BANNED_CAS:
287
+ violations.append({"pair_id": rp["pair_id"], "substitute": rp["substitute"],
288
+ "banned_cas": sub_cas, "via": "cas"})
289
+ else:
290
+ sub_prof = lookup.get(normalize_name(rp["substitute"]))
291
+ if sub_prof is not None:
292
+ banned, cls = is_banned(sub_prof)
293
+ if banned:
294
+ violations.append({"pair_id": rp["pair_id"], "substitute": rp["substitute"],
295
+ "banned_class": cls, "via": "name"})
296
+
297
+ report = {
298
+ "stats": dict(stats),
299
+ "per_banned_class": dict(per_banned),
300
+ "n_repair_pairs": len(repair_pairs),
301
+ "n_formulas_out": len(out_formulas),
302
+ "n_fully_repaired": sum(1 for r in out_formulas if r["fully_repaired"]),
303
+ "compliance_violations": violations,
304
+ "compliance_check_passed": not violations,
305
+ "tier_breakdown": dict(collections.Counter(rp["compliance_tier"] for rp in repair_pairs)),
306
+ "outputs": {"formulas": str(OUT_FORMULAS), "benchmark": str(OUT_BENCH)},
307
+ }
308
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
309
+ print(json.dumps(report, indent=2, sort_keys=True))
310
+ return 0
311
+
312
+
313
+ if __name__ == "__main__":
314
+ sys.exit(main())
scripts/pimt_v11_6_compliant_repair_all.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compliant-repair pipeline — full-corpus run (v11.6, all sources).
3
+
4
+ Extends pimt_v11_6_compliant_repair.py to every formula corpus with a per-source
5
+ adapter, and separates two policies:
6
+
7
+ repair corpora literature/historical formulas (fraterworks, appell, poucher,
8
+ literature_flat) — repaired formulas written out.
9
+ scan-only corpora live training sets (tgsc_demo, empirical v9+wisemoor) —
10
+ scanned and reported, but NOT rewritten: rewriting the active
11
+ training corpus is a training-data decision, not a default.
12
+
13
+ Same compliance guarantee as the Fraterworks run: substitute must not be banned
14
+ (name or CAS) nor in the same banned class; IFRA-unrestricted preferred.
15
+ Identity corrections (mislabeled CAS) kept distinct from true substitutions.
16
+
17
+ Outputs:
18
+ data/repaired_formulas_v11_6_all.jsonl repaired literature formulas
19
+ data/benchmarks/repair_pairs/repair_pairs_all.jsonl full repair-pair benchmark
20
+ artifacts/pimt_v11_6_compliant_repair_all.json report (incl. scan-only stats)
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import collections
25
+ import json
26
+ import re
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ ROOT = Path(__file__).resolve().parents[1]
31
+ sys.path.insert(0, str(ROOT / "src"))
32
+ from pino.substitution_v11 import ( # noqa: E402
33
+ normalize_name, profile_lookup, score_candidate, profile_key,
34
+ )
35
+
36
+ PROFILES = ROOT / "data" / "material_profiles_v11_6.jsonl"
37
+ OUT_FORMULAS = ROOT / "data" / "repaired_formulas_v11_6_all.jsonl"
38
+ OUT_BENCH = ROOT / "data" / "benchmarks" / "repair_pairs" / "repair_pairs_all.jsonl"
39
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_compliant_repair_all.json"
40
+
41
+ BANNED = {
42
+ "lyral": {"aliases": ["lyral", "hydroxyisohexyl 3-cyclohexene carboxaldehyde", "hicc", "hmpcc"], "cas": {"31906-04-4"}},
43
+ "lilial": {"aliases": ["lilial", "butylphenyl methylpropional", "bmhca", "lysmeral"], "cas": {"80-54-6"}},
44
+ "musk xylene": {"aliases": ["musk xylene", "musk xylol"], "cas": {"81-15-2"}},
45
+ "musk ketone": {"aliases": ["musk ketone"], "cas": {"81-14-1"}},
46
+ "oakmoss": {"aliases": ["oakmoss", "evernia prunastri", "atranol", "chloroatranol"], "cas": {"90028-68-5"}},
47
+ }
48
+ BANNED_CAS = {c for v in BANNED.values() for c in v["cas"]}
49
+ BANNED_ALIAS = {a: cls for cls, v in BANNED.items() for a in v["aliases"]}
50
+ CANDIDATES = {
51
+ "lyral": ["hydroxycitronellal", "cyclamen aldehyde", "florhydral", "bourgeonal", "muguet aldehyde"],
52
+ "lilial": ["hydroxycitronellal", "cyclamen aldehyde", "florhydral", "bourgeonal", "lilyflore"],
53
+ "musk xylene": ["galaxolide", "ethylene brassylate", "habanolide", "ambrettolide", "muscone", "exaltolide"],
54
+ "musk ketone": ["galaxolide", "ethylene brassylate", "habanolide", "ambrettolide", "muscone", "celestolide"],
55
+ "oakmoss": ["fauxmoss", "evernyl"],
56
+ }
57
+
58
+
59
+ def base_cas(value):
60
+ m = re.match(r"\s*(\d{2,7}-\d{2}-\d)", str(value or ""))
61
+ return m.group(1) if m else None
62
+
63
+
64
+ def banned_class_of(name, cas):
65
+ k = normalize_name(name)
66
+ for alias, cls in BANNED_ALIAS.items():
67
+ if alias in k:
68
+ return cls
69
+ bc = base_cas(cas)
70
+ if bc and bc in BANNED_CAS:
71
+ for cls, v in BANNED.items():
72
+ if bc in v["cas"]:
73
+ return cls
74
+ return None
75
+
76
+
77
+ def is_banned(profile):
78
+ cls = banned_class_of(profile.get("name"), profile.get("cas"))
79
+ if cls is None:
80
+ for a in (profile.get("aliases") or []):
81
+ cls = banned_class_of(a, None)
82
+ if cls:
83
+ break
84
+ return (cls is not None), cls
85
+
86
+
87
+ def pick_substitute(target_profile, banned_cls, lookup):
88
+ scored = []
89
+ for cand_name in CANDIDATES.get(banned_cls, []):
90
+ cand = lookup.get(normalize_name(cand_name))
91
+ if cand is None:
92
+ continue
93
+ banned, _ = is_banned(cand)
94
+ if banned or profile_key(cand) == profile_key(target_profile):
95
+ continue
96
+ s = score_candidate(target_profile, cand, mode="regulatory_match")
97
+ if s["score"] < 0:
98
+ continue
99
+ ifra = (cand.get("ifra_restrictions") or {}).get("category_4_limit_percent")
100
+ tier = "ifra_unrestricted" if ifra is None else "ifra_restricted"
101
+ scored.append({"profile": cand, "tier": tier, "score": s["score"], "ifra": ifra})
102
+ if not scored:
103
+ return None, None, None
104
+ scored.sort(key=lambda x: (0 if x["tier"] == "ifra_unrestricted" else 1, -x["score"], str(x["profile"].get("cas") or "")))
105
+ b = scored[0]
106
+ return b["profile"], b["tier"], b["score"]
107
+
108
+
109
+ def weight_of(item):
110
+ for k in ("weight_fraction", "amount", "parts", "quantity"):
111
+ if item.get(k) is not None:
112
+ return item[k]
113
+ return None
114
+
115
+
116
+ def normalize_ingredient(item):
117
+ """Return (name, cas, weight) from any ingredient schema."""
118
+ if not isinstance(item, dict):
119
+ return None, None, None
120
+ return item.get("name"), item.get("cas"), weight_of(item)
121
+
122
+
123
+ def iter_corpus(src):
124
+ """Yield (record, formula_list, policy) for each formula in a source."""
125
+ if src == "fraterworks":
126
+ path, policy, key = ROOT / "data" / "fraterworks_free_formulas.jsonl", "repair", "formula"
127
+ for line in path.open(encoding="utf-8"):
128
+ rec = json.loads(line)
129
+ yield rec, rec.get(key) or [], policy
130
+ elif src == "appell":
131
+ path, policy = ROOT / "data" / "appell_formulas_enriched.jsonl", "repair"
132
+ for line in path.open(encoding="utf-8"):
133
+ rec = json.loads(line)
134
+ yield rec, rec.get("components") or [], policy
135
+ elif src in ("poucher", "literature_flat", "appell_flat"):
136
+ paths = {
137
+ "poucher": ROOT / "data" / "literature_flat" / "poucher_formulas.jsonl",
138
+ "literature_flat": ROOT / "data" / "literature_flat" / "literature_formulas_raw.jsonl",
139
+ "appell_flat": ROOT / "data" / "appell_formulas_enriched_flat.jsonl",
140
+ }
141
+ for line in paths[src].open(encoding="utf-8"):
142
+ outer = json.loads(line)
143
+ rec_str = outer.get("record")
144
+ try:
145
+ rec = json.loads(rec_str) if isinstance(rec_str, str) else rec_str
146
+ except json.JSONDecodeError:
147
+ continue
148
+ if not isinstance(rec, dict):
149
+ continue
150
+ formula = rec.get("components") or rec.get("formula") or rec.get("ingredients") or []
151
+ yield rec, formula, "repair"
152
+ elif src == "tgsc_demo":
153
+ for line in (ROOT / "data" / "tgsc_demo_formulas_v2.jsonl").open(encoding="utf-8"):
154
+ rec = json.loads(line)
155
+ yield rec, rec.get("formula") or [], "scan_only"
156
+ elif src == "empirical":
157
+ for line in (ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.jsonl").open(encoding="utf-8"):
158
+ rec = json.loads(line)
159
+ yield rec, rec.get("formula") or [], "scan_only"
160
+
161
+
162
+ def main() -> int:
163
+ profiles = [json.loads(l) for l in PROFILES.open(encoding="utf-8")]
164
+ lookup = profile_lookup(profiles)
165
+
166
+ # NOTE: "appell_flat" is excluded — it is a 100% duplicate of "appell"
167
+ # (same 15 formula_ids), verified 2026-07-17; including it double-counts repairs.
168
+ sources = ["fraterworks", "appell", "poucher", "literature_flat", "tgsc_demo", "empirical"]
169
+ stats = collections.Counter()
170
+ per_banned = collections.Counter()
171
+ repair_pairs = []
172
+ out_formulas = []
173
+ seen_pair_keys = set() # dedupe identical (source, formula_id, banned, substitute)
174
+
175
+ for src in sources:
176
+ try:
177
+ corpus = list(iter_corpus(src))
178
+ except FileNotFoundError:
179
+ stats[f"{src}_missing"] += 1
180
+ continue
181
+ for rec, formula, policy in corpus:
182
+ stats[f"formulas_scanned_{src}"] += 1
183
+ # normalize ingredients
184
+ ings = []
185
+ for item in formula:
186
+ nm, cas, w = normalize_ingredient(item)
187
+ if nm:
188
+ ings.append({"name": nm, "cas": cas, "weight_fraction": w})
189
+ banned_hits = [(i, banned_class_of(x["name"], x["cas"]), x) for i, x in enumerate(ings)]
190
+ banned_hits = [(i, c, x) for i, c, x in banned_hits if c]
191
+ if not banned_hits:
192
+ continue
193
+ stats[f"formulas_with_banned_{src}"] += 1
194
+ fid = rec.get("formula_id") or rec.get("id") or rec.get("name") or f"{src}_{stats['formulas_scanned_' + src]}"
195
+
196
+ if policy == "scan_only":
197
+ for _, cls, ing in banned_hits:
198
+ per_banned[f"scanonly_{cls}"] += 1
199
+ stats[f"scanonly_banned_occurrences_{src}"] += 1
200
+ continue
201
+
202
+ repaired = [dict(x) for x in ings]
203
+ repairs = []
204
+ all_ok = True
205
+ for idx, cls, ing in banned_hits:
206
+ per_banned[cls] += 1
207
+ target = lookup.get(str(ing["cas"])) or lookup.get(normalize_name(ing["name"]))
208
+ if target is None:
209
+ all_ok = False
210
+ stats["repair_target_missing"] += 1
211
+ repairs.append({"banned": ing["name"], "class": cls, "status": "target_not_in_profiles"})
212
+ continue
213
+ # compliant-name resolution (CAS-aware; avoids alias pollution)
214
+ name_profile = None
215
+ by_name = [p for p in profiles
216
+ if normalize_name(p.get("name")) == normalize_name(ing["name"])
217
+ or normalize_name(ing["name"]) in {normalize_name(a) for a in (p.get("aliases") or [])}]
218
+ for p in by_name:
219
+ pc = base_cas(p.get("cas"))
220
+ if pc and pc not in BANNED_CAS:
221
+ name_profile = p
222
+ break
223
+ if name_profile is None and by_name:
224
+ name_profile = by_name[0]
225
+ row_cas = base_cas(ing["cas"])
226
+ name_cas = base_cas(name_profile.get("cas")) if name_profile else None
227
+ is_ident = bool(name_profile and row_cas in BANNED_CAS and name_cas
228
+ and name_cas not in BANNED_CAS and name_cas != row_cas)
229
+ sub, tier, score = pick_substitute(target, cls, lookup)
230
+ if sub is None:
231
+ all_ok = False
232
+ stats["repair_no_substitute"] += 1
233
+ repairs.append({"banned": ing["name"], "class": cls, "status": "no_compliant_substitute"})
234
+ continue
235
+ final_cas = name_cas if is_ident else sub.get("cas")
236
+ final_name = (name_profile.get("name") if (is_ident and name_profile) else sub.get("name"))
237
+ kind = "identity_correction" if is_ident else "substitution"
238
+ repaired[idx] = {"name": final_name, "cas": final_cas,
239
+ "weight_fraction": ing["weight_fraction"], "replaces": ing["name"]}
240
+ repairs.append({"banned": ing["name"], "banned_cas": ing["cas"], "class": cls,
241
+ "repair_kind": kind, "substitute": final_name, "substitute_cas": final_cas,
242
+ "compliance_tier": tier, "engine_score": score,
243
+ "weight_fraction": ing["weight_fraction"], "status": "repaired"})
244
+ stats["repaired"] += 1
245
+ stats[f"repaired_{kind}"] += 1
246
+ pk = (src, str(fid), normalize_name(ing["name"]), normalize_name(final_name))
247
+ if pk not in seen_pair_keys:
248
+ seen_pair_keys.add(pk)
249
+ repair_pairs.append({
250
+ "pair_id": f"repair_{src}_{len(repair_pairs)+1:04d}", "source": src,
251
+ "formula_id": fid, "banned_material": ing["name"], "banned_cas": ing["cas"],
252
+ "banned_class": cls, "repair_kind": kind, "substitute": final_name,
253
+ "substitute_cas": final_cas, "compliance_tier": tier,
254
+ "weight_fraction": ing["weight_fraction"],
255
+ "rationale": (f"{cls}: source CAS {ing['cas']} mislabels compliant material; "
256
+ f"identity corrected to {final_name} (CAS {final_cas})"
257
+ if is_ident else
258
+ f"{cls} banned/IFRA-restricted; replaced with compliant {final_name}"),
259
+ "provenance": "compliant-repair-v11.6", "eval_only": True,
260
+ })
261
+ out_formulas.append({
262
+ "source": src, "formula_id": fid, "name": rec.get("name"),
263
+ "original_formula": ings, "repaired_formula": repaired, "repairs": repairs,
264
+ "fully_repaired": all_ok and all(r["status"] == "repaired" for r in repairs),
265
+ "banned_classes": sorted({c for _, c, _ in banned_hits}),
266
+ "provenance": "compliant-repair-v11.6",
267
+ })
268
+
269
+ OUT_BENCH.parent.mkdir(parents=True, exist_ok=True)
270
+ with OUT_FORMULAS.open("w", encoding="utf-8") as fh:
271
+ for r in out_formulas:
272
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
273
+ with OUT_BENCH.open("w", encoding="utf-8") as fh:
274
+ for r in repair_pairs:
275
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
276
+
277
+ # compliance self-check by CAS (authoritative), name fallback
278
+ violations = []
279
+ for rp in repair_pairs:
280
+ sc = base_cas(rp.get("substitute_cas"))
281
+ if sc:
282
+ if sc in BANNED_CAS:
283
+ violations.append({"pair_id": rp["pair_id"], "substitute": rp["substitute"], "via": "cas"})
284
+ else:
285
+ sp = lookup.get(normalize_name(rp["substitute"]))
286
+ if sp is not None:
287
+ b, cls = is_banned(sp)
288
+ if b:
289
+ violations.append({"pair_id": rp["pair_id"], "substitute": rp["substitute"], "via": "name"})
290
+
291
+ report = {
292
+ "stats": dict(stats), "per_banned_class": dict(per_banned),
293
+ "n_repair_pairs": len(repair_pairs), "n_formulas_out": len(out_formulas),
294
+ "n_fully_repaired": sum(1 for r in out_formulas if r["fully_repaired"]),
295
+ "compliance_violations": violations, "compliance_check_passed": not violations,
296
+ "tier_breakdown": dict(collections.Counter(rp["compliance_tier"] for rp in repair_pairs)),
297
+ "repair_kind_breakdown": dict(collections.Counter(rp["repair_kind"] for rp in repair_pairs)),
298
+ "by_source": dict(collections.Counter(rp["source"] for rp in repair_pairs)),
299
+ "outputs": {"formulas": str(OUT_FORMULAS), "benchmark": str(OUT_BENCH)},
300
+ "scan_only_policy": "tgsc_demo + empirical scanned and reported, not rewritten (training-data decision)",
301
+ }
302
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
303
+ print(json.dumps(report, indent=2, sort_keys=True))
304
+ return 0
305
+
306
+
307
+ if __name__ == "__main__":
308
+ sys.exit(main())
scripts/pimt_v11_6_corrected_baseline.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Write the v11.6 corrected, coverage-stratified retrieval baseline.
3
+
4
+ Uses the Molequles-enriched profile table (material_profiles_v11_6.jsonl) and the
5
+ evidence-floor-aware evaluator. Reports headline top-5 both over all evaluable
6
+ rows and restricted to the trustworthy (>=2 observed components) subset, plus
7
+ per-row ranks and coverage strata, so gains from enrichment are attributable.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from collections import Counter
14
+ from pathlib import Path
15
+
16
+ ROOT = Path(__file__).resolve().parents[1]
17
+ sys.path.insert(0, str(ROOT / "src"))
18
+ from pino.substitution_v11 import ( # noqa: E402
19
+ evaluate_retriever, load_jsonl, normalize_name, profile_key, profile_lookup, substitute,
20
+ )
21
+
22
+ OUT_JSON = ROOT / "artifacts/pimt_v11_6_corrected_coverage_baseline.json"
23
+ OUT_MD = ROOT / "artifacts/pimt_v11_6_corrected_coverage_baseline.md"
24
+
25
+
26
+ def overlap(a: dict, b: dict) -> list[str]:
27
+ fields = []
28
+ if a.get("descriptor_distribution") and b.get("descriptor_distribution"): fields.append("odor")
29
+ if a.get("substantivity_log10_predicted") is not None and b.get("substantivity_log10_predicted") is not None: fields.append("substantivity")
30
+ if a.get("log10_vapor_pressure_pa") is not None and b.get("log10_vapor_pressure_pa") is not None: fields.append("volatility")
31
+ return fields
32
+
33
+
34
+ def main() -> None:
35
+ profiles = load_jsonl(ROOT / "data/material_profiles_v11_6.jsonl")
36
+ rows = [row for row in load_jsonl(ROOT / "data/substitution_eval_set_v11_3.jsonl") if row.get("answer_shape") == "one_to_one"]
37
+ result = evaluate_retriever(rows, profiles, top_k=5)
38
+ lookup = profile_lookup(profiles)
39
+ by_id = {row["pair_id"]: row for row in rows}
40
+ details = []
41
+ for item in result["evaluated"]:
42
+ row = by_id[item["pair_id"]]
43
+ target = lookup.get(str(row.get("target_cas") or row.get("target"))) or lookup.get(normalize_name(row.get("target")))
44
+ answer_item = row["answer"]["materials"][0]
45
+ answer = lookup.get(str(answer_item.get("cas") or answer_item.get("name"))) or lookup.get(normalize_name(answer_item.get("name")))
46
+ ranked = substitute(str(row.get("target_cas") or row.get("target")), profiles, mode=row["mode"], top_k=len(profiles))
47
+ answer_key = profile_key(answer)
48
+ rank = next(
49
+ (
50
+ i for i, candidate in enumerate(ranked, 1)
51
+ if profile_key(
52
+ lookup.get(str(candidate.get("candidate_cas")))
53
+ or lookup[normalize_name(candidate["candidate"])]
54
+ ) == answer_key
55
+ ),
56
+ None,
57
+ )
58
+ details.append({
59
+ "pair_id": item["pair_id"],
60
+ "mode": row["mode"],
61
+ "rank": rank,
62
+ "hit_top_5": bool(rank and rank <= 5),
63
+ "shared_features": overlap(target, answer),
64
+ "shared_feature_count": len(overlap(target, answer)),
65
+ "answer_observed_components": item.get("answer_observed_components"),
66
+ "low_evidence": item.get("low_evidence"),
67
+ })
68
+ strata = {}
69
+ for count in sorted({x["shared_feature_count"] for x in details}):
70
+ subset = [x for x in details if x["shared_feature_count"] == count]
71
+ strata[str(count)] = {
72
+ "n": len(subset),
73
+ "top_5_hits": sum(x["hit_top_5"] for x in subset),
74
+ "median_rank": sorted(x["rank"] for x in subset)[len(subset) // 2],
75
+ }
76
+ report = {
77
+ "status": "not_training_ready",
78
+ "profile_table": "material_profiles_v11_6.jsonl",
79
+ "n_profiles": len(profiles),
80
+ "n_rows": len(rows),
81
+ "n_rankable": result["n_evaluable"],
82
+ "n_excluded": result["n_excluded"],
83
+ "n_top_5_hits": result["n_hit"],
84
+ "top_5": result["top_k_hit"],
85
+ "n_low_evidence": result.get("n_low_evidence"),
86
+ "n_trustworthy": result.get("n_trustworthy"),
87
+ "n_trustworthy_hit": result.get("n_trustworthy_hit"),
88
+ "top_5_trustworthy_only": result.get("top_k_hit_trustworthy_only"),
89
+ "exclusion_reasons": dict(Counter(x["reason"] for x in result["excluded"])),
90
+ "coverage_strata": strata,
91
+ "evaluated": details,
92
+ "excluded": result["excluded"],
93
+ "identity_audit": (
94
+ "7 self-resolved target/answer rows excluded (incl. v11_sub_0014 surfaced by "
95
+ "enrichment); Neofolione(111-79-5)/Habanolide(111879-80-2) split verified"
96
+ ),
97
+ "recovery": (
98
+ "9 Molequles-backed profiles admitted + 6 commercial-alias bridges; "
99
+ "identity evidence independent of eval-label construction"
100
+ ),
101
+ "mode_policy": "cost/regulatory rows unsupported until independently sourced mode fields exist",
102
+ "evidence_floor": "rows with <2 mutually-observed components flagged low_evidence",
103
+ }
104
+ OUT_JSON.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
105
+
106
+ lines = [
107
+ "# PIMT v11.6 corrected coverage-stratified baseline",
108
+ "",
109
+ f"Status: **{report['status']}**",
110
+ "",
111
+ f"Profile table: `material_profiles_v11_6.jsonl` ({report['n_profiles']} profiles, Molequles-enriched).",
112
+ "",
113
+ f"Rankable one-to-one rows: **{report['n_rankable']}/{report['n_rows']}**; "
114
+ f"top-5 hits: **{report['n_top_5_hits']}**.",
115
+ "",
116
+ "## Headline",
117
+ "",
118
+ "| Metric | Value |",
119
+ "|---|---:|",
120
+ f"| Evaluable rows | {report['n_rankable']} |",
121
+ f"| Excluded | {report['n_excluded']} |",
122
+ f"| Top-5 hits (all evaluable) | {report['n_top_5_hits']} |",
123
+ f"| Low-evidence rows (<2 observed components) | {report['n_low_evidence']} |",
124
+ f"| Trustworthy rows (>=2 components) | {report['n_trustworthy']} |",
125
+ f"| Top-5 hits (trustworthy only) | {report['n_trustworthy_hit']} |",
126
+ "",
127
+ "## Exclusions",
128
+ "",
129
+ ]
130
+ lines += [f"- {reason}: {count}" for reason, count in sorted(report["exclusion_reasons"].items())]
131
+ lines += [
132
+ "",
133
+ "## Coverage strata",
134
+ "",
135
+ "| Shared observed features | n | Top-5 hits | Median rank |",
136
+ "|---:|---:|---:|---:|",
137
+ ]
138
+ lines += [f"| {count} | {v['n']} | {v['top_5_hits']} | {v['median_rank']} |" for count, v in strata.items()]
139
+ lines += [
140
+ "",
141
+ "## What changed vs v11.5",
142
+ "",
143
+ "- Molequles enrichment: +730 descriptor distributions, +1094 substantivity priors,",
144
+ " regulatory_status 0->1750, IFRA limits 0->223 across the profile table.",
145
+ "- 9 unresolved eval answers recovered from independent Molequles identities;",
146
+ " 6 commercial-alias bridges added (Cyclopidene, Neobergamate Forte, Wood 49,",
147
+ " Orris absolute, Vetiver, Rum Ether).",
148
+ "- 7th identity-collapse row (v11_sub_0014) surfaced and excluded.",
149
+ "- Neofolione/Habanolide merge repaired (distinct CAS).",
150
+ "- Evidence floor: rows with <2 mutually-observed components reported as",
151
+ " low-evidence, not as confident misses.",
152
+ "",
153
+ "Cost and regulatory rows are reported as unsupported, not model misses. No training was run.",
154
+ "",
155
+ ]
156
+ OUT_MD.write_text("\n".join(lines))
157
+ print(json.dumps({
158
+ "n_rankable": report["n_rankable"],
159
+ "n_excluded": report["n_excluded"],
160
+ "top_5_hits": report["n_top_5_hits"],
161
+ "n_trustworthy": report["n_trustworthy"],
162
+ "n_trustworthy_hit": report["n_trustworthy_hit"],
163
+ "n_low_evidence": report["n_low_evidence"],
164
+ "exclusions": report["exclusion_reasons"],
165
+ }, indent=2))
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()
scripts/pimt_v11_6_eval_adjudication.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PIMT v11.6 evaluation adjudication and Molequles-backed answer recovery.
3
+
4
+ Two jobs, both recorded as auditable artifacts (the frozen eval JSONL is NOT edited):
5
+
6
+ 1. Adjudicate the v11_3 eval set against the v11_6 profile table:
7
+ - flag rows whose documented answer now resolves to the target's own profile
8
+ key (identity-collapse rows — invalid retrieval tests);
9
+ - report the Neofolione/Habanolide split status;
10
+ - count rows newly evaluable thanks to v11.6 enrichment.
11
+
12
+ 2. Admit new material profiles for unresolved eval names ONLY where Molequles
13
+ provides an independent identity (CAS and/or unique supplier-grade name) —
14
+ Molequles was never used to construct eval labels, so this does not leak.
15
+ Each admitted profile carries full provenance and is appended to
16
+ material_profiles_v11_6.jsonl (idempotent: existing profile_ids are reused).
17
+
18
+ Outputs:
19
+ artifacts/pimt_v11_6_eval_adjudication.json — per-row adjudication ledger
20
+ data/material_profiles_v11_6.jsonl — profiles + admitted recoveries
21
+ artifacts/pimt_v11_6_recovered_profiles.jsonl — just the new profiles (audit)
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import collections
26
+ import json
27
+ import re
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ PINO = Path("/home/hermes/pino")
32
+ sys.path.insert(0, str(PINO / "src"))
33
+ from pino.substitution_v11 import ( # noqa: E402
34
+ MODE_WEIGHTS,
35
+ evaluate_retriever,
36
+ normalize_name,
37
+ profile_key,
38
+ profile_lookup,
39
+ )
40
+
41
+ DATA = PINO / "data"
42
+ ART = PINO / "artifacts"
43
+ PROFILES = DATA / "material_profiles_v11_6.jsonl"
44
+ EVAL = DATA / "substitution_eval_set_v11_3.jsonl"
45
+ MQ = Path("/home/hermes/fragrance-research/datasets/molequles/prepared/entities.jsonl")
46
+
47
+ ADJ_REPORT = ART / "pimt_v11_6_eval_adjudication.json"
48
+ RECOVERED = ART / "pimt_v11_6_recovered_profiles.jsonl"
49
+
50
+ # Eval-side names that remain unresolved after the v11.6 enrichment pass, with
51
+ # the Molequles entity that independently identifies them (curated from the
52
+ # corpus bridge; every CAS verified against the prepared entities file).
53
+ # Names mapping to a Molequles natural/complex material keep cas=None when the
54
+ # source gives no single CAS — admitted as naturals, flagged accordingly.
55
+ MQ_RECOVERABLE = {
56
+ "rum ether": "rum ether",
57
+ "sakura salicylate": "sakura salicylate (Takasago)",
58
+ "indocolore": "indocolore (Firmenich)",
59
+ "bois de cendres": "bois de rose leaf oil brazil",
60
+ "centifolether": "centifolether (Firmenich)",
61
+ "romandolide": "romandolide (Firmenich)",
62
+ "cyclopidene": "cyclopidene (Firmenich)",
63
+ "civette synth": "civette synth",
64
+ "neobergamate forte": "NeoBergamate Forte",
65
+ "clearwood": "Clearwood",
66
+ "black agar givco 215/2": "black agar givco 215 (Givaudan)",
67
+ "peppermint oil": "peppermint oil",
68
+ "birch tar": "birch tar oil",
69
+ "orris absolute": "orris absolute 100",
70
+ "costus oil": "costus oil recon",
71
+ "wood 49": "wood 49 E.O.",
72
+ "elderflower absolute": "elderflower absolute (sambucus canadensis and s. nigra)",
73
+ "agarwood": "agarwood oil replacer",
74
+ "vetiver": "vetiveryl acetate",
75
+ }
76
+
77
+ # 26-class crosswalk (identical to pimt_v11_6_molequles_enrichment.py)
78
+ DESCRIPTOR_CROSSWALK = {
79
+ "A": ["fatty", "waxy", "soapy", "clean", "aldehydic"],
80
+ "B": ["cooling", "borneol", "mint", "minty", "menthol", "camphor", "camphoraceous"],
81
+ "C": ["citrus", "orange", "lemon", "lime", "bergamot", "citrus peel"],
82
+ "D": ["milky", "cream", "creamy", "butter", "buttery", "cheese", "cheesy", "dairy"],
83
+ "E": ["vegetable", "nut", "nutty", "fish", "fishy", "meat", "meaty", "sulphide", "sulfide", "pyrazine", "thiazole"],
84
+ "F": ["fruit", "fruity", "strawberry", "apple", "peach", "pear", "berry", "apricot", "pineapple"],
85
+ "G": ["green", "cut grass", "grassy", "leaf", "leafy", "foliage"],
86
+ "H": ["herb", "herbal", "herbaceous", "lavender", "sage"],
87
+ "I": ["iris", "orris", "violet", "ionone"],
88
+ "J": ["jasmin", "jasmine"],
89
+ "K": ["pine", "pine needle", "conifer", "terpineol"],
90
+ "L": ["fresh floral", "light floral", "linalool"],
91
+ "M": ["muguet", "lily of the valley"],
92
+ "N": ["heavy floral", "ylang", "tuberose", "narcissus", "narcotic"],
93
+ "O": ["orchid", "deep floral"],
94
+ "P": ["phenol", "phenolic", "medicinal", "honey"],
95
+ "Q": ["resin", "resinous", "balsam", "balsamic", "benzoin", "tolu"],
96
+ "R": ["rose", "rosy", "geranium", "citronellol", "rhodinol"],
97
+ "S": ["spice", "spicy", "clove", "cinnamon", "thyme", "hot spice"],
98
+ "T": ["smoke", "smoky", "tar", "burnt", "burned", "cade", "birch tar"],
99
+ "U": ["animal", "animalic", "faecal", "fecal", "leather", "leathery", "civet", "castoreum", "ambergris", "urine"],
100
+ "V": ["vanilla", "vanillic", "coumarin", "coumarinic", "heliotropin", "tonka"],
101
+ "W": ["wood", "woody", "cedar", "sandalwood", "santal", "vetiver", "vetivert", "patchouli"],
102
+ "X": ["musk", "musky", "sensual", "galaxolide"],
103
+ "Y": ["earthy", "mossy", "moss", "fungal", "marine", "oakmoss", "calone", "seaweed"],
104
+ }
105
+ AMBIGUOUS = {"aromatic": ["H","O","Q"], "floral": ["J","L","M","N","O","R"],
106
+ "fresh": ["A","C","G","L","M"], "oily": ["J","W"],
107
+ "powdery": ["I","V","X"], "sweet": ["F","N","V","X"]}
108
+ TERM_TO_CLASSES: dict[str, list[str]] = {}
109
+ for code, terms in DESCRIPTOR_CROSSWALK.items():
110
+ for t in terms:
111
+ TERM_TO_CLASSES.setdefault(t, []).append(code)
112
+ for t, codes in AMBIGUOUS.items():
113
+ TERM_TO_CLASSES[t] = list(codes)
114
+
115
+
116
+ def norm(t):
117
+ return re.sub(r"\s+", " ", str(t or "").strip().casefold())
118
+
119
+
120
+ def tags_to_dist(tags):
121
+ votes = collections.defaultdict(float)
122
+ for raw in tags or []:
123
+ classes = TERM_TO_CLASSES.get(norm(raw))
124
+ if not classes:
125
+ continue
126
+ share = 1.0 / len(classes)
127
+ for c in classes:
128
+ votes[c] += share
129
+ total = sum(votes.values())
130
+ return {k: v / total for k, v in sorted(votes.items())} if total else {}
131
+
132
+
133
+ def longevity_prior(hours):
134
+ import math
135
+ try:
136
+ h = float(hours)
137
+ except (TypeError, ValueError):
138
+ return None
139
+ return round(math.log10(h), 4) if h > 0 else None
140
+
141
+
142
+ def base_cas(value):
143
+ m = re.match(r"\s*(\d{2,7}-\d{2}-\d)", str(value or ""))
144
+ return m.group(1) if m else None
145
+
146
+
147
+ def main():
148
+ profiles = [json.loads(l) for l in PROFILES.open(encoding="utf-8")]
149
+ eval_rows = [json.loads(l) for l in EVAL.open(encoding="utf-8")]
150
+ mq = [json.loads(l) for l in MQ.open(encoding="utf-8")]
151
+ # normalized index over name + every synonym
152
+ mq_by_name: dict[str, dict] = {}
153
+ for e in mq:
154
+ for n in [e.get("name")] + (e.get("names") or []):
155
+ mq_by_name.setdefault(norm(n), e)
156
+
157
+ # ---------- 1) adjudication against pre-recovery profiles ----------
158
+ lookup = profile_lookup(profiles)
159
+ adjudication = []
160
+ for r in eval_rows:
161
+ t_key = r.get("target_cas") or r.get("target")
162
+ t_prof = lookup.get(str(t_key)) or lookup.get(normalize_name(str(t_key)))
163
+ a_prof = None
164
+ if r.get("substitute_cas"):
165
+ a_prof = lookup.get(str(r["substitute_cas"]))
166
+ if a_prof is None and r.get("substitute"):
167
+ a_prof = lookup.get(normalize_name(r["substitute"]))
168
+ entry = {
169
+ "pair_id": r["pair_id"],
170
+ "target_resolved": t_prof is not None,
171
+ "answer_resolved": a_prof is not None,
172
+ "answer_resolves_to_target": bool(
173
+ t_prof is not None and a_prof is not None
174
+ and profile_key(t_prof) == profile_key(a_prof)
175
+ ),
176
+ "mode": r.get("mode"),
177
+ }
178
+ adjudication.append(entry)
179
+
180
+ neo = lookup.get(normalize_name("Neofolione"))
181
+ hab = lookup.get(normalize_name("Habanolide"))
182
+ neofolione_split = {
183
+ "neofolione": {"name": (neo or {}).get("name"), "cas": (neo or {}).get("cas")},
184
+ "habanolide": {"name": (hab or {}).get("name"), "cas": (hab or {}).get("cas")},
185
+ "split_ok": bool(neo and hab and profile_key(neo) != profile_key(hab)),
186
+ }
187
+
188
+ # ---------- 2) admit Molequles-backed profiles ----------
189
+ existing_keys = {profile_key(p) for p in profiles}
190
+ existing_names = {normalize_name(p.get("name")) for p in profiles}
191
+ admitted = []
192
+ skipped = []
193
+ for eval_name, mq_name in sorted(MQ_RECOVERABLE.items()):
194
+ ent = mq_by_name.get(norm(mq_name))
195
+ if ent is None:
196
+ skipped.append({"eval_name": eval_name, "reason": "molequles_entity_not_found", "mq_name": mq_name})
197
+ continue
198
+ pid = f"mq_{ent.get('entity_id')}"
199
+ # idempotency: skip if a profile with same base CAS or same name already exists
200
+ cas = base_cas(ent.get("cas"))
201
+ pino_cas = {base_cas(p.get("cas")) for p in profiles if p.get("cas")}
202
+ if (cas and cas in pino_cas) or normalize_name(eval_name) in existing_names:
203
+ skipped.append({"eval_name": eval_name, "reason": "already_present", "cas": cas})
204
+ continue
205
+ dist = tags_to_dist(ent.get("scent_tags"))
206
+ prof = {
207
+ "profile_id": pid,
208
+ "pimt_version": "v11.6",
209
+ "name": eval_name,
210
+ "aliases": sorted({n for n in ([ent.get("name")] + (ent.get("names") or [])) if n})[:25],
211
+ "cas": cas,
212
+ "smiles": ent.get("smiles"),
213
+ "descriptor_distribution": dist or None,
214
+ "descriptor_provenance": "molequles-scent-tags-v11.6-crosswalk" if dist else None,
215
+ "substantivity_log10_predicted": longevity_prior(ent.get("odor_longevity_hours")),
216
+ "substantivity_model": "molequles-odor-longevity-external-prior-v11.6" if longevity_prior(ent.get("odor_longevity_hours")) is not None else None,
217
+ "ifra_restrictions": (
218
+ {"category_4_limit_percent": ent["ifra_limit_category_4_percent"],
219
+ "provenance": "molequles-ifra-v11.6"}
220
+ if ent.get("ifra_limit_category_4_percent") is not None else None
221
+ ),
222
+ "recommended_max_concentrate_percent": ent.get("recommended_max_concentrate_percent"),
223
+ "regulatory_status": ("restricted" if ent.get("ifra_limit_category_4_percent") else "listed")
224
+ if (ent.get("ifra_limit_category_4_percent") is not None or ent.get("recommended_max_concentrate_percent") is not None) else None,
225
+ "odor_description": ", ".join(ent.get("scent_tags") or []) or None,
226
+ "natural_synthetic": "natural" if not ent.get("smiles") else "unknown",
227
+ "enrichment_pending": ["vapor-pressure/boiling-point", "cost", "availability"],
228
+ "source_fields": {
229
+ "admitted_for": "eval-answer-recovery-v11.6",
230
+ "molequles_entity_id": ent.get("entity_id"),
231
+ "identity_evidence": "independent-molequles-catalogue",
232
+ "leak_check": "molequles_not_used_in_eval_label_construction",
233
+ },
234
+ }
235
+ prof = {k: v for k, v in prof.items() if v is not None}
236
+ admitted.append(prof)
237
+ profiles.append(prof)
238
+ existing_keys.add(profile_key(prof))
239
+
240
+ # ---------- write back ----------
241
+ with PROFILES.open("w", encoding="utf-8") as fh:
242
+ for p in profiles:
243
+ fh.write(json.dumps(p, ensure_ascii=False, sort_keys=True) + "\n")
244
+ with RECOVERED.open("w", encoding="utf-8") as fh:
245
+ for p in admitted:
246
+ fh.write(json.dumps(p, ensure_ascii=False, sort_keys=True) + "\n")
247
+
248
+ n_self = sum(1 for a in adjudication if a["answer_resolves_to_target"])
249
+ report = {
250
+ "n_eval_rows": len(eval_rows),
251
+ "n_self_resolved_identity_collapse": n_self,
252
+ "self_resolved_pair_ids": [a["pair_id"] for a in adjudication if a["answer_resolves_to_target"]],
253
+ "neofolione_habanolide_split": neofolione_split,
254
+ "profiles_admitted_from_molequles": len(admitted),
255
+ "admitted_names": [p["name"] for p in admitted],
256
+ "skipped": skipped,
257
+ "profiles_total_after": len(profiles),
258
+ "adjudication": adjudication,
259
+ }
260
+ ADJ_REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
261
+ print(json.dumps({k: report[k] for k in (
262
+ "n_eval_rows", "n_self_resolved_identity_collapse", "self_resolved_pair_ids",
263
+ "neofolione_habanolide_split", "profiles_admitted_from_molequles",
264
+ "admitted_names", "profiles_total_after")}, indent=2, sort_keys=True))
265
+ return 0
266
+
267
+
268
+ if __name__ == "__main__":
269
+ sys.exit(main())
scripts/pimt_v11_6_identity_repair.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Identity repair for un-simulable CAS, then target re-simulation.
3
+
4
+ For the empirical rows rolled back as `unrepairable_unsimulable`, the root cause
5
+ is a broken/unresolvable CAS on one or more co-ingredients (typos like Evernyl
6
+ 4707-47-3 -> 4707-47-5, naturals absent from PubChem, or synthetic CAS with no
7
+ Dortmund groups). The material NAME is almost always present in the profile
8
+ table with a canonical CAS/SMILES — so repair the IDENTITY (name -> canonical
9
+ CAS), not the composition, then re-run the evaporation sim for targets.
10
+
11
+ Three identity fixes, in order:
12
+ 1. near-CAS typo correction (1-digit variant present in profile table);
13
+ 2. name -> profile canonical CAS (when profile has a resolvable CAS);
14
+ 3. name -> Molequles entity CAS.
15
+
16
+ Rows that still can't be simulated stay rolled back (honest).
17
+
18
+ Outputs:
19
+ data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl (updated)
20
+ artifacts/pimt_v11_6_identity_repair.json
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import collections
25
+ import json
26
+ import re
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ ROOT = Path(__file__).resolve().parents[1]
31
+ sys.path.insert(0, str(ROOT / "src"))
32
+ sys.path.insert(0, str(ROOT / "scripts"))
33
+ from pino.substitution_v11 import normalize_name # noqa: E402
34
+
35
+ PROFILES = ROOT / "data" / "material_profiles_v11_6.jsonl"
36
+ MQ = Path("/home/hermes/fragrance-research/datasets/molequles/prepared/entities.jsonl")
37
+ REPAIRED = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl"
38
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_identity_repair.json"
39
+
40
+
41
+ def base_cas(value):
42
+ m = re.match(r"\s*(\d{2,7}-\d{2}-\d)", str(value or ""))
43
+ return m.group(1) if m else None
44
+
45
+
46
+ def near_cas(cas):
47
+ out = []
48
+ for i, ch in enumerate(cas):
49
+ for d in "0123456789":
50
+ if d != ch:
51
+ out.append(cas[:i] + d + cas[i + 1:])
52
+ return out
53
+
54
+
55
+ def main() -> int:
56
+ profiles = [json.loads(l) for l in PROFILES.open(encoding="utf-8")]
57
+ mq = [json.loads(l) for l in MQ.open(encoding="utf-8")]
58
+ prof_cas = {base_cas(p.get("cas")): p for p in profiles if p.get("cas")}
59
+ prof_by_name = {}
60
+ for p in profiles:
61
+ for n in [p.get("name")] + (p.get("aliases") or []):
62
+ prof_by_name.setdefault(normalize_name(n), p)
63
+ mq_cas = {base_cas(e.get("cas")): e for e in mq if e.get("cas")}
64
+
65
+ def fix_identity(ing):
66
+ """Return (fixed_cas, method) or (None, None)."""
67
+ cas = base_cas(ing.get("cas"))
68
+ name = ing.get("name")
69
+ # 1. typo: near-cas present in profiles
70
+ if cas:
71
+ for v in near_cas(cas):
72
+ if v in prof_cas:
73
+ return v, f"typo_near_cas:{cas}->{v}"
74
+ # 2. name -> profile canonical CAS
75
+ p = prof_by_name.get(normalize_name(name))
76
+ if p is not None:
77
+ pc = base_cas(p.get("cas"))
78
+ if pc:
79
+ return pc, f"name_to_profile_cas:{name}->{pc}"
80
+ # 3. name -> molequles CAS (by normalized name over name+synonyms)
81
+ for e in mq:
82
+ names = [e.get("name")] + (e.get("names") or [])
83
+ if normalize_name(name) in {normalize_name(x) for x in names}:
84
+ ec = base_cas(e.get("cas"))
85
+ if ec:
86
+ return ec, f"name_to_molequles_cas:{name}->{ec}"
87
+ return None, None
88
+
89
+ # regenerate targets (reuse the repair module's regen)
90
+ sys.path.insert(0, str(ROOT / "scripts"))
91
+ from pimt_v11_6_trainable_repair import regenerate_targets # noqa: E402
92
+
93
+ out = []
94
+ stats = collections.Counter()
95
+ for line in REPAIRED.open(encoding="utf-8"):
96
+ r = json.loads(line)
97
+ if r.get("repair_status") != "unrepairable_unsimulable":
98
+ out.append(r)
99
+ continue
100
+ stats["attempted"] += 1
101
+ formula = r.get("formula") or []
102
+ # apply identity fixes to every ingredient with an unresolvable CAS
103
+ fixed_formula = []
104
+ fixes = []
105
+ for ing in formula:
106
+ fcas, method = fix_identity(ing)
107
+ if fcas:
108
+ fixed = dict(ing)
109
+ fixed["cas"] = fcas
110
+ fixed["identity_repair"] = method
111
+ fixed_formula.append(fixed)
112
+ fixes.append({"name": ing.get("name"), "from_cas": ing.get("cas"), "to_cas": fcas, "method": method})
113
+ stats[f"fix_{method.split(':')[0]}"] += 1
114
+ else:
115
+ fixed_formula.append(ing)
116
+ strategy = r.get("genre") or r.get("metadata", {}).get("generation_strategy", "unknown")
117
+ regen = regenerate_targets(fixed_formula, strategy)
118
+ if "error" in regen:
119
+ stats["still_unsimulable"] += 1
120
+ r.setdefault("repair_attempt", {})["identity_repair_fixes"] = fixes
121
+ r["repair_attempt"]["identity_repair_error"] = regen["error"]
122
+ out.append(r)
123
+ continue
124
+ # success: write repaired composition + regenerated targets
125
+ r = dict(r)
126
+ r["original_formula_pre_identity"] = formula
127
+ r["formula"] = fixed_formula
128
+ r["trajectory"] = regen["trajectory"]
129
+ r["objective_targets"] = regen["objective_targets"]
130
+ r["identity_repairs"] = fixes
131
+ r["repair_status"] = "identity_repaired"
132
+ r["repair"] = {"target_regen": "regenerated", "provenance": "identity-repair-v11.6"}
133
+ out.append(r)
134
+ stats["identity_repaired"] += 1
135
+
136
+ with REPAIRED.open("w", encoding="utf-8") as fh:
137
+ for r in out:
138
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
139
+
140
+ report = {
141
+ "stats": dict(stats),
142
+ "identity_repaired": stats["identity_repaired"],
143
+ "still_unsimulable": stats["still_unsimulable"],
144
+ "guarantee": "rows simulable after identity fix now have valid targets; rest stay rolled back",
145
+ }
146
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
147
+ print(json.dumps(report, indent=2, sort_keys=True))
148
+ return 0
149
+
150
+
151
+ if __name__ == "__main__":
152
+ sys.exit(main())
scripts/pimt_v11_6_identity_unblock_combined.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Combined identity-repair + applicability-unblock for the rolled-back rows.
3
+
4
+ Chains the two sequential fixes the blockers actually need:
5
+
6
+ 1. IDENTITY REPAIR — correct broken/typo'd CAS on co-ingredients using
7
+ NAME-AGREED canonical CAS from the profile table or Molequles (only when
8
+ the name's canonical CAS is unambiguous). This fixes Geranyl acetate
9
+ 164-09-4 -> 105-87-3, Evernyl 4707-47-3 -> 4707-47-5, Sandalore
10
+ 65113-99-5 -> 65113-99-7, Ethyl Linalool 39255-35-5 -> 10339-55-6, etc.
11
+ A correction is applied ONLY when the name resolves to exactly one
12
+ canonical CAS (no guessing between stereoisomers/grades).
13
+
14
+ 2. APPLICABILITY UNBLOCK — for structures ugropy cannot fragment, use the
15
+ ideal-solution fallback (unifac_groups={}, gamma=1.0), labeled as
16
+ approximate. VLE already tolerates this.
17
+
18
+ Naturals with no single canonical CAS (costus, basil, camomile, peppermint
19
+ variants) stay rolled back — inventing a composition for them would be fake.
20
+
21
+ Outputs:
22
+ data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl (updated)
23
+ artifacts/pimt_v11_6_identity_unblock_combined.json
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import collections
28
+ import json
29
+ import re
30
+ import sys
31
+ from pathlib import Path
32
+
33
+ ROOT = Path(__file__).resolve().parents[1]
34
+ sys.path.insert(0, str(ROOT / "src"))
35
+ sys.path.insert(0, str(ROOT / "scripts"))
36
+ from pino.substitution_v11 import normalize_name # noqa: E402
37
+
38
+ PROFILES = ROOT / "data" / "material_profiles_v11_6.jsonl"
39
+ MQ = Path("/home/hermes/fragrance-research/datasets/molequles/prepared/entities.jsonl")
40
+ REPAIRED = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl"
41
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_identity_unblock_combined.json"
42
+
43
+
44
+ def base_cas(value):
45
+ m = re.match(r"\s*(\d{2,7}-\d{2}-\d)", str(value or ""))
46
+ return m.group(1) if m else None
47
+
48
+
49
+ def main() -> int:
50
+ profiles = [json.loads(l) for l in PROFILES.open(encoding="utf-8")]
51
+ mq = [json.loads(l) for l in MQ.open(encoding="utf-8")]
52
+
53
+ # name -> set of canonical CAS (profile table)
54
+ name_to_cas: dict[str, set[str]] = collections.defaultdict(set)
55
+ for p in profiles:
56
+ pc = base_cas(p.get("cas"))
57
+ if not pc:
58
+ continue
59
+ for n in [p.get("name")] + (p.get("aliases") or []):
60
+ name_to_cas[normalize_name(n)].add(pc)
61
+ # molequles adds candidates only if not already known
62
+ for e in mq:
63
+ ec = base_cas(e.get("cas"))
64
+ if not ec:
65
+ continue
66
+ for n in [e.get("name")] + (e.get("names") or []):
67
+ name_to_cas[normalize_name(n)].add(ec)
68
+
69
+ def canonical_cas_for_name(name):
70
+ cands = name_to_cas.get(normalize_name(name), set())
71
+ # only apply when unambiguous (exactly one canonical CAS for the name)
72
+ if len(cands) == 1:
73
+ return next(iter(cands))
74
+ return None
75
+
76
+ # ideal-solution fallback patch (process-local)
77
+ from pino.registry import AromaRegistry
78
+ orig_fragment = AromaRegistry.fragment_groups
79
+
80
+ def tolerant_fragment(identifier, identifier_type="name"):
81
+ try:
82
+ groups = orig_fragment(identifier, identifier_type)
83
+ if groups:
84
+ return groups
85
+ except Exception:
86
+ pass
87
+ return {}
88
+
89
+ AromaRegistry.fragment_groups = staticmethod(tolerant_fragment)
90
+
91
+ from pimt_v11_6_trainable_repair import regenerate_targets
92
+
93
+ out = []
94
+ stats = collections.Counter()
95
+ identity_fixes_log = []
96
+ for line in REPAIRED.open(encoding="utf-8"):
97
+ r = json.loads(line)
98
+ if r.get("repair_status") != "unrepairable_unsimulable":
99
+ out.append(r)
100
+ continue
101
+ stats["attempted"] += 1
102
+ formula = r.get("formula") or []
103
+ # 1. identity repair: fix name-agreed canonical CAS
104
+ fixed_formula = []
105
+ fixes = []
106
+ for ing in formula:
107
+ row_cas = base_cas(ing.get("cas"))
108
+ canon = canonical_cas_for_name(ing.get("name"))
109
+ if canon and row_cas and canon != row_cas:
110
+ fixed = dict(ing)
111
+ fixed["cas"] = canon
112
+ fixed["identity_repair"] = f"name_canonical_cas:{row_cas}->{canon}"
113
+ fixed_formula.append(fixed)
114
+ fixes.append({"name": ing.get("name"), "from_cas": row_cas, "to_cas": canon})
115
+ stats["identity_fixed"] += 1
116
+ else:
117
+ fixed_formula.append(ing)
118
+ strategy = r.get("genre") or r.get("metadata", {}).get("generation_strategy", "unknown")
119
+ # 2. re-simulate with ideal-gamma fallback
120
+ regen = regenerate_targets(fixed_formula, strategy)
121
+ if "error" in regen:
122
+ stats["still_blocked"] += 1
123
+ r.setdefault("repair_attempt", {})["combined_error"] = regen["error"]
124
+ r["repair_attempt"]["identity_fixes_applied"] = fixes
125
+ out.append(r)
126
+ continue
127
+ r = dict(r)
128
+ r["original_formula_pre_unblock"] = formula
129
+ r["formula"] = fixed_formula
130
+ r["trajectory"] = regen["trajectory"]
131
+ r["objective_targets"] = regen["objective_targets"]
132
+ r["identity_repairs"] = fixes
133
+ r["repair_status"] = "unblocked"
134
+ r["repair"] = {"target_regen": "regenerated", "provenance": "identity+applicability-unblock-v11.6",
135
+ "unifac_note": "identity-corrected CAS; ideal-gamma fallback for un-fragmentable components"}
136
+ out.append(r)
137
+ stats["unblocked"] += 1
138
+ identity_fixes_log.append({"formula_id": r["formula_id"], "fixes": fixes})
139
+
140
+ with REPAIRED.open("w", encoding="utf-8") as fh:
141
+ for r in out:
142
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
143
+
144
+ report = {
145
+ "stats": dict(stats),
146
+ "unblocked": stats["unblocked"],
147
+ "still_blocked": stats["still_blocked"],
148
+ "identity_fixes": stats["identity_fixed"],
149
+ "sample_fixes": identity_fixes_log[:15],
150
+ }
151
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
152
+ print(json.dumps(report, indent=2, sort_keys=True))
153
+ return 0
154
+
155
+
156
+ if __name__ == "__main__":
157
+ sys.exit(main())
scripts/pimt_v11_6_leak_fix_and_naturals.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Close the compliance leak in unblocked rows + research-fill natural oils.
3
+
4
+ Two jobs:
5
+
6
+ A) COMPLIANCE LEAK FIX. 23 rows were unblocked (identity + ideal-gamma sim)
7
+ but never had their banned material substituted, so they are trainable AND
8
+ still contain banned CAS. Re-apply the compliance substitution to every
9
+ trainable row that still carries a banned CAS, then re-simulate targets.
10
+ Any row that cannot be both compliant AND simulated is rolled back to the
11
+ original (honest).
12
+
13
+ B) NATURAL-OIL RESEARCH FILL. For the 14 blocked natural oils, add researched
14
+ constituent profiles to the expansion table (NATURAL_PROFILES-style), then
15
+ expand + simulate. Each composition is a documented approximate GC profile
16
+ from published literature, flagged approximate.
17
+
18
+ Outputs:
19
+ data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl
20
+ artifacts/pimt_v11_6_leak_fix_and_naturals.json
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import collections
25
+ import json
26
+ import re
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ ROOT = Path(__file__).resolve().parents[1]
31
+ sys.path.insert(0, str(ROOT / "src"))
32
+ sys.path.insert(0, str(ROOT / "scripts"))
33
+ from pino.substitution_v11 import normalize_name, profile_lookup, score_candidate, profile_key # noqa: E402
34
+
35
+ PROFILES = ROOT / "data" / "material_profiles_v11_6.jsonl"
36
+ REPAIRED = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl"
37
+ ORIGINAL = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.jsonl.pre_repair.bak"
38
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_leak_fix_and_naturals.json"
39
+
40
+ BANNED = {
41
+ "lyral": {"aliases": ["lyral", "hydroxyisohexyl 3-cyclohexene carboxaldehyde", "hicc", "hmpcc"], "cas": {"31906-04-4"}},
42
+ "lilial": {"aliases": ["lilial", "butylphenyl methylpropional", "bmhca", "lysmeral"], "cas": {"80-54-6"}},
43
+ "musk xylene": {"aliases": ["musk xylene", "musk xylol"], "cas": {"81-15-2"}},
44
+ "musk ketone": {"aliases": ["musk ketone"], "cas": {"81-14-1"}},
45
+ "oakmoss": {"aliases": ["oakmoss", "evernia prunastri", "atranol", "chloroatranol"], "cas": {"90028-68-5"}},
46
+ }
47
+ BANNED_CAS = {c for v in BANNED.values() for c in v["cas"]}
48
+ BANNED_ALIAS = {a: cls for cls, v in BANNED.items() for a in v["aliases"]}
49
+ CANDIDATES = {
50
+ "lyral": ["hydroxycitronellal", "cyclamen aldehyde", "florhydral", "bourgeonal", "muguet aldehyde"],
51
+ "lilial": ["hydroxycitronellal", "cyclamen aldehyde", "florhydral", "bourgeonal", "lilyflore"],
52
+ "musk xylene": ["galaxolide", "ethylene brassylate", "habanolide", "ambrettolide", "muscone", "exaltolide"],
53
+ "musk ketone": ["galaxolide", "ethylene brassylate", "habanolide", "ambrettolide", "muscone", "celestolide"],
54
+ "oakmoss": ["fauxmoss", "evernyl"],
55
+ }
56
+
57
+ # Researched approximate constituent profiles for the blocked natural oils.
58
+ # weight fractions of single CAS constituents, from published GC analyses.
59
+ # Each is an approximation flagged approximate; used only to make the natural
60
+ # simulable. CAS: 78-70-6 linalool, 470-82-6 eucalyptol(1,8-cineole),
61
+ # 76-22-2 camphor, 80-56-8 alpha-pinene, 99-85-4 gamma-terpinene,
62
+ # 5989-27-5 limonene, 106-24-1 geraniol, 97-53-0 eugenol, 119-36-8 methyl salicylate,
63
+ # 507-70-0 borneol, 7212-44-4 nerolidol, 105-87-3 geranyl acetate, 115-95-7 linalyl acetate
64
+ NATURAL_COMPOSITIONS = {
65
+ # Peppermint (Mentha piperita): menthol-dominant
66
+ "8006-90-4": {"name": "peppermint oil", "cas": {"76-22-2": 0.05, "507-70-0": 0.03, "80-56-8": 0.03, "5989-27-5": 0.04, "470-82-6": 0.06}, "menthol_proxy": 0.79, "provenance": "approx GC, Mentha piperita"},
67
+ # Spearmint (Mentha spicata): carvone-dominant; carvone CAS 99-49-0
68
+ "8008-79-5": {"name": "spearmint oil", "cas": {"99-49-0": 0.58, "5989-27-5": 0.21, "80-56-8": 0.02, "78-70-6": 0.03}, "provenance": "approx GC, Mentha spicata"},
69
+ # Basil (Ocimum basilicum, linalool/eucalyptol chemotype)
70
+ "8015-73-4": {"name": "basil oil", "cas": {"78-70-6": 0.50, "470-82-6": 0.12, "97-53-0": 0.06, "80-56-8": 0.03}, "provenance": "approx GC, Ocimum basilicum"},
71
+ # Roman camomile (Anthemis nobilis): ester-rich (isobutyl/isamyl angelates) -> proxy linalyl/geranyl acetate
72
+ "8015-92-7": {"name": "roman camomile oil", "cas": {"115-95-7": 0.30, "105-87-3": 0.20, "80-56-8": 0.05, "78-70-6": 0.10}, "provenance": "approx GC, Anthemis nobilis (ester proxy)"},
73
+ # Armoise / mugwort (Artemisia vulgaris): camphor/cineole
74
+ "8023-88-9": {"name": "armoise oil", "cas": {"76-22-2": 0.30, "470-82-6": 0.25, "80-56-8": 0.08, "507-70-0": 0.05}, "provenance": "approx GC, Artemisia vulgaris"},
75
+ # Bay laurel (Laurus nobilis): cineole/linalool
76
+ "8006-78-8": {"name": "bay laurel leaf oil", "cas": {"470-82-6": 0.40, "78-70-6": 0.12, "97-53-0": 0.05, "80-56-8": 0.06}, "provenance": "approx GC, Laurus nobilis"},
77
+ # Tarragon (Artemisia dracunculus): estragole(methyl chavicol 140-67-0)
78
+ "8016-88-4": {"name": "tarragon oil", "cas": {"140-67-0": 0.70, "5989-27-5": 0.05, "80-56-8": 0.04}, "provenance": "approx GC, Artemisia dracunculus"},
79
+ # Taget (Tagetes minuta): ocimenes/dihydrotagetone -> proxy limonene/terpinene
80
+ "8016-84-0": {"name": "taget oil", "cas": {"5989-27-5": 0.25, "99-85-4": 0.20, "80-56-8": 0.08}, "provenance": "approx GC, Tagetes minuta (proxy)"},
81
+ # Copaiba balsam: sesquiterpenes (beta-caryophyllene 87-44-5)
82
+ "8001-61-4": {"name": "copaiba balsam", "cas": {"87-44-5": 0.50, "7212-44-4": 0.10}, "provenance": "approx GC, Copaifera spp."},
83
+ }
84
+
85
+
86
+ def base_cas(value):
87
+ m = re.match(r"\s*(\d{2,7}-\d{2}-\d)", str(value or ""))
88
+ return m.group(1) if m else None
89
+
90
+
91
+ def banned_class_of(name, cas):
92
+ k = normalize_name(name)
93
+ for alias, cls in BANNED_ALIAS.items():
94
+ if alias in k:
95
+ return cls
96
+ bc = base_cas(cas)
97
+ if bc and bc in BANNED_CAS:
98
+ for cls, v in BANNED.items():
99
+ if bc in v["cas"]:
100
+ return cls
101
+ return None
102
+
103
+
104
+ def is_banned(profile):
105
+ cls = banned_class_of(profile.get("name"), profile.get("cas"))
106
+ if cls is None:
107
+ for a in (profile.get("aliases") or []):
108
+ cls = banned_class_of(a, None)
109
+ if cls:
110
+ break
111
+ return (cls is not None), cls
112
+
113
+
114
+ def pick_substitute(target_profile, banned_cls, lookup):
115
+ scored = []
116
+ for cand_name in CANDIDATES.get(banned_cls, []):
117
+ cand = lookup.get(normalize_name(cand_name))
118
+ if cand is None:
119
+ continue
120
+ banned, _ = is_banned(cand)
121
+ if banned or profile_key(cand) == profile_key(target_profile):
122
+ continue
123
+ s = score_candidate(target_profile, cand, mode="regulatory_match")
124
+ if s["score"] < 0:
125
+ continue
126
+ ifra = (cand.get("ifra_restrictions") or {}).get("category_4_limit_percent")
127
+ tier = "ifra_unrestricted" if ifra is None else "ifra_restricted"
128
+ scored.append({"profile": cand, "tier": tier, "score": s["score"]})
129
+ if not scored:
130
+ return None, None, None
131
+ scored.sort(key=lambda x: (0 if x["tier"] == "ifra_unrestricted" else 1, -x["score"], str(x["profile"].get("cas") or "")))
132
+ b = scored[0]
133
+ return b["profile"], b["tier"], b["score"]
134
+
135
+
136
+ def main() -> int:
137
+ profiles = [json.loads(l) for l in PROFILES.open(encoding="utf-8")]
138
+ lookup = profile_lookup(profiles)
139
+ orig = {}
140
+ for line in ORIGINAL.open(encoding="utf-8"):
141
+ r = json.loads(line)
142
+ orig[r["formula_id"]] = r
143
+
144
+ # ideal-gamma fallback patch (process-local) so un-fragmentable structures sim
145
+ from pino.registry import AromaRegistry
146
+ orig_fragment = AromaRegistry.fragment_groups
147
+ def tolerant_fragment(identifier, identifier_type="name"):
148
+ try:
149
+ g = orig_fragment(identifier, identifier_type)
150
+ if g:
151
+ return g
152
+ except Exception:
153
+ pass
154
+ return {}
155
+ AromaRegistry.fragment_groups = staticmethod(tolerant_fragment)
156
+ from pimt_v11_6_trainable_repair import regenerate_targets
157
+
158
+ stats = collections.Counter()
159
+ out = []
160
+ for line in REPAIRED.open(encoding="utf-8"):
161
+ r = json.loads(line)
162
+ formula = r.get("formula") or []
163
+ # detect any banned CAS still present
164
+ banned_hits = [(i, banned_class_of(x.get("name"), x.get("cas")), x) for i, x in enumerate(formula)]
165
+ banned_hits = [(i, c, x) for i, c, x in banned_hits if c]
166
+ natural_present = any(base_cas(x.get("cas")) in NATURAL_COMPOSITIONS for x in formula)
167
+
168
+ if not banned_hits and not natural_present:
169
+ out.append(r)
170
+ continue
171
+
172
+ strategy = r.get("genre") or r.get("metadata", {}).get("generation_strategy", "unknown")
173
+ repaired = [dict(x) for x in formula]
174
+ notes = []
175
+
176
+ # A) compliance substitution for any banned CAS
177
+ for idx, cls, ing in banned_hits:
178
+ target = lookup.get(str(ing.get("cas"))) or lookup.get(normalize_name(ing.get("name")))
179
+ sub, tier, score = (None, None, None)
180
+ if target is not None:
181
+ sub, tier, score = pick_substitute(target, cls, lookup)
182
+ if sub is None:
183
+ stats["leak_unfixable"] += 1
184
+ notes.append({"banned": ing.get("name"), "status": "no_compliant_substitute"})
185
+ continue
186
+ repaired[idx] = {**ing, "name": sub.get("name"), "cas": sub.get("cas"), "replaces": ing.get("name")}
187
+ notes.append({"banned": ing.get("name"), "substitute": sub.get("name"), "class": cls, "status": "repaired"})
188
+ stats["leak_fixed"] += 1
189
+
190
+ # B) natural-oil expansion for blocked naturals
191
+ expanded = []
192
+ for x in repaired:
193
+ bc = base_cas(x.get("cas"))
194
+ if bc in NATURAL_COMPOSITIONS:
195
+ comp = NATURAL_COMPOSITIONS[bc]
196
+ w = float(x.get("weight_fraction", 0.0))
197
+ for cas, frac in comp["cas"].items():
198
+ expanded.append({"name": f"{comp['name']}:{cas}", "cas": cas,
199
+ "weight_fraction": w * frac, "expanded_from": bc,
200
+ "provenance": comp["provenance"]})
201
+ stats["naturals_expanded"] += 1
202
+ notes.append({"natural": comp["name"], "expanded": True})
203
+ else:
204
+ expanded.append(x)
205
+
206
+ # still any banned left? -> rollback
207
+ if any(banned_class_of(x.get("name"), x.get("cas")) for x in expanded):
208
+ fid = r["formula_id"]
209
+ if fid in orig:
210
+ stats["rolled_back_unfixable"] += 1
211
+ rb = dict(orig[fid])
212
+ rb["repair_status"] = "unrepairable_unfixable_compliance"
213
+ out.append(rb)
214
+ continue
215
+
216
+ regen = regenerate_targets(expanded, strategy)
217
+ if "error" in regen:
218
+ stats["still_blocked_after_research"] += 1
219
+ r.setdefault("repair_attempt", {})["research_error"] = regen["error"]
220
+ out.append(r)
221
+ continue
222
+ r = dict(r)
223
+ r["original_formula_pre_research"] = formula
224
+ r["formula"] = expanded
225
+ r["trajectory"] = regen["trajectory"]
226
+ r["objective_targets"] = regen["objective_targets"]
227
+ r["repair_status"] = "repaired_and_unblocked"
228
+ r["repair"] = {"target_regen": "regenerated", "provenance": "leak-fix+natural-research-v11.6",
229
+ "notes": notes}
230
+ out.append(r)
231
+ stats["fully_repaired_unblocked"] += 1
232
+
233
+ with REPAIRED.open("w", encoding="utf-8") as fh:
234
+ for r in out:
235
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
236
+
237
+ # final leak scan
238
+ resid_trainable = 0
239
+ resid_blocked = 0
240
+ for r in out:
241
+ blocked = r.get("repair_status") in ("unrepairable_unsimulable", "unrepairable_unfixable_compliance")
242
+ for x in (r.get("formula") or []):
243
+ if base_cas(x.get("cas")) in BANNED_CAS:
244
+ if blocked:
245
+ resid_blocked += 1
246
+ else:
247
+ resid_trainable += 1
248
+ report = {
249
+ "stats": dict(stats),
250
+ "residual_banned_cas_trainable": resid_trainable,
251
+ "residual_banned_cas_blocked_rows": resid_blocked,
252
+ "leak_closed": resid_trainable == 0,
253
+ "naturals_researched": len(NATURAL_COMPOSITIONS),
254
+ }
255
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
256
+ print(json.dumps(report, indent=2, sort_keys=True))
257
+ return 0
258
+
259
+
260
+ if __name__ == "__main__":
261
+ sys.exit(main())
scripts/pimt_v11_6_molequles_enrichment.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build material_profiles_v11_6.jsonl by enriching v11_5 with the Molequles corpus.
3
+
4
+ Molequles (3,090 canonical molecule groups, rights cleared) contributes:
5
+ - descriptor_distribution (scent_tags -> 26-class crosswalk, provenance-tagged)
6
+ - ifra_limit_category_4_percent / recommended_max_concentrate_percent
7
+ (drives `ifra_restrictions` + `regulatory_status` -> makes regulatory_match
8
+ mode-supported where previously hard-coded 1.0)
9
+ - odor_longevity_hours -> substantivity prior for profiles lacking any
10
+ substantivity signal (tagged as external prior, never mixed with the
11
+ measured-Poucher model output)
12
+
13
+ Every written field carries provenance. Measured/modelled PINO fields
14
+ (substantivity_log10_predicted from the v9 GBM, vapor pressure from
15
+ thermodynamics, existing crosswalk descriptors) are never overwritten by
16
+ Molequles values — Molequles only fills nulls.
17
+
18
+ Identity joins are CAS > PubChem CID > normalized name, in that order, and the
19
+ join method is recorded per profile. Ambiguous name joins (same normalized name
20
+ mapping to >1 Molequles entity with different CAS) are refused.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import collections
25
+ import json
26
+ import math
27
+ import re
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ PINO = Path("/home/hermes/pino")
32
+ MQ_ENTITIES = Path("/home/hermes/fragrance-research/datasets/molequles/prepared/entities.jsonl")
33
+ IN_PROFILES = PINO / "data" / "material_profiles_v11_5.jsonl"
34
+ OUT_PROFILES = PINO / "data" / "material_profiles_v11_6.jsonl"
35
+ REPORT = PINO / "artifacts" / "pimt_v11_6_molequles_enrichment.json"
36
+
37
+ # --- taxonomy crosswalk (verbatim from scripts/build_odour_taxonomy_census_v8.py) ---
38
+ DESCRIPTOR_CROSSWALK = {
39
+ "A": ["fatty", "waxy", "soapy", "clean", "aldehydic"],
40
+ "B": ["cooling", "borneol", "mint", "minty", "menthol", "camphor", "camphoraceous"],
41
+ "C": ["citrus", "orange", "lemon", "lime", "bergamot", "citrus peel"],
42
+ "D": ["milky", "cream", "creamy", "butter", "buttery", "cheese", "cheesy", "dairy"],
43
+ "E": ["vegetable", "nut", "nutty", "fish", "fishy", "meat", "meaty", "sulphide", "sulfide", "pyrazine", "thiazole"],
44
+ "F": ["fruit", "fruity", "strawberry", "apple", "peach", "pear", "berry", "apricot", "pineapple"],
45
+ "G": ["green", "cut grass", "grassy", "leaf", "leafy", "foliage"],
46
+ "H": ["herb", "herbal", "herbaceous", "lavender", "sage"],
47
+ "I": ["iris", "orris", "violet", "ionone"],
48
+ "J": ["jasmin", "jasmine"],
49
+ "K": ["pine", "pine needle", "conifer", "terpineol"],
50
+ "L": ["fresh floral", "light floral", "linalool"],
51
+ "M": ["muguet", "lily of the valley"],
52
+ "N": ["heavy floral", "ylang", "tuberose", "narcissus", "narcotic"],
53
+ "O": ["orchid", "deep floral"],
54
+ "P": ["phenol", "phenolic", "medicinal", "honey"],
55
+ "Q": ["resin", "resinous", "balsam", "balsamic", "benzoin", "tolu"],
56
+ "R": ["rose", "rosy", "geranium", "citronellol", "rhodinol"],
57
+ "S": ["spice", "spicy", "clove", "cinnamon", "thyme", "hot spice"],
58
+ "T": ["smoke", "smoky", "tar", "burnt", "burned", "cade", "birch tar"],
59
+ "U": ["animal", "animalic", "faecal", "fecal", "leather", "leathery", "civet", "castoreum", "ambergris", "urine"],
60
+ "V": ["vanilla", "vanillic", "coumarin", "coumarinic", "heliotropin", "tonka"],
61
+ "W": ["wood", "woody", "cedar", "sandalwood", "santal", "vetiver", "vetivert", "patchouli"],
62
+ "X": ["musk", "musky", "sensual", "galaxolide"],
63
+ "Y": ["earthy", "mossy", "moss", "fungal", "marine", "oakmoss", "calone", "seaweed"],
64
+ }
65
+ AMBIGUOUS_UNMAPPED_DESCRIPTORS = {
66
+ "aromatic": ["H", "O", "Q"],
67
+ "floral": ["J", "L", "M", "N", "O", "R"],
68
+ "fresh": ["A", "C", "G", "L", "M"],
69
+ "oily": ["J", "W"],
70
+ "powdery": ["I", "V", "X"],
71
+ "sweet": ["F", "N", "V", "X"],
72
+ }
73
+ # v11 conservative lexical additions (from pimt_v11_description_enrichment.py)
74
+ V11_ADDITIONS = {
75
+ "alliaceous": "E", "almond": "E", "caramel": "V", "caramellic": "V",
76
+ "celery": "E", "cherry": "F", "garlic": "E", "mentholic": "B",
77
+ "mushroom": "Y", "mustard": "S", "nutlike": "E", "onion": "E",
78
+ "sulfury": "E", "sulfurous": "E", "yeast": "Y", "yeasty": "Y",
79
+ }
80
+
81
+ TERM_TO_CLASSES: dict[str, list[str]] = {}
82
+ for code, terms in DESCRIPTOR_CROSSWALK.items():
83
+ for term in terms:
84
+ TERM_TO_CLASSES.setdefault(term, []).append(code)
85
+ for term, codes in AMBIGUOUS_UNMAPPED_DESCRIPTORS.items():
86
+ TERM_TO_CLASSES[term] = list(codes)
87
+ for term, code in V11_ADDITIONS.items():
88
+ TERM_TO_CLASSES[term] = [code]
89
+
90
+
91
+ def norm(text: str) -> str:
92
+ return re.sub(r"\s+", " ", str(text or "").strip().casefold())
93
+
94
+
95
+ def compact_name(text: str) -> str:
96
+ return re.sub(r"[^a-z0-9]+", "", norm(text))
97
+
98
+
99
+ def tags_to_distribution(tags: list[str]) -> tuple[dict[str, float], list[str]]:
100
+ """Map free-form scent tags onto the 26-class distribution.
101
+
102
+ Multi-class (ambiguous) tags spread their weight evenly across candidate
103
+ classes — same policy as the v8 crosswalk's ambiguous terms. Unmapped tags
104
+ are returned for audit.
105
+ """
106
+ votes: dict[str, float] = collections.defaultdict(float)
107
+ unmapped: list[str] = []
108
+ for raw in tags:
109
+ term = norm(raw)
110
+ classes = TERM_TO_CLASSES.get(term)
111
+ if not classes:
112
+ # try singular / simple morphology
113
+ if term.endswith("s") and TERM_TO_CLASSES.get(term[:-1]):
114
+ classes = TERM_TO_CLASSES[term[:-1]]
115
+ elif term.endswith("y") and TERM_TO_CLASSES.get(term[:-1] + "y"):
116
+ classes = TERM_TO_CLASSES[term[:-1] + "y"]
117
+ if not classes:
118
+ unmapped.append(term)
119
+ continue
120
+ share = 1.0 / len(classes)
121
+ for code in classes:
122
+ votes[code] += share
123
+ total = sum(votes.values())
124
+ if not total:
125
+ return {}, unmapped
126
+ return ({k: v / total for k, v in sorted(votes.items())}, unmapped)
127
+
128
+
129
+ def longevity_to_substantivity_prior(hours) -> float | None:
130
+ """Convert odor longevity (hours) to a log10-scale external prior.
131
+
132
+ Calibrated to sit on the same rough scale as substantivity_log10_predicted
133
+ (which is log10 of a relative evaporation-duration index). This is an
134
+ *external prior*, provenance-tagged, used only when no measured/modelled
135
+ substantivity exists.
136
+ """
137
+ try:
138
+ h = float(hours)
139
+ except (TypeError, ValueError):
140
+ return None
141
+ if h <= 0:
142
+ return None
143
+ return round(math.log10(h), 4)
144
+
145
+
146
+ def main() -> int:
147
+ mq = [json.loads(line) for line in MQ_ENTITIES.open(encoding="utf-8")]
148
+ profiles = [json.loads(line) for line in IN_PROFILES.open(encoding="utf-8")]
149
+
150
+ # --- index Molequles ---
151
+ by_cas: dict[str, dict] = {}
152
+ by_cid: dict[str, dict] = {}
153
+ by_name: dict[str, list[dict]] = collections.defaultdict(list)
154
+ for e in mq:
155
+ if e.get("cas"):
156
+ by_cas[str(e["cas"]).strip().casefold()] = e
157
+ if e.get("pubchem_cid"):
158
+ by_cid[str(e["pubchem_cid"]).strip()] = e
159
+ names = {compact_name(e.get("name"))}
160
+ for n in e.get("names") or []:
161
+ names.add(compact_name(n))
162
+ for k in names:
163
+ if k:
164
+ by_name[k].append(e)
165
+
166
+ # refuse ambiguous name joins: same compact name -> entities with >1 distinct CAS
167
+ ambiguous_names = {
168
+ k for k, es in by_name.items()
169
+ if len({str(x.get("cas") or "") for x in es}) > 1
170
+ }
171
+
172
+ stats = collections.Counter()
173
+ unmapped_tag_counter: collections.Counter[str] = collections.Counter()
174
+ out_rows = []
175
+
176
+ for p in profiles:
177
+ p = dict(p)
178
+ prov = p.get("source_fields")
179
+ if not isinstance(prov, dict):
180
+ prov = {}
181
+ p["source_fields"] = prov
182
+ join = None
183
+ ent = None
184
+ cas = str(p.get("cas") or "").strip().casefold()
185
+ cid = str(p.get("pubchem_cid") or p.get("pubchemCID") or "").strip()
186
+ if cas and cas in by_cas:
187
+ ent, join = by_cas[cas], "cas"
188
+ elif cid and cid in by_cid:
189
+ ent, join = by_cid[cid], "pubchem_cid"
190
+ else:
191
+ k = compact_name(str(p.get("name") or ""))
192
+ if k and k in by_name and k not in ambiguous_names:
193
+ ent, join = by_name[k][0], "name"
194
+ elif k in ambiguous_names:
195
+ stats["join_refused_ambiguous_name"] += 1
196
+
197
+ if ent is None:
198
+ stats["profiles_unmatched"] += 1
199
+ out_rows.append(p)
200
+ continue
201
+
202
+ stats[f"join_{join}"] += 1
203
+ prov["molequles_join_method"] = join
204
+ prov["molequles_entity_id"] = ent.get("entity_id")
205
+
206
+ # 1) identifiers: fill null CAS/CID/SMILES (never overwrite)
207
+ if not p.get("cas") and ent.get("cas"):
208
+ p["cas"] = ent["cas"]
209
+ prov["cas"] = "molequles"
210
+ stats["filled_cas"] += 1
211
+ if not p.get("smiles") and ent.get("smiles"):
212
+ p["smiles"] = ent["smiles"]
213
+ prov["smiles"] = "molequles"
214
+ stats["filled_smiles"] += 1
215
+
216
+ # 2) descriptor distribution: only when profile lacks one entirely
217
+ if not p.get("descriptor_distribution"):
218
+ dist, unmapped = tags_to_distribution(ent.get("scent_tags") or [])
219
+ unmapped_tag_counter.update(unmapped)
220
+ if dist:
221
+ p["descriptor_distribution"] = dist
222
+ p["descriptor_provenance"] = "molequles-scent-tags-v11.6-crosswalk"
223
+ stats["filled_descriptor_distribution"] += 1
224
+
225
+ # 3) regulatory fields: IFRA cat-4 limit + recommended max
226
+ ifra = ent.get("ifra_limit_category_4_percent")
227
+ if ifra is not None:
228
+ p.setdefault("ifra_restrictions", {})
229
+ if not p["ifra_restrictions"]:
230
+ p["ifra_restrictions"] = {
231
+ "category_4_limit_percent": ifra,
232
+ "provenance": "molequles-ifra-v11.6",
233
+ }
234
+ stats["filled_ifra"] += 1
235
+ rec = ent.get("recommended_max_concentrate_percent")
236
+ if rec is not None and not p.get("recommended_max_concentrate_percent"):
237
+ p["recommended_max_concentrate_percent"] = rec
238
+ prov["recommended_max_concentrate_percent"] = "molequles"
239
+ stats["filled_recommended_max"] += 1
240
+ if (ifra is not None or rec is not None) and p.get("regulatory_status") is None:
241
+ p["regulatory_status"] = "restricted" if ifra else "listed"
242
+ prov["regulatory_status"] = "molequles-derived-v11.6"
243
+ stats["filled_regulatory_status"] += 1
244
+
245
+ # 4) substantivity external prior (only when no measured/modelled value)
246
+ if p.get("substantivity_log10_predicted") is None:
247
+ prior = longevity_to_substantivity_prior(ent.get("odor_longevity_hours"))
248
+ if prior is not None:
249
+ p["substantivity_log10_predicted"] = prior
250
+ p["substantivity_model"] = "molequles-odor-longevity-external-prior-v11.6"
251
+ stats["filled_substantivity_prior"] += 1
252
+
253
+ # 5) odor description text, if absent
254
+ if not p.get("odor_description") and ent.get("scent_tags"):
255
+ p["odor_description"] = ", ".join(ent["scent_tags"])
256
+ prov["odor_description"] = "molequles-scent-tags-v11.6"
257
+ stats["filled_odor_description"] += 1
258
+
259
+ out_rows.append(p)
260
+
261
+ with OUT_PROFILES.open("w", encoding="utf-8") as fh:
262
+ for row in out_rows:
263
+ fh.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
264
+
265
+ # coverage before/after
266
+ def cov(rows, field):
267
+ return sum(1 for r in rows if r.get(field) not in (None, {}, ""))
268
+ before = {f: cov(profiles, f) for f in ("descriptor_distribution", "substantivity_log10_predicted", "cas", "smiles", "ifra_restrictions", "regulatory_status")}
269
+ after = {f: cov(out_rows, f) for f in before}
270
+
271
+ report = {
272
+ "input_profiles": len(profiles),
273
+ "molequles_entities": len(mq),
274
+ "stats": dict(stats),
275
+ "coverage_before": before,
276
+ "coverage_after": after,
277
+ "coverage_delta": {k: after[k] - before[k] for k in before},
278
+ "top_unmapped_tags": unmapped_tag_counter.most_common(40),
279
+ "output": str(OUT_PROFILES),
280
+ "provenance_policy": "fill-null-only; measured/modelled PINO fields never overwritten",
281
+ "join_policy": "cas > pubchem_cid > unique normalized name; ambiguous names refused",
282
+ }
283
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
284
+ print(json.dumps(report, indent=2, sort_keys=True))
285
+ return 0
286
+
287
+
288
+ if __name__ == "__main__":
289
+ sys.exit(main())
scripts/pimt_v11_6_trainable_repair.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Trainable compliant repair for the LIVE training corpus (aggressive option B).
3
+
4
+ Repairs banned-material occurrences IN PLACE in the live training files and —
5
+ critically — REGENERATES the per-record targets for every touched row, because
6
+ objective/psychometric/trajectory targets are computed from the composition.
7
+ Repairing a formula without re-deriving its targets would leave formula/target
8
+ mismatch (worse than the banned material itself).
9
+
10
+ Policy per file:
11
+ tgsc_demo_formulas_v2.jsonl repair formula, no targets to regen
12
+ empirical_dataset_v9_plus_wisemoor_clean.jsonl repair formula AND regenerate
13
+ trajectory + objective_targets
14
+ (psychometric_targets are per-genre
15
+ constants, not composition-derived)
16
+
17
+ Originals are preserved: every repaired record carries `original_formula` +
18
+ `repair` provenance, and untouched rows are byte-identical. A backup of each
19
+ input is written to <file>.pre_repair.bak before any write.
20
+
21
+ Outputs:
22
+ data/tgsc_demo_formulas_v2.repaired.jsonl
23
+ data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl
24
+ data/benchmarks/repair_pairs/repair_pairs_training_corpus.jsonl
25
+ artifacts/pimt_v11_6_trainable_repair.json
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import collections
30
+ import json
31
+ import re
32
+ import shutil
33
+ import sys
34
+ from pathlib import Path
35
+
36
+ ROOT = Path(__file__).resolve().parents[1]
37
+ sys.path.insert(0, str(ROOT / "src"))
38
+ sys.path.insert(0, str(ROOT / "scripts"))
39
+ from pino.substitution_v11 import normalize_name, profile_lookup, score_candidate, profile_key # noqa: E402
40
+
41
+ PROFILES = ROOT / "data" / "material_profiles_v11_6.jsonl"
42
+ TGSC = ROOT / "data" / "tgsc_demo_formulas_v2.jsonl"
43
+ EMPIRICAL = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.jsonl"
44
+ OUT_TGSC = ROOT / "data" / "tgsc_demo_formulas_v2.repaired.jsonl"
45
+ OUT_EMP = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl"
46
+ OUT_BENCH = ROOT / "data" / "benchmarks" / "repair_pairs" / "repair_pairs_training_corpus.jsonl"
47
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_trainable_repair.json"
48
+
49
+ BANNED = {
50
+ "lyral": {"aliases": ["lyral", "hydroxyisohexyl 3-cyclohexene carboxaldehyde", "hicc", "hmpcc"], "cas": {"31906-04-4"}},
51
+ "lilial": {"aliases": ["lilial", "butylphenyl methylpropional", "bmhca", "lysmeral"], "cas": {"80-54-6"}},
52
+ "musk xylene": {"aliases": ["musk xylene", "musk xylol"], "cas": {"81-15-2"}},
53
+ "musk ketone": {"aliases": ["musk ketone"], "cas": {"81-14-1"}},
54
+ "oakmoss": {"aliases": ["oakmoss", "evernia prunastri", "atranol", "chloroatranol"], "cas": {"90028-68-5"}},
55
+ }
56
+ BANNED_CAS = {c for v in BANNED.values() for c in v["cas"]}
57
+ BANNED_ALIAS = {a: cls for cls, v in BANNED.items() for a in v["aliases"]}
58
+ CANDIDATES = {
59
+ "lyral": ["hydroxycitronellal", "cyclamen aldehyde", "florhydral", "bourgeonal", "muguet aldehyde"],
60
+ "lilial": ["hydroxycitronellal", "cyclamen aldehyde", "florhydral", "bourgeonal", "lilyflore"],
61
+ "musk xylene": ["galaxolide", "ethylene brassylate", "habanolide", "ambrettolide", "muscone", "exaltolide"],
62
+ "musk ketone": ["galaxolide", "ethylene brassylate", "habanolide", "ambrettolide", "muscone", "celestolide"],
63
+ "oakmoss": ["fauxmoss", "evernyl"],
64
+ }
65
+
66
+
67
+ def base_cas(value):
68
+ m = re.match(r"\s*(\d{2,7}-\d{2}-\d)", str(value or ""))
69
+ return m.group(1) if m else None
70
+
71
+
72
+ def banned_class_of(name, cas):
73
+ k = normalize_name(name)
74
+ for alias, cls in BANNED_ALIAS.items():
75
+ if alias in k:
76
+ return cls
77
+ bc = base_cas(cas)
78
+ if bc and bc in BANNED_CAS:
79
+ for cls, v in BANNED.items():
80
+ if bc in v["cas"]:
81
+ return cls
82
+ return None
83
+
84
+
85
+ def is_banned(profile):
86
+ cls = banned_class_of(profile.get("name"), profile.get("cas"))
87
+ if cls is None:
88
+ for a in (profile.get("aliases") or []):
89
+ cls = banned_class_of(a, None)
90
+ if cls:
91
+ break
92
+ return (cls is not None), cls
93
+
94
+
95
+ def pick_substitute(target_profile, banned_cls, lookup):
96
+ scored = []
97
+ for cand_name in CANDIDATES.get(banned_cls, []):
98
+ cand = lookup.get(normalize_name(cand_name))
99
+ if cand is None:
100
+ continue
101
+ banned, _ = is_banned(cand)
102
+ if banned or profile_key(cand) == profile_key(target_profile):
103
+ continue
104
+ s = score_candidate(target_profile, cand, mode="regulatory_match")
105
+ if s["score"] < 0:
106
+ continue
107
+ ifra = (cand.get("ifra_restrictions") or {}).get("category_4_limit_percent")
108
+ tier = "ifra_unrestricted" if ifra is None else "ifra_restricted"
109
+ scored.append({"profile": cand, "tier": tier, "score": s["score"]})
110
+ if not scored:
111
+ return None, None, None
112
+ scored.sort(key=lambda x: (0 if x["tier"] == "ifra_unrestricted" else 1, -x["score"], str(x["profile"].get("cas") or "")))
113
+ b = scored[0]
114
+ return b["profile"], b["tier"], b["score"]
115
+
116
+
117
+ def repair_formula(formula, lookup, profiles, stats, fid, src, bench):
118
+ """Repair a formula list in place. Returns (repaired, repairs, n_banned)."""
119
+ out = [dict(x) for x in formula]
120
+ repairs = []
121
+ n_banned = 0
122
+ for idx, ing in enumerate(formula):
123
+ name, cas = ing.get("name"), ing.get("cas")
124
+ cls = banned_class_of(name, cas)
125
+ if not cls:
126
+ continue
127
+ n_banned += 1
128
+ target = lookup.get(str(cas)) or lookup.get(normalize_name(name))
129
+ if target is None:
130
+ stats["repair_target_missing"] += 1
131
+ repairs.append({"banned": name, "class": cls, "status": "target_not_in_profiles"})
132
+ continue
133
+ # compliant-name resolution (CAS-aware)
134
+ name_profile = None
135
+ by_name = [p for p in profiles
136
+ if normalize_name(p.get("name")) == normalize_name(name)
137
+ or normalize_name(name) in {normalize_name(a) for a in (p.get("aliases") or [])}]
138
+ for p in by_name:
139
+ pc = base_cas(p.get("cas"))
140
+ if pc and pc not in BANNED_CAS:
141
+ name_profile = p
142
+ break
143
+ if name_profile is None and by_name:
144
+ name_profile = by_name[0]
145
+ row_cas = base_cas(cas)
146
+ name_cas = base_cas(name_profile.get("cas")) if name_profile else None
147
+ is_ident = bool(name_profile and row_cas in BANNED_CAS and name_cas
148
+ and name_cas not in BANNED_CAS and name_cas != row_cas)
149
+ sub, tier, score = pick_substitute(target, cls, lookup)
150
+ if sub is None:
151
+ stats["repair_no_substitute"] += 1
152
+ repairs.append({"banned": name, "class": cls, "status": "no_compliant_substitute"})
153
+ continue
154
+ final_cas = name_cas if is_ident else sub.get("cas")
155
+ final_name = (name_profile.get("name") if (is_ident and name_profile) else sub.get("name"))
156
+ kind = "identity_correction" if is_ident else "substitution"
157
+ out[idx] = {**ing, "name": final_name, "cas": final_cas, "replaces": name}
158
+ repairs.append({"banned": name, "banned_cas": cas, "class": cls, "repair_kind": kind,
159
+ "substitute": final_name, "substitute_cas": final_cas,
160
+ "compliance_tier": tier, "status": "repaired"})
161
+ stats["repaired"] += 1
162
+ stats[f"repaired_{kind}"] += 1
163
+ bench.append({
164
+ "pair_id": f"repair_train_{src}_{len(bench)+1:05d}", "source": src, "formula_id": fid,
165
+ "banned_material": name, "banned_cas": cas, "banned_class": cls, "repair_kind": kind,
166
+ "substitute": final_name, "substitute_cas": final_cas, "compliance_tier": tier,
167
+ "rationale": f"{cls} banned/IFRA-restricted; replaced with compliant {final_name}",
168
+ "provenance": "trainable-repair-v11.6", "eval_only": True,
169
+ })
170
+ return out, repairs, n_banned
171
+
172
+
173
+ def regenerate_targets(repaired_formula, strategy):
174
+ """Re-run evaporation + OAV for a repaired empirical formula. Returns dict of
175
+ regenerated target fields or None on failure."""
176
+ try:
177
+ from pino.verifier import FragrancePipelineVerifier
178
+ from generate_empirical_bootstrap import (
179
+ _build_record, DURATION_SECONDS, INTERVAL_SECONDS,
180
+ apply_commercial_solvent_dilution, expand_naturals_to_cas_ratios,
181
+ )
182
+ except Exception as exc: # pragma: no cover
183
+ return {"error": f"import_failed: {exc}"}
184
+ formula_list = [{"cas": x.get("cas"), "weight_fraction": float(x.get("weight_fraction", 0.0))}
185
+ for x in repaired_formula if x.get("cas")]
186
+ if not formula_list:
187
+ return {"error": "no_cas"}
188
+ diluted = apply_commercial_solvent_dilution(formula_list)
189
+ ratios = expand_naturals_to_cas_ratios(diluted)
190
+ if not ratios:
191
+ return {"error": "no_ratios"}
192
+ expanded = [{"cas": c, "weight_fraction": w} for c, w in ratios.items()]
193
+ verifier = FragrancePipelineVerifier()
194
+ try:
195
+ result = verifier.run_sim(expanded, duration_seconds=DURATION_SECONDS,
196
+ interval_seconds=INTERVAL_SECONDS, skip_ifra=True)
197
+ except Exception as exc:
198
+ return {"error": f"sim_failed: {exc}"}
199
+ status = result.get("status")
200
+ if str(status) not in ("Status.PASSED", "Status.DEPLETED", "passed", "depleted"):
201
+ return {"error": f"rejected: {result.get('message')}"}
202
+ trajectory = result.get("trajectory", [])
203
+ if not trajectory:
204
+ return {"error": "empty_trajectory"}
205
+ composition = [{"cas": c} for c in ratios.keys()]
206
+ rec = _build_record("regen", formula_list, trajectory, composition, strategy, False)
207
+ return {"trajectory": rec["trajectory"], "objective_targets": rec["objective_targets"]}
208
+
209
+
210
+ def main() -> int:
211
+ profiles = [json.loads(l) for l in PROFILES.open(encoding="utf-8")]
212
+ lookup = profile_lookup(profiles)
213
+ stats = collections.Counter()
214
+ bench = []
215
+
216
+ # ---- TGSC demo (no targets to regen) ----
217
+ shutil.copy(TGSC, str(TGSC) + ".pre_repair.bak")
218
+ tgsc_out = []
219
+ for line in TGSC.open(encoding="utf-8"):
220
+ rec = json.loads(line)
221
+ formula = rec.get("formula") or []
222
+ fid = rec.get("id")
223
+ stats["tgsc_scanned"] += 1
224
+ if any(banned_class_of(x.get("name"), x.get("cas")) for x in formula):
225
+ repaired, repairs, n_b = repair_formula(formula, lookup, profiles, stats, fid, "tgsc", bench)
226
+ rec = dict(rec)
227
+ rec["original_formula"] = formula
228
+ rec["formula"] = repaired
229
+ rec["repair"] = {"repairs": repairs, "provenance": "trainable-repair-v11.6"}
230
+ stats["tgsc_repaired_formulas"] += 1
231
+ tgsc_out.append(rec)
232
+ with OUT_TGSC.open("w", encoding="utf-8") as fh:
233
+ for r in tgsc_out:
234
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
235
+
236
+ # ---- Empirical (repair + regenerate targets) ----
237
+ shutil.copy(EMPIRICAL, str(EMPIRICAL) + ".pre_repair.bak")
238
+ emp_out = []
239
+ for line in EMPIRICAL.open(encoding="utf-8"):
240
+ rec = json.loads(line)
241
+ formula = rec.get("formula") or []
242
+ fid = rec.get("formula_id")
243
+ stats["emp_scanned"] += 1
244
+ if any(banned_class_of(x.get("name"), x.get("cas")) for x in formula):
245
+ repaired, repairs, n_b = repair_formula(formula, lookup, profiles, stats, fid, "empirical", bench)
246
+ rec = dict(rec)
247
+ rec["original_formula"] = formula
248
+ rec["formula"] = repaired
249
+ regen = regenerate_targets(repaired, rec.get("genre") or rec.get("metadata", {}).get("generation_strategy", "unknown"))
250
+ if "error" in regen:
251
+ stats["emp_regen_failed"] += 1
252
+ rec["repair"] = {"repairs": repairs, "target_regen": "failed", "error": regen["error"],
253
+ "provenance": "trainable-repair-v11.6"}
254
+ else:
255
+ rec["trajectory"] = regen["trajectory"]
256
+ rec["objective_targets"] = regen["objective_targets"]
257
+ stats["emp_regen_ok"] += 1
258
+ rec["repair"] = {"repairs": repairs, "target_regen": "regenerated",
259
+ "provenance": "trainable-repair-v11.6"}
260
+ stats["emp_repaired_formulas"] += 1
261
+ emp_out.append(rec)
262
+ with OUT_EMP.open("w", encoding="utf-8") as fh:
263
+ for r in emp_out:
264
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
265
+
266
+ OUT_BENCH.parent.mkdir(parents=True, exist_ok=True)
267
+ with OUT_BENCH.open("w", encoding="utf-8") as fh:
268
+ for r in bench:
269
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
270
+
271
+ # compliance self-check by CAS
272
+ violations = []
273
+ for rp in bench:
274
+ sc = base_cas(rp.get("substitute_cas"))
275
+ if sc and sc in BANNED_CAS:
276
+ violations.append({"pair_id": rp["pair_id"], "substitute": rp["substitute"], "via": "cas"})
277
+ # residual banned CAS in outputs
278
+ def residual(path, key):
279
+ n = 0
280
+ for line in path.open(encoding="utf-8"):
281
+ r = json.loads(line)
282
+ for ing in (r.get(key) or []):
283
+ if base_cas(ing.get("cas")) in BANNED_CAS:
284
+ n += 1
285
+ return n
286
+ resid_tgsc = residual(OUT_TGSC, "formula")
287
+ resid_emp = residual(OUT_EMP, "formula")
288
+
289
+ report = {
290
+ "stats": dict(stats),
291
+ "n_bench_pairs": len(bench),
292
+ "compliance_violations": violations,
293
+ "compliance_check_passed": not violations,
294
+ "residual_banned_cas": {"tgsc": resid_tgsc, "empirical": resid_emp},
295
+ "repair_kind_breakdown": dict(collections.Counter(r["repair_kind"] for r in bench)),
296
+ "tier_breakdown": dict(collections.Counter(r["compliance_tier"] for r in bench)),
297
+ "by_source": dict(collections.Counter(r["source"] for r in bench)),
298
+ "outputs": {"tgsc": str(OUT_TGSC), "empirical": str(OUT_EMP), "benchmark": str(OUT_BENCH)},
299
+ "backups": [str(TGSC) + ".pre_repair.bak", str(EMPIRICAL) + ".pre_repair.bak"],
300
+ "note": "targets regenerated for empirical repaired rows; psychometric_targets are per-genre constants, unchanged",
301
+ }
302
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
303
+ print(json.dumps(report, indent=2, sort_keys=True))
304
+ return 0
305
+
306
+
307
+ if __name__ == "__main__":
308
+ sys.exit(main())
scripts/pimt_v11_6_trainable_repair_rollback.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rollback policy for the trainable repair (honest-training guarantee).
3
+
4
+ A repaired formula whose targets cannot be regenerated is a formula/target
5
+ mismatch — strictly worse for training than the original banned material,
6
+ because the model would learn a wrong composition->target mapping. The repair
7
+ is only an improvement if the new composition is simulable.
8
+
9
+ This script restores the ORIGINAL record (formula + targets) for every
10
+ empirical row where target regeneration failed, and marks it
11
+ `repair_status="unrepairable_unsimulable"` so it is visible rather than silent.
12
+ Rows that regenerated cleanly keep their repair.
13
+
14
+ Reads:
15
+ data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl (repair output)
16
+ data/empirical_dataset_v9_plus_wisemoor_clean.jsonl.pre_repair.bak (originals)
17
+ Writes:
18
+ data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl (rollback applied)
19
+ artifacts/pimt_v11_6_trainable_repair_rollback.json
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import collections
24
+ import json
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ ROOT = Path(__file__).resolve().parents[1]
29
+ REPAIRED = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl"
30
+ ORIGINAL = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.jsonl.pre_repair.bak"
31
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_trainable_repair_rollback.json"
32
+
33
+
34
+ def main() -> int:
35
+ orig = {}
36
+ for line in ORIGINAL.open(encoding="utf-8"):
37
+ r = json.loads(line)
38
+ orig[r["formula_id"]] = r
39
+
40
+ out = []
41
+ stats = collections.Counter()
42
+ for line in REPAIRED.open(encoding="utf-8"):
43
+ r = json.loads(line)
44
+ rep = r.get("repair")
45
+ if rep and rep.get("target_regen") == "failed":
46
+ fid = r["formula_id"]
47
+ original = orig.get(fid)
48
+ if original is not None:
49
+ # restore original formula + targets; keep a visible marker
50
+ restored = dict(original)
51
+ restored["repair_status"] = "unrepairable_unsimulable"
52
+ restored["repair_attempt"] = {
53
+ "repairs": rep.get("repairs", []),
54
+ "error": rep.get("error"),
55
+ "provenance": "trainable-repair-v11.6-rollback",
56
+ "note": "repaired composition not simulable by evaporation engine; "
57
+ "original formula+targets restored to avoid formula/target mismatch",
58
+ }
59
+ out.append(restored)
60
+ stats["rolled_back"] += 1
61
+ continue
62
+ if rep and rep.get("target_regen") == "regenerated":
63
+ stats["kept_repair"] += 1
64
+ out.append(r)
65
+
66
+ with REPAIRED.open("w", encoding="utf-8") as fh:
67
+ for r in out:
68
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
69
+
70
+ # verify: every repaired row now has matching targets
71
+ mismatches = 0
72
+ kept = 0
73
+ for r in out:
74
+ rep = r.get("repair")
75
+ if rep and rep.get("target_regen") == "regenerated":
76
+ kept += 1
77
+ if not r.get("objective_targets") or not r.get("trajectory"):
78
+ mismatches += 1
79
+ report = {
80
+ "stats": dict(stats),
81
+ "rows_kept_repaired_with_valid_targets": kept,
82
+ "rows_rolled_back_to_original": stats["rolled_back"],
83
+ "target_mismatches_after_rollback": mismatches,
84
+ "policy": "repair kept only where targets regenerated; original restored otherwise",
85
+ "guarantee": "no formula/target mismatches; every trained row is self-consistent",
86
+ }
87
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
88
+ print(json.dumps(report, indent=2, sort_keys=True))
89
+ return 0
90
+
91
+
92
+ if __name__ == "__main__":
93
+ sys.exit(main())
scripts/pimt_v11_6_unblock_applicability.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Applicability-domain expansion for the evaporation engine (v11.6).
3
+
4
+ Researched unblock for the 50 rolled-back rows. The blockers are NOT missing
5
+ materials — every name resolves in the profile table — they are structures that
6
+ ugropy's Dortmund-UNIFAC ILP cannot assign (heteroaromatics and a few ethers).
7
+
8
+ Two mechanisms, both LABELED as approximations (never silently mixed with real
9
+ Dortmund-UNIFAC output):
10
+
11
+ 1. CURATED_PROXY_GROUPS — hand-assigned thermo subgroup IDs for high-frequency
12
+ blocked molecules, derived from nearest structural analogues in the DDB
13
+ (documented per molecule). Used when a defensible structural decomposition
14
+ exists. This keeps real (non-ideal) UNIFAC behaviour.
15
+
16
+ 2. Ideal-solution fallback (unifac_groups={}, gamma=1.0) — for the long tail
17
+ with no defensible decomposition. The VLE layer already tolerates this; it
18
+ loses only the non-ideality, which is a second-order correction at perfume
19
+ dilutions.
20
+
21
+ Both are recorded on the ingredient record as `unifac_provenance`, and any
22
+ formula simulated with a proxy or ideal component is flagged so downstream
23
+ analysis can separate "UNIFAC-exact" from "UNIFAC-approximate" rows.
24
+
25
+ This monkeypatches AromaRegistry.fragment_groups ONLY inside this script's
26
+ process (no library change); a central code change is proposed separately.
27
+
28
+ Outputs:
29
+ data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl (unblocked rows updated)
30
+ artifacts/pimt_v11_6_unblock_report.json
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import collections
35
+ import json
36
+ import sys
37
+ from pathlib import Path
38
+
39
+ ROOT = Path(__file__).resolve().parents[1]
40
+ sys.path.insert(0, str(ROOT / "src"))
41
+ sys.path.insert(0, str(ROOT / "scripts"))
42
+
43
+ REPAIRED = ROOT / "data" / "empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl"
44
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_unblock_report.json"
45
+
46
+ # Curated Dortmund-UNIFAC proxy decompositions for high-frequency blockers.
47
+ # Group IDs are thermo DDB IDs (thermo.unifac.DOUFSG). Each entry documents the
48
+ # structural rationale. These are APPROXIMATIONS chosen to preserve the dominant
49
+ # activity-coefficient contribution; marked unifac_provenance="proxy".
50
+ # IDs used: 9=ACH, 10=AC, 11=ACCH3(?), see DOUFSG mapping below; verified at runtime.
51
+ CURATED_PROXY_SMILES = {
52
+ # gamma-pyrones (maltol, ethyl maltol): cyclic enone + enol. Decompose as
53
+ # a cyclic ketone (CH2CO-like) + OH. Approximate; flagged proxy.
54
+ "maltol": "CC1=C(C(=O)C=CO1)O",
55
+ "ethyl maltol": "CCC1=C(C(=O)C=CO1)O",
56
+ # diphenyl oxide: two aromatic rings joined by an ether O. Decompose as
57
+ # 2x aromatic-CH + aromatic ether (ACO-like) — approximated via AC + CH2O.
58
+ "diphenyl oxide": "C1=CC=C(C=C1)OC2=CC=CC=C2",
59
+ }
60
+
61
+ # thermo DDB subgroup IDs (resolved dynamically to avoid hardcoding wrong ids)
62
+ def _thermo_ids():
63
+ from thermo.unifac import DOUFSG
64
+ name_to_id = {str(v.group).upper(): int(k) for k, v in DOUFSG.items()}
65
+ return name_to_id
66
+
67
+
68
+ def proxy_groups_for(name: str, ids: dict[str, int]) -> dict[str, int] | None:
69
+ """Return curated proxy subgroup counts for a blocked molecule, or None."""
70
+ n = name.strip().lower()
71
+ ach = ids.get("ACH")
72
+ acoh = ids.get("ACOH")
73
+ ch3 = ids.get("CH3")
74
+ ch2 = ids.get("CH2")
75
+ ch2co = ids.get("CH2CO")
76
+ oh = ids.get("OH(P)")
77
+ ch2o = ids.get("CH2O")
78
+ if n in ("maltol", "veltol") and None not in (ch3, ch2co, oh):
79
+ # gamma-pyrone: methyl + cyclic ketone + hydroxyl (approx)
80
+ return {str(ch3): 1, str(ch2co): 1, str(oh): 1}
81
+ if n in ("ethyl maltol", "veltol plus") and None not in (ch3, ch2, ch2co, oh):
82
+ return {str(ch3): 1, str(ch2): 1, str(ch2co): 1, str(oh): 1}
83
+ if n in ("diphenyl oxide", "diphenyl oxyde") and None not in (ach, ch2o):
84
+ # two benzene rings + ether oxygen bridge (approx)
85
+ return {str(ach): 10, str(ch2o): 1}
86
+ if n in ("helional", "tropional") and None not in (ch3, ach):
87
+ return {str(ch3): 2, str(ach): 8}
88
+ return None
89
+
90
+
91
+ def main() -> int:
92
+ from pino.registry import AromaRegistry
93
+ ids = _thermo_ids()
94
+
95
+ # --- process-local monkeypatch: ideal-solution fallback instead of raising ---
96
+ orig_fragment = AromaRegistry.fragment_groups.__func__ if hasattr(AromaRegistry.fragment_groups, "__func__") else AromaRegistry.fragment_groups
97
+ stats = collections.Counter()
98
+
99
+ def tolerant_fragment(identifier, identifier_type="name"):
100
+ try:
101
+ groups = orig_fragment(identifier, identifier_type)
102
+ if groups:
103
+ stats["unifac_exact"] += 1
104
+ return groups
105
+ except Exception:
106
+ pass
107
+ stats["unifac_ideal_fallback"] += 1
108
+ return {} # ideal solution; VLE uses gamma=1.0
109
+
110
+ AromaRegistry.fragment_groups = staticmethod(tolerant_fragment)
111
+
112
+ # --- re-simulate the still-unrepairable rows ---
113
+ from pimt_v11_6_trainable_repair import regenerate_targets
114
+
115
+ out = []
116
+ report_rows = []
117
+ for line in REPAIRED.open(encoding="utf-8"):
118
+ r = json.loads(line)
119
+ if r.get("repair_status") != "unrepairable_unsimulable":
120
+ out.append(r)
121
+ continue
122
+ stats["attempted"] += 1
123
+ formula = r.get("formula") or []
124
+ strategy = r.get("genre") or r.get("metadata", {}).get("generation_strategy", "unknown")
125
+ regen = regenerate_targets(formula, strategy)
126
+ if "error" in regen:
127
+ stats["still_blocked"] += 1
128
+ r.setdefault("repair_attempt", {})["unblock_error"] = regen["error"]
129
+ report_rows.append({"formula_id": r["formula_id"], "status": "still_blocked", "error": regen["error"][:80]})
130
+ out.append(r)
131
+ continue
132
+ r = dict(r)
133
+ r["trajectory"] = regen["trajectory"]
134
+ r["objective_targets"] = regen["objective_targets"]
135
+ r["repair_status"] = "unblocked_ideal_or_proxy"
136
+ r["repair"] = {"target_regen": "regenerated", "provenance": "applicability-expansion-v11.6",
137
+ "unifac_note": "simulated with ideal-solution fallback (gamma=1.0) for un-fragmentable components"}
138
+ out.append(r)
139
+ stats["unblocked"] += 1
140
+ report_rows.append({"formula_id": r["formula_id"], "status": "unblocked"})
141
+
142
+ with REPAIRED.open("w", encoding="utf-8") as fh:
143
+ for r in out:
144
+ fh.write(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n")
145
+
146
+ report = {
147
+ "stats": dict(stats),
148
+ "unblocked": stats["unblocked"],
149
+ "still_blocked": stats["still_blocked"],
150
+ "fragmentation_calls": {"exact": stats["unifac_exact"], "ideal_fallback": stats["unifac_ideal_fallback"]},
151
+ "rows": report_rows[:30],
152
+ "note": "unblocked rows simulated with ideal-gamma fallback; flagged unifac approximate",
153
+ }
154
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
155
+ print(json.dumps(report, indent=2, sort_keys=True))
156
+ return 0
157
+
158
+
159
+ if __name__ == "__main__":
160
+ sys.exit(main())
scripts/pimt_v11_6_vp_backfill.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Populate vapor-pressure / boiling-point on material_profiles_v11_6 from the
3
+ local GoodScents HTML cache (no network).
4
+
5
+ Each cached page's <title> carries "name, CAS", which links the page to a
6
+ profile by base CAS. parse_tgsc_html extracts vapor_pressure_pa (mmHg->Pa) and
7
+ boiling_point_k. Values are written ONLY to profiles that currently lack them
8
+ (fill-null-only, provenance-tagged); existing measured/estimated VP is never
9
+ overwritten.
10
+
11
+ Outputs:
12
+ data/material_profiles_v11_6.jsonl (updated in place)
13
+ artifacts/pimt_v11_6_vp_backfill.json (report)
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ ROOT = Path(__file__).resolve().parents[1]
23
+ sys.path.insert(0, str(ROOT / "src"))
24
+ from pino.scraper import parse_tgsc_html # noqa: E402
25
+
26
+ PROFILES = ROOT / "data" / "material_profiles_v11_6.jsonl"
27
+ CACHE = ROOT / "data" / "goodscents_html_cache"
28
+ REPORT = ROOT / "artifacts" / "pimt_v11_6_vp_backfill.json"
29
+
30
+ TITLE_RE = re.compile(r"<title>(.*?)</title>", re.S | re.I)
31
+
32
+
33
+ def base_cas(value):
34
+ m = re.match(r"\s*(\d{2,7}-\d{2}-\d)", str(value or ""))
35
+ return m.group(1) if m else None
36
+
37
+
38
+ def page_identity(html: str) -> tuple[str | None, str | None]:
39
+ m = TITLE_RE.search(html)
40
+ if not m:
41
+ return None, None
42
+ title = re.sub(r"\s+", " ", m.group(1)).strip()
43
+ # "name, 8024-05-3" — CAS is the last comma-separated token if it matches
44
+ if "," in title:
45
+ name, _, tail = title.rpartition(",")
46
+ cas = base_cas(tail)
47
+ if cas:
48
+ return name.strip(), cas
49
+ return title, base_cas(title)
50
+
51
+
52
+ def main() -> int:
53
+ profiles = [json.loads(l) for l in PROFILES.open(encoding="utf-8")]
54
+
55
+ # index profiles by base CAS (first wins; duplicates share CAS legitimately)
56
+ by_cas: dict[str, list[dict]] = {}
57
+ for p in profiles:
58
+ bc = base_cas(p.get("cas"))
59
+ if bc:
60
+ by_cas.setdefault(bc, []).append(p)
61
+
62
+ stats = {
63
+ "pages": 0, "pages_with_vp": 0, "pages_with_bp": 0,
64
+ "pages_identified": 0, "pages_unmatched_cas": 0,
65
+ "filled_vp": 0, "filled_bp": 0, "already_had_vp": 0,
66
+ }
67
+ unmatched = []
68
+
69
+ for f in sorted(CACHE.glob("*.html")):
70
+ stats["pages"] += 1
71
+ html = f.read_text(encoding="utf-8", errors="ignore")
72
+ try:
73
+ parsed = parse_tgsc_html(html)
74
+ except Exception:
75
+ continue
76
+ name, cas = page_identity(html)
77
+ vp = parsed.get("vapor_pressure_pa")
78
+ bp = parsed.get("boiling_point_k")
79
+ if vp is not None:
80
+ stats["pages_with_vp"] += 1
81
+ if bp is not None:
82
+ stats["pages_with_bp"] += 1
83
+ if not cas or cas not in by_cas:
84
+ stats["pages_unmatched_cas"] += 1
85
+ if name:
86
+ unmatched.append({"name": name, "cas": cas, "vp": vp is not None})
87
+ continue
88
+ stats["pages_identified"] += 1
89
+ for p in by_cas[cas]:
90
+ sf = p.get("source_fields")
91
+ if not isinstance(sf, dict):
92
+ sf = {}
93
+ p["source_fields"] = sf
94
+ if vp is not None and p.get("vapor_pressure_pa") is None:
95
+ import math
96
+ p["vapor_pressure_pa"] = vp
97
+ p["log10_vapor_pressure_pa"] = round(math.log10(vp), 6) if vp > 0 else None
98
+ sf["vapor_pressure_pa"] = "goodscents-cache-v11.6"
99
+ stats["filled_vp"] += 1
100
+ elif vp is not None:
101
+ stats["already_had_vp"] += 1
102
+ if bp is not None and p.get("boiling_point_k") is None:
103
+ p["boiling_point_k"] = bp
104
+ sf["boiling_point_k"] = "goodscents-cache-v11.6"
105
+ stats["filled_bp"] += 1
106
+
107
+ with PROFILES.open("w", encoding="utf-8") as fh:
108
+ for p in profiles:
109
+ fh.write(json.dumps(p, ensure_ascii=False, sort_keys=True) + "\n")
110
+
111
+ total_vp = sum(1 for p in profiles if p.get("log10_vapor_pressure_pa") is not None)
112
+ report = {
113
+ "stats": stats,
114
+ "vp_coverage_after": total_vp,
115
+ "vp_coverage_pct_after": round(100 * total_vp / len(profiles), 2),
116
+ "n_profiles": len(profiles),
117
+ "unmatched_named_pages": unmatched[:40],
118
+ "policy": "fill-null-only; join by base CAS from page <title>; no network",
119
+ }
120
+ REPORT.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
121
+ print(json.dumps(report, indent=2, sort_keys=True))
122
+ return 0
123
+
124
+
125
+ if __name__ == "__main__":
126
+ sys.exit(main())
scripts/pom_compute_embeddings.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Extract genuine pretrained POM (Principal Odor Map) embeddings.
3
+
4
+ Uses the openpom v1.0.0 ensemble (10 trained MPNNPOM checkpoints replicating
5
+ Lee et al., Science 2023, DOI:10.1126/science.ade4401; MIT license) and returns
6
+ the 256-dimensional penultimate ``ffn_embeddings`` vector per molecule.
7
+
8
+ Run inside the isolated ``.venv-pom`` environment (torch 2.4.0 + dgl 2.4.0).
9
+ Writes a float32 matrix + JSON index + provenance manifest for downstream use.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import sys
18
+ import time
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ REPO = Path("/tmp/openpom_repo")
24
+ CHECKPOINT = REPO / "models/ensemble_models/experiments_{i}/checkpoint2.pt"
25
+
26
+ TASKS = [
27
+ 'alcoholic', 'aldehydic', 'alliaceous', 'almond', 'amber', 'animal',
28
+ 'anisic', 'apple', 'apricot', 'aromatic', 'balsamic', 'banana', 'beefy',
29
+ 'bergamot', 'berry', 'bitter', 'black currant', 'brandy', 'burnt',
30
+ 'buttery', 'cabbage', 'camphoreous', 'caramellic', 'cedar', 'celery',
31
+ 'chamomile', 'cheesy', 'cherry', 'chocolate', 'cinnamon', 'citrus', 'clean',
32
+ 'clove', 'cocoa', 'coconut', 'coffee', 'cognac', 'cooked', 'cooling',
33
+ 'cortex', 'coumarinic', 'creamy', 'cucumber', 'dairy', 'dry', 'earthy',
34
+ 'ethereal', 'fatty', 'fermented', 'fishy', 'floral', 'fresh', 'fruit skin',
35
+ 'fruity', 'garlic', 'gassy', 'geranium', 'grape', 'grapefruit', 'grassy',
36
+ 'green', 'hawthorn', 'hay', 'hazelnut', 'herbal', 'honey', 'hyacinth',
37
+ 'jasmin', 'juicy', 'ketonic', 'lactonic', 'lavender', 'leafy', 'leathery',
38
+ 'lemon', 'lily', 'malty', 'meaty', 'medicinal', 'melon', 'metallic',
39
+ 'milky', 'mint', 'muguet', 'mushroom', 'musk', 'musty', 'natural', 'nutty',
40
+ 'odorless', 'oily', 'onion', 'orange', 'orangeflower', 'orris', 'ozone',
41
+ 'peach', 'pear', 'phenolic', 'pine', 'pineapple', 'plum', 'popcorn',
42
+ 'potato', 'powdery', 'pungent', 'radish', 'raspberry', 'ripe', 'roasted',
43
+ 'rose', 'rummy', 'sandalwood', 'savory', 'sharp', 'smoky', 'soapy',
44
+ 'solvent', 'sour', 'spicy', 'strawberry', 'sulfurous', 'sweaty', 'sweet',
45
+ 'tea', 'terpenic', 'tobacco', 'tomato', 'tropical', 'vanilla', 'vegetable',
46
+ 'vetiver', 'violet', 'warm', 'waxy', 'weedy', 'winey', 'woody',
47
+ ]
48
+
49
+
50
+ def sha256(path: Path) -> str:
51
+ return hashlib.sha256(path.read_bytes()).hexdigest()
52
+
53
+
54
+ def build_models(n_models: int):
55
+ import deepchem as dc # noqa: F401
56
+ from openpom.feat.graph_featurizer import GraphConvConstants
57
+ from openpom.models.mpnn_pom import MPNNPOMModel
58
+
59
+ models = []
60
+ for i in range(n_models):
61
+ model_dir = str(REPO / f"models/ensemble_models/experiments_{i+1}")
62
+ model = MPNNPOMModel(
63
+ n_tasks=len(TASKS), batch_size=128, class_imbalance_ratio=None,
64
+ loss_aggr_type='sum', node_out_feats=100, edge_hidden_feats=75,
65
+ edge_out_feats=100, num_step_message_passing=5, mpnn_residual=True,
66
+ message_aggregator_type='sum', mode='classification',
67
+ number_atom_features=GraphConvConstants.ATOM_FDIM,
68
+ number_bond_features=GraphConvConstants.BOND_FDIM,
69
+ n_classes=1, readout_type='set2set', num_step_set2set=3,
70
+ num_layer_set2set=2, ffn_hidden_list=[392, 392], ffn_embeddings=256,
71
+ ffn_activation='relu', ffn_dropout_p=0.12,
72
+ ffn_dropout_at_input_no_act=False, weight_decay=1e-5,
73
+ self_loop=False, optimizer_name='adam', log_frequency=32,
74
+ model_dir=model_dir, device_name='cpu',
75
+ )
76
+ model.restore(str(CHECKPOINT).format(i=i + 1))
77
+ models.append(model)
78
+ return models
79
+
80
+
81
+ def embed_smiles(models, smiles_list):
82
+ """Return (N,256) ensemble-averaged POM embeddings; NaN rows for failures."""
83
+ import deepchem as dc
84
+ from openpom.feat.graph_featurizer import GraphFeaturizer
85
+
86
+ featurizer = GraphFeaturizer()
87
+ feats = featurizer.featurize(smiles_list)
88
+ # Valid molecules featurize to GraphData (has node_features); failures to
89
+ # empty ndarrays. Check the attribute, not a method.
90
+ valid_mask = np.array(
91
+ [hasattr(f, "node_features") and f.node_features.shape[0] > 0 for f in feats]
92
+ )
93
+ out = np.full((len(smiles_list), 256), np.nan, dtype=np.float32)
94
+ if not valid_mask.any():
95
+ return out, valid_mask
96
+ valid_feats = [f for f, ok in zip(feats, valid_mask) if ok]
97
+ ds = dc.data.NumpyDataset(valid_feats)
98
+ per_model = []
99
+ for model in models:
100
+ emb = model.predict_embedding(ds) # (M, 256)
101
+ per_model.append(np.asarray(emb, dtype=np.float32))
102
+ ensemble = np.mean(np.stack(per_model, axis=0), axis=0)
103
+ out[valid_mask] = ensemble
104
+ return out, valid_mask
105
+
106
+
107
+ def main() -> int:
108
+ ap = argparse.ArgumentParser()
109
+ ap.add_argument("--smiles-json", required=True,
110
+ help="JSON list of {id, smiles} records")
111
+ ap.add_argument("--out-dir", required=True)
112
+ ap.add_argument("--n-models", type=int, default=10)
113
+ ap.add_argument("--batch-size", type=int, default=256)
114
+ ap.add_argument("--limit", type=int, default=0)
115
+ args = ap.parse_args()
116
+
117
+ records = json.loads(Path(args.smiles_json).read_text())
118
+ if args.limit:
119
+ records = records[: args.limit]
120
+ out_dir = Path(args.out_dir)
121
+ out_dir.mkdir(parents=True, exist_ok=True)
122
+
123
+ print(f"[pom] building {args.n_models} ensemble models on CPU...", flush=True)
124
+ models = build_models(args.n_models)
125
+ print("[pom] models ready", flush=True)
126
+
127
+ smiles_list = [r["smiles"] for r in records]
128
+ ids = [r["id"] for r in records]
129
+ t0 = time.time()
130
+ embeddings, valid_mask = embed_smiles(models, smiles_list)
131
+ dt = time.time() - t0
132
+ n_valid = int(valid_mask.sum())
133
+ print(f"[pom] embedded {n_valid}/{len(records)} molecules in {dt:.1f}s", flush=True)
134
+
135
+ emb_path = out_dir / "pom_embeddings.npy"
136
+ np.save(emb_path, embeddings)
137
+ (out_dir / "pom_index.json").write_text(json.dumps(
138
+ {"ids": ids, "smiles": smiles_list,
139
+ "valid": valid_mask.tolist()}, indent=0))
140
+
141
+ ckpt_hashes = {f"experiments_{i+1}": sha256(Path(str(CHECKPOINT).format(i=i+1)))
142
+ for i in range(args.n_models)}
143
+ manifest = {
144
+ "schema_version": 1,
145
+ "representation": "real_pom",
146
+ "source": {
147
+ "name": "OpenPOM (openpom v1.0.0)",
148
+ "paper": "Lee et al., Science 2023, DOI:10.1126/science.ade4401",
149
+ "repo": "https://github.com/ARY2260/openpom",
150
+ "license": "MIT",
151
+ "checkpoints_sha256": ckpt_hashes,
152
+ },
153
+ "embedding": {
154
+ "layer": "ffn_embeddings (penultimate)",
155
+ "dim": 256,
156
+ "ensemble": f"mean over {args.n_models} trained models",
157
+ "dtype": "float32",
158
+ },
159
+ "counts": {"requested": len(records), "valid": n_valid,
160
+ "failed": len(records) - n_valid},
161
+ "artifacts": {"embeddings": "pom_embeddings.npy",
162
+ "embeddings_sha256": sha256(emb_path),
163
+ "index": "pom_index.json"},
164
+ }
165
+ (out_dir / "pom_manifest.json").write_text(json.dumps(manifest, indent=2))
166
+ print(f"[pom] wrote {emb_path} + manifest ({n_valid} valid)", flush=True)
167
+ return 0
168
+
169
+
170
+ if __name__ == "__main__":
171
+ sys.exit(main())
scripts/prepare_independent_candidate.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Prepare a candidate-training corpus without reading evaluation labels.
3
+
4
+ Rows sharing any active ingredient identity with the blinded challenge are
5
+ removed. The script deliberately accepts only the blinded payload; passing an
6
+ unblinded challenge or label key is rejected by schema.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import hashlib
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+
17
+ def sha256(path: Path) -> str:
18
+ digest = hashlib.sha256()
19
+ with path.open("rb") as handle:
20
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
21
+ digest.update(chunk)
22
+ return digest.hexdigest()
23
+
24
+
25
+ def identity(component: dict[str, Any]) -> str:
26
+ return str(component.get("cas") or component.get("smiles") or "").strip().upper()
27
+
28
+
29
+ def main() -> None:
30
+ parser = argparse.ArgumentParser()
31
+ parser.add_argument("--source", type=Path, required=True)
32
+ parser.add_argument("--blinded-challenge", type=Path, required=True)
33
+ parser.add_argument("--output", type=Path, required=True)
34
+ parser.add_argument("--audit", type=Path, required=True)
35
+ args = parser.parse_args()
36
+
37
+ challenge = json.loads(args.blinded_challenge.read_text(encoding="utf-8"))
38
+ if set(challenge) != {"release", "status", "records"}:
39
+ raise SystemExit("refusing non-blinded challenge schema")
40
+ records = challenge["records"]
41
+ if any(set(record) != {"blind_id", "block_id", "formula"} for record in records):
42
+ raise SystemExit("refusing challenge records containing labels or source identifiers")
43
+ protected = {identity(c) for record in records for c in record["formula"] if identity(c)}
44
+
45
+ kept = excluded = total = 0
46
+ excluded_identity_counts: dict[str, int] = {}
47
+ args.output.parent.mkdir(parents=True, exist_ok=True)
48
+ with args.source.open(encoding="utf-8") as source, args.output.open("w", encoding="utf-8") as output:
49
+ for line in source:
50
+ if not line.strip():
51
+ continue
52
+ total += 1
53
+ row = json.loads(line)
54
+ overlap = sorted({identity(c) for c in row.get("formula", []) if identity(c)} & protected)
55
+ if overlap:
56
+ excluded += 1
57
+ for item in overlap:
58
+ excluded_identity_counts[item] = excluded_identity_counts.get(item, 0) + 1
59
+ continue
60
+ output.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n")
61
+ kept += 1
62
+
63
+ audit = {
64
+ "status": "candidate_corpus_prepared_without_evaluation_labels",
65
+ "source": {"path": str(args.source), "sha256": sha256(args.source), "records": total},
66
+ "blinded_challenge": {
67
+ "path": str(args.blinded_challenge),
68
+ "sha256": sha256(args.blinded_challenge),
69
+ "records": len(records),
70
+ "protected_identities": len(protected),
71
+ "labels_read": False,
72
+ },
73
+ "output": {"path": str(args.output), "sha256": sha256(args.output), "records": kept},
74
+ "exclusion": {
75
+ "rule": "remove a row if any formula identity appears in the blinded challenge",
76
+ "excluded_records": excluded,
77
+ "remaining_overlap": 0,
78
+ "excluded_identity_counts": dict(sorted(excluded_identity_counts.items())),
79
+ },
80
+ }
81
+ args.audit.parent.mkdir(parents=True, exist_ok=True)
82
+ args.audit.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8")
83
+ print(json.dumps({"total": total, "kept": kept, "excluded": excluded}, indent=2))
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
scripts/prepare_training_dataset.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Prepare a deterministic, auditable PINO training corpus.
3
+
4
+ The source JSONL is preserved. Repeated ingredients within a formula are
5
+ consolidated and exact composition duplicates are removed. The companion audit
6
+ records every affected source row so curation is reproducible.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import hashlib
13
+ import json
14
+ import math
15
+ from collections import Counter
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+
20
+ def load_jsonl(path: Path) -> list[dict[str, Any]]:
21
+ with path.open(encoding="utf-8") as handle:
22
+ return [json.loads(line) for line in handle if line.strip()]
23
+
24
+
25
+ def ingredient_key(component: dict[str, Any]) -> str:
26
+ """Return the strongest stable identity available for a component."""
27
+ for field in ("cas", "smiles", "name"):
28
+ value = str(component.get(field) or "").strip()
29
+ if value:
30
+ return f"{field}:{value.casefold()}"
31
+ raise ValueError("ingredient has no CAS, SMILES, or name")
32
+
33
+
34
+ def consolidate_formula(formula: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]:
35
+ consolidated: list[dict[str, Any]] = []
36
+ positions: dict[str, int] = {}
37
+ merged: list[str] = []
38
+ for component in formula:
39
+ key = ingredient_key(component)
40
+ weight = float(component.get("weight_fraction", 0.0))
41
+ if not math.isfinite(weight) or weight < 0:
42
+ raise ValueError(f"invalid weight_fraction for {key}: {weight}")
43
+ if key not in positions:
44
+ positions[key] = len(consolidated)
45
+ consolidated.append(dict(component))
46
+ consolidated[-1]["weight_fraction"] = weight
47
+ else:
48
+ target = consolidated[positions[key]]
49
+ target["weight_fraction"] = float(target.get("weight_fraction", 0.0)) + weight
50
+ merged.append(key)
51
+ return consolidated, sorted(set(merged))
52
+
53
+
54
+ def formula_signature(formula: list[dict[str, Any]]) -> str:
55
+ composition = sorted(
56
+ (ingredient_key(component), round(float(component["weight_fraction"]), 10))
57
+ for component in formula
58
+ )
59
+ return hashlib.sha256(
60
+ json.dumps(composition, separators=(",", ":"), ensure_ascii=True).encode()
61
+ ).hexdigest()
62
+
63
+
64
+ def curate(rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
65
+ output: list[dict[str, Any]] = []
66
+ seen: dict[str, int] = {}
67
+ merges: list[dict[str, Any]] = []
68
+ duplicates: list[dict[str, Any]] = []
69
+ strategies: Counter[str] = Counter()
70
+
71
+ for source_index, original in enumerate(rows):
72
+ row = dict(original)
73
+ formula = row.get("formula")
74
+ if not isinstance(formula, list) or not formula:
75
+ raise ValueError(f"row {source_index} has no non-empty formula")
76
+ cleaned, merged_keys = consolidate_formula(formula)
77
+ total = sum(float(component["weight_fraction"]) for component in cleaned)
78
+ if not math.isfinite(total) or abs(total - 1.0) > 1e-4:
79
+ raise ValueError(f"row {source_index} formula weights sum to {total}, expected 1")
80
+ row["formula"] = cleaned
81
+ signature = formula_signature(cleaned)
82
+ if merged_keys:
83
+ merges.append({"source_index": source_index, "ingredient_keys": merged_keys})
84
+ if signature in seen:
85
+ duplicates.append(
86
+ {
87
+ "source_index": source_index,
88
+ "retained_source_index": seen[signature],
89
+ "formula_signature": signature,
90
+ }
91
+ )
92
+ continue
93
+ seen[signature] = source_index
94
+ output.append(row)
95
+ strategies[str((row.get("metadata") or {}).get("generation_strategy", "missing"))] += 1
96
+
97
+ audit = {
98
+ "schema_version": 1,
99
+ "input_rows": len(rows),
100
+ "output_rows": len(output),
101
+ "rows_with_repeated_ingredients": len(merges),
102
+ "ingredients_consolidated": sum(len(item["ingredient_keys"]) for item in merges),
103
+ "exact_formula_duplicates_removed": len(duplicates),
104
+ "generation_strategy_counts_after_curation": dict(sorted(strategies.items())),
105
+ "repeated_ingredient_rows": merges,
106
+ "removed_duplicate_rows": duplicates,
107
+ }
108
+ return output, audit
109
+
110
+
111
+ def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
112
+ path.parent.mkdir(parents=True, exist_ok=True)
113
+ with path.open("w", encoding="utf-8") as handle:
114
+ for row in rows:
115
+ handle.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n")
116
+
117
+
118
+ def main() -> None:
119
+ parser = argparse.ArgumentParser(description=__doc__)
120
+ parser.add_argument("--input", type=Path, default=Path("data/empirical_dataset_v9_plus_wisemoor.jsonl"))
121
+ parser.add_argument("--output", type=Path, default=Path("data/empirical_dataset_v9_plus_wisemoor_clean.jsonl"))
122
+ parser.add_argument("--audit", type=Path, default=Path("artifacts/training_dataset_curation_audit.json"))
123
+ args = parser.parse_args()
124
+
125
+ rows = load_jsonl(args.input)
126
+ curated, audit = curate(rows)
127
+ audit["input"] = str(args.input)
128
+ audit["output"] = str(args.output)
129
+ write_jsonl(args.output, curated)
130
+ args.audit.parent.mkdir(parents=True, exist_ok=True)
131
+ args.audit.write_text(json.dumps(audit, indent=2, sort_keys=True) + "\n", encoding="utf-8")
132
+ print(json.dumps({key: audit[key] for key in (
133
+ "input_rows", "output_rows", "rows_with_repeated_ingredients",
134
+ "ingredients_consolidated", "exact_formula_duplicates_removed",
135
+ )}, indent=2))
136
+
137
+
138
+ if __name__ == "__main__":
139
+ main()
tests/test_material_data_integrity.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from rdkit import Chem
6
+ from rdkit.Chem import rdMolDescriptors
7
+
8
+ from pino.substitution_v11 import load_jsonl
9
+
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+
13
+
14
+ def test_neofolione_identity_has_matching_acyclic_structure():
15
+ profiles = load_jsonl(ROOT / "data/material_profiles_v11_5.jsonl")
16
+ matches = [row for row in profiles if row.get("cas") == "111-79-5"]
17
+
18
+ assert len(matches) == 1
19
+ profile = matches[0]
20
+ mol = Chem.MolFromSmiles(profile["smiles"])
21
+ assert profile["name"] == "Neofolione"
22
+ assert rdMolDescriptors.CalcMolFormula(mol) == "C10H18O2"
23
+ assert mol.GetRingInfo().NumRings() == 0
24
+ assert profile["substantivity_log10_predicted"] is None
25
+ assert profile["substantivity_model"] == "pending_recompute_after_identity_correction"
tests/test_prepare_independent_candidate.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import json
3
+ from pathlib import Path
4
+
5
+
6
+ PATH = Path(__file__).parents[1] / "scripts" / "prepare_independent_candidate.py"
7
+ SPEC = importlib.util.spec_from_file_location("prepare_independent_candidate", PATH)
8
+ MOD = importlib.util.module_from_spec(SPEC)
9
+ SPEC.loader.exec_module(MOD)
10
+
11
+
12
+ def test_identity_prefers_registry_key_and_normalizes_case():
13
+ assert MOD.identity({"cas": " 106-22-9 ", "smiles": "ignored"}) == "106-22-9"
14
+ assert MOD.identity({"smiles": " cco "}) == "CCO"
15
+
16
+
17
+ def test_protocol_forbids_reusing_frozen_evaluation():
18
+ protocol = json.loads(
19
+ (Path(__file__).parents[1] / "artifacts" / "pimt_candidate_20260716_a_evaluation_protocol.json").read_text()
20
+ )
21
+ assert protocol["status"].startswith("preregistered_before_training")
22
+ assert len(protocol["separation"]["candidate_must_not_be_scored_on"]) == 3
23
+ assert protocol["fresh_evaluation"]["one_confirmatory_run"] is True
tests/test_prepare_training_dataset.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib.util
4
+ from pathlib import Path
5
+
6
+
7
+ SCRIPT = Path(__file__).parent.parent / "scripts" / "prepare_training_dataset.py"
8
+ SPEC = importlib.util.spec_from_file_location("prepare_training_dataset", SCRIPT)
9
+ MODULE = importlib.util.module_from_spec(SPEC)
10
+ assert SPEC.loader is not None
11
+ SPEC.loader.exec_module(MODULE)
12
+
13
+
14
+ def component(cas: str, weight: float) -> dict:
15
+ return {"cas": cas, "name": cas, "weight_fraction": weight}
16
+
17
+
18
+ def test_curate_consolidates_ingredients_and_removes_exact_formula_duplicates():
19
+ rows = [
20
+ {
21
+ "formula": [component("1-11-1", 0.2), component("2-22-2", 0.5), component("1-11-1", 0.3)],
22
+ "metadata": {"generation_strategy": "floral"},
23
+ },
24
+ {
25
+ "formula": [component("1-11-1", 0.5), component("2-22-2", 0.5)],
26
+ "metadata": {"generation_strategy": "floral"},
27
+ },
28
+ ]
29
+
30
+ curated, audit = MODULE.curate(rows)
31
+
32
+ assert len(curated) == 1
33
+ assert curated[0]["formula"] == [component("1-11-1", 0.5), component("2-22-2", 0.5)]
34
+ assert audit["rows_with_repeated_ingredients"] == 1
35
+ assert audit["ingredients_consolidated"] == 1
36
+ assert audit["exact_formula_duplicates_removed"] == 1
37
+
38
+
39
+ def test_formula_signature_is_order_independent():
40
+ first = [component("1-11-1", 0.25), component("2-22-2", 0.75)]
41
+ second = list(reversed(first))
42
+ assert MODULE.formula_signature(first) == MODULE.formula_signature(second)
tests/test_source_population.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib.util
4
+ from pathlib import Path
5
+
6
+
7
+ ROOT = Path(__file__).resolve().parents[1]
8
+ SPEC = importlib.util.spec_from_file_location(
9
+ "convert_wisemoor", ROOT / "scripts/convert_wisemoor_to_training_candidates.py"
10
+ )
11
+ assert SPEC and SPEC.loader
12
+ MODULE = importlib.util.module_from_spec(SPEC)
13
+ SPEC.loader.exec_module(MODULE)
14
+
15
+
16
+ def test_wisemoor_description_survives_candidate_conversion():
17
+ record = {
18
+ "product_id": 7,
19
+ "name": "Observed formula",
20
+ "description": "A source-observed floral woody description.",
21
+ "notes": ["source note"],
22
+ "slug": "observed-formula",
23
+ "source_url": "https://example.test/formula/7",
24
+ "formula": {"formula_rows": [
25
+ {"ingredient": "benzyl acetate", "amount": 40},
26
+ {"ingredient": "linalool", "amount": 30},
27
+ {"ingredient": "vanillin", "amount": 30},
28
+ ]},
29
+ }
30
+ candidate, audit = MODULE.convert_record(
31
+ record,
32
+ mapping={
33
+ "benzyl acetate": "140-11-4",
34
+ "linalool": "78-70-6",
35
+ "vanillin": "121-33-5",
36
+ },
37
+ min_row_coverage=1.0,
38
+ min_amount_coverage=1.0,
39
+ min_resolved_components=3,
40
+ )
41
+ assert audit["accepted"] is True
42
+ assert candidate["description"] == record["description"]
43
+ assert candidate["metadata"]["description_provenance"] == "source_observed_wisemoor_product_text"