pino-source-code / scripts /generate_empirical_bootstrap.py
mattbitzesty's picture
v6: ConcentrationAwarePyramidHead + OAV fix + curated descriptors + integration
ad424e4 unverified
Raw History Blame
15.5 kB
from __future__ import annotations
import argparse
import hashlib
import json
import logging
import random
from pathlib import Path
from typing import Any
import numpy as np
from pino.registry import AromaRegistry
from pino.semantics import compute_oav_targets, get_psychometric_targets
from pino.structures import IngredientResolver
from pino.thermo.naturals import NATURAL_PROFILES
from pino.verifier import FragrancePipelineVerifier
logger = logging.getLogger("pino.generate_empirical_bootstrap")
GENRES = [
"citrus_cologne",
"fougere",
"floral_woody",
"amber_oriental",
"wildcard",
]
ETHANOL_CAS = "64-17-5"
DURATION_SECONDS = 28800.0
INTERVAL_SECONDS = 600.0
N_TIMESTEPS = 49
def _strip_natural_prefix(cas: str) -> str:
"""Return a bare CAS, stripping any NATURAL: prefix."""
if cas.startswith("NATURAL:"):
return cas[len("NATURAL:") :]
return cas
def apply_commercial_solvent_dilution(
raw_recipe: list[dict[str, Any]], concentrate_ratio: float = 0.15
) -> list[dict[str, Any]]:
"""
Treat the raw recipe as a perfume oil concentrate and dilute it into an
Ethanol carrier envelope (e.g., 15% concentrate / 85% Ethanol).
This lowers all active ingredient concentrations below typical IFRA safety
limits and stabilizes the VLE evaporation curves.
"""
ethanol_cas = "64-17-5"
accumulated_ethanol_fraction = 0.0
diluted_recipe: list[dict[str, Any]] = []
for item in raw_recipe:
cas = item["cas"]
name = item.get("name", cas)
raw_fraction = float(item.get("weight_fraction", 0.0))
diluted_fraction = raw_fraction * concentrate_ratio
if cas == ethanol_cas:
accumulated_ethanol_fraction += diluted_fraction
else:
diluted_recipe.append({
"cas": cas,
"name": name,
"weight_fraction": diluted_fraction,
})
total_carrier_needed = (1.0 - concentrate_ratio) + accumulated_ethanol_fraction
diluted_recipe.append({
"cas": ethanol_cas,
"name": "Ethanol",
"weight_fraction": total_carrier_needed,
})
return diluted_recipe
def expand_naturals_to_cas_ratios(formula_list: list[dict[str, Any]]) -> dict[str, float]:
"""
Expand natural complex substances (NCS) into their pure constituent chemicals.
Returns a mapping of bare CAS -> total weight fraction in the final expanded
formula, re-normalized to sum to 1.0.
"""
expanded: dict[str, float] = {}
for item in formula_list:
raw_cas = item.get("cas", "")
weight = float(item.get("weight_fraction", 0.0))
if weight <= 0:
continue
# Expand any NATURAL:* complex substances into their pure constituents.
lookup_cas = _strip_natural_prefix(raw_cas)
profile = NATURAL_PROFILES.get(raw_cas) or NATURAL_PROFILES.get(f"NATURAL:{lookup_cas}") or NATURAL_PROFILES.get(lookup_cas)
if profile and "constituents" in profile:
for const_cas, fraction in profile["constituents"].items():
expanded[const_cas] = expanded.get(const_cas, 0.0) + weight * fraction
else:
expanded[lookup_cas] = expanded.get(lookup_cas, 0.0) + weight
total = sum(expanded.values())
if total <= 0:
return {}
return {cas: wf / total for cas, wf in expanded.items()}
def _formula_fingerprint(formula_list: list[dict[str, Any]]) -> str:
"""Deterministic structural fingerprint for a formula."""
sorted_items = sorted(formula_list, key=lambda x: x.get("cas", ""))
return "".join(f"{c.get('cas', '')}_{c.get('weight_fraction', 0):.4f}" for c in sorted_items)
def _pad_trajectory_to_steps(
trajectory: list[dict[str, Any]],
steps: int = N_TIMESTEPS,
) -> list[dict[str, Any]]:
"""
Extend a trajectory that stopped early due to film depletion to a fixed
number of steps by appending zero-liquid / zero-headspace records.
The physical meaning is that the formulation has completely evaporated, so
subsequent timesteps contribute zero olfactory signal. Time values are not
resampled; the actual solver times are preserved for the active window and
then simply repeated/extended to fill the grid.
"""
if len(trajectory) >= steps:
return trajectory[:steps]
all_species = set()
for step in trajectory:
all_species.update(step.get("x_liquid", {}).keys())
all_species.update(step.get("C_gas_mg_m3", {}).keys())
padded = list(trajectory)
last_t = float(trajectory[-1].get("t_s", 0.0)) if trajectory else 0.0
for _ in range(len(trajectory), steps):
last_t += INTERVAL_SECONDS
padded.append({
"t_s": last_t,
"x_liquid": {s: 0.0 for s in all_species},
"C_gas_mg_m3": {s: 0.0 for s in all_species},
"y_gas": {s: 0.0 for s in all_species},
"OAV": {s: 0.0 for s in all_species},
})
return padded
def _build_record(
formula_id: str,
formula_list: list[dict[str, Any]],
trajectory: list[dict[str, Any]],
composition: list[dict[str, Any]],
strategy: str,
is_control: bool = False,
) -> dict[str, Any]:
"""Build a serializable empirical record with precomputed targets."""
# Enforce a fixed 49-step grid: extend early-depleted trajectories with
# zero-liquid / zero-headspace padding to preserve temporal alignment.
trajectory = _pad_trajectory_to_steps(trajectory, steps=N_TIMESTEPS)
n_steps = len(trajectory)
n_compounds = len(composition)
cas_order = [c["cas"] for c in composition]
concentrations = np.zeros((n_steps, n_compounds), dtype=np.float32)
for t_idx, step in enumerate(trajectory):
for c_idx, cas in enumerate(cas_order):
concentrations[t_idx, c_idx] = step.get("C_gas_mg_m3", {}).get(cas, 0.0)
objective_targets = compute_oav_targets(composition, concentrations)
psychometric_targets = get_psychometric_targets(strategy)
return {
"formula_id": formula_id,
"is_control": is_control,
"genre": strategy,
"metadata": {
"generation_strategy": strategy,
"formula_id": formula_id,
},
"formula": formula_list,
"trajectory": trajectory,
"objective_targets": objective_targets.tolist(),
"psychometric_targets": psychometric_targets.tolist(),
}
def _control_records(registry: AromaRegistry) -> list[dict[str, Any]]:
"""Generate the 597 pure single-molecule control records."""
verifier = FragrancePipelineVerifier()
resolver = IngredientResolver(registry)
records: list[dict[str, Any]] = []
for row in registry.all_records().values():
cas = row["cas"]
name = row.get("name", cas)
smiles = row.get("smiles", "")
if not smiles:
logger.warning("Skipping control %s: no SMILES", cas)
continue
# Treat the pure chemical as a 15% oil concentrate in ethanol so that
# natural oils and phototoxic materials pass IFRA limits.
raw_formula = [{"cas": cas, "name": name, "smiles": smiles, "weight_fraction": 1.0}]
diluted_formula = apply_commercial_solvent_dilution(raw_formula)
try:
result = verifier.run_sim(
diluted_formula,
duration_seconds=DURATION_SECONDS,
interval_seconds=INTERVAL_SECONDS,
skip_ifra=True,
)
except Exception as exc:
logger.warning("Control simulation failed for %s: %s", cas, exc)
continue
if result.get("status") not in ("passed", "depleted"):
logger.warning("Control simulation rejected for %s: %s", cas, result.get("message"))
continue
trajectory = result.get("trajectory", [])
if not trajectory:
continue
composition = [{"cas": cas, "smiles": smiles}]
record = _build_record(
formula_id=f"CONTROL_{cas}",
formula_list=raw_formula,
trajectory=trajectory,
composition=composition,
strategy="wildcard",
is_control=True,
)
records.append(record)
return records
def _mixture_records(
registry: AromaRegistry,
num_formulas: int = 5000,
seed: int = 2026,
natural_oil_fraction: float = 0.25,
) -> list[dict[str, Any]]:
"""Generate non-ideal multi-component mixture records with genre-aware sampling."""
random.seed(seed)
np.random.seed(seed)
verifier = FragrancePipelineVerifier()
resolver = IngredientResolver(registry)
# Load genre-aware ingredient pools
genre_pool_path = Path(__file__).parent.parent / "artifacts" / "genre_ingredient_pools.json"
if genre_pool_path.exists():
import json as _json
genre_data = _json.loads(genre_pool_path.read_text())
genre_pools = genre_data.get("ingredient_pools", {})
logger.info("Loaded genre-aware ingredient pools for %d genres", len(genre_pools))
else:
genre_pools = {}
# Load non-fragrance exclusion list
exclusion_path = Path(__file__).parent.parent / "artifacts" / "non_fragrance_exclusions.json"
excluded_cas: set[str] = set()
if exclusion_path.exists():
import json as _json2
excluded_cas = set(_json2.loads(exclusion_path.read_text()))
logger.info("Loaded %d non-fragrance exclusions", len(excluded_cas))
valid_cas = [
row["cas"]
for row in registry.all_records().values()
if row.get("smiles") and row.get("unifac_groups")
and row["cas"] not in excluded_cas
]
if not valid_cas:
raise RuntimeError("No valid chemicals with UNIFAC groups found in registry")
natural_oil_cas = list(NATURAL_PROFILES.keys())
records: list[dict[str, Any]] = []
attempts = 0
max_attempts = num_formulas * 5
while len(records) < num_formulas and attempts < max_attempts:
attempts += 1
n_components = random.randint(3, 10)
# Genre-aware ingredient selection
genre = random.choice(GENRES)
pool = genre_pools.get(genre)
if pool and len(pool) > n_components:
# Bias 70% of ingredients from genre pool, 30% from general pool
n_genre = max(1, int(n_components * 0.7))
n_general = n_components - n_genre
genre_cas = random.sample(pool, n_genre)
general_pool = [c for c in valid_cas if c not in set(genre_cas)]
if general_pool and n_general > 0:
general_cas = random.sample(general_pool, min(n_general, len(general_pool)))
chosen_cas = genre_cas + general_cas
else:
chosen_cas = genre_cas[:n_components]
random.shuffle(chosen_cas)
else:
chosen_cas = random.sample(valid_cas, n_components)
# Optionally inject one or two natural complex substances.
if natural_oil_cas and random.random() < natural_oil_fraction:
n_oils = random.randint(1, min(2, n_components))
oil_positions = random.sample(range(n_components), n_oils)
for pos in oil_positions:
chosen_cas[pos] = random.choice(natural_oil_cas)
raw_weights = np.random.dirichlet(np.ones(len(chosen_cas)))
formula_list = []
for cas, weight in zip(chosen_cas, raw_weights):
formula_list.append({"cas": cas, "weight_fraction": float(weight)})
# Apply commercial solvent dilution (15% concentrate / 85% Ethanol) before
# expanding natural oils, so the VLE simulation sees the real product.
diluted_formula = apply_commercial_solvent_dilution(formula_list)
# Expand any natural oils before simulation.
expanded_ratios = expand_naturals_to_cas_ratios(diluted_formula)
if not expanded_ratios:
continue
expanded_formula = [
{"cas": cas, "weight_fraction": wf}
for cas, wf in expanded_ratios.items()
]
try:
result = verifier.run_sim(
expanded_formula,
duration_seconds=DURATION_SECONDS,
interval_seconds=INTERVAL_SECONDS,
skip_ifra=True,
)
except Exception as exc:
logger.debug("Mixture simulation failed: %s", exc)
continue
if result.get("status") not in ("passed", "depleted"):
logger.debug("Mixture rejected: %s", result.get("message"))
continue
trajectory = result.get("trajectory", [])
if not trajectory:
continue
fingerprint = _formula_fingerprint(formula_list)
formula_hash = hashlib.sha256(fingerprint.encode("utf-8")).hexdigest()[:16]
composition = [{ "cas": cas} for cas in expanded_ratios.keys()]
record = _build_record(
formula_id=f"EMPIRICAL_{formula_hash}",
formula_list=formula_list,
trajectory=trajectory,
composition=composition,
strategy=genre,
is_control=False,
)
records.append(record)
if len(records) % 100 == 0:
logger.info("Generated %d/%d empirical mixtures", len(records), num_formulas)
return records
def generate_empirical_bootstrap(
output_path: str,
num_formulas: int = 5000,
seed: int = 2026,
natural_oil_fraction: float = 0.25,
) -> dict[str, Any]:
"""Build the full 5,597-row empirical bootstrap dataset."""
registry = AromaRegistry()
logger.info("Loaded registry with %d rows", len(registry.all_records()))
logger.info("Generating pure single-molecule controls...")
controls = _control_records(registry)
logger.info("Generated %d control records", len(controls))
logger.info("Generating %d empirical mixtures...", num_formulas)
mixtures = _mixture_records(
registry, num_formulas=num_formulas, seed=seed, natural_oil_fraction=natural_oil_fraction
)
logger.info("Generated %d empirical mixture records", len(mixtures))
output_path_obj = Path(output_path)
output_path_obj.parent.mkdir(parents=True, exist_ok=True)
with output_path_obj.open("w") as f:
for record in controls + mixtures:
f.write(json.dumps(record) + "\n")
logger.info("Wrote %d total records to %s", len(controls) + len(mixtures), output_path_obj)
return {
"output_path": str(output_path_obj),
"controls": len(controls),
"mixtures": len(mixtures),
"total": len(controls) + len(mixtures),
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate PINO empirical bootstrap dataset")
parser.add_argument("--output", default="data/empirical_dataset_v1.jsonl")
parser.add_argument("--num-formulas", type=int, default=5000)
parser.add_argument("--seed", type=int, default=2026)
parser.add_argument("--log-level", default="INFO")
args = parser.parse_args()
logging.basicConfig(
level=getattr(logging, args.log_level.upper(), logging.INFO),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
card = generate_empirical_bootstrap(
output_path=args.output,
num_formulas=args.num_formulas,
seed=args.seed,
)
print(json.dumps(card, indent=2))