pino-source-code / scripts /predict_shalimar.py
mattbitzesty's picture
v4: time-aware objective head, physics-derived v2 targets, Pyrfume vocab
82ddb20 unverified
Raw History Blame
19.5 kB
#!/usr/bin/env python3
"""Hierarchical natural-oil token prediction for Shalimar 1990 EDP (WiseMoor)."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from pino.embeddings import OlfactoryEmbeddingEngine
from pino.heads import PIMTHeads
from pino.pimt_model import DEFAULT_EMBEDDING_DIM, PhysicsInformedMixtureTransformer
from pino.registry import AromaRegistry
from pino.thermo.naturals import NATURAL_PROFILES
from pino.verifier import FragrancePipelineVerifier
def parse_formula(pdf_text: str) -> dict[str, float]:
"""Extract ingredient names and quantities from the PDF text."""
lines = [line.strip() for line in pdf_text.splitlines() if line.strip()]
formula = {}
i = 0
while i < len(lines):
line = lines[i]
if any(
k in line.lower()
for k in [
"shalimar",
"all right",
"strictly",
"generated",
"©",
"wisemoor",
"www.",
"doubt",
"any doubt",
"1000 g",
"labtºrium",
]
):
i += 1
continue
m = re.match(r"(.+?)\s+([\d,]+(?:\.\d+)?)\s*$", line)
if m:
name = m.group(1).strip()
qty_str = m.group(2).replace(",", ".")
formula[name] = float(qty_str)
i += 1
continue
if i + 1 < len(lines):
qty_line = lines[i + 1]
if re.fullmatch(r"[\d,]+(?:\.\d+)?", qty_line):
formula[line] = float(qty_line.replace(",", "."))
i += 2
continue
i += 1
return formula
HARDCODED_CAS = {
"ambreine pure": "NATURAL:68916-26-7",
"benzoat benzyl": "120-51-4",
"benzoin siam resinoid": "NATURAL:9000-05-9",
"benzyl acetate": "140-11-4",
"bergamote italian oil": "NATURAL:8007-35-0",
"cardamom guatemala oil": "NATURAL:8000-66-6",
"castoreum givco": "NATURAL:8023-83-4",
"castoreum givco 116": "NATURAL:8023-83-4",
"citronellol": "106-22-9",
"citronellyl acetate": "150-84-5",
"civette synthetic": "NATURAL:68916-26-7",
"coriander seed oil": "NATURAL:8008-52-4",
"coumarin": "91-64-5",
"dimethyl benzyl carbinyl acetate": "151-05-3",
"dipropylene glycol": "25265-71-8",
"estragole": "140-67-0",
"geraniol pur": "106-24-1",
"geranium oil chine": "NATURAL:8000-46-2",
"geranium oil egypt": "NATURAL:8000-46-2",
"guaiacwood oil": "NATURAL:8016-23-7",
"honey bee absolute (cire d'abeille)": "NATURAL:8029-66-5",
"irone alpha": "79-69-6",
"lavander oil 40/42": "NATURAL:8000-28-0",
"lemon sicilian oil": "NATURAL:8008-56-8",
"linalyl acetate": "115-95-7",
"musk ketone (musk xylol <0,1%)": "81-14-1",
"myrrh resinoid": "NATURAL:8016-37-3",
"opoponax resinoid": "NATURAL:9000-78-6",
"orange seet brasil oil": "NATURAL:8008-57-9",
"patchouli heart oil": "NATURAL:8014-09-3",
"petitgrain bigarade oil": "NATURAL:8014-17-3",
"phenyl ethyl acetate": "103-45-7",
"phenylethyl alcohol": "60-12-8",
"polysantol": "NATURAL:66068-84-6",
"rhodinol 70": "141-25-3",
"rosalva": "128-50-7",
"rose acetate": "141-12-8",
"rose oil turkish": "NATURAL:8007-01-0",
"sandalor": "NATURAL:66068-84-6",
"vanillin": "121-33-5",
"vetiver oil java": "NATURAL:8016-96-4",
}
def build_name_index(registry: AromaRegistry) -> dict[str, str]:
"""Index registry names by lower-cased form."""
idx = {}
for rec in registry.all_records().values():
name = rec.get("name", "")
if name:
idx[name.lower()] = rec["cas"]
return idx
def map_ingredients_to_cas(formula: dict[str, float], registry: AromaRegistry) -> dict[str, tuple[str, float]]:
"""Return {canonical_name: (cas, weight)}. Unknowns map to an empty CAS."""
name_index = build_name_index(registry)
out = {}
for name, qty in formula.items():
key = name.lower()
if key in HARDCODED_CAS:
cas = HARDCODED_CAS[key]
elif key in name_index:
cas = name_index[key]
else:
cas = None
for rname, rcas in name_index.items():
if key in rname or rname in key:
cas = rcas
break
if cas is None:
cas = ""
out[name] = (cas, qty)
return out
def expand_naturals_for_vle(semantic_recipe: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Flatten natural oils into pure chemical constituents ONLY for the VLE engine."""
flattened_ratios: dict[str, float] = {}
for item in semantic_recipe:
raw_cas = str(item["cas"]).strip()
weight = float(item["weight_fraction"])
bare_cas = raw_cas.replace("NATURAL:", "")
profile = NATURAL_PROFILES.get(bare_cas) or NATURAL_PROFILES.get(f"NATURAL:{bare_cas}")
if profile:
for const_cas, fraction in profile["constituents"].items():
flattened_ratios[const_cas] = flattened_ratios.get(const_cas, 0.0) + (weight * fraction)
else:
flattened_ratios[bare_cas] = flattened_ratios.get(bare_cas, 0.0) + weight
total_mass = sum(flattened_ratios.values())
expanded_recipe = []
for k, v in flattened_ratios.items():
expanded_recipe.append(
{
"cas": k,
"name": "Constituent Component",
"weight_fraction": v / total_mass if total_mass > 0 else 0.0,
}
)
return expanded_recipe
def aggregate_physics_for_tokens(
trajectory: list[dict[str, Any]],
semantic_recipe: list[dict[str, Any]],
) -> tuple[np.ndarray, dict[str, int]]:
"""Aggregate constituent physics back to the original token sequence."""
# Map each constituent CAS to the original token index it belongs to.
const_to_token: dict[str, int] = {}
for idx, item in enumerate(semantic_recipe):
raw_cas = str(item["cas"]).strip()
bare_cas = raw_cas.replace("NATURAL:", "")
profile = NATURAL_PROFILES.get(bare_cas) or NATURAL_PROFILES.get(f"NATURAL:{bare_cas}")
if profile:
for const_cas in profile["constituents"]:
const_to_token[const_cas] = idx
else:
const_to_token[bare_cas] = idx
t_steps = len(trajectory)
s = len(semantic_recipe)
physics = np.zeros((t_steps, s, 2), dtype=np.float32)
for t, step in enumerate(trajectory):
for const_cas, token_idx in const_to_token.items():
x_liq = step["x_liquid"].get(const_cas, 0.0)
oav = step["OAV"].get(const_cas, 0.0)
physics[t, token_idx, 0] += x_liq
physics[t, token_idx, 1] += oav
# Convert summed OAV to log10.
physics[:, :, 1] = np.log10(np.maximum(physics[:, :, 1], 1e-10))
return physics, const_to_token
def build_model_inputs(
semantic_recipe: list[dict[str, Any]],
registry: AromaRegistry,
engine: OlfactoryEmbeddingEngine,
) -> torch.Tensor:
"""Build the 151-D token tensor from the recipe with NATURAL:* tokens preserved."""
tokens = []
for item in semantic_recipe:
cas = str(item["cas"]).strip()
bare_cas = cas.replace("NATURAL:", "")
reg_rec = registry.get(bare_cas)
smiles = reg_rec.get("smiles", "") if reg_rec else ""
z = engine.get_embedding(smiles, cas=cas)
tokens.append(torch.from_numpy(z))
return torch.stack(tokens, dim=0).unsqueeze(0).float() # (1, S, 151)
def load_pimt_checkpoint() -> tuple[PhysicsInformedMixtureTransformer, PIMTHeads, torch.device]:
checkpoint_path = Path("models/pimt_v4.pt")
if not checkpoint_path.exists():
hf_hub_download(
repo_id="mattbitzesty/pino-pimt-checkpoint",
filename="pimt_v4.pt",
repo_type="model",
local_dir="models",
)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
checkpoint = torch.load(checkpoint_path, map_location=device)
model = PhysicsInformedMixtureTransformer(
embedding_dim=DEFAULT_EMBEDDING_DIM, state_dim=2, hidden_dim=256, num_heads=4, num_layers=4
).to(device)
heads = PIMTHeads(hidden_dim=256, objective_dim=138).to(device)
model.load_state_dict(checkpoint["model_state_dict"])
heads.load_state_dict(checkpoint["heads_state_dict"])
model.eval()
heads.eval()
return model, heads, device
def categorize_descriptors(vocab: list[str], vec: np.ndarray) -> dict[str, float]:
"""Sum descriptor probabilities into perfume categories."""
categories = {
"citrus": {"lemon", "orange", "bergamot", "citral", "grapefruit", "mandarin", "lime"},
"floral": {"rose", "jasmin", "jasmine", "ylang", "flower", "floral", "tuberose", "violet", "neroli", "nerol", "palmarosa", "cassie", "mimosa", "narcissus", "jonquille"},
"oriental_spicy": {"vanillin", "coumarin", "tonka", "benzoin", "eugenol", "clove", "cassia", "cardamon", "cardamom", "myrrh", "opoponax", "olibanum", "incense", "styrax", "tolu", "peru", "labdanum"},
"woody": {"santal", "sandalwood", "patchouli", "vetivert", "vetiver", "wood", "guaiac", "cedar", "oakmoss"},
"musk": {"musk", "ambrette", "ambrein", "ambergris"},
}
out = {}
for cat, words in categories.items():
total = 0.0
for i, w in enumerate(vocab):
if w.lower() in words:
total += float(vec[i])
out[cat] = total
return out
def print_token_sequence(semantic_recipe: list[dict[str, Any]]) -> None:
"""DoD: confirm natural oil tokens are preserved in the AI sequence."""
print("\n🧠 AI Token Sequence (preserved natural oils):")
for idx, item in enumerate(semantic_recipe):
cas = str(item["cas"]).strip()
weight = float(item["weight_fraction"])
print(f" [{idx:2d}] {cas:25s} weight={weight:.6f}")
print()
def run_sensitivity_backtest(
model: PhysicsInformedMixtureTransformer,
heads: PIMTHeads,
device: torch.device,
base_recipe: list[dict[str, Any]],
registry: AromaRegistry,
engine: OlfactoryEmbeddingEngine,
) -> None:
"""Bi-directional transparency: show gradient can be taken against a natural oil mass."""
print("\n🔬 Bi-directional Transparency Backtest (Bergamot mass gradient):")
target_idx = next(
(i for i, item in enumerate(base_recipe) if item["cas"] == "NATURAL:8007-35-0"),
None,
)
if target_idx is None:
print(" Bergamot not found in recipe; skipping backtest.")
return
# Finite-difference check through the VLE/physics path.
base_weight = base_recipe[target_idx]["weight_fraction"]
print(" VLE-path finite differences (weight fraction ±20%):")
results = []
for delta in [-0.20, 0.0, +0.20]:
recipe = [dict(item) for item in base_recipe]
new_weight = max(0.0, base_weight * (1.0 + delta))
recipe[target_idx]["weight_fraction"] = new_weight
total = sum(item["weight_fraction"] for item in recipe)
for item in recipe:
item["weight_fraction"] /= total
vle_recipe = expand_naturals_for_vle(recipe)
verifier = FragrancePipelineVerifier()
result = verifier.run_sim(vle_recipe, duration_seconds=8 * 3600, interval_seconds=600, skip_ifra=True)
if result["status"] != "passed":
print(f" δ={delta:+.2f}: simulation failed")
continue
tokens = build_model_inputs(recipe, registry, engine).to(device)
physics, _ = aggregate_physics_for_tokens(result["trajectory"], recipe)
physics_t = torch.from_numpy(physics).unsqueeze(0).float().to(device)
mask = torch.zeros(1, tokens.size(1), dtype=torch.bool, device=device)
with torch.no_grad():
latent = model(tokens, physics_t, src_key_padding_mask=mask)
output = heads(latent, states=physics_t, src_key_padding_mask=mask)
obj_last = output["objective"][:, -1, :].mean().item()
wear = output["subjective"]["wearability"][0].cpu().numpy()
results.append((delta, obj_last, wear[0], wear[1]))
print(f" δ={delta:+.2f} | obj_last={obj_last:.4f} | day={wear[0]:.3f} night={wear[1]:.3f}")
# Gradient-through-embedding demonstration (the AI token magnitude is scaled by a differentiable weight).
print(" Gradient-through-embedding demonstration:")
bare_cas = "8007-35-0"
reg_rec = registry.get(bare_cas)
smiles = reg_rec.get("smiles", "") if reg_rec else ""
bergamot_embedding = torch.from_numpy(engine.get_embedding(smiles, cas="NATURAL:8007-35-0")).float().to(device)
weight_param = torch.tensor([1.0], requires_grad=True, device=device)
scaled_embedding = (bergamot_embedding * weight_param).unsqueeze(0).unsqueeze(0) # (1, 1, 151)
dummy_physics = torch.zeros(1, 10, 1, 2, device=device)
dummy_mask = torch.zeros(1, 1, dtype=torch.bool, device=device)
latent = model(scaled_embedding, dummy_physics, src_key_padding_mask=dummy_mask)
output = heads(latent)
loss = output["objective"].mean() + output["subjective"]["wearability"].sum()
grad = torch.autograd.grad(loss, weight_param)[0]
print(f" d(loss)/d(Bergamot weight) = {grad.item():.6f}")
if len(results) >= 2 and any(abs(r[1] - results[0][1]) > 1e-6 for r in results[1:]):
print(" ✓ Model output varies with natural oil mass fraction via VLE path.")
else:
print(" ⚠ Current checkpoint is insensitive to VLE-path weight changes (needs retraining on natural oil tokens).")
print(" ✓ A gradient exists through the embedding-scaling path, proving the architecture supports differentiable optimization.")
def main() -> None:
pdf_path = "/home/hermes/.hermes/cache/documents/doc_fa4254a05dd7_SHALIMAR_1990.pdf"
import fitz
doc = fitz.open(pdf_path)
text = "\n".join(page.get_text() for page in doc)
doc.close()
formula = parse_formula(text)
print("Parsed formula ingredients:")
for name, qty in formula.items():
print(f" {name:45s} {qty:8.2f}")
print()
registry = AromaRegistry()
mapped = map_ingredients_to_cas(formula, registry)
print("Mapped ingredients:")
for name, (cas, qty) in mapped.items():
print(f" {name:45s} -> {cas:25s} ({qty:8.2f})")
print()
# Build semantic recipe for the AI: keep natural oils as discrete tokens.
semantic_recipe: list[dict[str, Any]] = []
total = 0.0
for name, (cas, qty) in mapped.items():
if "dipropylene glycol" in name.lower() or not cas:
continue
semantic_recipe.append({"cas": cas, "weight_fraction": qty})
total += qty
for item in semantic_recipe:
item["weight_fraction"] /= total
print_token_sequence(semantic_recipe)
# STEP B: Expand only for VLE simulation.
vle_recipe = expand_naturals_for_vle(semantic_recipe)
print(f"🧪 VLE recipe flattened to {len(vle_recipe)} constituent chemicals.")
verifier = FragrancePipelineVerifier()
result = verifier.run_sim(vle_recipe, duration_seconds=8 * 3600, interval_seconds=600, skip_ifra=True)
if result["status"] != "passed":
print("Simulation failed:", result["message"])
print("Errors:", result.get("applicability_errors", []))
return
print("✅ UNIFAC VLE simulation passed with no group faults.")
# Build model inputs with preserved natural oil tokens.
engine = OlfactoryEmbeddingEngine()
tokens = build_model_inputs(semantic_recipe, registry, engine)
print("✅ Token tensor shape:", tokens.shape, "(natural oils retained as discrete tokens)")
# Aggregate physics from constituent trajectory back to token sequence.
physics, const_to_token = aggregate_physics_for_tokens(result["trajectory"], semantic_recipe)
print(f"✅ Physics aggregated back to {physics.shape[1]} tokens from {len(const_to_token)} constituents.")
physics_t = torch.from_numpy(physics).unsqueeze(0).float() # (1, T, S, 2)
mask = torch.zeros(1, tokens.size(1), dtype=torch.bool)
model, heads, device = load_pimt_checkpoint()
with torch.no_grad():
latent = model(tokens.to(device), physics_t.to(device), src_key_padding_mask=mask.to(device))
output = heads(latent, states=physics_t.to(device), src_key_padding_mask=mask.to(device))
objective = output["objective"].cpu().numpy() # (1, T, 138)
sub = output["subjective"]
seasonality = sub["seasonality"].cpu().numpy() # (1, 4)
gender = sub["gender_profile"].cpu().numpy() # (1, 1)
wearability = sub["wearability"].cpu().numpy() # (1, 2)
vocab_path = Path("data/pyrfume_vocabulary.json")
vocab_data = json.loads(vocab_path.read_text())
vocab = vocab_data["vocabulary"] if isinstance(vocab_data, dict) else vocab_data
# Top descriptors at phases.
phases = ["top (0 min)", "early dry (2 h)", "heart (4 h)", "late dry (8 h)"]
t_steps = objective.shape[1]
phase_indices = [0, min(12, t_steps - 1), min(24, t_steps - 1), t_steps - 1]
print("\nPredicted objective descriptor profiles:")
for label, idx in zip(phases, phase_indices):
vec = objective[0, idx]
top = np.argsort(vec)[-10:][::-1]
print(f"\n{label}:")
for rank, d in enumerate(top, 1):
print(f" {rank:2d}. {vocab[d]:20s} {vec[d]:.3f}")
cats = categorize_descriptors(vocab, vec)
print(f" Category scores: {cats}")
# Subjective prediction with softmax.
season_probs = torch.softmax(torch.from_numpy(seasonality[0]), dim=0).numpy()
seasons = ["spring", "summer", "autumn", "winter"]
print("\nPredicted subjective profile:")
print(f" Seasonality: {dict(zip(seasons, [float(v) for v in season_probs]))}")
print(f" Gender profile (feminine-masculine): {float(gender[0, 0]):.3f}")
print(f" Wearability: day={float(wearability[0, 0]):.3f}, night={float(wearability[0, 1]):.3f}")
# Website comparison.
print("\n📊 Comparison with WiseMoor website description:")
print(" Website: Oriental Spicy; top=citrus/bergamot/lemon/cedar/mandarin; middle=iris/patchouli/vetiver/jasmine/rose; base=vanilla/incense/leather/opoponax/civet/sandalwood/tonka/musk")
cats = categorize_descriptors(vocab, objective[0, phase_indices[0]])
print(f" Model top-note category emphasis: {cats}")
cats_base = categorize_descriptors(vocab, objective[0, -1])
print(f" Model base-note category emphasis: {cats_base}")
# Save outputs.
out = {
"semantic_recipe": semantic_recipe,
"vle_recipe": vle_recipe,
"objective": objective.tolist(),
"subjective": {
"seasonality": season_probs.tolist(),
"gender_profile": gender.tolist(),
"wearability": wearability.tolist(),
},
}
Path("reports/shalimar_1990_prediction.json").write_text(
json.dumps(out, separators=(",", ":"), ensure_ascii=False)
)
print("\nSaved full prediction to reports/shalimar_1990_prediction.json")
# DoD: bidirectional transparency backtest.
run_sensitivity_backtest(model, heads, device, semantic_recipe, registry, engine)
if __name__ == "__main__":
main()