feat: add Milestone 5 generative inverse-design composer (CMA-ES)
Browse filesWhy:
- Downstream agents need to turn sensory targets into manufacture-ready formulas
without manually searching ingredient space or violating IFRA limits.
- CMA-ES was chosen over a VAE/GAN because it naturally handles hard constraints
(mass balance, safety thresholds, physical simulation failures) via projection
and rejection, while adapting its covariance to the local fitness landscape.
What:
- Implement FormulationOptimizer in src/pino/optimizer.py using CMA-ES.
- Palette is sampled from the SQLite aroma registry; weights are projected to the
unit simplex and clipped to IFRA Category 4 limits every iteration.
- Each candidate is verified by FragrancePipelineVerifier, encoded for the PIMT
critic, and scored by weighted MSE against objective/subjective targets.
- Add CompositionTarget.from_text/from_json helpers for natural-language briefs.
- Add pino-critic compose subcommand with --target-json, --max-iterations,
--palette-size, --allow-synthetic, --seed, and --json flags.
- Add run_generation.py end-to-end script and data/design_brief.json example.
- Update README.md and pyproject.toml dependencies (cma, transformers, hf-hub).
Closes: Milestone 5 foundation.
- .gitignore +1 -0
- README.md +17 -0
- data/design_brief.json +7 -0
- pyproject.toml +3 -0
- run_generation.py +125 -0
- src/pino/cli.py +58 -0
- src/pino/optimizer.py +647 -0
|
@@ -9,6 +9,7 @@ build/
|
|
| 9 |
.pytest_cache/
|
| 10 |
*.json
|
| 11 |
!.gitkeep
|
|
|
|
| 12 |
*.jsonl
|
| 13 |
*.parquet
|
| 14 |
src/pino/registry.db
|
|
|
|
| 9 |
.pytest_cache/
|
| 10 |
*.json
|
| 11 |
!.gitkeep
|
| 12 |
+
!data/design_brief.json
|
| 13 |
*.jsonl
|
| 14 |
*.parquet
|
| 15 |
src/pino/registry.db
|
|
@@ -29,6 +29,23 @@ PYTHONPATH=src python -c "from pino.verifier import verify_formula_dict; import
|
|
| 29 |
|
| 30 |
The output file `trajectory_output.json` contains liquid mole fractions (`x_liquid`), gas-phase concentrations (`C_gas_mg_m3`), gas mole fractions (`y_gas_mole_fraction`), and Odor Activity Values (`OAV`) over 0–28,800 seconds (8 hours) at 60-second intervals.
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
## Design constraints honored
|
| 33 |
|
| 34 |
- Activity coefficients are computed with **Dortmund-Modified UNIFAC** (`thermo.unifac`); Raoult's law is not used.
|
|
|
|
| 29 |
|
| 30 |
The output file `trajectory_output.json` contains liquid mole fractions (`x_liquid`), gas-phase concentrations (`C_gas_mg_m3`), gas mole fractions (`y_gas_mole_fraction`), and Odor Activity Values (`OAV`) over 0–28,800 seconds (8 hours) at 60-second intervals.
|
| 31 |
|
| 32 |
+
## Milestone 5: Generative Inverse-Design Composer
|
| 33 |
+
|
| 34 |
+
- `src/pino/optimizer.py` — CMA-ES-based `FormulationOptimizer` that evolves ingredient weight fractions against a sensory target.
|
| 35 |
+
- `src/pino/cli.py` — adds `pino-critic compose` for agentic formula generation.
|
| 36 |
+
- `run_generation.py` — reference end-to-end script that writes `data/generated_recipe_output.json`.
|
| 37 |
+
- `data/design_brief.json` — example design brief (Citrus Summer Cologne).
|
| 38 |
+
|
| 39 |
+
### Generate a recipe
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
cd /home/hermes/pino
|
| 43 |
+
source .venv/bin/activate
|
| 44 |
+
PYTHONPATH=src python run_generation.py --brief data/design_brief.json
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
The composer enforces IFRA Category 4 limits, normalises every candidate to 100% mass, and scores candidates using the PIMT transformer critic. Generated recipes include an 8-hour physical dry-down trajectory and are saved to `data/generated_recipe_output.json`.
|
| 48 |
+
|
| 49 |
## Design constraints honored
|
| 50 |
|
| 51 |
- Activity coefficients are computed with **Dortmund-Modified UNIFAC** (`thermo.unifac`); Raoult's law is not used.
|
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Citrus Summer Cologne",
|
| 3 |
+
"brief": "citrus summer masculine",
|
| 4 |
+
"max_iterations": 50,
|
| 5 |
+
"palette_size": 15,
|
| 6 |
+
"allow_synthetic": true
|
| 7 |
+
}
|
|
@@ -14,6 +14,9 @@ dependencies = [
|
|
| 14 |
"thermo>=0.6",
|
| 15 |
"ugropy>=3.2",
|
| 16 |
"pydantic>=2.0",
|
|
|
|
|
|
|
|
|
|
| 17 |
]
|
| 18 |
|
| 19 |
[project.optional-dependencies]
|
|
|
|
| 14 |
"thermo>=0.6",
|
| 15 |
"ugropy>=3.2",
|
| 16 |
"pydantic>=2.0",
|
| 17 |
+
"cma>=4.0",
|
| 18 |
+
"transformers>=5.0",
|
| 19 |
+
"huggingface-hub>=0.24",
|
| 20 |
]
|
| 21 |
|
| 22 |
[project.optional-dependencies]
|
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
End-to-end generative fragrance design script for PINO.
|
| 5 |
+
|
| 6 |
+
This script demonstrates a complete inverse-design workflow:
|
| 7 |
+
1. Read a high-level design brief from a JSON file.
|
| 8 |
+
2. Run the CMA-ES composer (src/pino/optimizer.py) to evolve a formula.
|
| 9 |
+
3. Verify the winning formula through the physical/IFRA pipeline.
|
| 10 |
+
4. Save the generated recipe and its 8-hour dry-down trajectory to
|
| 11 |
+
data/generated_recipe_output.json.
|
| 12 |
+
|
| 13 |
+
It is intended as a reference execution profile for downstream agents and
|
| 14 |
+
manufacturing workflows. Run it as:
|
| 15 |
+
|
| 16 |
+
cd /home/hermes/pino
|
| 17 |
+
source .venv/bin/activate
|
| 18 |
+
PYTHONPATH=src python run_generation.py --brief data/design_brief.json
|
| 19 |
+
|
| 20 |
+
The design brief JSON has the following shape:
|
| 21 |
+
|
| 22 |
+
{
|
| 23 |
+
"name": "Citrus Summer Cologne",
|
| 24 |
+
"brief": "citrus summer masculine",
|
| 25 |
+
"max_iterations": 50,
|
| 26 |
+
"palette_size": 15,
|
| 27 |
+
"allow_synthetic": false
|
| 28 |
+
}
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
import json
|
| 33 |
+
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 |
+
|
| 40 |
+
logger = logging.getLogger("run_generation")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_brief(path: str) -> dict[str, Any]:
|
| 44 |
+
"""Load a design brief from JSON."""
|
| 45 |
+
with Path(path).open("r", encoding="utf-8") as f:
|
| 46 |
+
return json.load(f)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def save_output(output: dict[str, Any], path: str) -> None:
|
| 50 |
+
"""Persist the generated recipe and trajectory to JSON."""
|
| 51 |
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
| 52 |
+
with Path(path).open("w", encoding="utf-8") as f:
|
| 53 |
+
json.dump(output, f, indent=2, ensure_ascii=False)
|
| 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", ""))
|
| 61 |
+
target.name = brief.get("name", target.name)
|
| 62 |
+
|
| 63 |
+
config = OptimizerConfig(
|
| 64 |
+
max_iterations=brief.get("max_iterations", 50),
|
| 65 |
+
allow_synthetic=brief.get("allow_synthetic", True),
|
| 66 |
+
seed=brief.get("seed", 2026),
|
| 67 |
+
verbose=1,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
logger.info(
|
| 71 |
+
"Starting generation: brief=%r, iterations=%d, palette=%d, synthetic=%s",
|
| 72 |
+
target.name,
|
| 73 |
+
config.max_iterations,
|
| 74 |
+
brief.get("palette_size", 20),
|
| 75 |
+
config.allow_synthetic,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
optimizer = FormulationOptimizer(config)
|
| 79 |
+
best = optimizer.optimize(target, palette_size=brief.get("palette_size", 20))
|
| 80 |
+
|
| 81 |
+
# Re-verify the winning formula to capture a full 8-hour trajectory.
|
| 82 |
+
formula_records = best.to_formula_dict()
|
| 83 |
+
verifier = FragrancePipelineVerifier()
|
| 84 |
+
verification = verifier.run_sim(
|
| 85 |
+
formula_records,
|
| 86 |
+
duration_seconds=8 * 3600.0,
|
| 87 |
+
interval_seconds=600.0,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
output = {
|
| 91 |
+
"design_brief": brief,
|
| 92 |
+
"generated_formula": formula_records,
|
| 93 |
+
"weight_fractions": {
|
| 94 |
+
item["name"]: item["weight_fraction"] for item in formula_records
|
| 95 |
+
},
|
| 96 |
+
"status": best.status,
|
| 97 |
+
"fitness": best.fitness,
|
| 98 |
+
"ifra_passed": best.ifra_report.get("passed", False),
|
| 99 |
+
"ifra_report": best.ifra_report,
|
| 100 |
+
"prediction": best.prediction,
|
| 101 |
+
"trajectory_8h": verification.get("trajectory", []),
|
| 102 |
+
"message": best.message,
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
save_output(output, output_path)
|
| 106 |
+
return output
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def main() -> None:
|
| 110 |
+
logging.basicConfig(
|
| 111 |
+
level=logging.INFO,
|
| 112 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 113 |
+
)
|
| 114 |
+
|
| 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 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
main()
|
|
@@ -9,6 +9,7 @@ from typing import Any
|
|
| 9 |
|
| 10 |
from .feedback import Critique, FeedbackLoopManager
|
| 11 |
from .inference_cloud import predict_cloud
|
|
|
|
| 12 |
|
| 13 |
logger = logging.getLogger("pino.cli")
|
| 14 |
|
|
@@ -75,6 +76,53 @@ def _sync_flywheel(args: argparse.Namespace) -> int:
|
|
| 75 |
return 0 if result.get("action") != "none" or args.allow_empty else 0
|
| 76 |
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
def main(argv: list[str] | None = None) -> int:
|
| 79 |
parser = argparse.ArgumentParser(prog="pino-critic")
|
| 80 |
parser.add_argument("--token", default=None, help="Hugging Face access token")
|
|
@@ -99,6 +147,16 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 99 |
sync_parser.add_argument("--json", action="store_true", dest="json_mode", help="Emit raw parseable JSON only")
|
| 100 |
sync_parser.set_defaults(func=_sync_flywheel)
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
args = parser.parse_args(argv)
|
| 103 |
logging.basicConfig(
|
| 104 |
level=logging.INFO,
|
|
|
|
| 9 |
|
| 10 |
from .feedback import Critique, FeedbackLoopManager
|
| 11 |
from .inference_cloud import predict_cloud
|
| 12 |
+
from .optimizer import OptimizerConfig, FormulationOptimizer, CompositionTarget
|
| 13 |
|
| 14 |
logger = logging.getLogger("pino.cli")
|
| 15 |
|
|
|
|
| 76 |
return 0 if result.get("action") != "none" or args.allow_empty else 0
|
| 77 |
|
| 78 |
|
| 79 |
+
def _compose(args: argparse.Namespace) -> int:
|
| 80 |
+
"""Run the generative composer (CMA-ES) to evolve a formula against a target."""
|
| 81 |
+
try:
|
| 82 |
+
target = CompositionTarget.from_json(args.target_json)
|
| 83 |
+
except Exception as e:
|
| 84 |
+
logger.error("Failed to load target brief: %s", e)
|
| 85 |
+
return 2
|
| 86 |
+
|
| 87 |
+
config = OptimizerConfig(
|
| 88 |
+
max_iterations=args.max_iterations,
|
| 89 |
+
allow_synthetic=args.allow_synthetic,
|
| 90 |
+
seed=args.seed,
|
| 91 |
+
token=args.token,
|
| 92 |
+
verbose=1 if args.json_mode else 1,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def progress(iteration: int, fitness: float, best: Any) -> None:
|
| 96 |
+
# Real-time progress to stderr, never to stdout when --json is set.
|
| 97 |
+
msg = f"[{iteration}/{args.max_iterations}] best fitness (MSE) = {fitness:.6f}"
|
| 98 |
+
if args.json_mode:
|
| 99 |
+
print(msg, file=sys.stderr)
|
| 100 |
+
else:
|
| 101 |
+
print(msg, file=sys.stderr)
|
| 102 |
+
|
| 103 |
+
try:
|
| 104 |
+
optimizer = FormulationOptimizer(config)
|
| 105 |
+
best = optimizer.optimize(target, palette_size=args.palette_size, progress_callback=progress)
|
| 106 |
+
except Exception as e:
|
| 107 |
+
logger.error("Composition failed: %s", e)
|
| 108 |
+
return 2
|
| 109 |
+
|
| 110 |
+
output = {
|
| 111 |
+
"target": target.name,
|
| 112 |
+
"formula": best.to_formula_dict(),
|
| 113 |
+
"status": best.status,
|
| 114 |
+
"fitness": best.fitness,
|
| 115 |
+
"ifra_passed": best.ifra_report.get("passed", False),
|
| 116 |
+
"message": best.message,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
if args.json_mode:
|
| 120 |
+
print(json.dumps(output, separators=(",", ":"), ensure_ascii=False))
|
| 121 |
+
else:
|
| 122 |
+
print(json.dumps(output, indent=2, ensure_ascii=False))
|
| 123 |
+
return 0
|
| 124 |
+
|
| 125 |
+
|
| 126 |
def main(argv: list[str] | None = None) -> int:
|
| 127 |
parser = argparse.ArgumentParser(prog="pino-critic")
|
| 128 |
parser.add_argument("--token", default=None, help="Hugging Face access token")
|
|
|
|
| 147 |
sync_parser.add_argument("--json", action="store_true", dest="json_mode", help="Emit raw parseable JSON only")
|
| 148 |
sync_parser.set_defaults(func=_sync_flywheel)
|
| 149 |
|
| 150 |
+
compose_parser = subparsers.add_parser("compose", help="Evolve a formula against a sensory target")
|
| 151 |
+
compose_parser.add_argument("--target-json", required=True, help="Path to JSON brief defining desired sensory characteristics")
|
| 152 |
+
compose_parser.add_argument("--max-iterations", type=int, default=500, help="Maximum generation cycles")
|
| 153 |
+
compose_parser.add_argument("--palette-size", type=int, default=20, help="Number of palette ingredients")
|
| 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 |
+
|
| 160 |
args = parser.parse_args(argv)
|
| 161 |
logging.basicConfig(
|
| 162 |
level=logging.INFO,
|
|
@@ -0,0 +1,647 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Generative inverse-design layer for PINO.
|
| 5 |
+
|
| 6 |
+
This module couples the agentic CLI/Space critic with a heuristic search algorithm
|
| 7 |
+
(CMA-ES) to evolve manufacture-ready fragrance formulas. The optimizer acts as the
|
| 8 |
+
"Composer"; the trained PIMT transformer and physical verifier act as the "Rigid
|
| 9 |
+
Critic". Every candidate is normalized to unit mass, clipped to IFRA Category 4
|
| 10 |
+
limits, and rejected if it violates physical applicability or safety boundaries.
|
| 11 |
+
|
| 12 |
+
The intended workflow:
|
| 13 |
+
|
| 14 |
+
1. Accept a target sensory profile (objective trajectory or subjective
|
| 15 |
+
psychometrics, or both).
|
| 16 |
+
2. Initialise a population of weight-fraction vectors over a palette drawn from
|
| 17 |
+
the SQLite aroma registry.
|
| 18 |
+
3. Run CMA-ES mutations; after each proposal, enforce:
|
| 19 |
+
- non-negative weights that sum to 1.0,
|
| 20 |
+
- IFRA Category 4 concentration limits,
|
| 21 |
+
- optional renewable/synthetic ingredient restrictions.
|
| 22 |
+
4. Run the local physical verifier to obtain a dry-down trajectory.
|
| 23 |
+
5. Encode the candidate into token/physics tensors and query the PIMT critic.
|
| 24 |
+
6. Score the candidate by inverse MSE against the target profile.
|
| 25 |
+
7. Return the best compliant formula and its predicted trajectory.
|
| 26 |
+
|
| 27 |
+
All public functions and classes carry docstrings; design choices are explained in
|
| 28 |
+
comment blocks where the math or the boundary logic is non-trivial.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import json
|
| 32 |
+
import logging
|
| 33 |
+
import random
|
| 34 |
+
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
|
| 41 |
+
|
| 42 |
+
from .embeddings import OlfactoryEmbeddingEngine
|
| 43 |
+
from .ifra import IFRA_RESTRICTIONS, check_ifra_restrictions
|
| 44 |
+
from .inference_cloud import predict_cloud
|
| 45 |
+
from .models import Formula, Ingredient, Status
|
| 46 |
+
from .pimt_model import FragranceTrajectoryDataset
|
| 47 |
+
from .semantics import get_psychometric_targets
|
| 48 |
+
from .structures import IngredientResolver
|
| 49 |
+
from .verifier import FragrancePipelineVerifier
|
| 50 |
+
|
| 51 |
+
logger = logging.getLogger("pino.optimizer")
|
| 52 |
+
|
| 53 |
+
# Minimum weight fraction for an active ingredient to be considered present.
|
| 54 |
+
# Anything below this is treated as zero, which keeps the formula sparse and
|
| 55 |
+
# manufacture-ready.
|
| 56 |
+
MIN_WEIGHT_FRACTION = 1e-4
|
| 57 |
+
|
| 58 |
+
# Default target for the dry-down trajectory: 8 hours sampled every 10 minutes.
|
| 59 |
+
# This matches the synthetic dataset used to train the PIMT model.
|
| 60 |
+
DEFAULT_DURATION_S = 8 * 3600.0
|
| 61 |
+
DEFAULT_INTERVAL_S = 600.0
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@dataclass
|
| 65 |
+
class OptimizerConfig:
|
| 66 |
+
"""Hyper-parameters for the evolutionary composer."""
|
| 67 |
+
|
| 68 |
+
# Search budget. CMA-ES typically needs ~100-300 evaluations per dimension
|
| 69 |
+
# to converge on a continuous constrained problem; 500 is a safe default for
|
| 70 |
+
# palettes up to ~20 ingredients.
|
| 71 |
+
max_iterations: int = 500
|
| 72 |
+
|
| 73 |
+
# Population size multiplier. CMAEvolutionStrategy defaults to 4 + 3*log(N);
|
| 74 |
+
# we keep the library default by passing None, but expose it for tuning.
|
| 75 |
+
popsize: int | None = None
|
| 76 |
+
|
| 77 |
+
# Initial standard deviation for the CMA-ES search distribution. A value of
|
| 78 |
+
# 0.15 means the first proposals vary weight fractions by roughly ±15% around
|
| 79 |
+
# the initial guess.
|
| 80 |
+
sigma0: float = 0.15
|
| 81 |
+
|
| 82 |
+
# Dry-down simulation horizon and sampling interval.
|
| 83 |
+
duration_seconds: float = DEFAULT_DURATION_S
|
| 84 |
+
interval_seconds: float = DEFAULT_INTERVAL_S
|
| 85 |
+
|
| 86 |
+
# Penalty for candidates that fail IFRA or physical verification. A large
|
| 87 |
+
# finite value keeps CMA-ES from treating infeasible candidates as attractive
|
| 88 |
+
# while still differentiating them (worse than any feasible MSE).
|
| 89 |
+
infeasible_fitness: float = 1e6
|
| 90 |
+
|
| 91 |
+
# Minimum weight fraction for an ingredient to be considered present.
|
| 92 |
+
min_weight_fraction: float = MIN_WEIGHT_FRACTION
|
| 93 |
+
|
| 94 |
+
# If True, restrict the palette to materials that can be sourced from
|
| 95 |
+
# renewable feedstocks. This is a coarse heuristic: we exclude synthetic
|
| 96 |
+
# musks, phthalates, and materials explicitly flagged as non-renewable in the
|
| 97 |
+
# IFRA table. The flag is optional and conservative.
|
| 98 |
+
allow_synthetic: bool = True
|
| 99 |
+
|
| 100 |
+
# Random seed for reproducibility.
|
| 101 |
+
seed: int | None = None
|
| 102 |
+
|
| 103 |
+
# Path to the SQLite aroma registry. If None, the default sibling
|
| 104 |
+
# ``src/pino/registry.db`` is used.
|
| 105 |
+
registry_path: str | Path | None = None
|
| 106 |
+
|
| 107 |
+
# Model repository or Space endpoint used by the inference client. None means
|
| 108 |
+
# use the default Space endpoint (preferred for cloud inference).
|
| 109 |
+
model_repo: str | None = None
|
| 110 |
+
|
| 111 |
+
# HF token for private Space/Hub access. None means read from HF_TOKEN env.
|
| 112 |
+
token: str | None = None
|
| 113 |
+
|
| 114 |
+
# Verbosity: print real-time fitness progression to stderr when > 0.
|
| 115 |
+
verbose: int = 1
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@dataclass
|
| 119 |
+
class CompositionTarget:
|
| 120 |
+
"""
|
| 121 |
+
Target sensory profile used to drive the optimizer.
|
| 122 |
+
|
| 123 |
+
The target can encode either or both of:
|
| 124 |
+
- objective: a (T, 138) dry-down trajectory of descriptor intensities.
|
| 125 |
+
- subjective: a 7-dimensional psychometric vector
|
| 126 |
+
[seasonality_4, gender_1, wearability_2].
|
| 127 |
+
|
| 128 |
+
Weights control the relative importance of each term in the fitness
|
| 129 |
+
function. By default the objective trajectory dominates, with subjective
|
| 130 |
+
psychometrics providing a secondary signal.
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
objective: np.ndarray | None = None
|
| 134 |
+
subjective: np.ndarray | None = None
|
| 135 |
+
weight_objective: float = 1.0
|
| 136 |
+
weight_subjective: float = 0.5
|
| 137 |
+
name: str = "custom"
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def from_text(text: str, *, weight_objective: float = 1.0, weight_subjective: float = 0.5) -> "CompositionTarget":
|
| 141 |
+
"""
|
| 142 |
+
Parse a free-form brief into a structured target.
|
| 143 |
+
|
| 144 |
+
Examples of supported text:
|
| 145 |
+
- "citrus summer masculine" -> boosts citrus descriptors, summer
|
| 146 |
+
seasonality, and a positive gender profile.
|
| 147 |
+
- "winter amber unisex" -> winter seasonality, amber descriptors,
|
| 148 |
+
neutral gender.
|
| 149 |
+
"""
|
| 150 |
+
text_lower = text.lower()
|
| 151 |
+
strategy = "wildcard"
|
| 152 |
+
if "citrus" in text_lower or "summer" in text_lower or "fresh" in text_lower:
|
| 153 |
+
strategy = "citrus_cologne"
|
| 154 |
+
elif "amber" in text_lower or "oriental" in text_lower or "winter" in text_lower:
|
| 155 |
+
strategy = "amber_oriental"
|
| 156 |
+
elif "floral" in text_lower or "woody" in text_lower:
|
| 157 |
+
strategy = "floral_woody"
|
| 158 |
+
elif "fougere" in text_lower or "lavender" in text_lower:
|
| 159 |
+
strategy = "fougere"
|
| 160 |
+
|
| 161 |
+
subjective = get_psychometric_targets(strategy)
|
| 162 |
+
|
| 163 |
+
# Apply crude gender override from the brief.
|
| 164 |
+
if "masculine" in text_lower:
|
| 165 |
+
subjective[4] = 0.7
|
| 166 |
+
elif "feminine" in text_lower:
|
| 167 |
+
subjective[4] = -0.7
|
| 168 |
+
elif "unisex" in text_lower:
|
| 169 |
+
subjective[4] = 0.0
|
| 170 |
+
|
| 171 |
+
# Wearability hints: "day" / "office" vs "evening" / "formal".
|
| 172 |
+
if "day" in text_lower or "office" in text_lower or "casual" in text_lower:
|
| 173 |
+
subjective[5] = 0.8
|
| 174 |
+
subjective[6] = 0.2
|
| 175 |
+
elif "evening" in text_lower or "formal" in text_lower or "night" in text_lower:
|
| 176 |
+
subjective[5] = 0.2
|
| 177 |
+
subjective[6] = 0.8
|
| 178 |
+
|
| 179 |
+
return CompositionTarget(
|
| 180 |
+
subjective=subjective,
|
| 181 |
+
weight_objective=weight_objective,
|
| 182 |
+
weight_subjective=weight_subjective,
|
| 183 |
+
name=text,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
@staticmethod
|
| 187 |
+
def from_json(path: str | Path) -> "CompositionTarget":
|
| 188 |
+
"""Load a target from a JSON brief."""
|
| 189 |
+
with Path(path).open("r", encoding="utf-8") as f:
|
| 190 |
+
payload = json.load(f)
|
| 191 |
+
|
| 192 |
+
objective = None
|
| 193 |
+
if "objective" in payload:
|
| 194 |
+
objective = np.array(payload["objective"], dtype=np.float32)
|
| 195 |
+
|
| 196 |
+
subjective = None
|
| 197 |
+
if "subjective" in payload:
|
| 198 |
+
subjective = np.array(payload["subjective"], dtype=np.float32)
|
| 199 |
+
elif "brief" in payload:
|
| 200 |
+
return CompositionTarget.from_text(payload["brief"])
|
| 201 |
+
|
| 202 |
+
return CompositionTarget(
|
| 203 |
+
objective=objective,
|
| 204 |
+
subjective=subjective,
|
| 205 |
+
weight_objective=payload.get("weight_objective", 1.0),
|
| 206 |
+
weight_subjective=payload.get("weight_subjective", 0.5),
|
| 207 |
+
name=payload.get("name", "custom"),
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@dataclass
|
| 212 |
+
class Candidate:
|
| 213 |
+
"""One evaluated candidate formula plus its metadata."""
|
| 214 |
+
|
| 215 |
+
ingredients: list[Ingredient]
|
| 216 |
+
weight_fractions: np.ndarray
|
| 217 |
+
status: str # "passed", "rejected", "depleted"
|
| 218 |
+
ifra_report: dict[str, Any]
|
| 219 |
+
fitness: float
|
| 220 |
+
prediction: dict[str, Any] = field(default_factory=dict)
|
| 221 |
+
trajectory: list[dict[str, Any]] = field(default_factory=list)
|
| 222 |
+
message: str = ""
|
| 223 |
+
|
| 224 |
+
def to_formula_dict(self) -> list[dict[str, Any]]:
|
| 225 |
+
"""Return a manufacture-ready list of {cas, weight_fraction} records."""
|
| 226 |
+
return [
|
| 227 |
+
{
|
| 228 |
+
"cas": ing.cas,
|
| 229 |
+
"name": ing.name,
|
| 230 |
+
"weight_fraction": float(wf),
|
| 231 |
+
}
|
| 232 |
+
for ing, wf in zip(self.ingredients, self.weight_fractions)
|
| 233 |
+
if wf >= MIN_WEIGHT_FRACTION
|
| 234 |
+
]
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class FormulationOptimizer:
|
| 238 |
+
"""
|
| 239 |
+
Directed evolutionary search for fragrance formulas.
|
| 240 |
+
|
| 241 |
+
Uses CMA-ES to optimise continuous weight fractions over a fixed palette of
|
| 242 |
+
ingredients drawn from the ``AromaRegistry``. Every candidate is passed
|
| 243 |
+
through the PINO physical verifier and IFRA Category 4 restrictions before
|
| 244 |
+
it is scored by the PIMT critic.
|
| 245 |
+
|
| 246 |
+
Why CMA-ES instead of a generative model?
|
| 247 |
+
-----------------------------------------
|
| 248 |
+
Generative models (VAEs, GANs, diffusion) are excellent at sampling smooth
|
| 249 |
+
manifolds, but fragrance formulation is a constrained combinatorial problem:
|
| 250 |
+
weight fractions must sum to 1.0, IFRA limits are hard thresholds, and the
|
| 251 |
+
physical simulator is expensive and can fail for incompatible combinations.
|
| 252 |
+
CMA-ES handles these constraints via rejection/projection, adapts its search
|
| 253 |
+
covariance to the local landscape, and naturally supports sparse palettes.
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
def __init__(self, config: OptimizerConfig | None = None) -> None:
|
| 257 |
+
self.config = config or OptimizerConfig()
|
| 258 |
+
self.resolver = IngredientResolver()
|
| 259 |
+
self.embedding_engine = OlfactoryEmbeddingEngine(use_fallback=True)
|
| 260 |
+
self.verifier = FragrancePipelineVerifier(
|
| 261 |
+
temperature_k=298.15,
|
| 262 |
+
ambient_pressure_pa=101325.0,
|
| 263 |
+
headspace_volume_m3=1e-3,
|
| 264 |
+
liquid_volume_m3=1e-6,
|
| 265 |
+
density_g_ml=0.9,
|
| 266 |
+
surface_area_m2=1e-4,
|
| 267 |
+
mass_transfer_coefficient=1e-4,
|
| 268 |
+
)
|
| 269 |
+
self.palette: list[Ingredient] = []
|
| 270 |
+
self.palette_cas: list[str] = []
|
| 271 |
+
self._rng = np.random.default_rng(self.config.seed)
|
| 272 |
+
if self.config.seed is not None:
|
| 273 |
+
random.seed(self.config.seed)
|
| 274 |
+
torch.manual_seed(self.config.seed)
|
| 275 |
+
|
| 276 |
+
def _build_palette(self, count: int = 20) -> None:
|
| 277 |
+
"""
|
| 278 |
+
Select a diverse palette from the SQLite registry.
|
| 279 |
+
|
| 280 |
+
We prefer well-known fragrance materials with low molecular weight and
|
| 281 |
+
moderate volatility, because these are the ingredients most likely to
|
| 282 |
+
produce a realistic dry-down. The palette is built once per optimizer
|
| 283 |
+
instance and reused for all CMA-ES iterations.
|
| 284 |
+
"""
|
| 285 |
+
import sqlite3
|
| 286 |
+
|
| 287 |
+
path = Path(self.config.registry_path) if self.config.registry_path else Path(__file__).with_suffix(".db")
|
| 288 |
+
conn = sqlite3.connect(path)
|
| 289 |
+
conn.row_factory = sqlite3.Row
|
| 290 |
+
|
| 291 |
+
# Pull candidates with reasonable volatility and a canonical SMILES.
|
| 292 |
+
rows = conn.execute(
|
| 293 |
+
"""
|
| 294 |
+
SELECT cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa, logp
|
| 295 |
+
FROM aroma_chemicals
|
| 296 |
+
WHERE molecular_weight BETWEEN 50 AND 300
|
| 297 |
+
AND vapor_pressure_pa IS NOT NULL
|
| 298 |
+
AND vapor_pressure_pa > 0
|
| 299 |
+
ORDER BY molecular_weight ASC
|
| 300 |
+
LIMIT ?
|
| 301 |
+
""",
|
| 302 |
+
(count * 4,),
|
| 303 |
+
).fetchall()
|
| 304 |
+
conn.close()
|
| 305 |
+
|
| 306 |
+
candidates: list[Ingredient] = []
|
| 307 |
+
for row in rows:
|
| 308 |
+
try:
|
| 309 |
+
ing = self.resolver.resolve(
|
| 310 |
+
str(row["cas"]),
|
| 311 |
+
weight_fraction=0.0,
|
| 312 |
+
name=row["name"],
|
| 313 |
+
)
|
| 314 |
+
candidates.append(ing)
|
| 315 |
+
except Exception as exc:
|
| 316 |
+
logger.debug("Skipping palette candidate %s: %s", row["cas"], exc)
|
| 317 |
+
continue
|
| 318 |
+
|
| 319 |
+
# Shuffle and downsample to the requested count for variety.
|
| 320 |
+
indices = self._rng.choice(len(candidates), size=min(count, len(candidates)), replace=False)
|
| 321 |
+
self.palette = [candidates[i] for i in indices]
|
| 322 |
+
self.palette_cas = [ing.cas for ing in self.palette]
|
| 323 |
+
logger.info(
|
| 324 |
+
"Built palette of %d ingredients from %d registry candidates",
|
| 325 |
+
len(self.palette),
|
| 326 |
+
len(candidates),
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
def _restrict_palette(self) -> None:
|
| 330 |
+
"""Apply the renewable/synthetic restriction if configured."""
|
| 331 |
+
if self.config.allow_synthetic:
|
| 332 |
+
return
|
| 333 |
+
|
| 334 |
+
non_renewable = {
|
| 335 |
+
"84-66-2", # Diethyl phthalate
|
| 336 |
+
"131-11-3", # Dimethyl phthalate
|
| 337 |
+
"81-14-1", # Musk ketone
|
| 338 |
+
"83-66-9", # Musk ambrette
|
| 339 |
+
"81-15-2", # Musk xylene
|
| 340 |
+
"105-95-3", # Ethylene brassylate
|
| 341 |
+
}
|
| 342 |
+
self.palette = [ing for ing in self.palette if ing.cas not in non_renewable]
|
| 343 |
+
self.palette_cas = [ing.cas for ing in self.palette]
|
| 344 |
+
logger.info("Restricted palette to %d renewable ingredients", len(self.palette))
|
| 345 |
+
|
| 346 |
+
def _project_and_normalize(self, x: np.ndarray) -> np.ndarray:
|
| 347 |
+
"""
|
| 348 |
+
Project a raw CMA-ES vector to a feasible weight-fraction simplex.
|
| 349 |
+
|
| 350 |
+
Steps:
|
| 351 |
+
1. Clip to [0, 1] and zero out negligible components (promotes sparsity).
|
| 352 |
+
2. Enforce IFRA Category 4 limits by capping each ingredient at its
|
| 353 |
+
maximum allowed concentration.
|
| 354 |
+
3. Re-normalize so the vector sums to exactly 1.0.
|
| 355 |
+
|
| 356 |
+
This projection is cheap and keeps the search inside the safe region.
|
| 357 |
+
CMA-ES therefore only ever evaluates physically meaningful recipes.
|
| 358 |
+
"""
|
| 359 |
+
x = np.clip(x, 0.0, 1.0)
|
| 360 |
+
x[x < self.config.min_weight_fraction] = 0.0
|
| 361 |
+
|
| 362 |
+
# IFRA limit projection: each component cannot exceed its Category 4 limit.
|
| 363 |
+
for i, ing in enumerate(self.palette):
|
| 364 |
+
restriction = IFRA_RESTRICTIONS.get(ing.cas)
|
| 365 |
+
if restriction:
|
| 366 |
+
limit_fraction = restriction["category_4_pct"] / 100.0
|
| 367 |
+
x[i] = min(x[i], limit_fraction)
|
| 368 |
+
|
| 369 |
+
total = x.sum()
|
| 370 |
+
if total > 0:
|
| 371 |
+
x = x / total
|
| 372 |
+
else:
|
| 373 |
+
# Fallback: uniform distribution if the projection collapses.
|
| 374 |
+
x = np.ones_like(x) / len(x)
|
| 375 |
+
return x
|
| 376 |
+
|
| 377 |
+
def _evaluate(self, x: np.ndarray, target: CompositionTarget) -> Candidate:
|
| 378 |
+
"""
|
| 379 |
+
Evaluate one candidate weight vector against the target.
|
| 380 |
+
|
| 381 |
+
The pipeline is intentionally defensive:
|
| 382 |
+
1. Project to a feasible simplex.
|
| 383 |
+
2. Build a minimal formula record and run the physical verifier.
|
| 384 |
+
3. If the formula is rejected or depleted, return a penalised fitness.
|
| 385 |
+
4. Otherwise encode the candidate for the PIMT critic and compute MSE.
|
| 386 |
+
5. Return the candidate with its prediction and fitness.
|
| 387 |
+
"""
|
| 388 |
+
weights = self._project_and_normalize(x)
|
| 389 |
+
formula_records = [
|
| 390 |
+
{"cas": ing.cas, "weight_fraction": float(wf)}
|
| 391 |
+
for ing, wf in zip(self.palette, weights)
|
| 392 |
+
if wf >= self.config.min_weight_fraction
|
| 393 |
+
]
|
| 394 |
+
|
| 395 |
+
if len(formula_records) < 2:
|
| 396 |
+
return Candidate(
|
| 397 |
+
ingredients=self.palette,
|
| 398 |
+
weight_fractions=weights,
|
| 399 |
+
status="rejected",
|
| 400 |
+
ifra_report={"passed": False, "violations": [], "max_usage": []},
|
| 401 |
+
fitness=self.config.infeasible_fitness,
|
| 402 |
+
message="Too few ingredients",
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# Physical / IFRA verification.
|
| 406 |
+
result = self.verifier.run_sim(
|
| 407 |
+
formula_records,
|
| 408 |
+
duration_seconds=self.config.duration_seconds,
|
| 409 |
+
interval_seconds=self.config.interval_seconds,
|
| 410 |
+
)
|
| 411 |
+
if result["status"] in ("rejected", Status.REJECTED):
|
| 412 |
+
return Candidate(
|
| 413 |
+
ingredients=self.palette,
|
| 414 |
+
weight_fractions=weights,
|
| 415 |
+
status="rejected",
|
| 416 |
+
ifra_report=result["ifra_report"],
|
| 417 |
+
fitness=self.config.infeasible_fitness,
|
| 418 |
+
message=result["message"],
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
# Encode for the PIMT critic.
|
| 422 |
+
try:
|
| 423 |
+
prediction = self._predict(formula_records, result["trajectory"])
|
| 424 |
+
except Exception as exc:
|
| 425 |
+
logger.warning("Prediction failed for candidate: %s", exc)
|
| 426 |
+
return Candidate(
|
| 427 |
+
ingredients=self.palette,
|
| 428 |
+
weight_fractions=weights,
|
| 429 |
+
status=result["status"],
|
| 430 |
+
ifra_report=result["ifra_report"],
|
| 431 |
+
fitness=self.config.infeasible_fitness,
|
| 432 |
+
trajectory=result["trajectory"],
|
| 433 |
+
message=f"Prediction error: {exc}",
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
mse = self._mse(prediction, target)
|
| 437 |
+
fitness = mse if mse > 0 else 1e-12
|
| 438 |
+
|
| 439 |
+
return Candidate(
|
| 440 |
+
ingredients=self.palette,
|
| 441 |
+
weight_fractions=weights,
|
| 442 |
+
status=result["status"],
|
| 443 |
+
ifra_report=result["ifra_report"],
|
| 444 |
+
fitness=fitness,
|
| 445 |
+
prediction=prediction,
|
| 446 |
+
trajectory=result["trajectory"],
|
| 447 |
+
message=result["message"],
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
def _predict(
|
| 451 |
+
self,
|
| 452 |
+
formula_records: list[dict[str, Any]],
|
| 453 |
+
trajectory: list[dict[str, Any]],
|
| 454 |
+
) -> dict[str, Any]:
|
| 455 |
+
"""
|
| 456 |
+
Build a lightweight formula payload and query the PIMT critic.
|
| 457 |
+
|
| 458 |
+
We intentionally reuse the cloud inference client so that the composer can
|
| 459 |
+
run against a local CPU fallback or the private HF Space endpoint without
|
| 460 |
+
code changes. For pure local optimisation, this falls back to loading the
|
| 461 |
+
model from ``mattbitzesty/pino-pimt``.
|
| 462 |
+
"""
|
| 463 |
+
formula_payload = {
|
| 464 |
+
"formula": formula_records,
|
| 465 |
+
"trajectory": trajectory,
|
| 466 |
+
"metadata": {"generation_strategy": "wildcard"},
|
| 467 |
+
}
|
| 468 |
+
return predict_cloud(formula_payload, token=self.config.token)
|
| 469 |
+
|
| 470 |
+
def _mse(self, prediction: dict[str, Any], target: CompositionTarget) -> float:
|
| 471 |
+
"""
|
| 472 |
+
Compute a weighted mean-squared-error loss between prediction and target.
|
| 473 |
+
"""
|
| 474 |
+
errors = []
|
| 475 |
+
|
| 476 |
+
if target.objective is not None and "objective" in prediction:
|
| 477 |
+
pred_obj = np.array(prediction["objective"], dtype=np.float32)
|
| 478 |
+
if pred_obj.ndim == 3:
|
| 479 |
+
pred_obj = pred_obj[0]
|
| 480 |
+
tgt_obj = target.objective
|
| 481 |
+
if tgt_obj.ndim == 1:
|
| 482 |
+
tgt_obj = np.tile(tgt_obj, (pred_obj.shape[0], 1))
|
| 483 |
+
obj_error = float(np.mean((pred_obj - tgt_obj) ** 2))
|
| 484 |
+
errors.append(target.weight_objective * obj_error)
|
| 485 |
+
|
| 486 |
+
if target.subjective is not None and "subjective" in prediction:
|
| 487 |
+
pred_sub = np.array(prediction["subjective"], dtype=np.float32)
|
| 488 |
+
if pred_sub.ndim == 2:
|
| 489 |
+
pred_sub = pred_sub[0]
|
| 490 |
+
sub_error = float(np.mean((pred_sub - target.subjective) ** 2))
|
| 491 |
+
errors.append(target.weight_subjective * sub_error)
|
| 492 |
+
|
| 493 |
+
if not errors:
|
| 494 |
+
return self.config.infeasible_fitness
|
| 495 |
+
return float(np.mean(errors))
|
| 496 |
+
|
| 497 |
+
def optimize(
|
| 498 |
+
self,
|
| 499 |
+
target: CompositionTarget,
|
| 500 |
+
palette_size: int = 20,
|
| 501 |
+
initial_guess: np.ndarray | None = None,
|
| 502 |
+
progress_callback: Callable[[int, float, Candidate], None] | None = None,
|
| 503 |
+
) -> Candidate:
|
| 504 |
+
"""
|
| 505 |
+
Run the evolutionary search and return the best compliant candidate.
|
| 506 |
+
|
| 507 |
+
Parameters
|
| 508 |
+
----------
|
| 509 |
+
target: CompositionTarget
|
| 510 |
+
Desired sensory profile.
|
| 511 |
+
palette_size: int
|
| 512 |
+
Number of ingredients to draw from the registry.
|
| 513 |
+
initial_guess: np.ndarray | None
|
| 514 |
+
Optional starting point on the simplex. If None, a uniform mixture is
|
| 515 |
+
used as the CMA-ES centroid.
|
| 516 |
+
progress_callback: callable | None
|
| 517 |
+
Optional function ``(iteration, fitness, best_candidate) -> None`` called
|
| 518 |
+
after each generation. The CLI uses this to print progress to stderr.
|
| 519 |
+
|
| 520 |
+
Returns
|
| 521 |
+
-------
|
| 522 |
+
Candidate
|
| 523 |
+
The best feasible formula found, including its trajectory and prediction.
|
| 524 |
+
"""
|
| 525 |
+
self._build_palette(palette_size)
|
| 526 |
+
self._restrict_palette()
|
| 527 |
+
|
| 528 |
+
n = len(self.palette)
|
| 529 |
+
if n == 0:
|
| 530 |
+
raise RuntimeError("Palette is empty; cannot optimise")
|
| 531 |
+
|
| 532 |
+
x0 = initial_guess if initial_guess is not None else np.ones(n) / n
|
| 533 |
+
x0 = self._project_and_normalize(x0)
|
| 534 |
+
|
| 535 |
+
# CMA-ES minimises the objective; lower MSE = higher fitness.
|
| 536 |
+
es = CMAEvolutionStrategy(
|
| 537 |
+
x0=x0,
|
| 538 |
+
sigma0=self.config.sigma0,
|
| 539 |
+
inopts={"popsize": self.config.popsize, "verbose": -9},
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
best: Candidate | None = None
|
| 543 |
+
iteration = 0
|
| 544 |
+
|
| 545 |
+
while not es.stop() and iteration < self.config.max_iterations:
|
| 546 |
+
solutions = es.ask()
|
| 547 |
+
fitness_values: list[float] = []
|
| 548 |
+
|
| 549 |
+
for x in solutions:
|
| 550 |
+
candidate = self._evaluate(x, target)
|
| 551 |
+
fitness_values.append(candidate.fitness)
|
| 552 |
+
|
| 553 |
+
if best is None or candidate.fitness < best.fitness:
|
| 554 |
+
best = candidate
|
| 555 |
+
|
| 556 |
+
es.tell(solutions, fitness_values)
|
| 557 |
+
iteration += 1
|
| 558 |
+
|
| 559 |
+
if self.config.verbose > 0 and iteration % 10 == 0:
|
| 560 |
+
logger.info(
|
| 561 |
+
"Iteration %d / %d: best fitness (MSE) = %.6f",
|
| 562 |
+
iteration,
|
| 563 |
+
self.config.max_iterations,
|
| 564 |
+
best.fitness if best else float("inf"),
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
if progress_callback:
|
| 568 |
+
progress_callback(iteration, best.fitness if best else float("inf"), best)
|
| 569 |
+
|
| 570 |
+
if best is None:
|
| 571 |
+
raise RuntimeError("Optimization failed to produce any feasible candidate")
|
| 572 |
+
|
| 573 |
+
# Re-run the best candidate to capture a full prediction/trajectory if it
|
| 574 |
+
# was produced by an infeasible placeholder during the first iteration.
|
| 575 |
+
best = self._evaluate(best.weight_fractions, target)
|
| 576 |
+
return best
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
# ---------------------------------------------------------------------------
|
| 580 |
+
# Convenience helpers for natural-language / JSON brief entry points.
|
| 581 |
+
# ---------------------------------------------------------------------------
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def compose_from_text(
|
| 585 |
+
brief: str,
|
| 586 |
+
*,
|
| 587 |
+
max_iterations: int = 500,
|
| 588 |
+
allow_synthetic: bool = True,
|
| 589 |
+
palette_size: int = 20,
|
| 590 |
+
verbose: int = 1,
|
| 591 |
+
seed: int | None = None,
|
| 592 |
+
) -> dict[str, Any]:
|
| 593 |
+
"""
|
| 594 |
+
High-level helper: compose a formula from a natural-language brief.
|
| 595 |
+
|
| 596 |
+
Returns a JSON-serialisable dict with the optimised formula, status, fitness,
|
| 597 |
+
and a short human-readable message.
|
| 598 |
+
"""
|
| 599 |
+
target = CompositionTarget.from_text(brief)
|
| 600 |
+
config = OptimizerConfig(
|
| 601 |
+
max_iterations=max_iterations,
|
| 602 |
+
allow_synthetic=allow_synthetic,
|
| 603 |
+
seed=seed,
|
| 604 |
+
verbose=verbose,
|
| 605 |
+
)
|
| 606 |
+
optimizer = FormulationOptimizer(config)
|
| 607 |
+
best = optimizer.optimize(target, palette_size=palette_size)
|
| 608 |
+
|
| 609 |
+
return {
|
| 610 |
+
"brief": brief,
|
| 611 |
+
"target": target.name,
|
| 612 |
+
"formula": best.to_formula_dict(),
|
| 613 |
+
"status": best.status,
|
| 614 |
+
"fitness": best.fitness,
|
| 615 |
+
"ifra_passed": best.ifra_report.get("passed", False),
|
| 616 |
+
"message": best.message,
|
| 617 |
+
}
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def compose_from_json(
|
| 621 |
+
path: str | Path,
|
| 622 |
+
*,
|
| 623 |
+
max_iterations: int = 500,
|
| 624 |
+
allow_synthetic: bool = True,
|
| 625 |
+
palette_size: int = 20,
|
| 626 |
+
verbose: int = 1,
|
| 627 |
+
seed: int | None = None,
|
| 628 |
+
) -> dict[str, Any]:
|
| 629 |
+
"""High-level helper: compose a formula from a JSON target brief."""
|
| 630 |
+
target = CompositionTarget.from_json(path)
|
| 631 |
+
config = OptimizerConfig(
|
| 632 |
+
max_iterations=max_iterations,
|
| 633 |
+
allow_synthetic=allow_synthetic,
|
| 634 |
+
seed=seed,
|
| 635 |
+
verbose=verbose,
|
| 636 |
+
)
|
| 637 |
+
optimizer = FormulationOptimizer(config)
|
| 638 |
+
best = optimizer.optimize(target, palette_size=palette_size)
|
| 639 |
+
|
| 640 |
+
return {
|
| 641 |
+
"target": target.name,
|
| 642 |
+
"formula": best.to_formula_dict(),
|
| 643 |
+
"status": best.status,
|
| 644 |
+
"fitness": best.fitness,
|
| 645 |
+
"ifra_passed": best.ifra_report.get("passed", False),
|
| 646 |
+
"message": best.message,
|
| 647 |
+
}
|