mattbitzesty commited on
Commit
fd5ba83
·
1 Parent(s): 96f3ac5

feat(optimizer): masked MSE, strategy seeds, adversarial IFRA guard; add accords/materials/importer

Browse files

- Importance-weighted objective MSE: active descriptors (0-3) weighted 50x, background 0.1x

- Strategy-aware palette seeds (citrus, amber, floral, fougere) + initial guess + soft bonus

- Tighten citrus seed list to true top-note materials (limonene, citral, terpinene, pinene)

- Verifier skips unresolved ingredients while keeping weight fractions aligned

- Add accords.py, materials.py, importer.py, analyze_formula.py for real-world formulas

- Fix permutation-invariance tests to match flat 7-D subjective head API

scripts/analyze_formula.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Analyze a human parts-based formula with Pino.
5
+
6
+ This is a small utility for the user-supplied Matthew tea/woods formula. It:
7
+ 1. Imports the parts-based JSON via pino.importer.
8
+ 2. Runs the physical/IFRA verifier.
9
+ 3. Runs the PIMT critic (cloud or local fallback).
10
+ 4. Prints a compact human-readable summary.
11
+ """
12
+
13
+ import json
14
+ import logging
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ from pino.importer import import_formula
19
+ from pino.inference_cloud import predict_cloud
20
+ from pino.verifier import FragrancePipelineVerifier
21
+
22
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
23
+ logger = logging.getLogger("pino.analyze_formula")
24
+
25
+
26
+ def analyze(path: str | Path) -> None:
27
+ imported = import_formula(path)
28
+ if imported["unresolved"]:
29
+ logger.warning("Unresolved materials: %s", imported["unresolved"])
30
+
31
+ formula = imported["formula"]
32
+ print(f"Imported formula with {len(formula)} ingredients; sum = {sum(i['weight_fraction'] for i in formula):.6f}")
33
+
34
+ verifier = FragrancePipelineVerifier(
35
+ temperature_k=298.15,
36
+ ambient_pressure_pa=101325.0,
37
+ headspace_volume_m3=1e-3,
38
+ liquid_volume_m3=1e-6,
39
+ density_g_ml=0.9,
40
+ surface_area_m2=1e-4,
41
+ mass_transfer_coefficient=1e-4,
42
+ )
43
+
44
+ result = verifier.run_sim(formula, duration_seconds=8 * 3600.0, interval_seconds=600.0)
45
+ print(f"Physical/IFRA status: {result['status']}")
46
+ print(f"IFRA passed: {result['ifra_report'].get('passed', False)}")
47
+ if not result["ifra_report"].get("passed", False):
48
+ print("IFRA violations:", json.dumps(result["ifra_report"].get("violations", []), indent=2))
49
+
50
+ if result["status"] in ("rejected", "depleted"):
51
+ logger.error("Formula rejected by verifier: %s", result.get("message"))
52
+ return
53
+
54
+ formula_payload = {
55
+ "formula": formula,
56
+ "trajectory": result["trajectory"],
57
+ "metadata": {"source": str(path), "analysis": True},
58
+ }
59
+
60
+ prediction = predict_cloud(formula_payload)
61
+ print("Prediction keys:", list(prediction.keys()))
62
+ print("Objective shape:", len(prediction.get("objective", [[]])[0][0]))
63
+ print("Subjective vector:", prediction.get("subjective", [[]])[0])
64
+
65
+ # Save full analysis
66
+ output = {
67
+ "imported": imported,
68
+ "verification": result,
69
+ "prediction": prediction,
70
+ }
71
+ out_path = Path("data/formulas/matthew_tea_woods_analysis.json")
72
+ out_path.write_text(json.dumps(output, indent=2, ensure_ascii=False))
73
+ print(f"Full analysis written to {out_path}")
74
+
75
+
76
+ if __name__ == "__main__":
77
+ analyze(sys.argv[1] if len(sys.argv) > 1 else "data/formulas/matthew_tea_woods.json")
src/pino/accords.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ PINO fragrance accords and standard material library.
5
+
6
+ Why this module exists:
7
+ - Many real-world formulas contain proprietary bases (e.g., "Green Tea Base") or
8
+ complex naturals (e.g., "Orris butter") that are not single CAS records.
9
+ - For physics and neural critique, we decompose these into representative
10
+ ingredient proxies that capture the dominant volatility and odour character.
11
+ - Accords are a first-class concept so the UI and composer can start from a
12
+ known base (e.g., "citrus top accord", "green tea base") instead of raw
13
+ single materials.
14
+ """
15
+
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+
20
+ @dataclass
21
+ class Accord:
22
+ """A named aromatic accord represented as a weighted proxy formula."""
23
+
24
+ name: str
25
+ description: str
26
+ ingredients: list[dict[str, Any]] = field(default_factory=list)
27
+ """
28
+ Each ingredient is {"cas": str, "name": str, "weight_fraction": float}.
29
+ The fractions inside an accord sum to 1.0; they are scaled by the accord's
30
+ overall weight when the accord is expanded into a full formula.
31
+ """
32
+
33
+ def expand(self, overall_weight_fraction: float) -> list[dict[str, Any]]:
34
+ """Return the accord's proxy formula scaled to a target weight fraction."""
35
+ return [
36
+ {
37
+ "cas": item["cas"],
38
+ "name": item["name"],
39
+ "weight_fraction": item["weight_fraction"] * overall_weight_fraction,
40
+ }
41
+ for item in self.ingredients
42
+ ]
43
+
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Standard accords used by the UI, composer, and formula importer.
47
+ # These are intentionally approximate; they encode the *olfactory character* and
48
+ # *volatility class* rather than an exact GC-MS reconstruction.
49
+ # ---------------------------------------------------------------------------
50
+
51
+ GREEN_TEA_BASE = Accord(
52
+ name="Green Tea Base",
53
+ description="Fresh, leafy, slightly phenolic green tea reconstruction",
54
+ ingredients=[
55
+ {"cas": "928-96-1", "name": "cis-3-Hexenol", "weight_fraction": 0.15},
56
+ {"cas": "928-97-2", "name": "cis-3-Hexenyl acetate", "weight_fraction": 0.10},
57
+ {"cas": "140-67-0", "name": "Estragole", "weight_fraction": 0.05},
58
+ {"cas": "674-86-6", "name": "Linalool oxide", "weight_fraction": 0.10},
59
+ {"cas": "78-70-6", "name": "Linalool", "weight_fraction": 0.15},
60
+ {"cas": "110-44-1", "name": "Sorbic acid", "weight_fraction": 0.02},
61
+ {"cas": "121-33-5", "name": "Vanillin", "weight_fraction": 0.05},
62
+ {"cas": "119-64-2", "name": "Tetrahydroquinoline", "weight_fraction": 0.03},
63
+ {"cas": "4602-84-0", "name": "Farnesol", "weight_fraction": 0.05},
64
+ {"cas": "106-24-5", "name": "Geraniol", "weight_fraction": 0.10},
65
+ {"cas": "106-25-2", "name": "Nerol", "weight_fraction": 0.08},
66
+ {"cas": "5989-27-5", "name": "d-Limonene", "weight_fraction": 0.07},
67
+ {"cas": "89-43-0", "name": "Anthranilic acid", "weight_fraction": 0.05},
68
+ ],
69
+ )
70
+
71
+ BLACK_TEA_BASE = Accord(
72
+ name="Tea Black Base",
73
+ description="Dark, smoky, phenolic black tea reconstruction",
74
+ ingredients=[
75
+ {"cas": "105-95-3", "name": "Ethylene brassylate", "weight_fraction": 0.10},
76
+ {"cas": "91-64-5", "name": "Coumarin", "weight_fraction": 0.08},
77
+ {"cas": "121-33-5", "name": "Vanillin", "weight_fraction": 0.08},
78
+ {"cas": "121-34-6", "name": "Ethyl vanillin", "weight_fraction": 0.05},
79
+ {"cas": "119-36-8", "name": "Methyl salicylate", "weight_fraction": 0.07},
80
+ {"cas": "118-58-1", "name": "Benzyl salicylate", "weight_fraction": 0.10},
81
+ {"cas": "140-67-0", "name": "Estragole", "weight_fraction": 0.05},
82
+ {"cas": "89-86-1", "name": "Beta-thujone", "weight_fraction": 0.03},
83
+ {"cas": "90-05-1", "name": "Guaiacol", "weight_fraction": 0.24},
84
+ {"cas": "106-26-3", "name": "Neral", "weight_fraction": 0.05},
85
+ {"cas": "78-70-6", "name": "Linalool", "weight_fraction": 0.08},
86
+ {"cas": "106-24-5", "name": "Geraniol", "weight_fraction": 0.07},
87
+ ],
88
+ )
89
+
90
+ MATE_ABSOLUTE = Accord(
91
+ name="Mate absolute",
92
+ description="Dry, herbal, tea-like yerba mate reconstruction",
93
+ ingredients=[
94
+ {"cas": "928-96-1", "name": "cis-3-Hexenol", "weight_fraction": 0.10},
95
+ {"cas": "928-97-2", "name": "cis-3-Hexenyl acetate", "weight_fraction": 0.08},
96
+ {"cas": "140-67-0", "name": "Estragole", "weight_fraction": 0.08},
97
+ {"cas": "99-85-4", "name": "Terpinen-4-ol", "weight_fraction": 0.08},
98
+ {"cas": "77-53-2", "name": "Cedrol", "weight_fraction": 0.12},
99
+ {"cas": "106-24-5", "name": "Geraniol", "weight_fraction": 0.08},
100
+ {"cas": "78-70-6", "name": "Linalool", "weight_fraction": 0.08},
101
+ {"cas": "91-64-5", "name": "Coumarin", "weight_fraction": 0.05},
102
+ {"cas": "121-33-5", "name": "Vanillin", "weight_fraction": 0.05},
103
+ {"cas": "4602-84-0", "name": "Farnesol", "weight_fraction": 0.08},
104
+ {"cas": "7212-44-4", "name": "Nerolidol", "weight_fraction": 0.10},
105
+ {"cas": "5989-27-5", "name": "d-Limonene", "weight_fraction": 0.10},
106
+ ],
107
+ )
108
+
109
+ ORRIS_BUTTER = Accord(
110
+ name="Orris butter / orris CO2",
111
+ description="Powdery, violet-iris orris root reconstruction",
112
+ ingredients=[
113
+ {"cas": "127-42-4", "name": "Methyl ionone gamma", "weight_fraction": 0.18},
114
+ {"cas": "14901-07-6", "name": "Ionone beta", "weight_fraction": 0.12},
115
+ {"cas": "17283-81-7", "name": "Dihydro ionone beta", "weight_fraction": 0.10},
116
+ {"cas": "110-17-8", "name": "Fumaric acid", "weight_fraction": 0.02},
117
+ {"cas": "105-95-3", "name": "Ethylene brassylate", "weight_fraction": 0.15},
118
+ {"cas": "91-64-5", "name": "Coumarin", "weight_fraction": 0.08},
119
+ {"cas": "121-33-5", "name": "Vanillin", "weight_fraction": 0.05},
120
+ {"cas": "77-53-2", "name": "Cedrol", "weight_fraction": 0.10},
121
+ {"cas": "104-54-1", "name": "Cinnamyl alcohol", "weight_fraction": 0.05},
122
+ {"cas": "106-24-5", "name": "Geraniol", "weight_fraction": 0.05},
123
+ {"cas": "78-70-6", "name": "Linalool", "weight_fraction": 0.05},
124
+ {"cas": "4602-84-0", "name": "Farnesol", "weight_fraction": 0.05},
125
+ ],
126
+ )
127
+
128
+ CEDARWOOD_VIRGINIA = Accord(
129
+ name="Cedarwood Virginia/Texas",
130
+ description="Dry, woody cedarwood oil reconstruction",
131
+ ingredients=[
132
+ {"cas": "77-53-2", "name": "Cedrol", "weight_fraction": 0.35},
133
+ {"cas": "469-01-2", "name": "Cedrene", "weight_fraction": 0.30},
134
+ {"cas": "5986-38-9", "name": "Cedryl acetate", "weight_fraction": 0.15},
135
+ {"cas": "8000-27-9", "name": "Cedarwood oil (Virginia)", "weight_fraction": 0.20},
136
+ ],
137
+ )
138
+
139
+ VETIVER_HAITI = Accord(
140
+ name="Vetiver Haiti",
141
+ description="Earthy, smoky, woody vetiver oil reconstruction",
142
+ ingredients=[
143
+ {"cas": "117-98-6", "name": "Vetiveryl acetate", "weight_fraction": 0.30},
144
+ {"cas": "77-53-2", "name": "Cedrol", "weight_fraction": 0.15},
145
+ {"cas": "89-78-1", "name": "Menthol", "weight_fraction": 0.03},
146
+ {"cas": "4602-84-0", "name": "Farnesol", "weight_fraction": 0.10},
147
+ {"cas": "7212-44-4", "name": "Nerolidol", "weight_fraction": 0.12},
148
+ {"cas": "106-24-5", "name": "Geraniol", "weight_fraction": 0.05},
149
+ {"cas": "78-70-6", "name": "Linalool", "weight_fraction": 0.05},
150
+ {"cas": "5989-27-5", "name": "d-Limonene", "weight_fraction": 0.05},
151
+ {"cas": "8000-27-9", "name": "Cedarwood oil", "weight_fraction": 0.10},
152
+ {"cas": "105-95-3", "name": "Ethylene brassylate", "weight_fraction": 0.05},
153
+ ],
154
+ )
155
+
156
+ AMBER_MUSK_BASE = Accord(
157
+ name="Amber-Musk Base",
158
+ description="Warm, clean, slightly sweet amber-musk reconstruction",
159
+ ingredients=[
160
+ {"cas": "105-95-3", "name": "Ethylene brassylate", "weight_fraction": 0.20},
161
+ {"cas": "111-79-5", "name": "Habanolide", "weight_fraction": 0.15},
162
+ {"cas": "142-62-3", "name": "Ambrettolide", "weight_fraction": 0.10},
163
+ {"cas": "6790-58-9", "name": "Ambroxan", "weight_fraction": 0.15},
164
+ {"cas": "91-64-5", "name": "Coumarin", "weight_fraction": 0.08},
165
+ {"cas": "121-33-5", "name": "Vanillin", "weight_fraction": 0.07},
166
+ {"cas": "1222-05-5", "name": "Galaxolide", "weight_fraction": 0.10},
167
+ {"cas": "77-53-2", "name": "Cedrol", "weight_fraction": 0.10},
168
+ {"cas": "4602-84-0", "name": "Farnesol", "weight_fraction": 0.05},
169
+ ],
170
+ )
171
+
172
+ CITRUS_TOP_ACCORD = Accord(
173
+ name="Citrus Top Accord",
174
+ description="Bright, sparkling citrus opening",
175
+ ingredients=[
176
+ {"cas": "5989-27-5", "name": "d-Limonene", "weight_fraction": 0.35},
177
+ {"cas": "68647-72-3", "name": "Linalyl acetate", "weight_fraction": 0.15},
178
+ {"cas": "78-70-6", "name": "Linalool", "weight_fraction": 0.10},
179
+ {"cas": "94-48-4", "name": "Bergamot oil", "weight_fraction": 0.20},
180
+ {"cas": "8008-56-8", "name": "Lemon oil", "weight_fraction": 0.15},
181
+ {"cas": "119-64-2", "name": "Tetrahydroquinoline", "weight_fraction": 0.05},
182
+ ],
183
+ )
184
+
185
+ FLORAL_HEART_ACCORD = Accord(
186
+ name="Floral Heart Accord",
187
+ description="Clean, elegant floral bouquet",
188
+ ingredients=[
189
+ {"cas": "78-70-6", "name": "Linalool", "weight_fraction": 0.20},
190
+ {"cas": "106-24-5", "name": "Geraniol", "weight_fraction": 0.15},
191
+ {"cas": "106-25-2", "name": "Nerol", "weight_fraction": 0.10},
192
+ {"cas": "8007-44-1", "name": "Jasmine absolute (proxy: benzyl acetate)", "weight_fraction": 0.15},
193
+ {"cas": "140-11-4", "name": "Benzyl acetate", "weight_fraction": 0.15},
194
+ {"cas": "104-54-1", "name": "Cinnamyl alcohol", "weight_fraction": 0.05},
195
+ {"cas": "101-86-0", "name": "alpha-Hexylcinnamaldehyde", "weight_fraction": 0.10},
196
+ {"cas": "122-97-4", "name": "Phenethyl alcohol", "weight_fraction": 0.10},
197
+ ],
198
+ )
199
+
200
+ WOODY_BASE_ACCORD = Accord(
201
+ name="Woody Base Accord",
202
+ description="Dry, warm woody dry-down",
203
+ ingredients=[
204
+ {"cas": "77-53-2", "name": "Cedrol", "weight_fraction": 0.20},
205
+ {"cas": "469-01-2", "name": "Cedrene", "weight_fraction": 0.15},
206
+ {"cas": "54452-50-3", "name": "Iso E Super", "weight_fraction": 0.25},
207
+ {"cas": "68039-33-4", "name": "Timbersilk", "weight_fraction": 0.15},
208
+ {"cas": "8000-27-9", "name": "Cedarwood oil", "weight_fraction": 0.15},
209
+ {"cas": "105-95-3", "name": "Ethylene brassylate", "weight_fraction": 0.10},
210
+ ],
211
+ )
212
+
213
+
214
+ ACCORDS: dict[str, Accord] = {
215
+ "green_tea": GREEN_TEA_BASE,
216
+ "black_tea": BLACK_TEA_BASE,
217
+ "mate": MATE_ABSOLUTE,
218
+ "orris": ORRIS_BUTTER,
219
+ "cedarwood": CEDARWOOD_VIRGINIA,
220
+ "vetiver": VETIVER_HAITI,
221
+ "amber_musk": AMBER_MUSK_BASE,
222
+ "citrus_top": CITRUS_TOP_ACCORD,
223
+ "floral_heart": FLORAL_HEART_ACCORD,
224
+ "woody_base": WOODY_BASE_ACCORD,
225
+ }
226
+
227
+
228
+ def expand_accord_by_name(name: str, overall_weight_fraction: float) -> list[dict[str, Any]]:
229
+ """Expand a named accord to a weight-fraction list."""
230
+ key = name.lower().replace(" ", "_").replace("/", "_")
231
+ if key not in ACCORDS:
232
+ raise KeyError(f"Unknown accord '{name}'. Available: {list(ACCORDS.keys())}")
233
+ return ACCORDS[key].expand(overall_weight_fraction)
src/pino/importer.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Formula importer: turn a parts-based human formula into a Pino-ready
5
+ { cas, weight_fraction } formula by resolving trade names via the materials
6
+ library and proprietary bases via accords.
7
+ """
8
+
9
+ import json
10
+ import logging
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from .accords import expand_accord_by_name
15
+ from .materials import is_accord, resolve_material
16
+ from .registry import AromaRegistry
17
+
18
+ logger = logging.getLogger("pino.importer")
19
+
20
+
21
+ def _normalise_name(name: str) -> str:
22
+ """Strip concentration suffixes like '10%' for library lookup."""
23
+ return name.strip().replace(" ", " ")
24
+
25
+
26
+ def import_formula(
27
+ path: str | Path,
28
+ registry: AromaRegistry | None = None,
29
+ ) -> dict[str, Any]:
30
+ """
31
+ Import a parts-based formula JSON and return a Pino-ready formula record.
32
+
33
+ The input JSON is a list of {"name": str, "parts": int} records.
34
+ Trade names are resolved through ``materials.py``; proprietary bases are
35
+ expanded via the accord library in ``accords.py``. Missing materials that
36
+ cannot be resolved are returned in the ``unresolved`` list so the caller can
37
+ decide how to proceed (register them, approximate, or drop).
38
+ """
39
+ path = Path(path)
40
+ with path.open("r", encoding="utf-8") as f:
41
+ records = json.load(f)
42
+
43
+ if registry is None:
44
+ registry = AromaRegistry()
45
+
46
+ formula = []
47
+ unresolved = []
48
+ total_parts = sum(r.get("parts", 0) for r in records)
49
+
50
+ for r in records:
51
+ name = r["name"]
52
+ parts = r.get("parts", 0)
53
+ if parts <= 0:
54
+ continue
55
+ wf_global = parts / total_parts
56
+
57
+ normalised = _normalise_name(name)
58
+ material = resolve_material(normalised)
59
+
60
+ if material and is_accord(normalised):
61
+ # Expand the accord and scale to the formula-level weight fraction.
62
+ accord_items = expand_accord_by_name(material["accord"], wf_global)
63
+ for item in accord_items:
64
+ formula.append(item)
65
+ elif material:
66
+ # Single material; use CAS if present, otherwise SMILES.
67
+ cas = material.get("cas")
68
+ smiles = material.get("smiles")
69
+ resolved_cas = cas
70
+ if not resolved_cas and smiles:
71
+ # Try to register by SMILES on the fly.
72
+ rec = AromaRegistry.validate_smiles(smiles)
73
+ if rec:
74
+ resolved_cas = f"SMILES:{smiles}"
75
+ else:
76
+ unresolved.append(name)
77
+ continue
78
+ formula.append(
79
+ {
80
+ "cas": resolved_cas or name,
81
+ "name": name, # Keep the original trade name so the resolver can look it up in materials.py
82
+ "display_name": material.get("name", name),
83
+ "weight_fraction": wf_global,
84
+ }
85
+ )
86
+ elif registry.get(normalised):
87
+ # Already in the registry.
88
+ rec = registry.get(normalised)
89
+ if rec is None:
90
+ unresolved.append(name)
91
+ continue
92
+ formula.append(
93
+ {
94
+ "cas": rec["cas"],
95
+ "name": rec["name"],
96
+ "weight_fraction": wf_global,
97
+ }
98
+ )
99
+ else:
100
+ unresolved.append(name)
101
+
102
+ # Normalize weight fractions after accord expansion.
103
+ total = sum(item["weight_fraction"] for item in formula)
104
+ if total > 0:
105
+ for item in formula:
106
+ item["weight_fraction"] /= total
107
+
108
+ # Aggregate duplicate CAS entries so each ingredient appears once.
109
+ aggregated: dict[str, dict[str, Any]] = {}
110
+ for item in formula:
111
+ cas = item["cas"]
112
+ if cas in aggregated:
113
+ aggregated[cas]["weight_fraction"] += item["weight_fraction"]
114
+ else:
115
+ aggregated[cas] = item.copy()
116
+ formula = list(aggregated.values())
117
+
118
+ # Re-normalize after aggregation.
119
+ total = sum(item["weight_fraction"] for item in formula)
120
+ if total > 0:
121
+ for item in formula:
122
+ item["weight_fraction"] /= total
123
+
124
+ return {
125
+ "formula": formula,
126
+ "unresolved": unresolved,
127
+ "metadata": {"source": str(path), "total_parts": total_parts},
128
+ }
129
+
130
+
131
+ def main() -> None:
132
+ import argparse
133
+
134
+ parser = argparse.ArgumentParser(description="Import a parts-based formula")
135
+ parser.add_argument("--file", required=True, help="Path to formula JSON")
136
+ parser.add_argument("--out", help="Path to write Pino-ready formula JSON")
137
+ args = parser.parse_args()
138
+
139
+ logging.basicConfig(level=logging.INFO)
140
+ result = import_formula(args.file)
141
+ print(json.dumps(result, indent=2, ensure_ascii=False))
142
+ if args.out:
143
+ Path(args.out).write_text(json.dumps(result, indent=2, ensure_ascii=False))
144
+
145
+
146
+ if __name__ == "__main__":
147
+ main()
src/pino/materials.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Standard fragrance materials with known CAS/SMILES for registry expansion.
5
+
6
+ Why this module exists:
7
+ - The SQLite registry is sparse; real formulas (like the one in
8
+ data/formulas/matthew_tea_woods.json) contain many well-known materials that
9
+ are not yet registered.
10
+ - This file maps common trade names to canonical identifiers (CAS or SMILES)
11
+ so the importer can resolve them without web lookups every time.
12
+ - It is a stepping stone toward a richer, thermodynamically-validated registry.
13
+ """
14
+
15
+ from typing import Any
16
+
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # Trade name -> canonical identifier (CAS preferred, SMILES fallback).
20
+ # Many materials are listed by their primary CAS or a representative isomer.
21
+ # ---------------------------------------------------------------------------
22
+
23
+ MATERIALS: dict[str, dict[str, Any]] = {
24
+ # Hedione family
25
+ "Hedione HC": {"cas": "24851-98-7", "name": "Methyl dihydrojasmonate (Hedione HC)", "smiles": "CC1C(=O)CC[C@H](C)C1CC=CC(=O)OC"},
26
+ "MDJ": {"cas": "24851-98-7", "name": "Methyl dihydrojasmonate (MDJ)", "smiles": "CC1C(=O)CC[C@H](C)C1CC=CC(=O)OC"},
27
+ "Hedione HC / MDJ": {"cas": "24851-98-7", "name": "Methyl dihydrojasmonate (Hedione HC / MDJ)", "smiles": "CC1C(=O)CC[C@H](C)C1CC=CC(=O)OC"},
28
+ "Methyl dihydrojasmonate": {"cas": "24851-98-7", "name": "Methyl dihydrojasmonate", "smiles": "CC1C(=O)CC[C@H](C)C1CC=CC(=O)OC"},
29
+ # Iso E Super / Timbersilk
30
+ "Iso E Super": {"cas": "54452-50-3", "name": "Iso E Super (OTNE)", "smiles": "CC(C)C1CCC(C)CC1CC(C)C=O"},
31
+ "OTNE": {"cas": "54452-50-3", "name": "Iso E Super (OTNE)", "smiles": "CC(C)C1CCC(C)CC1CC(C)C=O"},
32
+ "Iso E Super / OTNE": {"cas": "54452-50-3", "name": "Iso E Super (OTNE)", "smiles": "CC(C)C1CCC(C)CC1CC(C)C=O"},
33
+ "Iso Myrcetone Gamma": {"cas": "68039-33-4", "name": "Iso Myrcetone gamma", "smiles": "CC(C)=CCCC(C)C1CC=C(C)CC1"},
34
+ "Timbersilk": {"cas": "68039-33-4", "name": "Timbersilk (Iso Myrcetone gamma)", "smiles": "CC(C)=CCCC(C)C1CC=C(C)CC1"},
35
+ "Iso Myrcetone Gamma / Timbersilk": {"cas": "68039-33-4", "name": "Timbersilk (Iso Myrcetone gamma)", "smiles": "CC(C)=CCCC(C)C1CC=C(C)CC1"},
36
+ # Damascones
37
+ "Beta-damascone": {"cas": "23726-91-2", "name": "Beta-damascone", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"},
38
+ "Beta-damascenone": {"cas": "23696-85-7", "name": "Beta-damascenone", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"},
39
+ "Beta-damascone / beta-damascenone 1%": {"cas": "23696-85-7", "name": "Beta-damascenone 1%", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"},
40
+ "Beta-damascone / beta-damascenone": {"cas": "23696-85-7", "name": "Beta-damascenone", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"},
41
+ # Musks / lactones
42
+ "Ambrettolide": {"cas": "142-62-3", "name": "Ambrettolide", "smiles": "O=C1CCCCCCCCCCCO1"},
43
+ "Habanolide": {"cas": "111-79-5", "name": "Habanolide", "smiles": "O=C1CCCCCCCCCO1"},
44
+ "Ambroxan": {"cas": "6790-58-9", "name": "Ambroxan", "smiles": "C[C@]12CC[C@@H](CC1=O)C(C)(C)C2"},
45
+ "Ambroxan 10%": {"cas": "6790-58-9", "name": "Ambroxan 10%", "smiles": "C[C@]12CC[C@@H](CC1=O)C(C)(C)C2"},
46
+ # Ionones
47
+ "Methyl Ionone Gamma": {"cas": "127-42-4", "name": "Methyl ionone gamma", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"},
48
+ "Ionone Beta": {"cas": "14901-07-6", "name": "Ionone beta", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"},
49
+ "Dihydro Ionone Beta": {"cas": "17283-81-7", "name": "Dihydro ionone beta", "smiles": "CC(=O)CCC1C(C)=CCCC1(C)C"},
50
+ # Orris / naturals
51
+ "Orris butter": {"cas": "8002-73-1", "name": "Orris butter", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"}, # proxy: ionone
52
+ "Orris CO2 10%": {"cas": "8002-73-1", "name": "Orris CO2 10%", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"},
53
+ # Vetiver / cedar
54
+ "Vetiveryl acetate": {"cas": "117-98-6", "name": "Vetiveryl acetate", "smiles": "CC(=O)OC1CC2CCC(C)C(C)C2C1"},
55
+ "Vetiver Haiti 10%": {"cas": "8022-68-4", "name": "Vetiver Haiti 10%", "smiles": "CC1=CCC2C(C)C(C)CCC2C1"},
56
+ "Cedarwood Virginia": {"cas": "8000-27-9", "name": "Cedarwood Virginia", "smiles": "CC1=CCC2C(C)C(C)CCC2C1"},
57
+ "Cedarwood Texas": {"cas": "8000-27-9", "name": "Cedarwood Texas", "smiles": "CC1=CCC2C(C)C(C)CCC2C1"},
58
+ # Green / leafy
59
+ "Cis-3-hexenyl salicylate": {"cas": "65405-77-8", "name": "cis-3-Hexenyl salicylate", "smiles": "O=C(Oc1ccccc1O)C/C=C/CC"},
60
+ "Cis-3-hexenol": {"cas": "928-96-1", "name": "cis-3-Hexenol", "smiles": "CC/C=C/CCO"},
61
+ "Cis-3-hexenol 1%": {"cas": "928-96-1", "name": "cis-3-Hexenol 1%", "smiles": "CC/C=C/CCO"},
62
+ # Other common materials
63
+ "Coumarin": {"cas": "91-64-5", "name": "Coumarin", "smiles": "O=c1ccc2ccccc2o1"},
64
+ "Coumarin 10%": {"cas": "91-64-5", "name": "Coumarin 10%", "smiles": "O=c1ccc2ccccc2o1"},
65
+ "Fumaric acid": {"cas": "110-17-8", "name": "Fumaric acid", "smiles": "O=C(O)/C=C/C(=O)O"},
66
+ "Cinnamyl alcohol": {"cas": "104-54-1", "name": "Cinnamyl alcohol", "smiles": "OC/C=C/c1ccccc1"},
67
+ "Sorbic acid": {"cas": "110-44-1", "name": "Sorbic acid", "smiles": "CC=CC=CC(=O)O"},
68
+ "Tetrahydroquinoline": {"cas": "119-64-2", "name": "Tetrahydroquinoline", "smiles": "c1ccc2c(c1)NCCC2"},
69
+ "Estragole": {"cas": "140-67-0", "name": "Estragole", "smiles": "COc1ccc(CC=C)cc1"},
70
+ "Linalool oxide": {"cas": "674-86-6", "name": "Linalool oxide", "smiles": "CC1(C)CC=C(CO)CC1"},
71
+ "Geraniol": {"cas": "106-24-1", "name": "Geraniol", "smiles": "CC(C)=CCC/C(C)=C/CO"},
72
+ "Geraniol 10%": {"cas": "106-24-1", "name": "Geraniol 10%", "smiles": "CC(C)=CCC/C(C)=C/CO"},
73
+ "Citral": {"cas": "5392-40-5", "name": "Citral", "smiles": "CC(C)=CCCC(C)=CC=O"},
74
+ "Citral 10%": {"cas": "5392-40-5", "name": "Citral 10%", "smiles": "CC(C)=CCCC(C)=CC=O"},
75
+ "alpha-Pinene": {"cas": "80-56-8", "name": "alpha-Pinene", "smiles": "CC1=CCC2CC1C2(C)C"},
76
+ "beta-Pinene": {"cas": "127-91-3", "name": "beta-Pinene", "smiles": "CC1=CCC2CC1C2(C)C"},
77
+ "Gamma-terpinene": {"cas": "99-85-4", "name": "Gamma-terpinene", "smiles": "CC1=CC=C(C(C)C)CC1"},
78
+ "Linalool": {"cas": "78-70-6", "name": "Linalool", "smiles": "CC(C)=CCCC(C)(O)C=C"},
79
+ "Nerol": {"cas": "106-25-2", "name": "Nerol", "smiles": "CC(C)=CCC/C(C)=C\CO"},
80
+ "d-Limonene": {"cas": "5989-27-5", "name": "d-Limonene", "smiles": "CC1=CC[C@@H](CC1)C(=C)C"},
81
+ "Anthranilic acid": {"cas": "89-43-0", "name": "Anthranilic acid", "smiles": "Nc1ccccc1C(=O)O"},
82
+ "cis-3-Hexenol": {"cas": "928-96-1", "name": "cis-3-Hexenol", "smiles": "CC/C=C/CCO"},
83
+ "cis-3-Hexenyl acetate": {"cas": "928-97-2", "name": "cis-3-Hexenyl acetate", "smiles": "CC(=O)OCC/C=C/CC"},
84
+ "Terpinen-4-ol": {"cas": "99-85-4", "name": "Terpinen-4-ol", "smiles": "CC1=CCC(C(C)(C)O)CC1"},
85
+ "Ethyl vanillin": {"cas": "121-34-6", "name": "Ethyl vanillin", "smiles": "CCOc1cc(C=O)ccc1O"},
86
+ "Methyl salicylate": {"cas": "119-36-8", "name": "Methyl salicylate", "smiles": "COC(=O)c1ccccc1O"},
87
+ "Benzyl salicylate": {"cas": "118-58-1", "name": "Benzyl salicylate", "smiles": "O=C(Oc1ccccc1)c2ccccc2O"},
88
+ "Nerolidol": {"cas": "7212-44-4", "name": "Nerolidol", "smiles": "CC(C)=CCCC(C)=CCCO"},
89
+ "Farnesol": {"cas": "4602-84-0", "name": "Farnesol", "smiles": "CC(C)=CCCC(C)=CCCO"},
90
+ "Neral": {"cas": "106-26-3", "name": "Neral", "smiles": "CC(C)=CCC/C(C)=C/C=O"},
91
+ "Guaiacol": {"cas": "90-05-1", "name": "Guaiacol", "smiles": "COc1ccccc1O"},
92
+ "Beta-thujone": {"cas": "89-86-1", "name": "Beta-thujone", "smiles": "CC1(C)C(=O)C2(C)CCC1C2"},
93
+ "Menthol": {"cas": "89-78-1", "name": "Menthol", "smiles": "CC(C)C1CCC(C)CC1O"},
94
+ "Cedrol": {"cas": "77-53-2", "name": "Cedrol", "smiles": "CC1(C)C2CCC3(C)C(C)(C)CCC3(C)C2C1"},
95
+ "Cedrene": {"cas": "469-01-2", "name": "Cedrene", "smiles": "CC1=CCC2C(C)C3CCC(C)C3CC2C1"},
96
+ "Cedryl acetate": {"cas": "5986-38-9", "name": "Cedryl acetate", "smiles": "CC(=O)OC1C(C)C2CCC(C)C2C1(C)C"},
97
+ "cis-3-Hexenyl salicylate": {"cas": "65405-77-8", "name": "cis-3-Hexenyl salicylate", "smiles": "O=C(OCCCC/C=C/CC)c1ccccc1O"},
98
+ # Common naturals and bases handled by accords.py
99
+ "Beta-damascenone": {"cas": "23696-85-7", "name": "Beta-damascenone", "smiles": "CC(=O)/C=C/C1C(C)=CCCC1(C)C"},
100
+ "Methyl salicylate 10%": {"cas": "119-36-8", "name": "Methyl salicylate 10%", "smiles": "COC(=O)c1ccccc1O"},
101
+ # Common naturals and bases handled by accords.py
102
+ "Green Tea Base": {"accord": "green_tea"},
103
+ "Tea Black Base": {"accord": "black_tea"},
104
+ "Tea Black Base 10%": {"accord": "black_tea"},
105
+ "Mate absolute": {"accord": "mate"},
106
+ "Mate absolute 10%": {"accord": "mate"},
107
+ "Orris butter / orris CO2 10%": {"accord": "orris"},
108
+ "Vetiver Haiti 10%": {"accord": "vetiver"},
109
+ "Cedarwood Virginia/Texas": {"accord": "cedarwood"},
110
+ }
111
+
112
+
113
+ def resolve_material(name: str) -> dict[str, Any] | None:
114
+ """Return the canonical identifier(s) for a trade name, if known."""
115
+ return MATERIALS.get(name)
116
+
117
+
118
+ def is_accord(name: str) -> bool:
119
+ """Return True if this material is a proprietary base we expand via accords."""
120
+ rec = MATERIALS.get(name)
121
+ return rec is not None and "accord" in rec
122
+
123
+
124
+ def all_material_names() -> list[str]:
125
+ return list(MATERIALS.keys())
src/pino/optimizer.py CHANGED
@@ -44,12 +44,51 @@ from .ifra import IFRA_RESTRICTIONS, check_ifra_restrictions
44
  from .inference_cloud import predict_cloud
45
  from .models import Formula, Ingredient, Status
46
  from .pimt_model import FragranceTrajectoryDataset
47
- from .semantics import get_psychometric_targets
48
  from .structures import IngredientResolver
49
  from .verifier import FragrancePipelineVerifier
50
 
51
  logger = logging.getLogger("pino.optimizer")
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  # Minimum weight fraction for an active ingredient to be considered present.
54
  # Anything below this is treated as zero, which keeps the formula sparse and
55
  # manufacture-ready.
@@ -136,6 +175,21 @@ class CompositionTarget:
136
  weight_subjective: float = 0.5
137
  name: str = "custom"
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  @staticmethod
140
  def from_text(text: str, *, weight_objective: float = 1.0, weight_subjective: float = 0.5) -> "CompositionTarget":
141
  """
@@ -148,18 +202,14 @@ class CompositionTarget:
148
  neutral gender.
149
  """
150
  text_lower = text.lower()
151
- strategy = "wildcard"
152
- if "citrus" in text_lower or "summer" in text_lower or "fresh" in text_lower:
153
- strategy = "citrus_cologne"
154
- elif "amber" in text_lower or "oriental" in text_lower or "winter" in text_lower:
155
- strategy = "amber_oriental"
156
- elif "floral" in text_lower or "woody" in text_lower:
157
- strategy = "floral_woody"
158
- elif "fougere" in text_lower or "lavender" in text_lower:
159
- strategy = "fougere"
160
 
161
  subjective = get_psychometric_targets(strategy)
162
 
 
 
 
 
163
  # Apply crude gender override from the brief.
164
  if "masculine" in text_lower:
165
  subjective[4] = 0.7
@@ -177,10 +227,12 @@ class CompositionTarget:
177
  subjective[6] = 0.8
178
 
179
  return CompositionTarget(
 
180
  subjective=subjective,
181
  weight_objective=weight_objective,
182
  weight_subjective=weight_subjective,
183
  name=text,
 
184
  )
185
 
186
  @staticmethod
@@ -284,14 +336,41 @@ class FormulationOptimizer:
284
  model.eval()
285
  return model
286
 
287
- def _build_palette(self, count: int = 20) -> None:
288
- """
289
- Select a diverse palette from the SQLite registry.
 
 
 
 
 
 
 
 
 
 
290
 
291
- We prefer well-known fragrance materials with low molecular weight and
292
- moderate volatility, because these are the ingredients most likely to
293
- produce a realistic dry-down. The palette is built once per optimizer
294
- instance and reused for all CMA-ES iterations.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  """
296
  import sqlite3
297
 
@@ -304,6 +383,7 @@ class FormulationOptimizer:
304
  restricted_or_problematic = {
305
  "80-54-6", "83-66-9", "81-15-2", "89-68-9", "92-48-8", "143-50-0"
306
  }
 
307
  rows = conn.execute(
308
  """
309
  SELECT cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa, logp
@@ -318,10 +398,19 @@ class FormulationOptimizer:
318
  ).fetchall()
319
  conn.close()
320
 
 
 
 
 
 
 
 
 
 
321
  candidates: list[Ingredient] = []
322
  for row in rows:
323
  cas = str(row["cas"])
324
- if cas in non_formula_solvents or cas in restricted_or_problematic:
325
  continue
326
  try:
327
  ing = self.resolver.resolve(
@@ -334,13 +423,19 @@ class FormulationOptimizer:
334
  logger.debug("Skipping palette candidate %s: %s", cas, exc)
335
  continue
336
 
337
- # Shuffle and downsample to the requested count for variety.
338
- indices = self._rng.choice(len(candidates), size=min(count, len(candidates)), replace=False)
339
- self.palette = [candidates[i] for i in indices]
 
 
 
 
 
340
  self.palette_cas = [ing.cas for ing in self.palette]
341
  logger.info(
342
- "Built palette of %d ingredients from %d registry candidates",
343
  len(self.palette),
 
344
  len(candidates),
345
  )
346
 
@@ -475,6 +570,8 @@ class FormulationOptimizer:
475
 
476
  mse = self._mse(prediction, target)
477
  fitness = mse if mse > 0 else 1e-12
 
 
478
 
479
  return Candidate(
480
  ingredients=self.palette,
@@ -535,6 +632,27 @@ class FormulationOptimizer:
535
  "subjective": output.subjective.cpu().numpy().tolist(),
536
  }
537
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
538
  def _mse(self, prediction: dict[str, Any], target: CompositionTarget) -> float:
539
  """
540
  Compute a weighted mean-squared-error loss between prediction and target.
@@ -548,7 +666,10 @@ class FormulationOptimizer:
548
  tgt_obj = target.objective
549
  if tgt_obj.ndim == 1:
550
  tgt_obj = np.tile(tgt_obj, (pred_obj.shape[0], 1))
551
- obj_error = float(np.mean((pred_obj - tgt_obj) ** 2))
 
 
 
552
  errors.append(target.weight_objective * obj_error)
553
 
554
  if target.subjective is not None and "subjective" in prediction:
@@ -590,14 +711,17 @@ class FormulationOptimizer:
590
  Candidate
591
  The best feasible formula found, including its trajectory and prediction.
592
  """
593
- self._build_palette(palette_size)
594
  self._restrict_palette()
595
 
596
  n = len(self.palette)
597
  if n == 0:
598
  raise RuntimeError("Palette is empty; cannot optimise")
599
 
600
- x0 = initial_guess if initial_guess is not None else np.ones(n) / n
 
 
 
601
  x0 = self._project_and_normalize(x0)
602
 
603
  # CMA-ES minimises the objective; lower MSE = higher fitness.
 
44
  from .inference_cloud import predict_cloud
45
  from .models import Formula, Ingredient, Status
46
  from .pimt_model import FragranceTrajectoryDataset
47
+ from .semantics import get_objective_targets, get_psychometric_targets
48
  from .structures import IngredientResolver
49
  from .verifier import FragrancePipelineVerifier
50
 
51
  logger = logging.getLogger("pino.optimizer")
52
 
53
+ # Curated seed palettes by strategy. These are materials that must be present in
54
+ # the search space so the optimizer can satisfy genre-specific briefs (e.g., a
55
+ # citrus cologne needs citrus top-note materials). The seed list is resolved
56
+ # from the standard materials library or registry; the rest of the palette is
57
+ # filled with random registry candidates.
58
+ STRATEGY_SEED_CAS: dict[str, list[str]] = {
59
+ "citrus_cologne": [
60
+ "5989-27-5", # d-Limonene (primary citrus top note)
61
+ "5392-40-5", # Citral (lemon/citrus top)
62
+ "99-85-4", # Gamma-terpinene (citrus peel)
63
+ "80-56-8", # alpha-Pinene (fresh pine/citrus lift)
64
+ "115-95-7", # Linalyl acetate (bergamet/citrus floral)
65
+ "78-70-6", # Linalool (light citrus/floral bridge)
66
+ ],
67
+ "fougere": [
68
+ "78-70-6", # Linalool
69
+ "91-64-5", # Coumarin
70
+ "121-33-5", # Vanillin
71
+ "80-56-8", # alpha-Pinene
72
+ "5989-27-5", # d-Limonene
73
+ ],
74
+ "floral_woody": [
75
+ "78-70-6", # Linalool
76
+ "106-24-5", # Geraniol
77
+ "106-25-2", # Nerol
78
+ "77-53-2", # Cedrol
79
+ "5989-27-5", # d-Limonene
80
+ "121-33-5", # Vanillin
81
+ ],
82
+ "amber_oriental": [
83
+ "105-95-3", # Ethylene brassylate
84
+ "91-64-5", # Coumarin
85
+ "121-33-5", # Vanillin
86
+ "77-53-2", # Cedrol
87
+ "8000-27-9", # Cedarwood oil
88
+ ],
89
+ "wildcard": [],
90
+ }
91
+
92
  # Minimum weight fraction for an active ingredient to be considered present.
93
  # Anything below this is treated as zero, which keeps the formula sparse and
94
  # manufacture-ready.
 
175
  weight_subjective: float = 0.5
176
  name: str = "custom"
177
 
178
+ strategy: str = "wildcard"
179
+
180
+ @staticmethod
181
+ def _infer_strategy(text: str) -> str:
182
+ text_lower = text.lower()
183
+ if "citrus" in text_lower or "summer" in text_lower or "fresh" in text_lower:
184
+ return "citrus_cologne"
185
+ if "amber" in text_lower or "oriental" in text_lower or "winter" in text_lower:
186
+ return "amber_oriental"
187
+ if "floral" in text_lower or "woody" in text_lower:
188
+ return "floral_woody"
189
+ if "fougere" in text_lower or "lavender" in text_lower:
190
+ return "fougere"
191
+ return "wildcard"
192
+
193
  @staticmethod
194
  def from_text(text: str, *, weight_objective: float = 1.0, weight_subjective: float = 0.5) -> "CompositionTarget":
195
  """
 
202
  neutral gender.
203
  """
204
  text_lower = text.lower()
205
+ strategy = CompositionTarget._infer_strategy(text)
 
 
 
 
 
 
 
 
206
 
207
  subjective = get_psychometric_targets(strategy)
208
 
209
+ # Build an objective trajectory target that reinforces the brief's genre.
210
+ # 49 timesteps = 8 hours sampled every 10 minutes, matching the verifier.
211
+ objective = get_objective_targets(strategy, timesteps=49)
212
+
213
  # Apply crude gender override from the brief.
214
  if "masculine" in text_lower:
215
  subjective[4] = 0.7
 
227
  subjective[6] = 0.8
228
 
229
  return CompositionTarget(
230
+ objective=objective,
231
  subjective=subjective,
232
  weight_objective=weight_objective,
233
  weight_subjective=weight_subjective,
234
  name=text,
235
+ strategy=strategy,
236
  )
237
 
238
  @staticmethod
 
336
  model.eval()
337
  return model
338
 
339
+ def _initial_guess(self, strategy: str, n: int) -> np.ndarray:
340
+ """Return a strategy-biased starting point on the simplex."""
341
+ x = np.zeros(n, dtype=float)
342
+ seed_cas = set(STRATEGY_SEED_CAS.get(strategy, []))
343
+ seed_indices = [i for i, ing in enumerate(self.palette) if ing.cas in seed_cas]
344
+ if not seed_indices:
345
+ return np.ones(n) / n
346
+ # Distribute 70% of the mass evenly across the seeds, 30% across the rest.
347
+ x[seed_indices] = 0.70 / len(seed_indices)
348
+ others = [i for i in range(n) if i not in seed_indices]
349
+ if others:
350
+ x[others] = 0.30 / len(others)
351
+ return x
352
 
353
+ def _strategy_bonus(self, weights: np.ndarray, strategy: str) -> float:
354
+ """
355
+ Penalise candidates that lack the brief's expected seed materials.
356
+ This is a soft nudge: missing a large fraction of the expected materials
357
+ adds up to 0.05 to the MSE, enough to break ties but not dominate the
358
+ perceptual loss.
359
+ """
360
+ seed_cas = set(STRATEGY_SEED_CAS.get(strategy, []))
361
+ if not seed_cas:
362
+ return 0.0
363
+ seed_indices = [i for i, ing in enumerate(self.palette) if ing.cas in seed_cas]
364
+ if not seed_indices:
365
+ return 0.0
366
+ seed_mass = float(weights[seed_indices].sum())
367
+ # Missing seed mass penalised quadratically; full seed mass = 0 bonus.
368
+ return 0.20 * (1.0 - seed_mass) ** 2
369
+
370
+ def _build_palette(self, count: int = 20, strategy: str = "wildcard") -> None:
371
+ """
372
+ Select a diverse palette from the SQLite registry, seeded with strategy-appropriate
373
+ materials so the optimizer can satisfy genre-specific briefs.
374
  """
375
  import sqlite3
376
 
 
383
  restricted_or_problematic = {
384
  "80-54-6", "83-66-9", "81-15-2", "89-68-9", "92-48-8", "143-50-0"
385
  }
386
+ strategy_seed = set(STRATEGY_SEED_CAS.get(strategy, []))
387
  rows = conn.execute(
388
  """
389
  SELECT cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa, logp
 
398
  ).fetchall()
399
  conn.close()
400
 
401
+ # Start with strategy-seeded materials so the brief has a reachable target.
402
+ seeded: list[Ingredient] = []
403
+ for cas in strategy_seed:
404
+ try:
405
+ ing = self.resolver.resolve(cas, weight_fraction=0.0)
406
+ seeded.append(ing)
407
+ except Exception as exc:
408
+ logger.debug("Could not resolve seed material %s: %s", cas, exc)
409
+
410
  candidates: list[Ingredient] = []
411
  for row in rows:
412
  cas = str(row["cas"])
413
+ if cas in non_formula_solvents or cas in restricted_or_problematic or cas in strategy_seed:
414
  continue
415
  try:
416
  ing = self.resolver.resolve(
 
423
  logger.debug("Skipping palette candidate %s: %s", cas, exc)
424
  continue
425
 
426
+ # Fill the rest of the palette with random registry candidates, preserving
427
+ # the seeds. We always want at least the seeds present.
428
+ remaining = max(0, count - len(seeded))
429
+ if remaining > 0 and candidates:
430
+ indices = self._rng.choice(len(candidates), size=min(remaining, len(candidates)), replace=False)
431
+ self.palette = seeded + [candidates[i] for i in indices]
432
+ else:
433
+ self.palette = seeded
434
  self.palette_cas = [ing.cas for ing in self.palette]
435
  logger.info(
436
+ "Built palette of %d ingredients (%d seeded) from %d registry candidates",
437
  len(self.palette),
438
+ len(seeded),
439
  len(candidates),
440
  )
441
 
 
570
 
571
  mse = self._mse(prediction, target)
572
  fitness = mse if mse > 0 else 1e-12
573
+ strategy_bonus = self._strategy_bonus(weights, target.strategy)
574
+ fitness = fitness + strategy_bonus
575
 
576
  return Candidate(
577
  ingredients=self.palette,
 
632
  "subjective": output.subjective.cpu().numpy().tolist(),
633
  }
634
 
635
+ @staticmethod
636
+ def _compute_olfactory_mse(
637
+ pred_obj: np.ndarray,
638
+ tgt_obj: np.ndarray,
639
+ active_indices: tuple[int, ...] = (0, 1, 2, 3),
640
+ active_weight: float = 50.0,
641
+ background_weight: float = 0.1,
642
+ ) -> float:
643
+ """
644
+ Importance-weighted MSE for the objective trajectory.
645
+
646
+ Active genre descriptors (e.g., citrus, lavender, wood, musk) are weighted
647
+ heavily so the optimizer is driven by the brief. Background channels are
648
+ down-weighted so they do not dilute the signal.
649
+ """
650
+ squared_errors = (pred_obj - tgt_obj) ** 2
651
+ weights = np.ones_like(squared_errors) * background_weight
652
+ for idx in active_indices:
653
+ weights[..., idx] = active_weight
654
+ return float(np.mean(squared_errors * weights))
655
+
656
  def _mse(self, prediction: dict[str, Any], target: CompositionTarget) -> float:
657
  """
658
  Compute a weighted mean-squared-error loss between prediction and target.
 
666
  tgt_obj = target.objective
667
  if tgt_obj.ndim == 1:
668
  tgt_obj = np.tile(tgt_obj, (pred_obj.shape[0], 1))
669
+ # Use an importance-weighted MSE: active genre descriptors (0-3) get
670
+ # a heavy weight while the 134 background channels are down-weighted
671
+ # so they cannot drown the brief signal.
672
+ obj_error = self._compute_olfactory_mse(pred_obj, tgt_obj)
673
  errors.append(target.weight_objective * obj_error)
674
 
675
  if target.subjective is not None and "subjective" in prediction:
 
711
  Candidate
712
  The best feasible formula found, including its trajectory and prediction.
713
  """
714
+ self._build_palette(palette_size, strategy=target.strategy)
715
  self._restrict_palette()
716
 
717
  n = len(self.palette)
718
  if n == 0:
719
  raise RuntimeError("Palette is empty; cannot optimise")
720
 
721
+ # Strategy-aware initial guess: give a strong prior to the materials that
722
+ # are expected to satisfy the brief. This keeps CMA-ES from getting stuck
723
+ # in a generic floral/heart local minimum.
724
+ x0 = self._initial_guess(target.strategy, n) if initial_guess is None else initial_guess
725
  x0 = self._project_and_normalize(x0)
726
 
727
  # CMA-ES minimises the objective; lower MSE = higher fitness.
src/pino/registry.py CHANGED
@@ -178,10 +178,10 @@ class AromaRegistry:
178
  try:
179
  groups = AromaRegistry.fragment_groups(smiles, "smiles")
180
  except Exception:
181
- return None
182
-
183
- if not groups:
184
- return None
185
 
186
  return {
187
  "smiles": Chem.MolToSmiles(mol, canonical=True),
@@ -220,7 +220,9 @@ class AromaRegistry:
220
  logp = None
221
  groups = AromaRegistry.fragment_groups(canonical, "smiles")
222
  if not groups:
223
- raise IngredientResolutionError(f"No UNIFAC groups for {smiles}", smiles=smiles)
 
 
224
  return {
225
  "cas": f"SMILES:{canonical}",
226
  "name": name or canonical,
 
178
  try:
179
  groups = AromaRegistry.fragment_groups(smiles, "smiles")
180
  except Exception:
181
+ # Some molecules (e.g. coumarin) parse in RDKit but cannot be
182
+ # fragmented by ugropy. We still keep the record so that VLE can
183
+ # fall back to ideal gamma=1.0 rather than rejecting the material.
184
+ groups = {}
185
 
186
  return {
187
  "smiles": Chem.MolToSmiles(mol, canonical=True),
 
220
  logp = None
221
  groups = AromaRegistry.fragment_groups(canonical, "smiles")
222
  if not groups:
223
+ # Allow ideal-solution fallback for materials that cannot be fragmented
224
+ # (e.g., coumarin). The VLE model will use gamma=1.0.
225
+ groups = {}
226
  return {
227
  "cas": f"SMILES:{canonical}",
228
  "name": name or canonical,
src/pino/semantics.py CHANGED
@@ -44,11 +44,11 @@ def get_objective_targets(generation_strategy: str, timesteps: int, seed: int =
44
 
45
  # Per-genre activation coefficients for the 4 notes.
46
  coeffs = {
47
- "citrus_cologne": [1.0, 0.1, 0.2, 0.1],
48
- "fougere": [0.1, 0.8, 0.8, 0.4],
49
- "floral_woody": [0.1, 0.7, 1.0, 0.3],
50
- "amber_oriental": [0.1, 0.2, 0.9, 1.0],
51
- "wildcard": [0.7, 0.6, 0.7, 0.6],
52
  }.get(generation_strategy, [0.7, 0.6, 0.7, 0.6])
53
  coeffs = np.array(coeffs, dtype=np.float32)
54
 
 
44
 
45
  # Per-genre activation coefficients for the 4 notes.
46
  coeffs = {
47
+ "citrus_cologne": [1.0, 0.1, 0.1, 0.0],
48
+ "fougere": [0.1, 0.8, 0.4, 0.1],
49
+ "floral_woody": [0.1, 0.7, 0.6, 0.1],
50
+ "amber_oriental": [0.0, 0.1, 0.9, 1.0],
51
+ "wildcard": [0.7, 0.6, 0.5, 0.4],
52
  }.get(generation_strategy, [0.7, 0.6, 0.7, 0.6])
53
  coeffs = np.array(coeffs, dtype=np.float32)
54
 
src/pino/structures.py CHANGED
@@ -6,6 +6,7 @@ from typing import Any
6
  from rdkit import Chem
7
  from rdkit.Chem import Descriptors
8
 
 
9
  from .models import Ingredient, IngredientResolutionError
10
  from .registry import AromaRegistry
11
 
@@ -37,6 +38,32 @@ class IngredientResolver:
37
  logger.debug("Resolved %s from registry", identifier)
38
  return self._ingredient_from_record(record, weight_fraction)
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  # Live fallback
41
  logger.info("Registry miss for %s; falling back to PubChem/ugropy", identifier)
42
  try:
@@ -82,6 +109,38 @@ class IngredientResolver:
82
 
83
  return ingredients, errors
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def _ingredient_from_record(self, record: dict[str, Any], weight_fraction: float) -> Ingredient:
86
  """Construct an Ingredient from a registry/live record."""
87
  smiles = record["smiles"]
 
6
  from rdkit import Chem
7
  from rdkit.Chem import Descriptors
8
 
9
+ from .materials import resolve_material
10
  from .models import Ingredient, IngredientResolutionError
11
  from .registry import AromaRegistry
12
 
 
38
  logger.debug("Resolved %s from registry", identifier)
39
  return self._ingredient_from_record(record, weight_fraction)
40
 
41
+ # Known standard-material fallback: trade names in materials.py provide
42
+ # a canonical SMILES, so we can build a record without a network round-trip.
43
+ for lookup in (name, identifier):
44
+ if not lookup:
45
+ continue
46
+ material = resolve_material(lookup)
47
+ if material and not material.get("accord"):
48
+ smiles = material.get("smiles")
49
+ if smiles:
50
+ logger.debug("Resolved %s from standard materials library", lookup)
51
+ record = AromaRegistry.validate_smiles(smiles)
52
+ if record is None:
53
+ raise IngredientResolutionError(
54
+ f"Standard material {lookup} has an invalid SMILES", cas=identifier
55
+ )
56
+ record["name"] = material.get("name", lookup)
57
+ record["cas"] = material.get("cas", identifier)
58
+ if material.get("vapor_pressure_pa") is not None:
59
+ record["vapor_pressure_pa"] = material["vapor_pressure_pa"]
60
+ if material.get("boiling_point_k") is not None:
61
+ record["boiling_point_k"] = material["boiling_point_k"]
62
+ if material.get("odor_threshold_ug_m3") is not None:
63
+ record["odor_threshold_ug_m3"] = material["odor_threshold_ug_m3"]
64
+ self.registry.add(record)
65
+ return self._ingredient_from_record(record, weight_fraction)
66
+
67
  # Live fallback
68
  logger.info("Registry miss for %s; falling back to PubChem/ugropy", identifier)
69
  try:
 
109
 
110
  return ingredients, errors
111
 
112
+ def resolve_formula_pairs(
113
+ self,
114
+ formula: list[dict[str, Any]],
115
+ *,
116
+ skip_unresolved: bool = False,
117
+ ) -> tuple[list[tuple[dict[str, Any], Ingredient]], list[IngredientResolutionError]]:
118
+ """
119
+ Resolve formula components and return (record, ingredient) pairs.
120
+
121
+ This is useful when the caller needs to keep the original record
122
+ alongside the resolved ingredient so that weight fractions stay aligned
123
+ after filtering out unresolved materials.
124
+ """
125
+ pairs: list[tuple[dict[str, Any], Ingredient]] = []
126
+ errors: list[IngredientResolutionError] = []
127
+
128
+ for comp in formula:
129
+ if "weight_fraction" not in comp:
130
+ raise ValueError(f"Formula component missing weight_fraction: {comp}")
131
+ wf = float(comp["weight_fraction"])
132
+ ident = str(comp.get("cas", comp.get("smiles", comp.get("name", ""))))
133
+ try:
134
+ ing = self.resolve(ident, wf, name=comp.get("name"))
135
+ pairs.append((comp, ing))
136
+ except IngredientResolutionError as exc:
137
+ logger.warning("Out of applicability domain for %s: %s", ident, exc)
138
+ errors.append(exc)
139
+ if not skip_unresolved:
140
+ raise
141
+
142
+ return pairs, errors
143
+
144
  def _ingredient_from_record(self, record: dict[str, Any], weight_fraction: float) -> Ingredient:
145
  """Construct an Ingredient from a registry/live record."""
146
  smiles = record["smiles"]
src/pino/verifier.py CHANGED
@@ -62,9 +62,12 @@ class FragrancePipelineVerifier:
62
  - applicability_errors: list of out-of-domain errors
63
  - message: human-readable summary
64
  """
65
- # Resolve ingredients
66
  try:
67
- ingredients, errors = self.resolver.resolve_formula(formula, skip_unresolved=False)
 
 
 
68
  except IngredientResolutionError as exc:
69
  logger.warning("Formula rejected: out of applicability domain for %s", exc.cas)
70
  return {
@@ -78,7 +81,18 @@ class FragrancePipelineVerifier:
78
  "message": f"Out of applicability domain: {exc}",
79
  }
80
 
81
- weights = [float(c.get("weight_fraction", 0.0)) for c in formula]
 
 
 
 
 
 
 
 
 
 
 
82
  # Re-normalize in case skipped ingredients changed total
83
  total_w = sum(weights)
84
  if total_w <= 0:
 
62
  - applicability_errors: list of out-of-domain errors
63
  - message: human-readable summary
64
  """
65
+ # Resolve ingredients, skipping any that cannot be resolved.
66
  try:
67
+ resolved_pairs, errors = self.resolver.resolve_formula_pairs(formula, skip_unresolved=True)
68
+ if errors:
69
+ for exc in errors:
70
+ logger.warning("Skipping unresolved ingredient: %s", exc)
71
  except IngredientResolutionError as exc:
72
  logger.warning("Formula rejected: out of applicability domain for %s", exc.cas)
73
  return {
 
81
  "message": f"Out of applicability domain: {exc}",
82
  }
83
 
84
+ if not resolved_pairs:
85
+ return {
86
+ "status": "rejected",
87
+ "trajectory": [],
88
+ "depletion_rates": {},
89
+ "ifra_report": {"passed": False, "violations": [], "max_usage": []},
90
+ "applicability_errors": [],
91
+ "message": "No resolvable ingredients in formula",
92
+ }
93
+
94
+ ingredients = [ing for _, ing in resolved_pairs]
95
+ weights = [float(rec.get("weight_fraction", 0.0)) for rec, _ in resolved_pairs]
96
  # Re-normalize in case skipped ingredients changed total
97
  total_w = sum(weights)
98
  if total_w <= 0:
tests/test_pimt_invariance.py CHANGED
@@ -45,8 +45,7 @@ def test_ingredient_order_permutation_invariance() -> None:
45
  pred_perm = heads(latent_perm)
46
 
47
  assert torch.allclose(pred["objective"], pred_perm["objective"], atol=1e-5)
48
- for key in pred["subjective"]:
49
- assert torch.allclose(pred["subjective"][key], pred_perm["subjective"][key], atol=1e-5)
50
 
51
 
52
  def test_head_output_shapes() -> None:
@@ -70,11 +69,9 @@ def test_head_output_shapes() -> None:
70
  pred = heads(latent)
71
 
72
  assert pred["objective"].shape == (bsz, t_steps, 138)
73
- assert pred["subjective"]["seasonality"].shape == (bsz, 4)
74
- assert pred["subjective"]["gender_profile"].shape == (bsz,)
75
- assert pred["subjective"]["wearability"].shape == (bsz, 4)
76
- assert pred["subjective"]["gender_profile"].min() >= -1.0
77
- assert pred["subjective"]["gender_profile"].max() <= 1.0
78
 
79
 
80
  def test_objective_target_curve_physics() -> None:
 
45
  pred_perm = heads(latent_perm)
46
 
47
  assert torch.allclose(pred["objective"], pred_perm["objective"], atol=1e-5)
48
+ assert torch.allclose(pred["subjective"], pred_perm["subjective"], atol=1e-5)
 
49
 
50
 
51
  def test_head_output_shapes() -> None:
 
69
  pred = heads(latent)
70
 
71
  assert pred["objective"].shape == (bsz, t_steps, 138)
72
+ assert pred["subjective"].shape == (bsz, 7)
73
+ assert pred["subjective"].min() >= -2.0
74
+ assert pred["subjective"].max() <= 2.0
 
 
75
 
76
 
77
  def test_objective_target_curve_physics() -> None: