Matthew Ford commited on
Commit
3458215
·
1 Parent(s): bf3a770

v11 evaluator: substitution eval set n=30, assessment interface

Browse files

Former-commit-id: 691cd7dbad42c37b82c6b0e8b6428ee02811fa03
Former-commit-id: 63395bac7224a5e17b86d4a92bc9a0f2ea606f92

data/substitution_eval_set_v11.jsonl ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"evidence": "Direct replacement for restricted oakmoss absolute; unrestricted oakmoss replacement.", "grade": "acceptable", "mode": "regulatory_match", "pair_id": "v11_sub_0001", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Fauxmoss product note", "source_url": "https://fraterworks.com/products/fauxmoss", "substitute": "Fauxmoss", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Oakmoss absolute", "target_cas": "90028-68-5"}
2
+ {"evidence": "IFRA-compliant replacement for oakmoss, providing mossy character and fixative properties.", "grade": "partial", "mode": "regulatory_match", "pair_id": "v11_sub_0002", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Veramoss product note", "source_url": "https://fraterworks.com/products/veramoss", "substitute": "Veramoss / Evernyl", "substitute_cas": "4707-47-5", "suggested_percentage_adjustment": null, "target": "Oakmoss absolute", "target_cas": "90028-68-5"}
3
+ {"evidence": "One for one replacer for Hedione and Hedione High Cis; diffusion/radiance role.", "grade": "functional-only", "mode": "function_match", "pair_id": "v11_sub_0003", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Paradise Molecule product note", "source_url": "https://fraterworks.com/products/paradise-molecule", "substitute": "Paradise Molecule", "substitute_cas": null, "suggested_percentage_adjustment": "one-for-one documented by supplier", "target": "Hedione", "target_cas": "24851-98-7"}
4
+ {"evidence": "One for one replacer for Hedione and Hedione High Cis.", "grade": "functional-only", "mode": "function_match", "pair_id": "v11_sub_0004", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Paradise Molecule product note", "source_url": "https://fraterworks.com/products/paradise-molecule", "substitute": "Paradise Molecule", "substitute_cas": null, "suggested_percentage_adjustment": "one-for-one documented by supplier", "target": "Hedione High Cis", "target_cas": "24851-98-7"}
5
+ {"evidence": "Non-discolouring alternative to vanillin for soap; vanillic gourmand profile.", "grade": "functional-only", "mode": "function_match", "pair_id": "v11_sub_0005", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Isobutavan product note", "source_url": "https://fraterworks.com/products/isobutavan", "substitute": "Isobutavan", "substitute_cas": "20665-85-4", "suggested_percentage_adjustment": null, "target": "Vanillin", "target_cas": "121-33-5"}
6
+ {"evidence": "Same chemical/laevo form; can be used one for one in place of Bacdanol.", "grade": "acceptable", "mode": "function_match", "pair_id": "v11_sub_0006", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Dartanol product note", "source_url": "https://fraterworks.com/products/dartanol", "substitute": "Dartanol", "substitute_cas": "28219-61-6", "suggested_percentage_adjustment": "one-for-one documented by supplier", "target": "Bacdanol", "target_cas": "28219-61-6"}
7
+ {"evidence": "One of the finest substitutes for natural sandalwood in chemical form.", "grade": "partial", "mode": "odor_match", "pair_id": "v11_sub_0007", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Dartanol product note", "source_url": "https://fraterworks.com/products/dartanol", "substitute": "Dartanol", "substitute_cas": "28219-61-6", "suggested_percentage_adjustment": null, "target": "Natural sandalwood", "target_cas": "8006-87-9"}
8
+ {"evidence": "Alternative to virtually prohibited Lilial and Lyral; muguet volume/structure.", "grade": "functional-only", "mode": "regulatory_match", "pair_id": "v11_sub_0008", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Lilyflore product note", "source_url": "https://fraterworks.com/products/lilyflore", "substitute": "Lilyflore", "substitute_cas": "285977-85-7", "suggested_percentage_adjustment": null, "target": "Lilial", "target_cas": "80-54-6"}
9
+ {"evidence": "Alternative to virtually prohibited Lilial and Lyral.", "grade": "functional-only", "mode": "regulatory_match", "pair_id": "v11_sub_0009", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Lilyflore product note", "source_url": "https://fraterworks.com/products/lilyflore", "substitute": "Lilyflore", "substitute_cas": "285977-85-7", "suggested_percentage_adjustment": null, "target": "Lyral", "target_cas": "31906-04-4"}
10
+ {"evidence": "Softer alternative to Linalool with bergamot/lavender floral facets.", "grade": "partial", "mode": "odor_match", "pair_id": "v11_sub_0010", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Ethyl Linalool product note", "source_url": "https://fraterworks.com/products/ethyl-linalool", "substitute": "Ethyl Linalool", "substitute_cas": "10339-55-6", "suggested_percentage_adjustment": null, "target": "Linalool", "target_cas": "78-70-6"}
11
+ {"evidence": "Replacement for Indol in most fragrance types with much lower discolouration.", "grade": "functional-only", "mode": "regulatory_match", "pair_id": "v11_sub_0011", "provenance_flag": "authoritative-supplier-catalogue", "source_name": "PerfumersWorld perfume supplies catalogue", "source_url": "https://www.perfumersworld.com/perfume-supplies.php", "substitute": "Indofleur ND", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Indole", "target_cas": "120-72-9"}
12
+ {"evidence": "Low discolouring option where an Indol or Indolene note is required.", "grade": "functional-only", "mode": "regulatory_match", "pair_id": "v11_sub_0012", "provenance_flag": "authoritative-supplier-catalogue", "source_name": "PerfumersWorld perfume supplies catalogue", "source_url": "https://www.perfumersworld.com/perfume-supplies.php", "substitute": "Indolene ND Replacer", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Indole", "target_cas": "120-72-9"}
13
+ {"evidence": "IFRA-51 and EU compliant base used to replace HMPCC / Lyral.", "grade": "functional-only", "mode": "regulatory_match", "pair_id": "v11_sub_0013", "provenance_flag": "authoritative-supplier-catalogue", "source_name": "PerfumersWorld perfume supplies catalogue", "source_url": "https://www.perfumersworld.com/perfume-supplies.php", "substitute": "Lilyreal ND", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Lyral / HMPCC", "target_cas": "31906-04-4"}
14
+ {"evidence": "Nitro musk base to replace Musk Xylol; contains IFRA-compliant Musk Ketone.", "grade": "functional-only", "mode": "regulatory_match", "pair_id": "v11_sub_0014", "provenance_flag": "authoritative-supplier-catalogue", "source_name": "PerfumersWorld perfume supplies catalogue", "source_url": "https://www.perfumersworld.com/perfume-supplies.php", "substitute": "Musk Xylol Replacer", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Musk xylene", "target_cas": "81-15-2"}
15
+ {"evidence": "Supplier sells a dedicated Isoeugenol Replacer and contrasts it with less true replacers.", "grade": "functional-only", "mode": "regulatory_match", "pair_id": "v11_sub_0015", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Isoeugenol Replacer product note", "source_url": "https://fraterworks.com/products/isoeugenol-repl-296766", "substitute": "Isoeugenol Replacer", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Isoeugenol", "target_cas": "97-54-1"}
16
+ {"evidence": "Dedicated Tolu replacer base; supplier recommends purchase even when natural products are usable.", "grade": "functional-only", "mode": "function_match", "pair_id": "v11_sub_0016", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Tolu Absolute Replacer product note", "source_url": "https://fraterworks.com/products/tolu-replacer-decol", "substitute": "Tolu Absolute Replacer 50%", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Tolu balsam", "target_cas": "9000-64-0"}
17
+ {"evidence": "Clean musk substitution family; held as partial eval because not source-documented as one-for-one.", "grade": "partial", "mode": "function_match", "pair_id": "v11_sub_0017", "provenance_flag": "local-authoritative-literature-derived", "source_name": "Poucher tier profile and local material matrix", "source_url": "local:data/literature_profiles_poucher_cleaned_v8.jsonl", "substitute": "Ethylene brassylate", "substitute_cas": "105-95-3", "suggested_percentage_adjustment": null, "target": "Galaxolide", "target_cas": "1222-05-5"}
18
+ {"evidence": "Macrocyclic musk family control pair for evaluator, not used for training.", "grade": "partial", "mode": "function_match", "pair_id": "v11_sub_0018", "provenance_flag": "local-material-family-control", "source_name": "Local material matrix musk family", "source_url": "local:data/aroma_chemicals.jsonl", "substitute": "Habanolide", "substitute_cas": "111-79-5", "suggested_percentage_adjustment": null, "target": "Ambrettolide", "target_cas": "142-62-3"}
19
+ {"evidence": "Nerol listed among rose alcohols beside citronellol, geraniol, and phenyl ethyl alcohol.", "grade": "odor-only", "mode": "odor_match", "pair_id": "v11_sub_0019", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Nerol product note", "source_url": "https://fraterworks.com/products/nerol", "substitute": "Nerol", "substitute_cas": "106-25-2", "suggested_percentage_adjustment": null, "target": "Geraniol", "target_cas": "106-24-1"}
20
+ {"evidence": "Citral/neral isomer-family control pair for evaluator, not used for training.", "grade": "partial", "mode": "odor_match", "pair_id": "v11_sub_0020", "provenance_flag": "local-material-family-control", "source_name": "Local material matrix isomer control", "source_url": "local:data/aroma_chemicals.jsonl", "substitute": "Neral", "substitute_cas": "106-26-3", "suggested_percentage_adjustment": null, "target": "Citral", "target_cas": "5392-40-5"}
21
+ {"evidence": "Woody amber family control from curated trade-name resolver; not used for training.", "grade": "partial", "mode": "function_match", "pair_id": "v11_sub_0021", "provenance_flag": "local-trade-name-control", "source_name": "Local material resolver trade-name family", "source_url": "local:src/pino/materials.py", "substitute": "Timbersilk", "substitute_cas": "68039-33-4", "suggested_percentage_adjustment": null, "target": "Iso E Super", "target_cas": "54452-50-3"}
22
+ {"evidence": "Ambrofix listed as Ambroxan material; same-CAS alias control.", "grade": "acceptable", "mode": "function_match", "pair_id": "v11_sub_0022", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Ambrofix product listing", "source_url": "https://fraterworks.com/products/ambrofix", "substitute": "Ambrofix", "substitute_cas": "6790-58-9", "suggested_percentage_adjustment": null, "target": "Ambroxan", "target_cas": "6790-58-9"}
23
+ {"evidence": "Similar to Bicyclononalactone with hay/almond/coconut facets; coconut accord comment flags coumarin comparison.", "grade": "odor-only", "mode": "odor_match", "pair_id": "v11_sub_0023", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Florex product note", "source_url": "https://fraterworks.com/products/florex", "substitute": "Florex", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Coumarin", "target_cas": "91-64-5"}
24
+ {"evidence": "Stable alternative to traditional anisic aldehydes.", "grade": "partial", "mode": "function_match", "pair_id": "v11_sub_0024", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Canthoxal product note", "source_url": "https://fraterworks.com/products/canthoxal", "substitute": "Canthoxal", "substitute_cas": "5462-06-6", "suggested_percentage_adjustment": null, "target": "Anisic aldehyde", "target_cas": "123-11-5"}
25
+ {"evidence": "Premium fixative with distinctive patchouli-like facets.", "grade": "partial", "mode": "function_match", "pair_id": "v11_sub_0025", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Neo Patchouli product note", "source_url": "https://fraterworks.com/products/caryophyllene-formate", "substitute": "Neo Patchouli", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Patchouli", "target_cas": "8014-09-3"}
26
+ {"evidence": "Superior alternative to discontinued Fixateur 404.", "grade": "functional-only", "mode": "function_match", "pair_id": "v11_sub_0026", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Ambrexol product note", "source_url": "https://fraterworks.com/products/ambrexol", "substitute": "Ambrexol", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Fixateur 404", "target_cas": null}
27
+ {"evidence": "Review reports similar smell to damascone with red fruit facets; weaker provenance.", "grade": "odor-only", "mode": "odor_match", "pair_id": "v11_sub_0027", "provenance_flag": "supplier-page-customer-observation", "source_name": "Fraterworks Givescone customer/product note", "source_url": "https://fraterworks.com/products/givescone", "substitute": "Givescone", "substitute_cas": null, "suggested_percentage_adjustment": null, "target": "Damascone", "target_cas": "23726-91-2"}
28
+ {"evidence": "50% dilution in benzyl benzoate for practical handling.", "grade": "acceptable", "mode": "function_match", "pair_id": "v11_sub_0028", "provenance_flag": "authoritative-supplier-catalogue", "source_name": "PerfumersWorld perfume supplies catalogue", "source_url": "https://www.perfumersworld.com/perfume-supplies.php", "substitute": "Peru Balsam Resinoid 50% in BB", "substitute_cas": "8007-00-9", "suggested_percentage_adjustment": "50% dilution documented by supplier", "target": "Peru balsam resinoid", "target_cas": "8007-00-9"}
29
+ {"evidence": "50% dilution in DPG for practical handling.", "grade": "acceptable", "mode": "function_match", "pair_id": "v11_sub_0029", "provenance_flag": "authoritative-supplier-catalogue", "source_name": "PerfumersWorld perfume supplies catalogue", "source_url": "https://www.perfumersworld.com/perfume-supplies.php", "substitute": "Peru Balsam Resinoid 50% in DPG", "substitute_cas": "8007-00-9", "suggested_percentage_adjustment": "50% dilution documented by supplier", "target": "Peru balsam resinoid", "target_cas": "8007-00-9"}
30
+ {"evidence": "100% natural alternative to synthetics like BHT for antioxidant preservation role.", "grade": "functional-only", "mode": "function_match", "pair_id": "v11_sub_0030", "provenance_flag": "authoritative-supplier-page", "source_name": "Fraterworks Tocopherol product note", "source_url": "https://fraterworks.com/products/tocopherol", "substitute": "Tocopherol", "substitute_cas": "59-02-9", "suggested_percentage_adjustment": null, "target": "BHT", "target_cas": "128-37-0"}
src/pino/substitution_v11.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ from collections import Counter
6
+ from pathlib import Path
7
+ from typing import Any, Iterable
8
+
9
+ import numpy as np
10
+
11
+ PIMT_V11 = "v11"
12
+
13
+
14
+ def load_jsonl(path: str | Path) -> list[dict[str, Any]]:
15
+ return [json.loads(line) for line in Path(path).open(encoding="utf-8") if line.strip()]
16
+
17
+
18
+ def write_jsonl(path: str | Path, rows: Iterable[dict[str, Any]]) -> None:
19
+ path = Path(path)
20
+ path.parent.mkdir(parents=True, exist_ok=True)
21
+ path.write_text(
22
+ "".join(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n" for row in rows),
23
+ encoding="utf-8",
24
+ )
25
+
26
+
27
+ def normalize_name(value: str | None) -> str:
28
+ if not value:
29
+ return ""
30
+ keep = []
31
+ for ch in value.lower():
32
+ keep.append(ch if ch.isalnum() else " ")
33
+ return " ".join("".join(keep).split())
34
+
35
+
36
+ def profile_key(profile: dict[str, Any]) -> str:
37
+ return str(profile.get("cas") or profile.get("profile_id") or normalize_name(profile.get("name")))
38
+
39
+
40
+ def descriptor_distribution_from_codes(codes: Iterable[str]) -> dict[str, float]:
41
+ counts = Counter(code for code in codes if code)
42
+ total = sum(counts.values())
43
+ if not total:
44
+ return {}
45
+ return {code: count / total for code, count in sorted(counts.items())}
46
+
47
+
48
+ def cosine_similarity(left: dict[str, float], right: dict[str, float]) -> float:
49
+ keys = sorted(set(left) | set(right))
50
+ if not keys:
51
+ return 0.0
52
+ a = np.asarray([left.get(key, 0.0) for key in keys], dtype=float)
53
+ b = np.asarray([right.get(key, 0.0) for key in keys], dtype=float)
54
+ denom = float(np.linalg.norm(a) * np.linalg.norm(b))
55
+ if denom <= 0:
56
+ return 0.0
57
+ return float(np.dot(a, b) / denom)
58
+
59
+
60
+ def numeric_proximity(a: Any, b: Any, scale: float) -> float:
61
+ try:
62
+ fa = float(a)
63
+ fb = float(b)
64
+ except (TypeError, ValueError):
65
+ return 0.5
66
+ if not (math.isfinite(fa) and math.isfinite(fb)):
67
+ return 0.5
68
+ return float(math.exp(-abs(fa - fb) / scale))
69
+
70
+
71
+ def note_role(profile: dict[str, Any]) -> str:
72
+ role = profile.get("poucher_tier")
73
+ if role in {"top", "heart", "mid", "base"}:
74
+ return "heart" if role == "mid" else str(role)
75
+ log_vp = profile.get("log10_vapor_pressure_pa")
76
+ if log_vp is None:
77
+ return "unknown"
78
+ try:
79
+ value = float(log_vp)
80
+ except (TypeError, ValueError):
81
+ return "unknown"
82
+ if value >= 2.0:
83
+ return "top"
84
+ if value <= 0.0:
85
+ return "base"
86
+ return "heart"
87
+
88
+
89
+ def role_score(left: dict[str, Any], right: dict[str, Any]) -> float:
90
+ l_role = note_role(left)
91
+ r_role = note_role(right)
92
+ if "unknown" in {l_role, r_role}:
93
+ return 0.5
94
+ return 1.0 if l_role == r_role else 0.25
95
+
96
+
97
+ def profile_lookup(profiles: Iterable[dict[str, Any]]) -> dict[str, dict[str, Any]]:
98
+ out: dict[str, dict[str, Any]] = {}
99
+ for profile in profiles:
100
+ keys = {profile_key(profile), normalize_name(profile.get("name"))}
101
+ cas = profile.get("cas")
102
+ if cas:
103
+ keys.add(str(cas))
104
+ for alias in profile.get("aliases") or []:
105
+ keys.add(normalize_name(alias))
106
+ for key in keys:
107
+ if key:
108
+ out[key] = profile
109
+ return out
110
+
111
+
112
+ MODE_WEIGHTS: dict[str, dict[str, float]] = {
113
+ "odor_match": {"odor": 0.70, "substantivity": 0.10, "volatility": 0.10, "role": 0.10},
114
+ "function_match": {"odor": 0.25, "substantivity": 0.25, "volatility": 0.25, "role": 0.25},
115
+ "evaporation_match": {"odor": 0.10, "substantivity": 0.35, "volatility": 0.40, "role": 0.15},
116
+ "regulatory_match": {"odor": 0.30, "substantivity": 0.20, "volatility": 0.20, "role": 0.15, "constraints": 0.15},
117
+ "cost_match": {"odor": 0.35, "substantivity": 0.20, "volatility": 0.20, "role": 0.15, "constraints": 0.10},
118
+ "accord_rebuild": {"odor": 0.35, "substantivity": 0.20, "volatility": 0.20, "role": 0.25},
119
+ }
120
+
121
+
122
+ def score_candidate(
123
+ target: dict[str, Any],
124
+ candidate: dict[str, Any],
125
+ mode: str = "function_match",
126
+ constraints: dict[str, Any] | None = None,
127
+ ) -> dict[str, Any]:
128
+ constraints = constraints or {}
129
+ banned = {normalize_name(v) for v in constraints.get("banned_materials", [])}
130
+ banned.update(str(v) for v in constraints.get("banned_cas", []))
131
+ c_key = profile_key(candidate)
132
+ if c_key == profile_key(target):
133
+ return {"score": -1.0, "reasons": {"self": True}}
134
+ if c_key in banned or normalize_name(candidate.get("name")) in banned:
135
+ return {"score": -1.0, "reasons": {"banned": True}}
136
+
137
+ components = {
138
+ "odor": cosine_similarity(target.get("descriptor_distribution") or {}, candidate.get("descriptor_distribution") or {}),
139
+ "substantivity": numeric_proximity(
140
+ target.get("substantivity_log10_predicted"),
141
+ candidate.get("substantivity_log10_predicted"),
142
+ 0.45,
143
+ ),
144
+ "volatility": numeric_proximity(target.get("log10_vapor_pressure_pa"), candidate.get("log10_vapor_pressure_pa"), 1.0),
145
+ "role": role_score(target, candidate),
146
+ "constraints": 1.0,
147
+ }
148
+ weights = MODE_WEIGHTS.get(mode, MODE_WEIGHTS["function_match"])
149
+ score = sum(components[name] * weight for name, weight in weights.items())
150
+ return {"score": float(score), "reasons": components}
151
+
152
+
153
+ def substitute(
154
+ target: str,
155
+ profiles: list[dict[str, Any]],
156
+ constraints: dict[str, Any] | None = None,
157
+ mode: str = "function_match",
158
+ top_k: int = 5,
159
+ ) -> list[dict[str, Any]]:
160
+ lookup = profile_lookup(profiles)
161
+ target_profile = lookup.get(str(target)) or lookup.get(normalize_name(target))
162
+ if target_profile is None:
163
+ raise KeyError(f"target material not found in v11 profile table: {target}")
164
+ ranked = []
165
+ for candidate in profiles:
166
+ scored = score_candidate(target_profile, candidate, mode=mode, constraints=constraints)
167
+ if scored["score"] < 0:
168
+ continue
169
+ ranked.append(
170
+ {
171
+ "candidate": candidate.get("name"),
172
+ "candidate_cas": candidate.get("cas"),
173
+ "score": scored["score"],
174
+ "components": scored["reasons"],
175
+ "note_role": note_role(candidate),
176
+ }
177
+ )
178
+ ranked.sort(key=lambda row: row["score"], reverse=True)
179
+ return ranked[:top_k]
180
+
181
+
182
+ def evaluate_material(material: str, profiles: list[dict[str, Any]]) -> dict[str, Any]:
183
+ lookup = profile_lookup(profiles)
184
+ profile = lookup.get(str(material)) or lookup.get(normalize_name(material))
185
+ if profile is None:
186
+ raise KeyError(f"material not found in v11 profile table: {material}")
187
+ return {
188
+ "pimt_version": PIMT_V11,
189
+ "type": "material",
190
+ "material": profile.get("name"),
191
+ "cas": profile.get("cas"),
192
+ "odor_family_fit": profile.get("descriptor_distribution") or {},
193
+ "predicted_substantivity_log10": profile.get("substantivity_log10_predicted"),
194
+ "volatility": {
195
+ "vapor_pressure_pa": profile.get("vapor_pressure_pa"),
196
+ "log10_vapor_pressure_pa": profile.get("log10_vapor_pressure_pa"),
197
+ "boiling_point_k": profile.get("boiling_point_k"),
198
+ "note_role": note_role(profile),
199
+ },
200
+ "substitution_risks": profile.get("substitution_risks") or [],
201
+ "enrichment_pending": profile.get("enrichment_pending") or [],
202
+ }
203
+
204
+
205
+ def evaluate_formula(formula: list[dict[str, Any]], profiles: list[dict[str, Any]]) -> dict[str, Any]:
206
+ lookup = profile_lookup(profiles)
207
+ materials = []
208
+ missing = []
209
+ total_weight = 0.0
210
+ role_weights = Counter()
211
+ for item in formula:
212
+ name = item.get("cas") or item.get("name")
213
+ profile = lookup.get(str(name)) or lookup.get(normalize_name(str(name)))
214
+ if profile is None:
215
+ missing.append(name)
216
+ continue
217
+ weight = float(item.get("weight_fraction", item.get("percent", 0.0)) or 0.0)
218
+ total_weight += weight
219
+ role_weights[note_role(profile)] += weight
220
+ materials.append(evaluate_material(str(name), profiles) | {"input_weight": weight})
221
+ return {
222
+ "pimt_version": PIMT_V11,
223
+ "type": "formula",
224
+ "n_materials": len(materials),
225
+ "missing_materials": missing,
226
+ "total_weight": total_weight,
227
+ "top_heart_base_balance": dict(role_weights),
228
+ "materials": materials,
229
+ "substitution_risks": ["safety/use-level flags enrichment-pending; no safety claims emitted"],
230
+ }
231
+
232
+
233
+ def evaluate_retriever(
234
+ eval_rows: list[dict[str, Any]],
235
+ profiles: list[dict[str, Any]],
236
+ mode: str = "function_match",
237
+ top_k: int = 5,
238
+ ) -> dict[str, Any]:
239
+ lookup = profile_lookup(profiles)
240
+ evaluated = []
241
+ skipped = []
242
+ for row in eval_rows:
243
+ target_key = row.get("target_cas") or row.get("target")
244
+ expected_keys = [row.get("substitute_cas"), row.get("substitute")]
245
+ if not (lookup.get(str(target_key)) or lookup.get(normalize_name(str(target_key)))):
246
+ skipped.append({"pair_id": row["pair_id"], "reason": "target_missing_profile"})
247
+ continue
248
+ if not any(lookup.get(str(key)) or lookup.get(normalize_name(str(key))) for key in expected_keys if key):
249
+ skipped.append({"pair_id": row["pair_id"], "reason": "documented_substitute_missing_profile"})
250
+ continue
251
+ ranked = substitute(str(target_key), profiles, mode=mode, top_k=top_k)
252
+ rank_names = {normalize_name(r["candidate"]) for r in ranked}
253
+ rank_cas = {str(r.get("candidate_cas")) for r in ranked if r.get("candidate_cas")}
254
+ hit = any(
255
+ str(key) in rank_cas or normalize_name(str(key)) in rank_names
256
+ for key in expected_keys
257
+ if key
258
+ )
259
+ target_profile = lookup.get(str(target_key)) or lookup.get(normalize_name(str(target_key)))
260
+ substitute_profile = next(
261
+ (lookup.get(str(key)) or lookup.get(normalize_name(str(key))) for key in expected_keys if key),
262
+ None,
263
+ )
264
+ evaluated.append(
265
+ {
266
+ "pair_id": row["pair_id"],
267
+ "grade": row["grade"],
268
+ "hit_top_k": bool(hit),
269
+ "top_k": ranked,
270
+ "documented_substitute": row.get("substitute"),
271
+ "substantivity_delta_abs": (
272
+ abs(
273
+ float(target_profile.get("substantivity_log10_predicted"))
274
+ - float(substitute_profile.get("substantivity_log10_predicted"))
275
+ )
276
+ if target_profile
277
+ and substitute_profile
278
+ and target_profile.get("substantivity_log10_predicted") is not None
279
+ and substitute_profile.get("substantivity_log10_predicted") is not None
280
+ else None
281
+ ),
282
+ }
283
+ )
284
+ n = len(evaluated)
285
+ hit_rate = sum(1 for row in evaluated if row["hit_top_k"]) / n if n else 0.0
286
+ subst_deltas = [row["substantivity_delta_abs"] for row in evaluated if row["substantivity_delta_abs"] is not None]
287
+ return {
288
+ "pimt_version": PIMT_V11,
289
+ "mode": mode,
290
+ "top_k": top_k,
291
+ "n_eval_rows": len(eval_rows),
292
+ "n_evaluable": n,
293
+ "n_skipped": len(skipped),
294
+ "top_k_hit_rate": hit_rate,
295
+ "mean_substantivity_delta_abs": float(np.mean(subst_deltas)) if subst_deltas else None,
296
+ "evaluated": evaluated,
297
+ "skipped": skipped,
298
+ }
tests/test_substitution_v11.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pino.substitution_v11 import evaluate_formula, evaluate_material, evaluate_retriever, substitute
4
+
5
+
6
+ def tiny_profiles():
7
+ return [
8
+ {
9
+ "pimt_version": "v11",
10
+ "cas": "1",
11
+ "name": "Target Floral",
12
+ "descriptor_distribution": {"F": 1.0},
13
+ "substantivity_log10_predicted": 1.0,
14
+ "log10_vapor_pressure_pa": 0.5,
15
+ "boiling_point_k": 450.0,
16
+ "vapor_pressure_pa": 3.0,
17
+ "enrichment_pending": ["IFRA/allergen/use-level"],
18
+ },
19
+ {
20
+ "pimt_version": "v11",
21
+ "cas": "2",
22
+ "name": "Documented Floral Substitute",
23
+ "descriptor_distribution": {"F": 0.9, "G": 0.1},
24
+ "substantivity_log10_predicted": 1.05,
25
+ "log10_vapor_pressure_pa": 0.4,
26
+ "boiling_point_k": 455.0,
27
+ "vapor_pressure_pa": 2.5,
28
+ "enrichment_pending": ["IFRA/allergen/use-level"],
29
+ },
30
+ {
31
+ "pimt_version": "v11",
32
+ "cas": "3",
33
+ "name": "Wrong Citrus",
34
+ "descriptor_distribution": {"A": 1.0},
35
+ "substantivity_log10_predicted": 3.0,
36
+ "log10_vapor_pressure_pa": 4.0,
37
+ "boiling_point_k": 330.0,
38
+ "vapor_pressure_pa": 1000.0,
39
+ "enrichment_pending": ["IFRA/allergen/use-level"],
40
+ },
41
+ ]
42
+
43
+
44
+ def test_substitute_ranks_documented_like_profile_first():
45
+ ranked = substitute("1", tiny_profiles(), mode="function_match", top_k=2)
46
+
47
+ assert ranked[0]["candidate_cas"] == "2"
48
+ assert ranked[0]["score"] > ranked[1]["score"]
49
+
50
+
51
+ def test_evaluate_retriever_uses_eval_rows_without_training():
52
+ rows = [
53
+ {
54
+ "pair_id": "pair-1",
55
+ "target": "Target Floral",
56
+ "target_cas": "1",
57
+ "substitute": "Documented Floral Substitute",
58
+ "substitute_cas": "2",
59
+ "grade": "acceptable",
60
+ }
61
+ ]
62
+
63
+ result = evaluate_retriever(rows, tiny_profiles(), top_k=1)
64
+
65
+ assert result["n_evaluable"] == 1
66
+ assert result["top_k_hit_rate"] == 1.0
67
+ assert "trained" not in result
68
+
69
+
70
+ def test_assessment_interfaces_do_not_emit_safety_authority():
71
+ material = evaluate_material("1", tiny_profiles())
72
+ formula = evaluate_formula([{"cas": "1", "weight_fraction": 0.4}], tiny_profiles())
73
+
74
+ assert material["pimt_version"] == "v11"
75
+ assert "IFRA/allergen/use-level" in material["enrichment_pending"]
76
+ assert formula["substitution_risks"] == ["safety/use-level flags enrichment-pending; no safety claims emitted"]