Commit ·
e8a073b
1
Parent(s): 1691a25
feat(literature): ingest and seed human-designed fragrance skeletons
Browse files- Add src/pino/ingest_formulas.py to normalize raw literature recipes
- Support recursive sub_base unpacking to pure CAS
- Integrate --seed-id into pino-critic compose and run_generation.py
- Add sample Poucher chypre manifest in data/literature_formulas.json
- .gitignore +1 -0
- data/literature_formulas.json +22 -0
- run_generation.py +22 -3
- src/pino/cli.py +23 -1
- src/pino/ingest_formulas.py +206 -0
- src/pino/optimizer.py +52 -7
.gitignore
CHANGED
|
@@ -10,6 +10,7 @@ build/
|
|
| 10 |
*.json
|
| 11 |
!data/design_brief.json
|
| 12 |
!data/genre_rules.json
|
|
|
|
| 13 |
*.db
|
| 14 |
!src/pino/registry.db
|
| 15 |
*.jsonl
|
|
|
|
| 10 |
*.json
|
| 11 |
!data/design_brief.json
|
| 12 |
!data/genre_rules.json
|
| 13 |
+
!data/literature_formulas.json
|
| 14 |
*.db
|
| 15 |
!src/pino/registry.db
|
| 16 |
*.jsonl
|
data/literature_formulas.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"formula_id": "poucher_1959_classic_chypre",
|
| 3 |
+
"name": "Classic Oakmoss Chypre Baseline",
|
| 4 |
+
"source": "Poucher - Perfumes, Cosmetics and Soaps Vol 2",
|
| 5 |
+
"raw_basis_sum": 1000.0,
|
| 6 |
+
"components": [
|
| 7 |
+
{"cas": "5989-27-5", "amount": 250.0, "type": "pure"},
|
| 8 |
+
{"cas": "78-70-6", "amount": 150.0, "type": "pure"},
|
| 9 |
+
{"cas": "24851-98-7", "amount": 200.0, "type": "pure"},
|
| 10 |
+
{"cas": "54464-57-2", "amount": 100.0, "type": "pure"},
|
| 11 |
+
{
|
| 12 |
+
"name": "Mousse de Saxe Base",
|
| 13 |
+
"amount": 300.0,
|
| 14 |
+
"type": "sub_base",
|
| 15 |
+
"composition": [
|
| 16 |
+
{"cas": "91-64-5", "amount": 0.40},
|
| 17 |
+
{"cas": "121-33-5", "amount": 0.20},
|
| 18 |
+
{"cas": "97-53-0", "amount": 0.40}
|
| 19 |
+
]
|
| 20 |
+
}
|
| 21 |
+
]
|
| 22 |
+
}
|
run_generation.py
CHANGED
|
@@ -34,6 +34,10 @@ import logging
|
|
| 34 |
from pathlib import Path
|
| 35 |
from typing import Any
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
from pino.optimizer import CompositionTarget, FormulationOptimizer, OptimizerConfig
|
| 38 |
from pino.verifier import FragrancePipelineVerifier
|
| 39 |
|
|
@@ -54,7 +58,7 @@ def save_output(output: dict[str, Any], path: str) -> None:
|
|
| 54 |
logger.info("Saved generated recipe to %s", path)
|
| 55 |
|
| 56 |
|
| 57 |
-
def run(brief_path: str, output_path: str) -> dict[str, Any]:
|
| 58 |
"""Execute the full generative design profile."""
|
| 59 |
brief = load_brief(brief_path)
|
| 60 |
target = CompositionTarget.from_text(brief.get("brief", ""))
|
|
@@ -75,8 +79,22 @@ def run(brief_path: str, output_path: str) -> dict[str, Any]:
|
|
| 75 |
config.allow_synthetic,
|
| 76 |
)
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
optimizer = FormulationOptimizer(config)
|
| 79 |
-
best = optimizer.optimize(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
# Re-verify the winning formula to capture a full 8-hour trajectory.
|
| 82 |
formula_records = best.to_formula_dict()
|
|
@@ -115,9 +133,10 @@ def main() -> None:
|
|
| 115 |
parser = argparse.ArgumentParser(description="Generate a fragrance recipe from a design brief")
|
| 116 |
parser.add_argument("--brief", default="data/design_brief.json", help="Path to design brief JSON")
|
| 117 |
parser.add_argument("--output", default="data/generated_recipe_output.json", help="Output JSON path")
|
|
|
|
| 118 |
args = parser.parse_args()
|
| 119 |
|
| 120 |
-
result = run(args.brief, args.output)
|
| 121 |
print(json.dumps(result["generated_formula"], indent=2, ensure_ascii=False))
|
| 122 |
|
| 123 |
|
|
|
|
| 34 |
from pathlib import Path
|
| 35 |
from typing import Any
|
| 36 |
|
| 37 |
+
from pino.ingest_formulas import (
|
| 38 |
+
load_literature_manifest,
|
| 39 |
+
normalize_and_unpack_recipe_from_dict,
|
| 40 |
+
)
|
| 41 |
from pino.optimizer import CompositionTarget, FormulationOptimizer, OptimizerConfig
|
| 42 |
from pino.verifier import FragrancePipelineVerifier
|
| 43 |
|
|
|
|
| 58 |
logger.info("Saved generated recipe to %s", path)
|
| 59 |
|
| 60 |
|
| 61 |
+
def run(brief_path: str, output_path: str, literature_formulas: str = "data/literature_formulas.json") -> dict[str, Any]:
|
| 62 |
"""Execute the full generative design profile."""
|
| 63 |
brief = load_brief(brief_path)
|
| 64 |
target = CompositionTarget.from_text(brief.get("brief", ""))
|
|
|
|
| 79 |
config.allow_synthetic,
|
| 80 |
)
|
| 81 |
|
| 82 |
+
seed_recipe = None
|
| 83 |
+
seed_id = brief.get("seed_id")
|
| 84 |
+
if seed_id:
|
| 85 |
+
recipes = load_literature_manifest(literature_formulas)
|
| 86 |
+
recipe = next((r for r in recipes if r.get("formula_id") == seed_id), None)
|
| 87 |
+
if recipe is None:
|
| 88 |
+
raise ValueError(f"Seed recipe {seed_id} not found in {literature_formulas}")
|
| 89 |
+
seed_recipe = normalize_and_unpack_recipe_from_dict(recipe)
|
| 90 |
+
logger.info("Loaded literature seed recipe %s with %d components", seed_id, len(seed_recipe["components"]))
|
| 91 |
+
|
| 92 |
optimizer = FormulationOptimizer(config)
|
| 93 |
+
best = optimizer.optimize(
|
| 94 |
+
target,
|
| 95 |
+
palette_size=brief.get("palette_size", 20),
|
| 96 |
+
seed_recipe=seed_recipe,
|
| 97 |
+
)
|
| 98 |
|
| 99 |
# Re-verify the winning formula to capture a full 8-hour trajectory.
|
| 100 |
formula_records = best.to_formula_dict()
|
|
|
|
| 133 |
parser = argparse.ArgumentParser(description="Generate a fragrance recipe from a design brief")
|
| 134 |
parser.add_argument("--brief", default="data/design_brief.json", help="Path to design brief JSON")
|
| 135 |
parser.add_argument("--output", default="data/generated_recipe_output.json", help="Output JSON path")
|
| 136 |
+
parser.add_argument("--literature-formulas", default="data/literature_formulas.json", help="Path to literature formula manifest")
|
| 137 |
args = parser.parse_args()
|
| 138 |
|
| 139 |
+
result = run(args.brief, args.output, literature_formulas=args.literature_formulas)
|
| 140 |
print(json.dumps(result["generated_formula"], indent=2, ensure_ascii=False))
|
| 141 |
|
| 142 |
|
src/pino/cli.py
CHANGED
|
@@ -100,9 +100,29 @@ def _compose(args: argparse.Namespace) -> int:
|
|
| 100 |
else:
|
| 101 |
print(msg, file=sys.stderr)
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
try:
|
| 104 |
optimizer = FormulationOptimizer(config)
|
| 105 |
-
best = optimizer.optimize(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
except Exception as e:
|
| 107 |
logger.error("Composition failed: %s", e)
|
| 108 |
return 2
|
|
@@ -154,6 +174,8 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 154 |
compose_parser.add_argument("--allow-synthetic", action="store_true", default=True, help="Allow non-renewable ingredients")
|
| 155 |
compose_parser.add_argument("--no-synthetic", action="store_false", dest="allow_synthetic", help="Restrict to renewable ingredients")
|
| 156 |
compose_parser.add_argument("--seed", type=int, default=None, help="Random seed")
|
|
|
|
|
|
|
| 157 |
compose_parser.add_argument("--json", action="store_true", dest="json_mode", help="Emit raw parseable JSON only")
|
| 158 |
compose_parser.set_defaults(func=_compose)
|
| 159 |
|
|
|
|
| 100 |
else:
|
| 101 |
print(msg, file=sys.stderr)
|
| 102 |
|
| 103 |
+
seed_recipe = None
|
| 104 |
+
if args.seed_id:
|
| 105 |
+
from .ingest_formulas import load_literature_manifest, normalize_and_unpack_recipe_from_dict
|
| 106 |
+
try:
|
| 107 |
+
recipes = load_literature_manifest(args.literature_formulas)
|
| 108 |
+
recipe = next((r for r in recipes if r.get("formula_id") == args.seed_id), None)
|
| 109 |
+
if recipe is None:
|
| 110 |
+
logger.error("Seed recipe %s not found in %s", args.seed_id, args.literature_formulas)
|
| 111 |
+
return 2
|
| 112 |
+
seed_recipe = normalize_and_unpack_recipe_from_dict(recipe)
|
| 113 |
+
logger.info("Loaded literature seed recipe %s with %d components", args.seed_id, len(seed_recipe["components"]))
|
| 114 |
+
except Exception as e:
|
| 115 |
+
logger.error("Failed to load seed recipe: %s", e)
|
| 116 |
+
return 2
|
| 117 |
+
|
| 118 |
try:
|
| 119 |
optimizer = FormulationOptimizer(config)
|
| 120 |
+
best = optimizer.optimize(
|
| 121 |
+
target,
|
| 122 |
+
palette_size=args.palette_size,
|
| 123 |
+
progress_callback=progress,
|
| 124 |
+
seed_recipe=seed_recipe,
|
| 125 |
+
)
|
| 126 |
except Exception as e:
|
| 127 |
logger.error("Composition failed: %s", e)
|
| 128 |
return 2
|
|
|
|
| 174 |
compose_parser.add_argument("--allow-synthetic", action="store_true", default=True, help="Allow non-renewable ingredients")
|
| 175 |
compose_parser.add_argument("--no-synthetic", action="store_false", dest="allow_synthetic", help="Restrict to renewable ingredients")
|
| 176 |
compose_parser.add_argument("--seed", type=int, default=None, help="Random seed")
|
| 177 |
+
compose_parser.add_argument("--seed-id", default=None, help="Literature recipe ID to seed the first generation")
|
| 178 |
+
compose_parser.add_argument("--literature-formulas", default="data/literature_formulas.json", help="Path to literature formula manifest")
|
| 179 |
compose_parser.add_argument("--json", action="store_true", dest="json_mode", help="Emit raw parseable JSON only")
|
| 180 |
compose_parser.set_defaults(func=_compose)
|
| 181 |
|
src/pino/ingest_formulas.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Literature fragrance formula ingestion and normalization.
|
| 5 |
+
|
| 6 |
+
Reads raw recipe manifests (e.g., from Poucher, Arctander, Calkin & Jellinek),
|
| 7 |
+
recursively unpacks proprietary sub-bases into pure CAS constituents, and scales
|
| 8 |
+
all masses to strict unit weight fractions (Σ w_i = 1.0).
|
| 9 |
+
|
| 10 |
+
The output is directly consumable by the PINO optimizer and verifier.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import logging
|
| 15 |
+
from collections import defaultdict
|
| 16 |
+
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],
|
| 27 |
+
parent_multiplier: float = 1.0,
|
| 28 |
+
) -> None:
|
| 29 |
+
"""
|
| 30 |
+
Recursively unpack a component into pure CAS mass contributions.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
component: dict
|
| 35 |
+
A recipe component with keys 'type', 'amount', 'cas'/'name'/'composition'.
|
| 36 |
+
accumulator: dict
|
| 37 |
+
Running map of CAS -> absolute mass.
|
| 38 |
+
parent_multiplier: float
|
| 39 |
+
Scale factor inherited from parent bases (product of ancestor amounts).
|
| 40 |
+
"""
|
| 41 |
+
comp_type = component.get("type", "pure")
|
| 42 |
+
amount = float(component.get("amount", 0.0)) * parent_multiplier
|
| 43 |
+
|
| 44 |
+
if comp_type == "pure":
|
| 45 |
+
cas = component.get("cas")
|
| 46 |
+
if not cas:
|
| 47 |
+
raise ValueError(f"Pure component missing CAS: {component}")
|
| 48 |
+
accumulator[cas] += amount
|
| 49 |
+
|
| 50 |
+
elif comp_type == "sub_base":
|
| 51 |
+
base_composition = component.get("composition") or []
|
| 52 |
+
if not base_composition:
|
| 53 |
+
logger.warning("Sub-base '%s' has no composition; skipping", component.get("name"))
|
| 54 |
+
return
|
| 55 |
+
|
| 56 |
+
# Determine how sub-base internal fractions are expressed.
|
| 57 |
+
sub_total = sum(float(sub.get("amount", 0.0)) for sub in base_composition)
|
| 58 |
+
if sub_total <= 0:
|
| 59 |
+
raise ValueError(f"Sub-base '{component.get('name')}' composition sums to <= 0")
|
| 60 |
+
|
| 61 |
+
for sub in base_composition:
|
| 62 |
+
sub_component = dict(sub)
|
| 63 |
+
sub_component["amount"] = float(sub.get("amount", 0.0)) / sub_total * amount
|
| 64 |
+
_recursive_unpack(sub_component, accumulator, parent_multiplier=1.0)
|
| 65 |
+
|
| 66 |
+
else:
|
| 67 |
+
raise ValueError(f"Unknown component type: {comp_type}")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def normalize_and_unpack_recipe(raw_recipe_path: str | Path) -> dict[str, Any]:
|
| 71 |
+
"""
|
| 72 |
+
Load a raw literature recipe and return a normalized pure-CAS formula.
|
| 73 |
+
|
| 74 |
+
The returned dict has:
|
| 75 |
+
- formula_id, name, source
|
| 76 |
+
- components: list of {"cas", "weight_fraction"} with Σ = 1.0
|
| 77 |
+
"""
|
| 78 |
+
path = Path(raw_recipe_path)
|
| 79 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 80 |
+
|
| 81 |
+
flat_composition: dict[str, float] = defaultdict(float)
|
| 82 |
+
|
| 83 |
+
for comp in data.get("components", []):
|
| 84 |
+
_recursive_unpack(comp, flat_composition)
|
| 85 |
+
|
| 86 |
+
absolute_sum = sum(flat_composition.values())
|
| 87 |
+
if absolute_sum <= 0:
|
| 88 |
+
raise ValueError(f"Recipe {data.get('formula_id')} has zero total mass")
|
| 89 |
+
|
| 90 |
+
normalized_components = []
|
| 91 |
+
for cas in sorted(flat_composition.keys()):
|
| 92 |
+
weight_fraction = round(flat_composition[cas] / absolute_sum, 6)
|
| 93 |
+
normalized_components.append({"cas": cas, "weight_fraction": weight_fraction})
|
| 94 |
+
|
| 95 |
+
# Micro-adjust to ensure exact 1.0 after rounding.
|
| 96 |
+
total_fraction = sum(c["weight_fraction"] for c in normalized_components)
|
| 97 |
+
if total_fraction != 1.0 and normalized_components:
|
| 98 |
+
normalized_components[0]["weight_fraction"] = round(
|
| 99 |
+
normalized_components[0]["weight_fraction"] + (1.0 - total_fraction), 6
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
return {
|
| 103 |
+
"formula_id": data.get("formula_id"),
|
| 104 |
+
"name": data.get("name"),
|
| 105 |
+
"source": data.get("source"),
|
| 106 |
+
"components": normalized_components,
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def load_literature_manifest(manifest_path: str | Path) -> list[dict[str, Any]]:
|
| 111 |
+
"""Load a JSON file that may be either a single recipe or a list of recipes."""
|
| 112 |
+
path = Path(manifest_path)
|
| 113 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 114 |
+
if isinstance(data, list):
|
| 115 |
+
return data
|
| 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(
|
| 140 |
+
"Recipe %s contains unknown CAS entries: %s",
|
| 141 |
+
normalized["formula_id"],
|
| 142 |
+
unknown,
|
| 143 |
+
)
|
| 144 |
+
normalized["registry_status"] = "unknown_cas"
|
| 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]]:
|
| 183 |
+
"""Convert a normalized recipe into the verifier-friendly formula format."""
|
| 184 |
+
return [
|
| 185 |
+
{"cas": c["cas"], "weight_fraction": c["weight_fraction"]}
|
| 186 |
+
for c in recipe.get("components", [])
|
| 187 |
+
]
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
import argparse
|
| 192 |
+
|
| 193 |
+
parser = argparse.ArgumentParser(description="Normalize literature fragrance recipes")
|
| 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")
|
| 205 |
+
else:
|
| 206 |
+
print(out_text)
|
src/pino/optimizer.py
CHANGED
|
@@ -35,6 +35,12 @@ from dataclasses import dataclass, field
|
|
| 35 |
from pathlib import Path
|
| 36 |
from typing import Any, Callable
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
import numpy as np
|
| 39 |
import torch
|
| 40 |
from cma import CMAEvolutionStrategy
|
|
@@ -689,6 +695,7 @@ class FormulationOptimizer:
|
|
| 689 |
palette_size: int = 20,
|
| 690 |
initial_guess: np.ndarray | None = None,
|
| 691 |
progress_callback: Callable[[int, float, Candidate], None] | None = None,
|
|
|
|
| 692 |
) -> Candidate:
|
| 693 |
"""
|
| 694 |
Run the evolutionary search and return the best compliant candidate.
|
|
@@ -705,15 +712,17 @@ class FormulationOptimizer:
|
|
| 705 |
progress_callback: callable | None
|
| 706 |
Optional function ``(iteration, fitness, best_candidate) -> None`` called
|
| 707 |
after each generation. The CLI uses this to print progress to stderr.
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 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")
|
|
@@ -721,9 +730,13 @@ class FormulationOptimizer:
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 725 |
x0 = self._project_and_normalize(x0)
|
| 726 |
-
|
| 727 |
# CMA-ES minimises the objective; lower MSE = higher fitness.
|
| 728 |
es = CMAEvolutionStrategy(
|
| 729 |
x0=x0,
|
|
@@ -767,6 +780,38 @@ class FormulationOptimizer:
|
|
| 767 |
best = self._evaluate(best.weight_fractions, target)
|
| 768 |
return best
|
| 769 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 770 |
|
| 771 |
# ---------------------------------------------------------------------------
|
| 772 |
# Convenience helpers for natural-language / JSON brief entry points.
|
|
|
|
| 35 |
from pathlib import Path
|
| 36 |
from typing import Any, Callable
|
| 37 |
|
| 38 |
+
from .ingest_formulas import (
|
| 39 |
+
load_literature_manifest,
|
| 40 |
+
normalize_and_unpack_recipe,
|
| 41 |
+
recipe_to_formula_records,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
import numpy as np
|
| 45 |
import torch
|
| 46 |
from cma import CMAEvolutionStrategy
|
|
|
|
| 695 |
palette_size: int = 20,
|
| 696 |
initial_guess: np.ndarray | None = None,
|
| 697 |
progress_callback: Callable[[int, float, Candidate], None] | None = None,
|
| 698 |
+
seed_recipe: dict[str, Any] | None = None,
|
| 699 |
) -> Candidate:
|
| 700 |
"""
|
| 701 |
Run the evolutionary search and return the best compliant candidate.
|
|
|
|
| 712 |
progress_callback: callable | None
|
| 713 |
Optional function ``(iteration, fitness, best_candidate) -> None`` called
|
| 714 |
after each generation. The CLI uses this to print progress to stderr.
|
| 715 |
+
seed_recipe: dict | None
|
| 716 |
+
Optional normalized literature recipe whose CAS/weights seed the first
|
| 717 |
+
generation. The recipe's materials are guaranteed to be in the palette,
|
| 718 |
+
and its weight vector becomes the CMA-ES centroid.
|
|
|
|
| 719 |
"""
|
| 720 |
self._build_palette(palette_size, strategy=target.strategy)
|
| 721 |
self._restrict_palette()
|
| 722 |
|
| 723 |
+
if seed_recipe:
|
| 724 |
+
self._inject_seed_recipe(seed_recipe)
|
| 725 |
+
|
| 726 |
n = len(self.palette)
|
| 727 |
if n == 0:
|
| 728 |
raise RuntimeError("Palette is empty; cannot optimise")
|
|
|
|
| 730 |
# Strategy-aware initial guess: give a strong prior to the materials that
|
| 731 |
# are expected to satisfy the brief. This keeps CMA-ES from getting stuck
|
| 732 |
# in a generic floral/heart local minimum.
|
| 733 |
+
if initial_guess is not None:
|
| 734 |
+
x0 = initial_guess
|
| 735 |
+
elif seed_recipe is not None:
|
| 736 |
+
x0 = self.recipe_initial_guess(seed_recipe)
|
| 737 |
+
else:
|
| 738 |
+
x0 = self._initial_guess(target.strategy, n)
|
| 739 |
x0 = self._project_and_normalize(x0)
|
|
|
|
| 740 |
# CMA-ES minimises the objective; lower MSE = higher fitness.
|
| 741 |
es = CMAEvolutionStrategy(
|
| 742 |
x0=x0,
|
|
|
|
| 780 |
best = self._evaluate(best.weight_fractions, target)
|
| 781 |
return best
|
| 782 |
|
| 783 |
+
def _inject_seed_recipe(self, seed_recipe: dict[str, Any]) -> None:
|
| 784 |
+
"""
|
| 785 |
+
Ensure every CAS in a normalized literature recipe is present in the palette,
|
| 786 |
+
and patch the palette order so the recipe weight vector aligns with the
|
| 787 |
+
optimizer's internal arrays.
|
| 788 |
+
"""
|
| 789 |
+
recipe_cas = {c["cas"] for c in seed_recipe.get("components", [])}
|
| 790 |
+
current_cas = {ing.cas for ing in self.palette}
|
| 791 |
+
missing = recipe_cas - current_cas
|
| 792 |
+
if missing:
|
| 793 |
+
logger.info("Expanding palette to include %d recipe CAS entries", len(missing))
|
| 794 |
+
for cas in missing:
|
| 795 |
+
try:
|
| 796 |
+
ing = self.resolver.resolve(cas, weight_fraction=0.0)
|
| 797 |
+
self.palette.append(ing)
|
| 798 |
+
except Exception as exc:
|
| 799 |
+
logger.warning("Could not resolve seed recipe CAS %s: %s", cas, exc)
|
| 800 |
+
self.palette_cas = [ing.cas for ing in self.palette]
|
| 801 |
+
|
| 802 |
+
def recipe_initial_guess(self, seed_recipe: dict[str, Any]) -> np.ndarray:
|
| 803 |
+
"""Build a weight vector from a normalized recipe aligned to the current palette."""
|
| 804 |
+
if not self.palette:
|
| 805 |
+
raise RuntimeError("Palette not built before constructing recipe initial guess")
|
| 806 |
+
x = np.zeros(len(self.palette), dtype=float)
|
| 807 |
+
recipe_by_cas = {c["cas"]: c["weight_fraction"] for c in seed_recipe.get("components", [])}
|
| 808 |
+
for i, ing in enumerate(self.palette):
|
| 809 |
+
x[i] = recipe_by_cas.get(ing.cas, 0.0)
|
| 810 |
+
total = x.sum()
|
| 811 |
+
if total <= 0:
|
| 812 |
+
raise RuntimeError("Seed recipe has zero total weight after palette mapping")
|
| 813 |
+
return x / total
|
| 814 |
+
|
| 815 |
|
| 816 |
# ---------------------------------------------------------------------------
|
| 817 |
# Convenience helpers for natural-language / JSON brief entry points.
|