mattbitzesty commited on
Commit
5568c6a
·
unverified ·
1 Parent(s): 75c66ff

feat(data): deploy integrated empirical bootstrap generator

Browse files

- Pulls directly from AromaRegistry SQLite.
- Expands natural oils via expand_naturals_to_cas_ratios before VLE.
- Uses FragrancePipelineVerifier.run_sim for non-ideal evaporation.
- Precomputes objective_targets (49x138) and psychometric_targets (7,)
so the patched FragranceTrajectoryDataset reads them directly.

scripts/generate_empirical_bootstrap.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import random
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+
13
+ from pino.registry import AromaRegistry
14
+ from pino.semantics import compute_oav_targets, get_psychometric_targets
15
+ from pino.structures import IngredientResolver
16
+ from pino.thermo.naturals import NATURAL_PROFILES
17
+ from pino.verifier import FragrancePipelineVerifier
18
+
19
+ logger = logging.getLogger("pino.generate_empirical_bootstrap")
20
+
21
+
22
+ GENRES = [
23
+ "citrus_cologne",
24
+ "fougere",
25
+ "floral_woody",
26
+ "amber_oriental",
27
+ "wildcard",
28
+ ]
29
+
30
+ ETHANOL_CAS = "64-17-5"
31
+ DURATION_SECONDS = 28800.0
32
+ INTERVAL_SECONDS = 600.0
33
+ N_TIMESTEPS = 49
34
+
35
+
36
+ def _strip_natural_prefix(cas: str) -> str:
37
+ """Return a bare CAS, stripping any NATURAL: prefix."""
38
+ if cas.startswith("NATURAL:"):
39
+ return cas[len("NATURAL:") :]
40
+ return cas
41
+
42
+
43
+ def expand_naturals_to_cas_ratios(formula_list: list[dict[str, Any]]) -> dict[str, float]:
44
+ """
45
+ Expand natural complex substances (NCS) into their pure constituent chemicals.
46
+
47
+ Returns a mapping of bare CAS -> total weight fraction in the final expanded
48
+ formula, re-normalized to sum to 1.0.
49
+ """
50
+ expanded: dict[str, float] = {}
51
+ for item in formula_list:
52
+ cas = _strip_natural_prefix(item.get("cas", ""))
53
+ weight = float(item.get("weight_fraction", 0.0))
54
+ if weight <= 0:
55
+ continue
56
+
57
+ if cas in NATURAL_PROFILES:
58
+ profile = NATURAL_PROFILES[cas]
59
+ for const_cas, fraction in profile["constituents"].items():
60
+ expanded[const_cas] = expanded.get(const_cas, 0.0) + weight * fraction
61
+ else:
62
+ expanded[cas] = expanded.get(cas, 0.0) + weight
63
+
64
+ total = sum(expanded.values())
65
+ if total <= 0:
66
+ return {}
67
+ return {cas: wf / total for cas, wf in expanded.items()}
68
+
69
+
70
+ def _formula_fingerprint(formula_list: list[dict[str, Any]]) -> str:
71
+ """Deterministic structural fingerprint for a formula."""
72
+ sorted_items = sorted(formula_list, key=lambda x: x.get("cas", ""))
73
+ return "".join(f"{c.get('cas', '')}_{c.get('weight_fraction', 0):.4f}" for c in sorted_items)
74
+
75
+
76
+ def _build_record(
77
+ formula_id: str,
78
+ formula_list: list[dict[str, Any]],
79
+ trajectory: list[dict[str, Any]],
80
+ composition: list[dict[str, Any]],
81
+ strategy: str,
82
+ is_control: bool = False,
83
+ ) -> dict[str, Any]:
84
+ """Build a serializable empirical record with precomputed targets."""
85
+ n_steps = len(trajectory)
86
+ n_compounds = len(composition)
87
+
88
+ cas_order = [c["cas"] for c in composition]
89
+ concentrations = np.zeros((n_steps, n_compounds), dtype=np.float32)
90
+ for t_idx, step in enumerate(trajectory):
91
+ for c_idx, cas in enumerate(cas_order):
92
+ concentrations[t_idx, c_idx] = step.get("C_gas_mg_m3", {}).get(cas, 0.0)
93
+
94
+ objective_targets = compute_oav_targets(composition, concentrations)
95
+ psychometric_targets = get_psychometric_targets(strategy)
96
+
97
+ return {
98
+ "formula_id": formula_id,
99
+ "is_control": is_control,
100
+ "genre": strategy,
101
+ "metadata": {
102
+ "generation_strategy": strategy,
103
+ "formula_id": formula_id,
104
+ },
105
+ "formula": formula_list,
106
+ "trajectory": trajectory,
107
+ "objective_targets": objective_targets.tolist(),
108
+ "psychometric_targets": psychometric_targets.tolist(),
109
+ }
110
+
111
+
112
+ def _control_records(registry: AromaRegistry) -> list[dict[str, Any]]:
113
+ """Generate the 597 pure single-molecule control records."""
114
+ verifier = FragrancePipelineVerifier()
115
+ resolver = IngredientResolver(registry)
116
+ records: list[dict[str, Any]] = []
117
+
118
+ for row in registry.all_records().values():
119
+ cas = row["cas"]
120
+ name = row.get("name", cas)
121
+ smiles = row.get("smiles", "")
122
+ if not smiles:
123
+ logger.warning("Skipping control %s: no SMILES", cas)
124
+ continue
125
+
126
+ formula_list = [{"cas": cas, "name": name, "smiles": smiles, "weight_fraction": 1.0}]
127
+ try:
128
+ result = verifier.run_sim(
129
+ formula_list,
130
+ duration_seconds=DURATION_SECONDS,
131
+ interval_seconds=INTERVAL_SECONDS,
132
+ )
133
+ except Exception as exc:
134
+ logger.warning("Control simulation failed for %s: %s", cas, exc)
135
+ continue
136
+
137
+ if result.get("status") not in ("passed", "depleted"):
138
+ logger.warning("Control simulation rejected for %s: %s", cas, result.get("message"))
139
+ continue
140
+
141
+ trajectory = result.get("trajectory", [])
142
+ if not trajectory:
143
+ continue
144
+
145
+ composition = [{"cas": cas, "smiles": smiles}]
146
+ record = _build_record(
147
+ formula_id=f"CONTROL_{cas}",
148
+ formula_list=formula_list,
149
+ trajectory=trajectory,
150
+ composition=composition,
151
+ strategy="wildcard",
152
+ is_control=True,
153
+ )
154
+ records.append(record)
155
+
156
+ return records
157
+
158
+
159
+ def _mixture_records(
160
+ registry: AromaRegistry,
161
+ num_formulas: int = 5000,
162
+ seed: int = 2026,
163
+ ) -> list[dict[str, Any]]:
164
+ """Generate non-ideal multi-component mixture records."""
165
+ random.seed(seed)
166
+ np.random.seed(seed)
167
+
168
+ verifier = FragrancePipelineVerifier()
169
+ resolver = IngredientResolver(registry)
170
+
171
+ valid_cas = [
172
+ row["cas"]
173
+ for row in registry.all_records().values()
174
+ if row.get("smiles") and row.get("unifac_groups")
175
+ ]
176
+ if not valid_cas:
177
+ raise RuntimeError("No valid chemicals with UNIFAC groups found in registry")
178
+
179
+ records: list[dict[str, Any]] = []
180
+ attempts = 0
181
+ max_attempts = num_formulas * 5
182
+
183
+ while len(records) < num_formulas and attempts < max_attempts:
184
+ attempts += 1
185
+ n_components = random.randint(3, 10)
186
+ chosen_cas = random.sample(valid_cas, n_components)
187
+ raw_weights = np.random.dirichlet(np.ones(n_components))
188
+
189
+ formula_list = []
190
+ for cas, weight in zip(chosen_cas, raw_weights):
191
+ formula_list.append({"cas": cas, "weight_fraction": float(weight)})
192
+
193
+ # Expand any natural oils before simulation.
194
+ expanded_ratios = expand_naturals_to_cas_ratios(formula_list)
195
+ if not expanded_ratios:
196
+ continue
197
+
198
+ expanded_formula = [
199
+ {"cas": cas, "weight_fraction": wf}
200
+ for cas, wf in expanded_ratios.items()
201
+ ]
202
+
203
+ try:
204
+ result = verifier.run_sim(
205
+ expanded_formula,
206
+ duration_seconds=DURATION_SECONDS,
207
+ interval_seconds=INTERVAL_SECONDS,
208
+ )
209
+ except Exception as exc:
210
+ logger.debug("Mixture simulation failed: %s", exc)
211
+ continue
212
+
213
+ if result.get("status") not in ("passed", "depleted"):
214
+ logger.debug("Mixture rejected: %s", result.get("message"))
215
+ continue
216
+
217
+ trajectory = result.get("trajectory", [])
218
+ if not trajectory:
219
+ continue
220
+
221
+ fingerprint = _formula_fingerprint(formula_list)
222
+ formula_hash = hashlib.sha256(fingerprint.encode("utf-8")).hexdigest()[:16]
223
+ strategy = random.choice(GENRES)
224
+
225
+ composition = [{"cas": cas} for cas in expanded_ratios.keys()]
226
+ record = _build_record(
227
+ formula_id=f"EMPIRICAL_{formula_hash}",
228
+ formula_list=formula_list,
229
+ trajectory=trajectory,
230
+ composition=composition,
231
+ strategy=strategy,
232
+ is_control=False,
233
+ )
234
+ records.append(record)
235
+
236
+ if len(records) % 100 == 0:
237
+ logger.info("Generated %d/%d empirical mixtures", len(records), num_formulas)
238
+
239
+ return records
240
+
241
+
242
+ def generate_empirical_bootstrap(
243
+ output_path: str,
244
+ num_formulas: int = 5000,
245
+ seed: int = 2026,
246
+ ) -> dict[str, Any]:
247
+ """Build the full 5,597-row empirical bootstrap dataset."""
248
+ registry = AromaRegistry()
249
+ logger.info("Loaded registry with %d rows", len(registry.all_records()))
250
+
251
+ logger.info("Generating pure single-molecule controls...")
252
+ controls = _control_records(registry)
253
+ logger.info("Generated %d control records", len(controls))
254
+
255
+ logger.info("Generating %d empirical mixtures...", num_formulas)
256
+ mixtures = _mixture_records(registry, num_formulas=num_formulas, seed=seed)
257
+ logger.info("Generated %d empirical mixture records", len(mixtures))
258
+
259
+ output_path_obj = Path(output_path)
260
+ output_path_obj.parent.mkdir(parents=True, exist_ok=True)
261
+ with output_path_obj.open("w") as f:
262
+ for record in controls + mixtures:
263
+ f.write(json.dumps(record) + "\n")
264
+
265
+ logger.info("Wrote %d total records to %s", len(controls) + len(mixtures), output_path_obj)
266
+ return {
267
+ "output_path": str(output_path_obj),
268
+ "controls": len(controls),
269
+ "mixtures": len(mixtures),
270
+ "total": len(controls) + len(mixtures),
271
+ }
272
+
273
+
274
+ if __name__ == "__main__":
275
+ parser = argparse.ArgumentParser(description="Generate PINO empirical bootstrap dataset")
276
+ parser.add_argument("--output", default="data/empirical_dataset_v1.jsonl")
277
+ parser.add_argument("--num-formulas", type=int, default=5000)
278
+ parser.add_argument("--seed", type=int, default=2026)
279
+ parser.add_argument("--log-level", default="INFO")
280
+ args = parser.parse_args()
281
+
282
+ logging.basicConfig(
283
+ level=getattr(logging, args.log_level.upper(), logging.INFO),
284
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
285
+ )
286
+ card = generate_empirical_bootstrap(
287
+ output_path=args.output,
288
+ num_formulas=args.num_formulas,
289
+ seed=args.seed,
290
+ )
291
+ print(json.dumps(card, indent=2))