mattbitzesty commited on
Commit
884ed70
·
unverified ·
1 Parent(s): dc36068

feat(data): generate OAV targets in dataset builder and validate UNIFAC subgroups

Browse files

DatasetBuilder now writes objective_targets and psychometric_targets.
Ingest normalizer filters recipes by valid DOUFSG subgroups and
rescales remaining weight fractions to unity.

src/pino/dataset_builder.py CHANGED
@@ -10,6 +10,8 @@ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
10
  from pathlib import Path
11
  from typing import Any
12
 
 
 
13
  from pino.draft_engine import FormulaGenerator
14
  from pino.verifier import FragrancePipelineVerifier
15
 
@@ -104,6 +106,22 @@ class DatasetBuilder:
104
  if result.get("status") not in ("passed", "depleted"):
105
  return None
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  return {
108
  "status": result.get("status"),
109
  "formula_id": formula_id,
@@ -116,6 +134,8 @@ class DatasetBuilder:
116
  "formula": formula,
117
  "depletion_rates": result.get("depletion_rates", {}),
118
  "trajectory": result.get("trajectory", []),
 
 
119
  }
120
 
121
  def _append_record(self, record: dict[str, Any]) -> None:
 
10
  from pathlib import Path
11
  from typing import Any
12
 
13
+ import numpy as np
14
+
15
  from pino.draft_engine import FormulaGenerator
16
  from pino.verifier import FragrancePipelineVerifier
17
 
 
106
  if result.get("status") not in ("passed", "depleted"):
107
  return None
108
 
109
+ # Build OAV-weighted descriptor targets using the new semantics module.
110
+ from pino import semantics
111
+ composition = [
112
+ {"cas": c.get("cas"), "smiles": c.get("smiles")}
113
+ for c in formula
114
+ ]
115
+ C_gas = np.array([step["C_gas_mg_m3"] for step in result["trajectory"]])
116
+ # Align concentration matrix by canonical CAS ordering.
117
+ cas_order = [c["cas"] for c in composition]
118
+ concentrations = np.zeros((C_gas.shape[0], len(cas_order)), dtype=np.float32)
119
+ for t_idx, step in enumerate(result["trajectory"]):
120
+ for c_idx, cas in enumerate(cas_order):
121
+ concentrations[t_idx, c_idx] = step["C_gas_mg_m3"].get(cas, 0.0)
122
+ objective_targets = semantics.compute_oav_targets(composition, concentrations)
123
+ psychometric_targets = semantics.get_psychometric_targets(genre)
124
+
125
  return {
126
  "status": result.get("status"),
127
  "formula_id": formula_id,
 
134
  "formula": formula,
135
  "depletion_rates": result.get("depletion_rates", {}),
136
  "trajectory": result.get("trajectory", []),
137
+ "objective_targets": objective_targets.tolist(),
138
+ "psychometric_targets": psychometric_targets.tolist(),
139
  }
140
 
141
  def _append_record(self, record: dict[str, Any]) -> None:
src/pino/ingest_formulas.py CHANGED
@@ -17,10 +17,14 @@ from pathlib import Path
17
  from typing import Any
18
 
19
  from .registry import AromaRegistry
 
20
 
21
  logger = logging.getLogger("pino.ingest_formulas")
22
 
23
 
 
 
 
24
  def _recursive_unpack(
25
  component: dict[str, Any],
26
  accumulator: dict[str, float],
@@ -116,24 +120,107 @@ def load_literature_manifest(manifest_path: str | Path) -> list[dict[str, Any]]:
116
  return [data]
117
 
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  def normalize_manifest(
120
  manifest_path: str | Path,
121
  registry_path: str | Path | None = None,
 
 
122
  ) -> list[dict[str, Any]]:
123
  """
124
  Normalize every recipe in a manifest and validate each CAS against the registry.
125
 
126
  Recipes that contain unknown CAS numbers are flagged but still returned so
127
  the caller can decide whether to drop, map, or back-fill them.
 
 
 
 
128
  """
129
  registry = AromaRegistry(registry_path)
130
- known_cas = {row[0] for row in registry._conn.execute("SELECT cas FROM aroma_chemicals")}
131
 
132
  results = []
133
  for raw_recipe in load_literature_manifest(manifest_path):
134
- # Write a temporary single-recipe dict for normalization.
135
  tmp = dict(raw_recipe)
136
  normalized = normalize_and_unpack_recipe_from_dict(tmp)
 
137
  unknown = [c["cas"] for c in normalized["components"] if c["cas"] not in known_cas]
138
  if unknown:
139
  logger.warning(
@@ -145,38 +232,42 @@ def normalize_manifest(
145
  normalized["unknown_cas"] = unknown
146
  else:
147
  normalized["registry_status"] = "ok"
148
- results.append(normalized)
149
- return results
150
-
151
-
152
- def normalize_and_unpack_recipe_from_dict(data: dict[str, Any]) -> dict[str, Any]:
153
- """In-memory version of normalize_and_unpack_recipe for a single recipe dict."""
154
- flat_composition: dict[str, float] = defaultdict(float)
155
-
156
- for comp in data.get("components", []):
157
- _recursive_unpack(comp, flat_composition)
158
-
159
- absolute_sum = sum(flat_composition.values())
160
- if absolute_sum <= 0:
161
- raise ValueError(f"Recipe {data.get('formula_id')} has zero total mass")
162
 
163
- normalized_components = []
164
- for cas in sorted(flat_composition.keys()):
165
- weight_fraction = round(flat_composition[cas] / absolute_sum, 6)
166
- normalized_components.append({"cas": cas, "weight_fraction": weight_fraction})
167
-
168
- total_fraction = sum(c["weight_fraction"] for c in normalized_components)
169
- if total_fraction != 1.0 and normalized_components:
170
- normalized_components[0]["weight_fraction"] = round(
171
- normalized_components[0]["weight_fraction"] + (1.0 - total_fraction), 6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  )
 
 
173
 
174
- return {
175
- "formula_id": data.get("formula_id"),
176
- "name": data.get("name"),
177
- "source": data.get("source"),
178
- "components": normalized_components,
179
- }
180
 
181
 
182
  def recipe_to_formula_records(recipe: dict[str, Any]) -> list[dict[str, Any]]:
@@ -194,11 +285,20 @@ if __name__ == "__main__":
194
  parser.add_argument("manifest", help="Path to raw recipe JSON or JSON list")
195
  parser.add_argument("--registry", default="src/pino/registry.db", help="SQLite registry path")
196
  parser.add_argument("--output", help="Optional output JSON path")
 
 
 
 
 
197
  args = parser.parse_args()
198
 
199
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
200
 
201
- results = normalize_manifest(args.manifest, registry_path=args.registry)
 
 
 
 
202
  out_text = json.dumps(results, indent=2, ensure_ascii=False)
203
  if args.output:
204
  Path(args.output).write_text(out_text, encoding="utf-8")
 
17
  from typing import Any
18
 
19
  from .registry import AromaRegistry
20
+ from .thermo.unifac import validate_subgroups
21
 
22
  logger = logging.getLogger("pino.ingest_formulas")
23
 
24
 
25
+ ETHANOL_CAS = "64-17-5"
26
+
27
+
28
  def _recursive_unpack(
29
  component: dict[str, Any],
30
  accumulator: dict[str, float],
 
120
  return [data]
121
 
122
 
123
+ def normalize_and_unpack_recipe_from_dict(data: dict[str, Any]) -> dict[str, Any]:
124
+ """In-memory version of normalize_and_unpack_recipe for a single recipe dict."""
125
+ flat_composition: dict[str, float] = defaultdict(float)
126
+
127
+ for comp in data.get("components", []):
128
+ _recursive_unpack(comp, flat_composition)
129
+
130
+ absolute_sum = sum(flat_composition.values())
131
+ if absolute_sum <= 0:
132
+ raise ValueError(f"Recipe {data.get('formula_id')} has zero total mass")
133
+
134
+ normalized_components = []
135
+ for cas in sorted(flat_composition.keys()):
136
+ weight_fraction = round(flat_composition[cas] / absolute_sum, 6)
137
+ normalized_components.append({"cas": cas, "weight_fraction": weight_fraction})
138
+
139
+ total_fraction = sum(c["weight_fraction"] for c in normalized_components)
140
+ if total_fraction != 1.0 and normalized_components:
141
+ normalized_components[0]["weight_fraction"] = round(
142
+ normalized_components[0]["weight_fraction"] + (1.0 - total_fraction), 6
143
+ )
144
+
145
+ return {
146
+ "formula_id": data.get("formula_id"),
147
+ "name": data.get("name"),
148
+ "source": data.get("source"),
149
+ "components": normalized_components,
150
+ }
151
+
152
+
153
+ def _build_registry_cas_sets(registry: AromaRegistry) -> tuple[set[str], set[str]]:
154
+ """Return (known_cas, unifac_valid_cas) from the registry."""
155
+ rows = registry._conn.execute(
156
+ "SELECT cas, name, unifac_groups FROM aroma_chemicals"
157
+ ).fetchall()
158
+ known_cas = {row[0] for row in rows}
159
+
160
+ unifac_valid_cas: set[str] = set()
161
+ for cas, name, groups_json in rows:
162
+ try:
163
+ groups = json.loads(groups_json or "{}")
164
+ except Exception:
165
+ groups = {}
166
+ valid, _ = validate_subgroups(groups)
167
+ if valid:
168
+ unifac_valid_cas.add(cas)
169
+
170
+ return known_cas, unifac_valid_cas
171
+
172
+
173
+ def _filter_and_rescale_components(
174
+ components: list[dict[str, Any]],
175
+ keep_cas: set[str],
176
+ formula_id: str | None,
177
+ ) -> list[dict[str, Any]]:
178
+ """Drop filtered components and rescale the remaining weight fractions to 1.0."""
179
+ if len(components) == len(keep_cas):
180
+ return components
181
+
182
+ filtered = [c for c in components if c["cas"] in keep_cas]
183
+ total = sum(c["weight_fraction"] for c in filtered)
184
+ if total <= 0:
185
+ logger.warning("Recipe %s has no valid components after filtering", formula_id)
186
+ return []
187
+
188
+ for c in filtered:
189
+ c["weight_fraction"] = round(c["weight_fraction"] / total, 6)
190
+
191
+ adj = sum(c["weight_fraction"] for c in filtered)
192
+ if filtered and adj != 1.0:
193
+ filtered[0]["weight_fraction"] = round(
194
+ filtered[0]["weight_fraction"] + (1.0 - adj), 6
195
+ )
196
+
197
+ return filtered
198
+
199
+
200
  def normalize_manifest(
201
  manifest_path: str | Path,
202
  registry_path: str | Path | None = None,
203
+ *,
204
+ strict_unifac: bool = True,
205
  ) -> list[dict[str, Any]]:
206
  """
207
  Normalize every recipe in a manifest and validate each CAS against the registry.
208
 
209
  Recipes that contain unknown CAS numbers are flagged but still returned so
210
  the caller can decide whether to drop, map, or back-fill them.
211
+
212
+ If strict_unifac is True, components whose stored UNIFAC subgroups are not
213
+ available in DOUFSG are rejected (ethanol, the canonical solvent, is always
214
+ allowed). Weight fractions are re-scaled after any filtering.
215
  """
216
  registry = AromaRegistry(registry_path)
217
+ known_cas, unifac_valid_cas = _build_registry_cas_sets(registry)
218
 
219
  results = []
220
  for raw_recipe in load_literature_manifest(manifest_path):
 
221
  tmp = dict(raw_recipe)
222
  normalized = normalize_and_unpack_recipe_from_dict(tmp)
223
+
224
  unknown = [c["cas"] for c in normalized["components"] if c["cas"] not in known_cas]
225
  if unknown:
226
  logger.warning(
 
232
  normalized["unknown_cas"] = unknown
233
  else:
234
  normalized["registry_status"] = "ok"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
+ if strict_unifac:
237
+ unifac_missing = [
238
+ c["cas"] for c in normalized["components"]
239
+ if c["cas"] not in unifac_valid_cas and c["cas"] != ETHANOL_CAS
240
+ ]
241
+ if unifac_missing:
242
+ logger.warning(
243
+ "Recipe %s contains components without valid DOUFSG subgroups: %s",
244
+ normalized["formula_id"],
245
+ unifac_missing,
246
+ )
247
+ normalized["unifac_status"] = "invalid_subgroups"
248
+ normalized["unifac_invalid_cas"] = unifac_missing
249
+ else:
250
+ normalized["unifac_status"] = "ok"
251
+ else:
252
+ normalized["unifac_status"] = "skipped"
253
+
254
+ # Build the set of components to keep after registry + UNIFAC filtering.
255
+ keep_cas = {
256
+ c["cas"] for c in normalized["components"]
257
+ if c["cas"] in known_cas
258
+ and (not strict_unifac or c["cas"] in unifac_valid_cas or c["cas"] == ETHANOL_CAS)
259
+ }
260
+
261
+ normalized["components"] = _filter_and_rescale_components(
262
+ normalized["components"],
263
+ keep_cas,
264
+ normalized["formula_id"],
265
  )
266
+ if not normalized["components"]:
267
+ normalized["registry_status"] = "no_valid_components"
268
 
269
+ results.append(normalized)
270
+ return results
 
 
 
 
271
 
272
 
273
  def recipe_to_formula_records(recipe: dict[str, Any]) -> list[dict[str, Any]]:
 
285
  parser.add_argument("manifest", help="Path to raw recipe JSON or JSON list")
286
  parser.add_argument("--registry", default="src/pino/registry.db", help="SQLite registry path")
287
  parser.add_argument("--output", help="Optional output JSON path")
288
+ parser.add_argument(
289
+ "--no-strict-unifac",
290
+ action="store_true",
291
+ help="Allow components with missing DOUFSG subgroups to pass validation",
292
+ )
293
  args = parser.parse_args()
294
 
295
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
296
 
297
+ results = normalize_manifest(
298
+ args.manifest,
299
+ registry_path=args.registry,
300
+ strict_unifac=not args.no_strict_unifac,
301
+ )
302
  out_text = json.dumps(results, indent=2, ensure_ascii=False)
303
  if args.output:
304
  Path(args.output).write_text(out_text, encoding="utf-8")