Commit ·
b233cf7
0
Parent(s):
feat: Milestone 4 clean code snapshot
Browse files- .gitignore +13 -0
- README.md +35 -0
- pyproject.toml +31 -0
- scripts/build_registry.py +184 -0
- src/pino/__init__.py +5 -0
- src/pino/__main__.py +13 -0
- src/pino/cli.py +116 -0
- src/pino/dataset_builder.py +255 -0
- src/pino/draft_engine.py +318 -0
- src/pino/embeddings.py +87 -0
- src/pino/evaporation.py +213 -0
- src/pino/factory.py +94 -0
- src/pino/feedback.py +179 -0
- src/pino/heads.py +78 -0
- src/pino/ifra.py +111 -0
- src/pino/inference_cloud.py +137 -0
- src/pino/models.py +108 -0
- src/pino/palette_expander.py +188 -0
- src/pino/pimt_model.py +207 -0
- src/pino/pimt_model_hf.py +180 -0
- src/pino/predict.py +70 -0
- src/pino/registry.py +381 -0
- src/pino/semantics.py +149 -0
- src/pino/structures.py +152 -0
- src/pino/synthetic.py +229 -0
- src/pino/train.py +315 -0
- src/pino/train_hf.py +130 -0
- src/pino/unifac_mapping.py +70 -0
- src/pino/verifier.py +223 -0
- src/pino/vle.py +106 -0
- tests/test_factory.py +97 -0
- tests/test_pimt_invariance.py +92 -0
- tests/test_pino.py +199 -0
- tests/test_synthetic.py +87 -0
- tests/test_verifier_pipeline.py +60 -0
.gitignore
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
*.egg-info/
|
| 5 |
+
dist/
|
| 6 |
+
build/
|
| 7 |
+
.eggs/
|
| 8 |
+
*.whl
|
| 9 |
+
.pytest_cache/
|
| 10 |
+
*.json
|
| 11 |
+
!.gitkeep
|
| 12 |
+
*.jsonl
|
| 13 |
+
*.parquet
|
README.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PINO — Physics-Informed Neural Olfaction
|
| 2 |
+
|
| 3 |
+
Foundational thermodynamic engine and evaporation verifier for time-resolved fragrance evaluation.
|
| 4 |
+
|
| 5 |
+
## Milestone 1: Thermodynamic Engine & Synthetic Formula Verifier
|
| 6 |
+
|
| 7 |
+
- `src/pino/structures.py` — RDKit/ugropy structure handling and UNIFAC group extraction.
|
| 8 |
+
- `src/pino/vle.py` — Dortmund-Modified UNIFAC activity coefficients and non-ideal VLE.
|
| 9 |
+
- `src/pino/evaporation.py` — Stiff ODE evaporation kinetics via `scipy.integrate`.
|
| 10 |
+
- `src/pino/verifier.py` — High-level verifier producing `trajectory_output.json`.
|
| 11 |
+
- `src/pino/models.py` — Pydantic/dataclass domain models.
|
| 12 |
+
- `tests/test_pino.py` — Passing pytest suite for the classic 5-component accord in ethanol.
|
| 13 |
+
|
| 14 |
+
## Run the test suite
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
cd /home/hermes/pino
|
| 18 |
+
source .venv/bin/activate
|
| 19 |
+
python -m pytest tests/ -v
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
## Generate the deterministic trajectory artifact
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
cd /home/hermes/pino
|
| 26 |
+
source .venv/bin/activate
|
| 27 |
+
PYTHONPATH=src python -c "from pino.verifier import verify_formula_dict; import json, numpy as np; ..."
|
| 28 |
+
```
|
| 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.
|
| 35 |
+
- Evaporation kinetics are solved with **scipy stiff integration** (`BDF`), not fixed Euler.
|
pyproject.toml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["hatchling"]
|
| 3 |
+
build-backend = "hatchling.build"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "pino"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "Physics-Informed Neural Olfaction (PINO) — thermodynamic fragrance evaporation verifier"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.11"
|
| 11 |
+
dependencies = [
|
| 12 |
+
"rdkit>=2024.0",
|
| 13 |
+
"scipy>=1.12",
|
| 14 |
+
"thermo>=0.6",
|
| 15 |
+
"ugropy>=3.2",
|
| 16 |
+
"pydantic>=2.0",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
[project.optional-dependencies]
|
| 20 |
+
dev = ["pytest>=8.0"]
|
| 21 |
+
|
| 22 |
+
[project.scripts]
|
| 23 |
+
pino = "pino.__main__:main"
|
| 24 |
+
pino-critic = "pino.cli:main"
|
| 25 |
+
|
| 26 |
+
[tool.hatch.build.targets.wheel]
|
| 27 |
+
packages = ["src/pino"]
|
| 28 |
+
|
| 29 |
+
[tool.pytest.ini_options]
|
| 30 |
+
testpaths = ["tests"]
|
| 31 |
+
pythonpath = ["src"]
|
scripts/build_registry.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 8 |
+
|
| 9 |
+
from pino.registry import AromaRegistry
|
| 10 |
+
|
| 11 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 12 |
+
logger = logging.getLogger("build_registry")
|
| 13 |
+
|
| 14 |
+
# Curated list of ~150 common fragrance materials. Approximate room-temperature
|
| 15 |
+
# vapor pressures (Pa), boiling points (K), and odor thresholds (ug/m3) are
|
| 16 |
+
# literature estimates. Natural oils are included as multi-component entries;
|
| 17 |
+
# they may fail fragmentation, which is acceptable because the registry
|
| 18 |
+
# builder skips unresolvable entries.
|
| 19 |
+
AROMA_CHEMICALS = [
|
| 20 |
+
# Solvents / carriers
|
| 21 |
+
{"cas": "64-17-5", "vapor_pressure_pa": 7900.0, "boiling_point_k": 351.45, "odor_threshold_ug_m3": 250000.0},
|
| 22 |
+
{"cas": "67-63-0", "vapor_pressure_pa": 5700.0, "boiling_point_k": 355.5, "odor_threshold_ug_m3": 400000.0},
|
| 23 |
+
{"cas": "25265-71-8", "vapor_pressure_pa": 1.0, "boiling_point_k": 503.0, "odor_threshold_ug_m3": 5000.0},
|
| 24 |
+
{"cas": "120-51-4", "vapor_pressure_pa": 0.02, "boiling_point_k": 597.0, "odor_threshold_ug_m3": 50.0},
|
| 25 |
+
{"cas": "84-66-2", "vapor_pressure_pa": 0.002, "boiling_point_k": 568.0, "odor_threshold_ug_m3": 100.0},
|
| 26 |
+
# Citrus / terpenes
|
| 27 |
+
{"cas": "5989-27-5", "vapor_pressure_pa": 195.0, "boiling_point_k": 449.0, "odor_threshold_ug_m3": 30.0},
|
| 28 |
+
{"cas": "138-86-3", "vapor_pressure_pa": 195.0, "boiling_point_k": 449.0, "odor_threshold_ug_m3": 30.0},
|
| 29 |
+
{"cas": "5392-40-5", "vapor_pressure_pa": 25.0, "boiling_point_k": 501.0, "odor_threshold_ug_m3": 5.0},
|
| 30 |
+
{"cas": "106-24-1", "vapor_pressure_pa": 2.0, "boiling_point_k": 503.0, "odor_threshold_ug_m3": 10.0},
|
| 31 |
+
{"cas": "106-25-2", "vapor_pressure_pa": 2.0, "boiling_point_k": 503.0, "odor_threshold_ug_m3": 10.0},
|
| 32 |
+
{"cas": "106-22-9", "vapor_pressure_pa": 1.0, "boiling_point_k": 493.0, "odor_threshold_ug_m3": 5.0},
|
| 33 |
+
{"cas": "624-15-7", "vapor_pressure_pa": 1.5, "boiling_point_k": 503.0, "odor_threshold_ug_m3": 10.0},
|
| 34 |
+
{"cas": "111-71-7", "vapor_pressure_pa": 12.0, "boiling_point_k": 477.0, "odor_threshold_ug_m3": 10.0},
|
| 35 |
+
{"cas": "99-85-4", "vapor_pressure_pa": 160.0, "boiling_point_k": 446.0, "odor_threshold_ug_m3": 50.0},
|
| 36 |
+
{"cas": "68647-72-3", "vapor_pressure_pa": 55.0, "boiling_point_k": 453.0, "odor_threshold_ug_m3": 30.0},
|
| 37 |
+
{"cas": "93-58-3", "vapor_pressure_pa": 14.0, "boiling_point_k": 472.0, "odor_threshold_ug_m3": 10.0},
|
| 38 |
+
{"cas": "115-95-7", "vapor_pressure_pa": 0.1, "boiling_point_k": 498.0, "odor_threshold_ug_m3": 1.0},
|
| 39 |
+
{"cas": "105-87-3", "vapor_pressure_pa": 1.0, "boiling_point_k": 493.0, "odor_threshold_ug_m3": 5.0},
|
| 40 |
+
{"cas": "150-84-5", "vapor_pressure_pa": 1.0, "boiling_point_k": 493.0, "odor_threshold_ug_m3": 5.0},
|
| 41 |
+
{"cas": "140-11-4", "vapor_pressure_pa": 2.0, "boiling_point_k": 486.0, "odor_threshold_ug_m3": 10.0},
|
| 42 |
+
{"cas": "103-45-7", "vapor_pressure_pa": 0.5, "boiling_point_k": 499.0, "odor_threshold_ug_m3": 5.0},
|
| 43 |
+
# Floral alcohols / aldehydes
|
| 44 |
+
{"cas": "78-70-6", "vapor_pressure_pa": 22.0, "boiling_point_k": 471.0, "odor_threshold_ug_m3": 6.0},
|
| 45 |
+
{"cas": "60-12-8", "vapor_pressure_pa": 3.0, "boiling_point_k": 488.0, "odor_threshold_ug_m3": 10.0},
|
| 46 |
+
{"cas": "100-51-6", "vapor_pressure_pa": 5.0, "boiling_point_k": 478.0, "odor_threshold_ug_m3": 20.0},
|
| 47 |
+
{"cas": "104-54-1", "vapor_pressure_pa": 1.0, "boiling_point_k": 516.0, "odor_threshold_ug_m3": 10.0},
|
| 48 |
+
{"cas": "104-55-2", "vapor_pressure_pa": 2.0, "boiling_point_k": 531.0, "odor_threshold_ug_m3": 5.0},
|
| 49 |
+
{"cas": "124-13-0", "vapor_pressure_pa": 120.0, "boiling_point_k": 421.0, "odor_threshold_ug_m3": 50.0},
|
| 50 |
+
{"cas": "112-31-2", "vapor_pressure_pa": 18.0, "boiling_point_k": 480.0, "odor_threshold_ug_m3": 10.0},
|
| 51 |
+
{"cas": "112-54-9", "vapor_pressure_pa": 1.5, "boiling_point_k": 520.0, "odor_threshold_ug_m3": 1.0},
|
| 52 |
+
{"cas": "122-40-7", "vapor_pressure_pa": 0.8, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 1.0},
|
| 53 |
+
{"cas": "101-86-0", "vapor_pressure_pa": 0.1, "boiling_point_k": 548.0, "odor_threshold_ug_m3": 0.5},
|
| 54 |
+
{"cas": "80-54-6", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 1.0},
|
| 55 |
+
{"cas": "31906-04-4", "vapor_pressure_pa": 0.05, "boiling_point_k": 533.0, "odor_threshold_ug_m3": 0.5},
|
| 56 |
+
# Jasmine / muguet / ionones
|
| 57 |
+
{"cas": "24851-98-7", "vapor_pressure_pa": 1.2, "boiling_point_k": 548.0, "odor_threshold_ug_m3": 1.0},
|
| 58 |
+
{"cas": "1211-29-0", "vapor_pressure_pa": 0.05, "boiling_point_k": 573.0, "odor_threshold_ug_m3": 0.2},
|
| 59 |
+
{"cas": "18871-14-9", "vapor_pressure_pa": 0.3, "boiling_point_k": 573.0, "odor_threshold_ug_m3": 0.5},
|
| 60 |
+
{"cas": "127-41-3", "vapor_pressure_pa": 0.2, "boiling_point_k": 518.0, "odor_threshold_ug_m3": 0.5},
|
| 61 |
+
{"cas": "14901-07-6", "vapor_pressure_pa": 0.2, "boiling_point_k": 518.0, "odor_threshold_ug_m3": 0.5},
|
| 62 |
+
{"cas": "127-51-5", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 0.3},
|
| 63 |
+
{"cas": "1335-46-2", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 0.3},
|
| 64 |
+
{"cas": "23726-91-0", "vapor_pressure_pa": 0.05, "boiling_point_k": 533.0, "odor_threshold_ug_m3": 0.1},
|
| 65 |
+
{"cas": "43052-87-5", "vapor_pressure_pa": 0.05, "boiling_point_k": 533.0, "odor_threshold_ug_m3": 0.1},
|
| 66 |
+
{"cas": "706-14-9", "vapor_pressure_pa": 1.0, "boiling_point_k": 450.0, "odor_threshold_ug_m3": 5.0},
|
| 67 |
+
{"cas": "713-95-1", "vapor_pressure_pa": 0.2, "boiling_point_k": 478.0, "odor_threshold_ug_m3": 1.0},
|
| 68 |
+
# Musks
|
| 69 |
+
{"cas": "1222-05-5", "vapor_pressure_pa": 0.05, "boiling_point_k": 623.0, "odor_threshold_ug_m3": 0.1},
|
| 70 |
+
{"cas": "21145-77-7", "vapor_pressure_pa": 0.01, "boiling_point_k": 593.0, "odor_threshold_ug_m3": 0.05},
|
| 71 |
+
{"cas": "6790-58-5", "vapor_pressure_pa": 0.01, "boiling_point_k": 573.0, "odor_threshold_ug_m3": 0.02},
|
| 72 |
+
{"cas": "54464-57-2", "vapor_pressure_pa": 0.01, "boiling_point_k": 573.0, "odor_threshold_ug_m3": 0.05},
|
| 73 |
+
{"cas": "81-14-1", "vapor_pressure_pa": 0.004, "boiling_point_k": 613.0, "odor_threshold_ug_m3": 0.02},
|
| 74 |
+
{"cas": "81-15-2", "vapor_pressure_pa": 0.001, "boiling_point_k": 603.0, "odor_threshold_ug_m3": 0.05},
|
| 75 |
+
{"cas": "105-95-3", "vapor_pressure_pa": 0.003, "boiling_point_k": 573.0, "odor_threshold_ug_m3": 0.02},
|
| 76 |
+
{"cas": "541-91-3", "vapor_pressure_pa": 0.02, "boiling_point_k": 600.0, "odor_threshold_ug_m3": 0.05},
|
| 77 |
+
{"cas": "83-66-9", "vapor_pressure_pa": 0.001, "boiling_point_k": 583.0, "odor_threshold_ug_m3": 0.05},
|
| 78 |
+
# Woods / ambers
|
| 79 |
+
{"cas": "77-53-2", "vapor_pressure_pa": 0.5, "boiling_point_k": 549.0, "odor_threshold_ug_m3": 1.0},
|
| 80 |
+
{"cas": "77-42-9", "vapor_pressure_pa": 0.3, "boiling_point_k": 553.0, "odor_threshold_ug_m3": 1.0},
|
| 81 |
+
{"cas": "19870-74-7", "vapor_pressure_pa": 0.05, "boiling_point_k": 563.0, "odor_threshold_ug_m3": 0.5},
|
| 82 |
+
{"cas": "32388-55-9", "vapor_pressure_pa": 0.05, "boiling_point_k": 563.0, "odor_threshold_ug_m3": 0.5},
|
| 83 |
+
{"cas": "33704-61-9", "vapor_pressure_pa": 0.01, "boiling_point_k": 573.0, "odor_threshold_ug_m3": 0.2},
|
| 84 |
+
{"cas": "198404-98-7", "vapor_pressure_pa": 0.005, "boiling_point_k": 583.0, "odor_threshold_ug_m3": 0.1},
|
| 85 |
+
{"cas": "115-71-9", "vapor_pressure_pa": 1.5, "boiling_point_k": 477.0, "odor_threshold_ug_m3": 5.0},
|
| 86 |
+
{"cas": "87-44-5", "vapor_pressure_pa": 6.0, "boiling_point_k": 447.0, "odor_threshold_ug_m3": 10.0},
|
| 87 |
+
# Spicy / gourmand
|
| 88 |
+
{"cas": "97-53-0", "vapor_pressure_pa": 2.0, "boiling_point_k": 527.0, "odor_threshold_ug_m3": 5.0},
|
| 89 |
+
{"cas": "97-54-1", "vapor_pressure_pa": 0.5, "boiling_point_k": 543.0, "odor_threshold_ug_m3": 1.0},
|
| 90 |
+
{"cas": "121-33-5", "vapor_pressure_pa": 0.01, "boiling_point_k": 558.0, "odor_threshold_ug_m3": 0.2},
|
| 91 |
+
{"cas": "91-64-5", "vapor_pressure_pa": 0.05, "boiling_point_k": 574.0, "odor_threshold_ug_m3": 0.5},
|
| 92 |
+
{"cas": "120-57-0", "vapor_pressure_pa": 0.1, "boiling_point_k": 531.0, "odor_threshold_ug_m3": 1.0},
|
| 93 |
+
{"cas": "119-36-8", "vapor_pressure_pa": 8.0, "boiling_point_k": 449.0, "odor_threshold_ug_m3": 50.0},
|
| 94 |
+
{"cas": "118-58-1", "vapor_pressure_pa": 0.01, "boiling_point_k": 586.0, "odor_threshold_ug_m3": 5.0},
|
| 95 |
+
{"cas": "90-05-1", "vapor_pressure_pa": 5.0, "boiling_point_k": 477.0, "odor_threshold_ug_m3": 10.0},
|
| 96 |
+
{"cas": "120-72-9", "vapor_pressure_pa": 0.5, "boiling_point_k": 540.0, "odor_threshold_ug_m3": 0.5},
|
| 97 |
+
{"cas": "83-34-1", "vapor_pressure_pa": 0.5, "boiling_point_k": 540.0, "odor_threshold_ug_m3": 0.5},
|
| 98 |
+
{"cas": "134-20-3", "vapor_pressure_pa": 0.05, "boiling_point_k": 546.0, "odor_threshold_ug_m3": 0.5},
|
| 99 |
+
{"cas": "103-82-2", "vapor_pressure_pa": 0.05, "boiling_point_k": 553.0, "odor_threshold_ug_m3": 1.0},
|
| 100 |
+
# Naturals (may fail fragmentation; registry builder will skip them)
|
| 101 |
+
{"cas": "8000-27-9", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 102 |
+
{"cas": "8006-90-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 103 |
+
{"cas": "8008-57-9", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 104 |
+
{"cas": "8008-56-8", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 105 |
+
{"cas": "8007-75-8", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 106 |
+
{"cas": "8000-28-0", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 107 |
+
{"cas": "8014-09-3", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 108 |
+
{"cas": "8016-96-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 109 |
+
{"cas": "8006-87-9", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 110 |
+
{"cas": "8002-73-1", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 111 |
+
{"cas": "8022-96-6", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 112 |
+
{"cas": "8006-81-3", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 113 |
+
{"cas": "8000-46-2", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 114 |
+
{"cas": "8014-17-3", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 115 |
+
{"cas": "8016-38-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 116 |
+
{"cas": "8007-01-0", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 117 |
+
{"cas": "8000-48-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 118 |
+
{"cas": "8000-25-7", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 119 |
+
{"cas": "68647-73-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 120 |
+
{"cas": "8006-78-8", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 121 |
+
{"cas": "8000-34-8", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 122 |
+
{"cas": "8007-08-7", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 123 |
+
{"cas": "8006-84-6", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 124 |
+
{"cas": "8007-70-3", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 125 |
+
{"cas": "8007-02-1", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 126 |
+
{"cas": "8000-29-1", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 127 |
+
{"cas": "8006-75-5", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 128 |
+
{"cas": "8008-31-9", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 129 |
+
{"cas": "8008-79-5", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 130 |
+
{"cas": "8000-66-6", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 131 |
+
{"cas": "8002-66-2", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 132 |
+
{"cas": "8015-91-6", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 133 |
+
{"cas": "8008-45-5", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 134 |
+
{"cas": "8006-82-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 135 |
+
{"cas": "8016-20-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 136 |
+
{"cas": "8008-26-2", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 137 |
+
{"cas": "72968-86-0", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 138 |
+
{"cas": "8015-73-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 139 |
+
{"cas": "8022-56-8", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 140 |
+
{"cas": "8007-46-3", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 141 |
+
{"cas": "8007-11-2", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 142 |
+
{"cas": "8014-71-9", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 143 |
+
{"cas": "8024-12-2", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 144 |
+
{"cas": "68855-99-2", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 145 |
+
{"cas": "68606-83-1", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 146 |
+
{"cas": "8023-91-4", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 147 |
+
{"cas": "8023-89-9", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 148 |
+
{"cas": "8016-36-2", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 149 |
+
{"cas": "8016-37-3", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 150 |
+
{"cas": "8046-42-0", "vapor_pressure_pa": 0.2, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 151 |
+
{"cas": "9000-05-9", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 152 |
+
{"cas": "9000-50-4", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 153 |
+
{"cas": "68606-12-6", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 154 |
+
{"cas": "8024-08-6", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 155 |
+
{"cas": "9000-64-0", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 156 |
+
{"cas": "8007-00-9", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 157 |
+
{"cas": "90045-23-1", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 158 |
+
{"cas": "89958-31-6", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 159 |
+
{"cas": "8023-75-2", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 160 |
+
{"cas": "8031-03-6", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 161 |
+
{"cas": "8024-05-3", "vapor_pressure_pa": 0.1, "boiling_point_k": 523.0, "odor_threshold_ug_m3": 50.0},
|
| 162 |
+
{"cas": "76-22-2", "vapor_pressure_pa": 10.0, "boiling_point_k": 481.0, "odor_threshold_ug_m3": 50.0},
|
| 163 |
+
{"cas": "2216-51-5", "vapor_pressure_pa": 5.0, "boiling_point_k": 489.0, "odor_threshold_ug_m3": 50.0},
|
| 164 |
+
{"cas": "16409-43-1", "vapor_pressure_pa": 0.5, "boiling_point_k": 480.0, "odor_threshold_ug_m3": 5.0},
|
| 165 |
+
{"cas": "6259-76-3", "vapor_pressure_pa": 0.05, "boiling_point_k": 533.0, "odor_threshold_ug_m3": 5.0},
|
| 166 |
+
{"cas": "4602-84-0", "vapor_pressure_pa": 0.001, "boiling_point_k": 543.0, "odor_threshold_ug_m3": 0.5},
|
| 167 |
+
{"cas": "7212-44-4", "vapor_pressure_pa": 0.001, "boiling_point_k": 543.0, "odor_threshold_ug_m3": 0.5},
|
| 168 |
+
{"cas": "515-69-5", "vapor_pressure_pa": 0.001, "boiling_point_k": 543.0, "odor_threshold_ug_m3": 0.5},
|
| 169 |
+
{"cas": "5986-55-0", "vapor_pressure_pa": 0.001, "boiling_point_k": 543.0, "odor_threshold_ug_m3": 0.5},
|
| 170 |
+
{"cas": "515-03-7", "vapor_pressure_pa": 0.001, "boiling_point_k": 543.0, "odor_threshold_ug_m3": 0.5},
|
| 171 |
+
{"cas": "7779-50-2", "vapor_pressure_pa": 0.001, "boiling_point_k": 573.0, "odor_threshold_ug_m3": 0.5},
|
| 172 |
+
{"cas": "104-67-6", "vapor_pressure_pa": 0.3, "boiling_point_k": 480.0, "odor_threshold_ug_m3": 1.0},
|
| 173 |
+
{"cas": "104-61-0", "vapor_pressure_pa": 0.3, "boiling_point_k": 480.0, "odor_threshold_ug_m3": 1.0},
|
| 174 |
+
]
|
| 175 |
+
|
| 176 |
+
logger.info("Starting registry build with %d entries", len(AROMA_CHEMICALS))
|
| 177 |
+
with AromaRegistry() as registry:
|
| 178 |
+
failed = registry.populate(AROMA_CHEMICALS, skip_failures=True)
|
| 179 |
+
count = registry._conn.execute(
|
| 180 |
+
"SELECT COUNT(*) FROM aroma_chemicals"
|
| 181 |
+
).fetchone()[0]
|
| 182 |
+
logger.info("Registry built: %d entries, %d failures", count, len(failed))
|
| 183 |
+
if failed:
|
| 184 |
+
logger.warning("Failed entries: %s", [f["cas"] for f in failed])
|
src/pino/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pino import models, structures, verifier, vle, evaporation
|
| 4 |
+
|
| 5 |
+
__all__ = ["models", "structures", "verifier", "vle", "evaporation"]
|
src/pino/__main__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
"""Entry point for `python -m pino`."""
|
| 4 |
+
|
| 5 |
+
from .factory import main as factory_main
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def main() -> None:
|
| 9 |
+
factory_main()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
main()
|
src/pino/cli.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
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 |
+
|
| 15 |
+
|
| 16 |
+
def _load_formula(path: str) -> dict[str, Any]:
|
| 17 |
+
with Path(path).open("r", encoding="utf-8") as f:
|
| 18 |
+
return json.load(f)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _predict(args: argparse.Namespace) -> int:
|
| 22 |
+
try:
|
| 23 |
+
formula = _load_formula(args.file)
|
| 24 |
+
except Exception as e:
|
| 25 |
+
logger.error("Failed to load formula file: %s", e)
|
| 26 |
+
return 2
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
result = predict_cloud(formula, token=args.token)
|
| 30 |
+
except Exception as e:
|
| 31 |
+
logger.error("Prediction failed: %s", e)
|
| 32 |
+
return 2
|
| 33 |
+
|
| 34 |
+
if args.json_mode:
|
| 35 |
+
print(json.dumps(result, separators=(",", ":"), ensure_ascii=False))
|
| 36 |
+
else:
|
| 37 |
+
print("Predicted note pyramid and psychometrics:")
|
| 38 |
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
| 39 |
+
return 0
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _feedback(args: argparse.Namespace) -> int:
|
| 43 |
+
try:
|
| 44 |
+
critique = Critique(
|
| 45 |
+
formula_id=args.formula_id,
|
| 46 |
+
correct_gender=args.correct_gender,
|
| 47 |
+
correct_notes=json.loads(args.correct_notes) if args.correct_notes else {},
|
| 48 |
+
notes=args.notes or "",
|
| 49 |
+
)
|
| 50 |
+
manager = FeedbackLoopManager()
|
| 51 |
+
manager.append(critique)
|
| 52 |
+
except Exception as e:
|
| 53 |
+
logger.error("Failed to log feedback: %s", e)
|
| 54 |
+
return 2
|
| 55 |
+
|
| 56 |
+
if args.json_mode:
|
| 57 |
+
print(json.dumps({"status": "logged", "formula_id": args.formula_id}, separators=(",", ":")))
|
| 58 |
+
else:
|
| 59 |
+
print(f"Feedback logged for {args.formula_id}")
|
| 60 |
+
return 0
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _sync_flywheel(args: argparse.Namespace) -> int:
|
| 64 |
+
try:
|
| 65 |
+
manager = FeedbackLoopManager()
|
| 66 |
+
result = manager.sync_flywheel(job_config_path=args.job_config)
|
| 67 |
+
except Exception as e:
|
| 68 |
+
logger.error("Sync flywheel failed: %s", e)
|
| 69 |
+
return 2
|
| 70 |
+
|
| 71 |
+
if args.json_mode:
|
| 72 |
+
print(json.dumps(result, separators=(",", ":"), ensure_ascii=False))
|
| 73 |
+
else:
|
| 74 |
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
| 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")
|
| 81 |
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
| 82 |
+
|
| 83 |
+
predict_parser = subparsers.add_parser("predict", help="Run cloud inference on a formula")
|
| 84 |
+
predict_parser.add_argument("--file", required=True, help="Path to formula JSON file")
|
| 85 |
+
predict_parser.add_argument("--json", action="store_true", dest="json_mode", help="Emit raw parseable JSON only")
|
| 86 |
+
predict_parser.set_defaults(func=_predict)
|
| 87 |
+
|
| 88 |
+
feedback_parser = subparsers.add_parser("feedback", help="Log a correction for a recipe")
|
| 89 |
+
feedback_parser.add_argument("--formula_id", required=True)
|
| 90 |
+
feedback_parser.add_argument("--correct_gender", type=float, default=None, help="-1.0 to +1.0")
|
| 91 |
+
feedback_parser.add_argument("--correct_notes", default="{}", help="JSON dict of index -> value")
|
| 92 |
+
feedback_parser.add_argument("--notes", default="", help="Free-form correction notes")
|
| 93 |
+
feedback_parser.add_argument("--json", action="store_true", dest="json_mode", help="Emit raw parseable JSON only")
|
| 94 |
+
feedback_parser.set_defaults(func=_feedback)
|
| 95 |
+
|
| 96 |
+
sync_parser = subparsers.add_parser("sync-flywheel", help="Merge feedback, push dataset, retrain")
|
| 97 |
+
sync_parser.add_argument("--job-config", default="hf_job.yaml")
|
| 98 |
+
sync_parser.add_argument("--allow-empty", action="store_true", help="Return 0 even if no feedback")
|
| 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,
|
| 105 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
try:
|
| 109 |
+
return args.func(args)
|
| 110 |
+
except Exception as e:
|
| 111 |
+
logger.exception("Unhandled runtime exception")
|
| 112 |
+
return 2
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
sys.exit(main())
|
src/pino/dataset_builder.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import signal
|
| 7 |
+
import threading
|
| 8 |
+
import uuid
|
| 9 |
+
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
from pino.draft_engine import FormulaGenerator
|
| 14 |
+
from pino.verifier import FragrancePipelineVerifier
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger("pino.dataset_builder")
|
| 17 |
+
|
| 18 |
+
GENRES = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 19 |
+
|
| 20 |
+
# Worker-thread local storage for generator and verifier reuse.
|
| 21 |
+
_worker_local = threading.local()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _get_worker_generator(
|
| 25 |
+
genre: str,
|
| 26 |
+
rules_path: Path,
|
| 27 |
+
registry_path: Path,
|
| 28 |
+
base_seed: int,
|
| 29 |
+
) -> FormulaGenerator:
|
| 30 |
+
"""Return a thread-local FormulaGenerator for this genre."""
|
| 31 |
+
current_genre = getattr(_worker_local, "genre", None)
|
| 32 |
+
if current_genre != genre or not hasattr(_worker_local, "generator"):
|
| 33 |
+
thread_id = threading.current_thread().ident or 0
|
| 34 |
+
_worker_local.generator = FormulaGenerator(
|
| 35 |
+
genre=genre,
|
| 36 |
+
rules_path=rules_path,
|
| 37 |
+
registry_path=registry_path,
|
| 38 |
+
seed=base_seed + hash(genre) + thread_id,
|
| 39 |
+
min_k=5,
|
| 40 |
+
max_k=20,
|
| 41 |
+
)
|
| 42 |
+
_worker_local.genre = genre
|
| 43 |
+
return _worker_local.generator
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _get_worker_verifier() -> FragrancePipelineVerifier:
|
| 47 |
+
"""Return a thread-local FragrancePipelineVerifier."""
|
| 48 |
+
if not hasattr(_worker_local, "verifier"):
|
| 49 |
+
_worker_local.verifier = FragrancePipelineVerifier()
|
| 50 |
+
return _worker_local.verifier
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class DatasetBuilder:
|
| 54 |
+
"""
|
| 55 |
+
Streaming, multi-threaded dataset builder for PINO synthetic trajectories.
|
| 56 |
+
|
| 57 |
+
Runs one stratified sweep per genre, writes verified records append-only to
|
| 58 |
+
a JSON-Lines file, and emits a final analytics card.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
output_path: str | Path,
|
| 64 |
+
rules_path: str | Path,
|
| 65 |
+
registry_path: str | Path,
|
| 66 |
+
per_genre: int = 1000,
|
| 67 |
+
max_workers: int = 16,
|
| 68 |
+
seed: int = 2026,
|
| 69 |
+
) -> None:
|
| 70 |
+
self.output_path = Path(output_path)
|
| 71 |
+
self.output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 72 |
+
self.rules_path = Path(rules_path)
|
| 73 |
+
self.registry_path = Path(registry_path)
|
| 74 |
+
self.per_genre = per_genre
|
| 75 |
+
self.max_workers = max_workers
|
| 76 |
+
self.seed = seed
|
| 77 |
+
self._shutdown = False
|
| 78 |
+
|
| 79 |
+
def _signal_handler(self, signum: int, frame: Any) -> None:
|
| 80 |
+
logger.warning("Shutdown signal received; finishing in-flight work ...")
|
| 81 |
+
self._shutdown = True
|
| 82 |
+
|
| 83 |
+
def _task(self, idx: int, genre: str) -> dict[str, Any] | None:
|
| 84 |
+
"""Generate and verify a single formula in a worker thread."""
|
| 85 |
+
generator = _get_worker_generator(
|
| 86 |
+
genre, self.rules_path, self.registry_path, self.seed
|
| 87 |
+
)
|
| 88 |
+
formula, formula_id = generator.generate(idx=idx)
|
| 89 |
+
|
| 90 |
+
if not generator.light_ifra_check(formula)["passed"]:
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
verifier = _get_worker_verifier()
|
| 95 |
+
result = verifier.run_sim(formula, duration_seconds=28800, interval_seconds=600)
|
| 96 |
+
except Exception as exc:
|
| 97 |
+
logger.debug("Verifier rejected %s: %s", formula_id, exc)
|
| 98 |
+
return None
|
| 99 |
+
|
| 100 |
+
if result.get("status") not in ("passed", "depleted"):
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
return {
|
| 104 |
+
"status": result.get("status"),
|
| 105 |
+
"formula_id": formula_id,
|
| 106 |
+
"metadata": {
|
| 107 |
+
"generation_strategy": genre,
|
| 108 |
+
"active_components_count": len(formula) - 1, # exclude solvent
|
| 109 |
+
"formula_id": formula_id,
|
| 110 |
+
},
|
| 111 |
+
"formula": formula,
|
| 112 |
+
"depletion_rates": result.get("depletion_rates", {}),
|
| 113 |
+
"trajectory": result.get("trajectory", []),
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
def _append_record(self, record: dict[str, Any]) -> None:
|
| 117 |
+
with self.output_path.open("a") as f:
|
| 118 |
+
f.write(json.dumps(record) + "\n")
|
| 119 |
+
|
| 120 |
+
def _count_existing(self, genre: str) -> int:
|
| 121 |
+
if not self.output_path.exists():
|
| 122 |
+
return 0
|
| 123 |
+
count = 0
|
| 124 |
+
with self.output_path.open("r") as f:
|
| 125 |
+
for line in f:
|
| 126 |
+
try:
|
| 127 |
+
rec = json.loads(line)
|
| 128 |
+
if rec.get("metadata", {}).get("generation_strategy") == genre:
|
| 129 |
+
count += 1
|
| 130 |
+
except Exception:
|
| 131 |
+
continue
|
| 132 |
+
return count
|
| 133 |
+
|
| 134 |
+
def _run_genre(self, genre: str, global_start_idx: int) -> dict[str, Any]:
|
| 135 |
+
"""Generate and verify `per_genre` records for a single genre."""
|
| 136 |
+
existing = self._count_existing(genre)
|
| 137 |
+
target = self.per_genre - existing
|
| 138 |
+
if target <= 0:
|
| 139 |
+
logger.info("Genre %s already has %d records; skipping", genre, existing)
|
| 140 |
+
return {"genre": genre, "verified": existing, "drafted": 0, "rejected": 0}
|
| 141 |
+
|
| 142 |
+
logger.info("Starting genre %s | need %d more records", genre, target)
|
| 143 |
+
|
| 144 |
+
verified = existing
|
| 145 |
+
drafted = 0
|
| 146 |
+
rejected = 0
|
| 147 |
+
next_idx = global_start_idx
|
| 148 |
+
|
| 149 |
+
with ThreadPoolExecutor(max_workers=self.max_workers, thread_name_prefix=f"pino-{genre}") as executor:
|
| 150 |
+
futures: set[Any] = set()
|
| 151 |
+
|
| 152 |
+
while verified < self.per_genre and not self._shutdown:
|
| 153 |
+
# Keep the worker pool saturated.
|
| 154 |
+
while len(futures) < self.max_workers * 4 and not self._shutdown:
|
| 155 |
+
futures.add(executor.submit(self._task, next_idx, genre))
|
| 156 |
+
next_idx += 1
|
| 157 |
+
drafted += 1
|
| 158 |
+
if drafted >= target * 5:
|
| 159 |
+
# Safety valve: stop drafting if rejection rate is too high.
|
| 160 |
+
break
|
| 161 |
+
|
| 162 |
+
if not futures:
|
| 163 |
+
break
|
| 164 |
+
|
| 165 |
+
done, futures = wait(futures, return_when=FIRST_COMPLETED)
|
| 166 |
+
for future in done:
|
| 167 |
+
result = future.result()
|
| 168 |
+
if result is None:
|
| 169 |
+
rejected += 1
|
| 170 |
+
continue
|
| 171 |
+
self._append_record(result)
|
| 172 |
+
verified += 1
|
| 173 |
+
|
| 174 |
+
if verified % 100 == 0 and verified > existing:
|
| 175 |
+
logger.info(
|
| 176 |
+
"Genre %s: verified %d/%d | drafted %d | rejected %d",
|
| 177 |
+
genre,
|
| 178 |
+
verified,
|
| 179 |
+
self.per_genre,
|
| 180 |
+
drafted,
|
| 181 |
+
rejected,
|
| 182 |
+
)
|
| 183 |
+
if verified >= self.per_genre:
|
| 184 |
+
break
|
| 185 |
+
|
| 186 |
+
# Safety valve: if rejection rate is high, move on anyway.
|
| 187 |
+
if drafted > max(100, verified * 3) and verified < self.per_genre:
|
| 188 |
+
logger.warning(
|
| 189 |
+
"Genre %s has high rejection rate (verified %d, drafted %d); continuing",
|
| 190 |
+
genre, verified, drafted
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
logger.info(
|
| 194 |
+
"Genre %s complete: verified %d/%d | drafted %d | rejected %d",
|
| 195 |
+
genre,
|
| 196 |
+
verified,
|
| 197 |
+
self.per_genre,
|
| 198 |
+
drafted,
|
| 199 |
+
rejected,
|
| 200 |
+
)
|
| 201 |
+
return {"genre": genre, "verified": verified, "drafted": drafted, "rejected": rejected}
|
| 202 |
+
|
| 203 |
+
def build(self) -> dict[str, Any]:
|
| 204 |
+
"""Run the full stratified sweep and return the analytics card."""
|
| 205 |
+
signal.signal(signal.SIGINT, self._signal_handler)
|
| 206 |
+
signal.signal(signal.SIGTERM, self._signal_handler)
|
| 207 |
+
|
| 208 |
+
# Wipe only if empty; otherwise resume.
|
| 209 |
+
if not self.output_path.exists() or self.output_path.stat().st_size == 0:
|
| 210 |
+
self.output_path.write_text("")
|
| 211 |
+
|
| 212 |
+
card = {"genres": [], "total_verified": 0, "total_drafted": 0, "total_rejected": 0}
|
| 213 |
+
global_idx = 0
|
| 214 |
+
for genre in GENRES:
|
| 215 |
+
summary = self._run_genre(genre, global_idx)
|
| 216 |
+
card["genres"].append(summary)
|
| 217 |
+
card["total_verified"] += summary["verified"]
|
| 218 |
+
card["total_drafted"] += summary["drafted"]
|
| 219 |
+
card["total_rejected"] += summary["rejected"]
|
| 220 |
+
global_idx += self.per_genre
|
| 221 |
+
|
| 222 |
+
logger.info(
|
| 223 |
+
"Dataset complete: %d verified | %d drafted | %d rejected",
|
| 224 |
+
card["total_verified"],
|
| 225 |
+
card["total_drafted"],
|
| 226 |
+
card["total_rejected"],
|
| 227 |
+
)
|
| 228 |
+
return card
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
if __name__ == "__main__":
|
| 232 |
+
parser = argparse.ArgumentParser(description="Build PINO synthetic dataset v2")
|
| 233 |
+
parser.add_argument("--output", default="data/synthetic_dataset_v2.jsonl")
|
| 234 |
+
parser.add_argument("--rules", default="data/genre_rules.json")
|
| 235 |
+
parser.add_argument("--registry", default="src/pino/registry.db")
|
| 236 |
+
parser.add_argument("--per-genre", type=int, default=1000)
|
| 237 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 238 |
+
parser.add_argument("--seed", type=int, default=2026)
|
| 239 |
+
parser.add_argument("--log-level", default="INFO")
|
| 240 |
+
args = parser.parse_args()
|
| 241 |
+
|
| 242 |
+
logging.basicConfig(
|
| 243 |
+
level=getattr(logging, args.log_level.upper()),
|
| 244 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 245 |
+
)
|
| 246 |
+
builder = DatasetBuilder(
|
| 247 |
+
output_path=args.output,
|
| 248 |
+
rules_path=args.rules,
|
| 249 |
+
registry_path=args.registry,
|
| 250 |
+
per_genre=args.per_genre,
|
| 251 |
+
max_workers=args.workers,
|
| 252 |
+
seed=args.seed,
|
| 253 |
+
)
|
| 254 |
+
card = builder.build()
|
| 255 |
+
print(json.dumps(card, indent=2))
|
src/pino/draft_engine.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import random
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from pino.ifra import IFRA_RESTRICTIONS
|
| 12 |
+
from pino.registry import AromaRegistry
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger("pino.draft_engine")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class FormulaGenerator:
|
| 18 |
+
"""
|
| 19 |
+
Genre-aware, tier-biased formulation sampler.
|
| 20 |
+
|
| 21 |
+
Reads an expanded aroma-chemical registry, classifies compounds into
|
| 22 |
+
performance tiers by molecular weight, and generates weight-fraction
|
| 23 |
+
formulas that satisfy genre-specific blending rules.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
genre: str,
|
| 29 |
+
rules_path: str | Path,
|
| 30 |
+
registry_path: str | Path | None = None,
|
| 31 |
+
seed: int | None = None,
|
| 32 |
+
min_k: int = 5,
|
| 33 |
+
max_k: int = 25,
|
| 34 |
+
) -> None:
|
| 35 |
+
self.genre = genre
|
| 36 |
+
self.rules_path = Path(rules_path)
|
| 37 |
+
self.seed = seed
|
| 38 |
+
self.rng = random.Random(seed)
|
| 39 |
+
self.min_k = min_k
|
| 40 |
+
self.max_k = max_k
|
| 41 |
+
|
| 42 |
+
self.rules = json.loads(self.rules_path.read_text())
|
| 43 |
+
if genre not in self.rules["genres"] and genre != "uniform":
|
| 44 |
+
raise ValueError(f"Unknown genre: {genre}")
|
| 45 |
+
self.genre_rules = self.rules["genres"].get(genre, {})
|
| 46 |
+
self.solvent_cas = self.rules["solvent_cas"]
|
| 47 |
+
|
| 48 |
+
self.registry = AromaRegistry(registry_path)
|
| 49 |
+
self.compounds = self._load_compounds()
|
| 50 |
+
self.tiers = self._classify_tiers()
|
| 51 |
+
self.active_pool = self._build_active_pool()
|
| 52 |
+
|
| 53 |
+
def _load_compounds(self) -> dict[str, dict[str, Any]]:
|
| 54 |
+
"""Load all active aroma compounds from the registry."""
|
| 55 |
+
rows = self.registry._conn.execute(
|
| 56 |
+
"SELECT cas, name, smiles, molecular_weight, vapor_pressure_pa, logp FROM aroma_chemicals"
|
| 57 |
+
).fetchall()
|
| 58 |
+
compounds = {}
|
| 59 |
+
for row in rows:
|
| 60 |
+
record = dict(row)
|
| 61 |
+
cas = record["cas"]
|
| 62 |
+
if cas in self.rules.get("prohibited_cas", []):
|
| 63 |
+
continue
|
| 64 |
+
if cas == self.solvent_cas:
|
| 65 |
+
continue
|
| 66 |
+
# Assign default guardrails based on IFRA.
|
| 67 |
+
max_w = self._default_max_weight(record)
|
| 68 |
+
record["max_weight_fraction"] = max_w
|
| 69 |
+
record["min_weight_fraction"] = self.rules["default_min_weight"]
|
| 70 |
+
compounds[cas] = record
|
| 71 |
+
return compounds
|
| 72 |
+
|
| 73 |
+
def _default_max_weight(self, record: dict[str, Any]) -> float:
|
| 74 |
+
"""Assign a default maximum weight fraction based on IFRA."""
|
| 75 |
+
cas = record["cas"]
|
| 76 |
+
if cas in IFRA_RESTRICTIONS:
|
| 77 |
+
limit = IFRA_RESTRICTIONS[cas]["category_4_pct"]
|
| 78 |
+
if limit == 0.0:
|
| 79 |
+
return 0.0
|
| 80 |
+
return min(limit / 100.0, self.rules["default_max_weight"])
|
| 81 |
+
return self.rules["default_max_weight"]
|
| 82 |
+
|
| 83 |
+
def _classify_tiers(self) -> dict[str, list[str]]:
|
| 84 |
+
"""Classify compounds into top/heart/base tiers by molecular weight."""
|
| 85 |
+
cutoffs = self.rules["tier_cutoffs"]
|
| 86 |
+
tiers: dict[str, list[str]] = {"top": [], "heart": [], "base": []}
|
| 87 |
+
for cas, meta in self.compounds.items():
|
| 88 |
+
mw = meta["molecular_weight"]
|
| 89 |
+
if mw <= cutoffs["top"]["max_mw"]:
|
| 90 |
+
tiers["top"].append(cas)
|
| 91 |
+
elif mw < cutoffs["base"].get("min_mw", 1e9):
|
| 92 |
+
tiers["heart"].append(cas)
|
| 93 |
+
else:
|
| 94 |
+
tiers["base"].append(cas)
|
| 95 |
+
return tiers
|
| 96 |
+
|
| 97 |
+
def _build_active_pool(self) -> list[str]:
|
| 98 |
+
"""Build the allowed sampling pool for the current genre."""
|
| 99 |
+
if self.genre == "uniform" or self.genre_rules.get("uniform"):
|
| 100 |
+
return [cas for cas, meta in self.compounds.items() if meta["max_weight_fraction"] > 0.0]
|
| 101 |
+
# Genre mode: start with required tiers plus any tier referenced by a
|
| 102 |
+
# min_X_mass constraint, then allow heart/base as supporting elements.
|
| 103 |
+
needed_tiers: set[str] = set(self.genre_rules.get("required_tiers", []))
|
| 104 |
+
for tier in ["top", "heart", "base"]:
|
| 105 |
+
if f"min_{tier}_mass" in self.genre_rules:
|
| 106 |
+
needed_tiers.add(tier)
|
| 107 |
+
needed_tiers.update(["heart", "base"])
|
| 108 |
+
pool: set[str] = set()
|
| 109 |
+
for tier in needed_tiers:
|
| 110 |
+
pool.update(self.tiers.get(tier, []))
|
| 111 |
+
return [cas for cas in pool if self.compounds[cas]["max_weight_fraction"] > 0.0]
|
| 112 |
+
|
| 113 |
+
def _genre_formula_id(self, idx: int) -> str:
|
| 114 |
+
prefix = self.genre[:4].lower()
|
| 115 |
+
return f"gen_{prefix}_{idx:04d}"
|
| 116 |
+
|
| 117 |
+
def generate(self, idx: int = 0) -> tuple[list[dict[str, Any]], str]:
|
| 118 |
+
"""Generate one candidate formula and return it with a deterministic genre ID."""
|
| 119 |
+
formula = self._generate_formula()
|
| 120 |
+
return formula, self._genre_formula_id(idx)
|
| 121 |
+
|
| 122 |
+
def _generate_formula(self) -> list[dict[str, Any]]:
|
| 123 |
+
"""Generate a raw {cas, weight_fraction} formula list satisfying genre constraints."""
|
| 124 |
+
solvent_min = self.rules.get("solvent_min", 0.50)
|
| 125 |
+
solvent_max = self.rules.get("solvent_max", 0.95)
|
| 126 |
+
|
| 127 |
+
for _ in range(100):
|
| 128 |
+
if self.genre == "uniform" or self.genre_rules.get("uniform"):
|
| 129 |
+
k = self.rng.randint(self.min_k, min(self.max_k, len(self.active_pool)))
|
| 130 |
+
selected = self.rng.sample(self.active_pool, k)
|
| 131 |
+
else:
|
| 132 |
+
selected = self._select_with_tier_constraints()
|
| 133 |
+
|
| 134 |
+
if not selected:
|
| 135 |
+
selected = self.rng.sample(self.active_pool, min(self.min_k, len(self.active_pool)))
|
| 136 |
+
|
| 137 |
+
target_aroma = self.rng.uniform(1.0 - solvent_max, 1.0 - solvent_min)
|
| 138 |
+
weights = self._assign_tier_constrained_weights(selected, target_aroma)
|
| 139 |
+
if weights:
|
| 140 |
+
solvent_share = 1.0 - sum(weights.values())
|
| 141 |
+
formula = [{"cas": self.solvent_cas, "weight_fraction": solvent_share}]
|
| 142 |
+
for cas, w in weights.items():
|
| 143 |
+
if w > 0:
|
| 144 |
+
formula.append({"cas": cas, "weight_fraction": w})
|
| 145 |
+
return formula
|
| 146 |
+
|
| 147 |
+
logger.warning("Genre %s constraints infeasible after 100 attempts; falling back", self.genre)
|
| 148 |
+
selected = self.rng.sample(self.active_pool, min(self.min_k, len(self.active_pool)))
|
| 149 |
+
target_aroma = self.rng.uniform(1.0 - solvent_max, 1.0 - solvent_min)
|
| 150 |
+
weights = {cas: self._random_weight(cas) for cas in selected}
|
| 151 |
+
weights = self._project_weights(weights, target_aroma)
|
| 152 |
+
solvent_share = 1.0 - sum(weights.values())
|
| 153 |
+
formula = [{"cas": self.solvent_cas, "weight_fraction": solvent_share}]
|
| 154 |
+
for cas, w in weights.items():
|
| 155 |
+
if w > 0:
|
| 156 |
+
formula.append({"cas": cas, "weight_fraction": w})
|
| 157 |
+
return formula
|
| 158 |
+
|
| 159 |
+
def _select_with_tier_constraints(self) -> list[str]:
|
| 160 |
+
"""Pick aroma compounds that can physically satisfy the genre tier-mass rules."""
|
| 161 |
+
default_max = self.rules["default_max_weight"]
|
| 162 |
+
selected: set[str] = set()
|
| 163 |
+
|
| 164 |
+
# Determine which tiers are needed: explicit required tiers plus any tier
|
| 165 |
+
# that has a min_X_mass constraint.
|
| 166 |
+
needed_tiers: set[str] = set(self.genre_rules.get("required_tiers", []))
|
| 167 |
+
for tier in ["top", "heart", "base"]:
|
| 168 |
+
if f"min_{tier}_mass" in self.genre_rules:
|
| 169 |
+
needed_tiers.add(tier)
|
| 170 |
+
|
| 171 |
+
# Ensure at least one compound from each needed tier.
|
| 172 |
+
for tier in needed_tiers:
|
| 173 |
+
candidates = [cas for cas in self.tiers.get(tier, []) if cas in self.active_pool]
|
| 174 |
+
if candidates:
|
| 175 |
+
selected.add(self.rng.choice(candidates))
|
| 176 |
+
|
| 177 |
+
# Ensure enough compounds from each constrained tier to satisfy proportions
|
| 178 |
+
# at the largest possible aroma mass (so per-member minimum stays below max).
|
| 179 |
+
max_aroma = 1.0 - self.rules.get("solvent_min", 0.50)
|
| 180 |
+
for tier in ["top", "heart", "base"]:
|
| 181 |
+
key = f"min_{tier}_mass"
|
| 182 |
+
if key not in self.genre_rules:
|
| 183 |
+
continue
|
| 184 |
+
need_mass = self.genre_rules[key] * max_aroma
|
| 185 |
+
present = sum(1 for c in selected if c in self.tiers.get(tier, []))
|
| 186 |
+
need = max(0, int(need_mass / default_max) - present + 1)
|
| 187 |
+
candidates = [cas for cas in self.tiers.get(tier, []) if cas in self.active_pool and cas not in selected]
|
| 188 |
+
need = min(need, len(candidates))
|
| 189 |
+
if need > 0:
|
| 190 |
+
selected.update(self.rng.sample(candidates, need))
|
| 191 |
+
|
| 192 |
+
# Fill remaining slots for diversity.
|
| 193 |
+
remaining_slots = self.rng.randint(
|
| 194 |
+
max(0, self.min_k - len(selected)),
|
| 195 |
+
max(0, self.max_k - len(selected)),
|
| 196 |
+
)
|
| 197 |
+
candidates = [cas for cas in self.active_pool if cas not in selected]
|
| 198 |
+
remaining_slots = min(remaining_slots, len(candidates))
|
| 199 |
+
if remaining_slots > 0:
|
| 200 |
+
selected.update(self.rng.sample(candidates, remaining_slots))
|
| 201 |
+
|
| 202 |
+
return list(selected)
|
| 203 |
+
|
| 204 |
+
def _assign_tier_constrained_weights(
|
| 205 |
+
self,
|
| 206 |
+
selected: list[str],
|
| 207 |
+
target_aroma: float,
|
| 208 |
+
) -> dict[str, float] | None:
|
| 209 |
+
"""
|
| 210 |
+
Assign weights such that tier proportions relative to the aroma mass
|
| 211 |
+
are satisfied. Returns None if infeasible.
|
| 212 |
+
"""
|
| 213 |
+
mins = {cas: self.compounds[cas]["min_weight_fraction"] for cas in selected}
|
| 214 |
+
maxs = {cas: self.compounds[cas]["max_weight_fraction"] for cas in selected}
|
| 215 |
+
|
| 216 |
+
if self.genre != "uniform" and not self.genre_rules.get("uniform"):
|
| 217 |
+
for tier in ["top", "heart", "base"]:
|
| 218 |
+
key = f"min_{tier}_mass"
|
| 219 |
+
if key not in self.genre_rules:
|
| 220 |
+
continue
|
| 221 |
+
need = self.genre_rules[key] * target_aroma
|
| 222 |
+
tier_members = [cas for cas in selected if cas in self.tiers.get(tier, [])]
|
| 223 |
+
if not tier_members:
|
| 224 |
+
return None
|
| 225 |
+
if sum(maxs[cas] for cas in tier_members) < need:
|
| 226 |
+
return None
|
| 227 |
+
per_member = need / len(tier_members)
|
| 228 |
+
for cas in tier_members:
|
| 229 |
+
mins[cas] = min(maxs[cas], max(mins[cas], per_member))
|
| 230 |
+
|
| 231 |
+
max_top = self.genre_rules.get("max_top_mass")
|
| 232 |
+
if max_top is not None:
|
| 233 |
+
top_members = [cas for cas in selected if cas in self.tiers.get("top", [])]
|
| 234 |
+
if top_members:
|
| 235 |
+
top_total_max = max_top * target_aroma
|
| 236 |
+
current_top_max = sum(maxs[cas] for cas in top_members)
|
| 237 |
+
if current_top_max > top_total_max:
|
| 238 |
+
scale = top_total_max / current_top_max
|
| 239 |
+
for cas in top_members:
|
| 240 |
+
maxs[cas] = max(mins[cas], maxs[cas] * scale)
|
| 241 |
+
|
| 242 |
+
if sum(mins.values()) > target_aroma or sum(maxs.values()) < target_aroma:
|
| 243 |
+
return None
|
| 244 |
+
|
| 245 |
+
weights = {cas: self.rng.uniform(mins[cas], maxs[cas]) for cas in selected}
|
| 246 |
+
return self._project_weights(weights, target_aroma, mins, maxs)
|
| 247 |
+
|
| 248 |
+
def _random_weight(self, cas: str) -> float:
|
| 249 |
+
"""Sample a random weight fraction within empirical guardrails."""
|
| 250 |
+
meta = self.compounds[cas]
|
| 251 |
+
min_w = float(meta.get("min_weight_fraction", 0.001))
|
| 252 |
+
max_w = float(meta["max_weight_fraction"])
|
| 253 |
+
if max_w <= min_w:
|
| 254 |
+
return 0.0
|
| 255 |
+
return self.rng.uniform(min_w, max_w)
|
| 256 |
+
|
| 257 |
+
def _project_weights(
|
| 258 |
+
self,
|
| 259 |
+
weights: dict[str, float],
|
| 260 |
+
target: float,
|
| 261 |
+
mins: dict[str, float] | None = None,
|
| 262 |
+
maxs: dict[str, float] | None = None,
|
| 263 |
+
tol: float = 1e-12,
|
| 264 |
+
) -> dict[str, float]:
|
| 265 |
+
"""Project weights onto a box-constrained simplex via Lagrange multiplier."""
|
| 266 |
+
cas_list = list(weights.keys())
|
| 267 |
+
x = np.array([weights[cas] for cas in cas_list], dtype=float)
|
| 268 |
+
l = np.array(
|
| 269 |
+
[float((mins or {}).get(cas, self.compounds[cas]["min_weight_fraction"])) for cas in cas_list],
|
| 270 |
+
dtype=float,
|
| 271 |
+
)
|
| 272 |
+
u = np.array(
|
| 273 |
+
[float((maxs or {}).get(cas, self.compounds[cas]["max_weight_fraction"])) for cas in cas_list],
|
| 274 |
+
dtype=float,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
if l.sum() > target or u.sum() < target:
|
| 278 |
+
y = np.clip(x, l, u)
|
| 279 |
+
return dict(zip(cas_list, y))
|
| 280 |
+
|
| 281 |
+
def _sum_y(lambda_: float) -> float:
|
| 282 |
+
return float(np.clip(x - lambda_, l, u).sum())
|
| 283 |
+
|
| 284 |
+
lambda_low, lambda_high = -1.0, 1.0
|
| 285 |
+
lambda_mid = 0.0
|
| 286 |
+
while _sum_y(lambda_low) < target:
|
| 287 |
+
lambda_low *= 2.0
|
| 288 |
+
if lambda_low < -1e12:
|
| 289 |
+
break
|
| 290 |
+
while _sum_y(lambda_high) > target:
|
| 291 |
+
lambda_high *= 2.0
|
| 292 |
+
if lambda_high > 1e12:
|
| 293 |
+
break
|
| 294 |
+
|
| 295 |
+
for _ in range(64):
|
| 296 |
+
lambda_mid = (lambda_low + lambda_high) / 2.0
|
| 297 |
+
s = _sum_y(lambda_mid)
|
| 298 |
+
if abs(s - target) < tol:
|
| 299 |
+
break
|
| 300 |
+
if s > target:
|
| 301 |
+
lambda_low = lambda_mid
|
| 302 |
+
else:
|
| 303 |
+
lambda_high = lambda_mid
|
| 304 |
+
|
| 305 |
+
y = np.clip(x - lambda_mid, l, u)
|
| 306 |
+
return dict(zip(cas_list, y))
|
| 307 |
+
|
| 308 |
+
def light_ifra_check(self, formula: list[dict[str, Any]]) -> dict[str, Any]:
|
| 309 |
+
"""Fast pre-check against IFRA restrictions using raw dict input."""
|
| 310 |
+
violations = []
|
| 311 |
+
for f in formula:
|
| 312 |
+
cas = f["cas"]
|
| 313 |
+
pct = f["weight_fraction"] * 100.0
|
| 314 |
+
if cas in IFRA_RESTRICTIONS:
|
| 315 |
+
limit = IFRA_RESTRICTIONS[cas]["category_4_pct"]
|
| 316 |
+
if (limit == 0.0 and pct > 0.0) or (limit > 0.0 and pct > limit):
|
| 317 |
+
violations.append({"cas": cas, "used_pct": pct, "limit_pct": limit})
|
| 318 |
+
return {"passed": not violations, "violations": violations}
|
src/pino/embeddings.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from rdkit import Chem
|
| 8 |
+
from rdkit.Chem import AllChem, Descriptors
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger("pino.embeddings")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class OlfactoryEmbeddingEngine:
|
| 14 |
+
"""
|
| 15 |
+
Standardized interface for 138-dimensional olfactory molecule embeddings.
|
| 16 |
+
|
| 17 |
+
In production this loads a pre-trained OpenPOM GNN checkpoint. For offline
|
| 18 |
+
reproducibility, a deterministic fallback (128-bit Morgan fingerprint + 10
|
| 19 |
+
physicochemical descriptors) is used. The fallback is structure-preserving
|
| 20 |
+
but does not encode perceptual odor space, so downstream losses are expected
|
| 21 |
+
to be higher until a real OpenPOM model is swapped in.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, use_fallback: bool = True):
|
| 25 |
+
self.use_fallback = use_fallback
|
| 26 |
+
self.embedding_dim = 138
|
| 27 |
+
if not self.use_fallback:
|
| 28 |
+
self._initialize_real_openpom()
|
| 29 |
+
|
| 30 |
+
def _initialize_real_openpom(self) -> None:
|
| 31 |
+
# Placeholder for future on-disk GNN model loading.
|
| 32 |
+
logger.warning("Real OpenPOM model not available; enabling fallback automatically")
|
| 33 |
+
self.use_fallback = True
|
| 34 |
+
|
| 35 |
+
def get_embedding(self, smiles: str) -> np.ndarray:
|
| 36 |
+
"""Main entry point. Returns a 138-dimensional float32 array."""
|
| 37 |
+
if self.use_fallback:
|
| 38 |
+
return self._compute_deterministic_fallback(smiles)
|
| 39 |
+
return self._compute_real_openpom(smiles)
|
| 40 |
+
|
| 41 |
+
def _compute_deterministic_fallback(self, smiles: str) -> np.ndarray:
|
| 42 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 43 |
+
if not mol:
|
| 44 |
+
logger.warning("Invalid SMILES for embedding: %s", smiles)
|
| 45 |
+
return np.zeros(self.embedding_dim, dtype=np.float32)
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
# Modern RDKit 2024+ zero-deprecation Generator API.
|
| 49 |
+
fpgen = AllChem.GetMorganGenerator(radius=2, fpSize=128)
|
| 50 |
+
fp_bitvect = fpgen.GetFingerprint(mol)
|
| 51 |
+
fp_array = np.array(fp_bitvect, dtype=np.float32)
|
| 52 |
+
except AttributeError:
|
| 53 |
+
# Legacy fallback for older environments.
|
| 54 |
+
fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=128)
|
| 55 |
+
fp_array = np.array(fp, dtype=np.float32)
|
| 56 |
+
|
| 57 |
+
physchem = np.array([
|
| 58 |
+
Descriptors.MolWt(mol),
|
| 59 |
+
Descriptors.ExactMolWt(mol),
|
| 60 |
+
Descriptors.MolLogP(mol),
|
| 61 |
+
Descriptors.HeavyAtomCount(mol),
|
| 62 |
+
Descriptors.NumHAcceptors(mol),
|
| 63 |
+
Descriptors.NumHDonors(mol),
|
| 64 |
+
Descriptors.NumRotatableBonds(mol),
|
| 65 |
+
Descriptors.FractionCSP3(mol),
|
| 66 |
+
Descriptors.TPSA(mol),
|
| 67 |
+
Descriptors.LabuteASA(mol)
|
| 68 |
+
], dtype=np.float32)
|
| 69 |
+
|
| 70 |
+
combined = np.concatenate([fp_array, physchem]).astype(np.float32)
|
| 71 |
+
norm = np.linalg.norm(combined)
|
| 72 |
+
return combined / norm if norm > 0 else combined
|
| 73 |
+
|
| 74 |
+
def _compute_real_openpom(self, smiles: str) -> np.ndarray:
|
| 75 |
+
raise NotImplementedError("Real OpenPOM model not yet loaded")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Module-level default engine for convenience.
|
| 79 |
+
_DEFAULT_ENGINE = OlfactoryEmbeddingEngine(use_fallback=True)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_openpom_embedding(smiles: str, dim: int = 138) -> np.ndarray:
|
| 83 |
+
"""Convenience accessor used by the PIMT pipeline."""
|
| 84 |
+
embedding = _DEFAULT_ENGINE.get_embedding(smiles)
|
| 85 |
+
if embedding.shape[0] != dim:
|
| 86 |
+
raise ValueError(f"Embedding dimension mismatch: {embedding.shape[0]} != {dim}")
|
| 87 |
+
return embedding
|
src/pino/evaporation.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from scipy.integrate import solve_ivp
|
| 8 |
+
|
| 9 |
+
from .models import Formula, Trajectory
|
| 10 |
+
from .vle import VLECalculator
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger("pino.evaporation")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class EvaporationModel:
|
| 16 |
+
"""
|
| 17 |
+
Stiff ODE model for multi-component fragrance evaporation.
|
| 18 |
+
|
| 19 |
+
State vector: n_i(t) = moles of component i remaining in the liquid film.
|
| 20 |
+
Assumptions:
|
| 21 |
+
- Well-mixed thin liquid film of fixed surface area A (m2).
|
| 22 |
+
- Evaporation flux J_i = k_i * (f_i^L / P) (mol/m2/s) using liquid fugacity ratios.
|
| 23 |
+
- k_i = k_base * (MW_i / MW_ethanol)^alpha / (P_i^sat)^beta as a volatility scaling.
|
| 24 |
+
- Gas phase is instantaneously well-mixed with the headspace volume.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
formula: Formula,
|
| 30 |
+
vle: VLECalculator | None = None,
|
| 31 |
+
surface_area_m2: float = 1e-4, # 1 cm^2 film
|
| 32 |
+
mass_transfer_coefficient: float = 1e-4, # m/s base
|
| 33 |
+
volatility_exponent: float = 0.5,
|
| 34 |
+
mw_exponent: float = -0.5,
|
| 35 |
+
skin_sink_alpha: float = -6.0, # Potts-Guy intercept (log10 scale)
|
| 36 |
+
skin_sink_beta: float = 0.4, # Potts-Guy LogP coefficient
|
| 37 |
+
skin_sink_gamma: float = 0.005, # Potts-Guy MW coefficient
|
| 38 |
+
skin_sink_max: float = 1e-6, # s^-1 clamp
|
| 39 |
+
) -> None:
|
| 40 |
+
self.formula = formula
|
| 41 |
+
self.vle = vle or VLECalculator(formula)
|
| 42 |
+
self.surface_area = surface_area_m2
|
| 43 |
+
self.k_base = mass_transfer_coefficient
|
| 44 |
+
self.alpha = volatility_exponent
|
| 45 |
+
self.beta = mw_exponent
|
| 46 |
+
self.skin_sink_alpha = skin_sink_alpha
|
| 47 |
+
self.skin_sink_beta = skin_sink_beta
|
| 48 |
+
self.skin_sink_gamma = skin_sink_gamma
|
| 49 |
+
self.skin_sink_max = skin_sink_max
|
| 50 |
+
self._mws = np.array([i.molecular_weight for i in formula.ingredients], dtype=float)
|
| 51 |
+
self._p_sat = np.array([i.vapor_pressure_pa for i in formula.ingredients], dtype=float)
|
| 52 |
+
self._logp = np.array(
|
| 53 |
+
[i.logp if i.logp is not None else 0.0 for i in formula.ingredients], dtype=float
|
| 54 |
+
)
|
| 55 |
+
self._k_skin = self._compute_skin_sink_rates()
|
| 56 |
+
self._n0 = self._initial_moles()
|
| 57 |
+
# Terminal film-depletion event for solve_ivp.
|
| 58 |
+
self._film_depleted_event = self._make_film_depleted_event()
|
| 59 |
+
|
| 60 |
+
def _make_film_depleted_event(self):
|
| 61 |
+
"""Return a solve_ivp event that fires when the total liquid film is depleted."""
|
| 62 |
+
def event(t: float, n: np.ndarray) -> float:
|
| 63 |
+
# Triggers when total liquid moles drops below a physical trace limit.
|
| 64 |
+
return float(np.maximum(n, 0.0).sum() - 1e-7)
|
| 65 |
+
|
| 66 |
+
event.terminal = True
|
| 67 |
+
return event
|
| 68 |
+
|
| 69 |
+
def _initial_moles(self) -> np.ndarray:
|
| 70 |
+
"""Moles of each component in the initial 1 mL liquid sample."""
|
| 71 |
+
# Assume liquid density ~ 0.9 g/mL for fragrance oil (overridden by formula metadata)
|
| 72 |
+
total_volume_l = self.formula.liquid_volume_m3 * 1000.0
|
| 73 |
+
density_g_ml = self.formula.metadata.get("density_g_ml", 0.9)
|
| 74 |
+
total_mass_g = total_volume_l * density_g_ml
|
| 75 |
+
w = np.array(self.formula.weight_fractions, dtype=float)
|
| 76 |
+
masses_g = w * total_mass_g
|
| 77 |
+
return masses_g / self._mws
|
| 78 |
+
|
| 79 |
+
def _mass_transfer_coefficients(self, x: np.ndarray) -> np.ndarray:
|
| 80 |
+
"""Species-specific k_i."""
|
| 81 |
+
mw_ethanol = 46.07
|
| 82 |
+
scaling = (self._mws / mw_ethanol) ** self.beta
|
| 83 |
+
# Lower saturation pressure => higher boiling point => slower evaporation
|
| 84 |
+
volatility_scaling = (self._p_sat / 1e5) ** self.alpha
|
| 85 |
+
return self.k_base * scaling / (volatility_scaling + 1e-12)
|
| 86 |
+
|
| 87 |
+
def _compute_skin_sink_rates(self) -> np.ndarray:
|
| 88 |
+
"""
|
| 89 |
+
Potts-Guy inspired per-species skin absorption rate constant (s^-1).
|
| 90 |
+
log10(k_skin) = alpha + beta*logP - gamma*MW
|
| 91 |
+
"""
|
| 92 |
+
log10_k = (
|
| 93 |
+
self.skin_sink_alpha
|
| 94 |
+
+ self.skin_sink_beta * self._logp
|
| 95 |
+
- self.skin_sink_gamma * self._mws
|
| 96 |
+
)
|
| 97 |
+
with np.errstate(over="ignore", under="ignore"):
|
| 98 |
+
k_skin = 10.0 ** log10_k
|
| 99 |
+
return np.clip(k_skin, 0.0, self.skin_sink_max)
|
| 100 |
+
|
| 101 |
+
def _skin_absorption_rate(self, n: np.ndarray) -> np.ndarray:
|
| 102 |
+
"""
|
| 103 |
+
First-order skin sink: rate_i = k_skin_i * n_i (mol/s).
|
| 104 |
+
Vanishes as n_i -> 0, so it cannot drive moles negative.
|
| 105 |
+
"""
|
| 106 |
+
return self._k_skin * n
|
| 107 |
+
|
| 108 |
+
def _surface_coverage(self, n_total: float) -> float:
|
| 109 |
+
"""
|
| 110 |
+
Smooth, differentiable surface coverage factor that gates all mass transport
|
| 111 |
+
as the liquid film approaches total exhaustion. Avoids the n_total -> 0
|
| 112 |
+
cliff in the mole-fraction calculation.
|
| 113 |
+
"""
|
| 114 |
+
return float(np.tanh(n_total / 1e-6))
|
| 115 |
+
|
| 116 |
+
def _dn_dt(self, n: np.ndarray) -> np.ndarray:
|
| 117 |
+
"""Physical d n_i / dt = -theta * (evaporation + skin absorption)."""
|
| 118 |
+
# Clamp individual species to a tiny positive floor to keep x_i > 0.
|
| 119 |
+
n = np.maximum(n, 1e-30)
|
| 120 |
+
n_total = n.sum()
|
| 121 |
+
# Smoothly gate the entire derivative as the film dries out.
|
| 122 |
+
theta = self._surface_coverage(n_total)
|
| 123 |
+
if theta <= 1e-12:
|
| 124 |
+
return np.zeros_like(n)
|
| 125 |
+
x = n / n_total
|
| 126 |
+
fugacity_ratio = self.vle.fugacity_ratios(x)
|
| 127 |
+
k_i = self._mass_transfer_coefficients(x)
|
| 128 |
+
# flux (mol/m2/s) * area (m2) = mol/s
|
| 129 |
+
evaporation = -k_i * self.surface_area * fugacity_ratio
|
| 130 |
+
skin_sink = -self._skin_absorption_rate(n)
|
| 131 |
+
return theta * (evaporation + skin_sink)
|
| 132 |
+
|
| 133 |
+
def _rhs(self, t: float, n: np.ndarray) -> np.ndarray:
|
| 134 |
+
"""d n_i / dt = - evaporation - skin absorption."""
|
| 135 |
+
return self._dn_dt(n)
|
| 136 |
+
|
| 137 |
+
def solve(
|
| 138 |
+
self,
|
| 139 |
+
t_span: tuple[float, float] = (0.0, 28800.0),
|
| 140 |
+
t_eval: np.ndarray | None = None,
|
| 141 |
+
method: str = "BDF",
|
| 142 |
+
rtol: float = 1e-6,
|
| 143 |
+
atol: float = 1e-12,
|
| 144 |
+
film_depletion_threshold: float = 1e-6,
|
| 145 |
+
) -> Trajectory:
|
| 146 |
+
if t_eval is None:
|
| 147 |
+
t_eval = np.linspace(t_span[0], t_span[1], 481)
|
| 148 |
+
|
| 149 |
+
res = solve_ivp(
|
| 150 |
+
self._rhs,
|
| 151 |
+
t_span,
|
| 152 |
+
self._n0,
|
| 153 |
+
method=method,
|
| 154 |
+
t_eval=t_eval,
|
| 155 |
+
events=self._film_depleted_event,
|
| 156 |
+
rtol=rtol,
|
| 157 |
+
atol=atol,
|
| 158 |
+
dense_output=True,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
if not res.success:
|
| 162 |
+
raise RuntimeError(f"ODE integration failed: {res.message}")
|
| 163 |
+
|
| 164 |
+
t = res.t
|
| 165 |
+
n = res.y
|
| 166 |
+
# Clip tiny numerical undershoots to enforce physical positivity.
|
| 167 |
+
n = np.maximum(n, 0.0)
|
| 168 |
+
x_liquid = np.zeros_like(n)
|
| 169 |
+
C_gas = np.zeros_like(n)
|
| 170 |
+
y_gas = np.zeros_like(n)
|
| 171 |
+
OAV = np.zeros_like(n)
|
| 172 |
+
|
| 173 |
+
for idx in range(n.shape[1]):
|
| 174 |
+
n_col = n[:, idx]
|
| 175 |
+
n_total = n_col.sum()
|
| 176 |
+
if n_total > 1e-18:
|
| 177 |
+
x = n_col / n_total
|
| 178 |
+
# Clamp tiny numerical negatives to zero and re-normalize.
|
| 179 |
+
x = np.clip(x, 0.0, None)
|
| 180 |
+
x = x / x.sum()
|
| 181 |
+
else:
|
| 182 |
+
x = np.zeros_like(n_col)
|
| 183 |
+
x_liquid[:, idx] = x
|
| 184 |
+
C_gas[:, idx] = self.vle.gas_concentrations_mg_m3(x)
|
| 185 |
+
y_gas[:, idx] = self.vle.gas_mole_fractions(x)
|
| 186 |
+
OAV[:, idx] = self._oav(x, C_gas[:, idx])
|
| 187 |
+
|
| 188 |
+
return Trajectory(
|
| 189 |
+
t=t,
|
| 190 |
+
n_liquid=n,
|
| 191 |
+
x_liquid=x_liquid,
|
| 192 |
+
C_gas=C_gas,
|
| 193 |
+
y_gas=y_gas,
|
| 194 |
+
OAV=OAV,
|
| 195 |
+
formula=self.formula,
|
| 196 |
+
notes={
|
| 197 |
+
"method": method,
|
| 198 |
+
"surface_area_m2": self.surface_area,
|
| 199 |
+
"k_base_m_s": self.k_base,
|
| 200 |
+
"k_skin_s-1": self._k_skin.tolist(),
|
| 201 |
+
"n_eval": len(t_eval),
|
| 202 |
+
"ode_message": res.message,
|
| 203 |
+
},
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
def _oav(self, x: np.ndarray, C_gas: np.ndarray) -> np.ndarray:
|
| 207 |
+
"""Odor Activity Value = C_gas_i / odor_threshold_i (ug/m3)."""
|
| 208 |
+
thresholds = np.array(
|
| 209 |
+
[i.odor_threshold_ug_m3 or np.nan for i in self.formula.ingredients],
|
| 210 |
+
dtype=float,
|
| 211 |
+
)
|
| 212 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 213 |
+
return np.where(thresholds > 0, C_gas / thresholds, 0.0)
|
src/pino/factory.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import pyarrow as pa
|
| 10 |
+
import pyarrow.parquet as pq
|
| 11 |
+
|
| 12 |
+
from .dataset_builder import DatasetBuilder
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger("pino.factory")
|
| 15 |
+
|
| 16 |
+
GENRES = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _record_to_parquet_row(record: dict[str, Any]) -> dict[str, Any]:
|
| 20 |
+
"""Flatten a record into Parquet-compatible columns."""
|
| 21 |
+
metadata = record.get("metadata", {})
|
| 22 |
+
return {
|
| 23 |
+
"formula_id": record.get("formula_id", ""),
|
| 24 |
+
"generation_strategy": metadata.get("generation_strategy", ""),
|
| 25 |
+
"status": record.get("status", ""),
|
| 26 |
+
"active_components_count": metadata.get("active_components_count", 0),
|
| 27 |
+
"formula": json.dumps(record.get("formula", [])),
|
| 28 |
+
"depletion_rates": json.dumps(record.get("depletion_rates", {})),
|
| 29 |
+
"trajectory": json.dumps(record.get("trajectory", [])),
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def write_jsonl_to_parquet(jsonl_path: Path, parquet_path: Path) -> int:
|
| 34 |
+
"""Convert an existing JSON-L dataset to Parquet."""
|
| 35 |
+
rows = []
|
| 36 |
+
with jsonl_path.open("r") as f:
|
| 37 |
+
for line in f:
|
| 38 |
+
try:
|
| 39 |
+
record = json.loads(line)
|
| 40 |
+
rows.append(_record_to_parquet_row(record))
|
| 41 |
+
except Exception:
|
| 42 |
+
continue
|
| 43 |
+
|
| 44 |
+
schema = pa.schema([
|
| 45 |
+
pa.field("formula_id", pa.string()),
|
| 46 |
+
pa.field("generation_strategy", pa.string()),
|
| 47 |
+
pa.field("status", pa.string()),
|
| 48 |
+
pa.field("active_components_count", pa.int64()),
|
| 49 |
+
pa.field("formula", pa.string()),
|
| 50 |
+
pa.field("depletion_rates", pa.string()),
|
| 51 |
+
pa.field("trajectory", pa.string()),
|
| 52 |
+
])
|
| 53 |
+
|
| 54 |
+
arrays = {k: [r[k] for r in rows] for k in rows[0].keys()}
|
| 55 |
+
table = pa.table(arrays, schema=schema)
|
| 56 |
+
pq.write_table(table, parquet_path)
|
| 57 |
+
return len(rows)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def main() -> None:
|
| 61 |
+
parser = argparse.ArgumentParser(description="PINO Synthetic Data Factory")
|
| 62 |
+
parser.add_argument("--output", default="data/trajectories.parquet", help="Output Parquet path")
|
| 63 |
+
parser.add_argument("--count", type=int, default=5000, help="Total number of records")
|
| 64 |
+
parser.add_argument("--rules", default="data/genre_rules.json")
|
| 65 |
+
parser.add_argument("--registry", default="src/pino/registry.db")
|
| 66 |
+
parser.add_argument("--workers", type=int, default=16)
|
| 67 |
+
parser.add_argument("--seed", type=int, default=2026)
|
| 68 |
+
parser.add_argument("--from-jsonl", default="data/synthetic_dataset_v2.jsonl", help="Convert existing JSON-L instead of regenerating")
|
| 69 |
+
parser.add_argument("--regenerate", action="store_true", help="Regenerate from scratch")
|
| 70 |
+
args = parser.parse_args()
|
| 71 |
+
|
| 72 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
| 73 |
+
output_path = Path(args.output)
|
| 74 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
|
| 76 |
+
jsonl_path = Path(args.from_jsonl)
|
| 77 |
+
if args.regenerate or not jsonl_path.exists() or jsonl_path.stat().st_size == 0:
|
| 78 |
+
per_genre = args.count // len(GENRES)
|
| 79 |
+
builder = DatasetBuilder(
|
| 80 |
+
output_path=jsonl_path,
|
| 81 |
+
rules_path=args.rules,
|
| 82 |
+
registry_path=args.registry,
|
| 83 |
+
per_genre=per_genre,
|
| 84 |
+
max_workers=args.workers,
|
| 85 |
+
seed=args.seed,
|
| 86 |
+
)
|
| 87 |
+
builder.build()
|
| 88 |
+
|
| 89 |
+
count = write_jsonl_to_parquet(jsonl_path, output_path)
|
| 90 |
+
logger.info("Wrote %d records to %s", count, output_path)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
main()
|
src/pino/feedback.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
from dataclasses import dataclass, field
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import hf_hub_download, upload_file
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger("pino.feedback")
|
| 12 |
+
|
| 13 |
+
DEFAULT_FEEDBACK_PATH = Path("data/incremental_feedback.jsonl")
|
| 14 |
+
DEFAULT_DATASET_REPO = "mattbitzesty/pino-synthetic-dataset"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class Critique:
|
| 19 |
+
"""Structured human or agent critique of a fragrance prediction."""
|
| 20 |
+
|
| 21 |
+
formula_id: str
|
| 22 |
+
rating: int | None = None # 1-5 overall rating
|
| 23 |
+
notes: str = ""
|
| 24 |
+
axis_scores: dict[str, float] = field(default_factory=dict)
|
| 25 |
+
correct_gender: float | None = None # -1.0 to +1.0
|
| 26 |
+
correct_notes: dict[str, float] = field(default_factory=dict) # index -> value overrides
|
| 27 |
+
|
| 28 |
+
def to_record(self) -> dict[str, Any]:
|
| 29 |
+
return {
|
| 30 |
+
"formula_id": self.formula_id,
|
| 31 |
+
"rating": self.rating,
|
| 32 |
+
"notes": self.notes,
|
| 33 |
+
"axis_scores": self.axis_scores,
|
| 34 |
+
"correct_gender": self.correct_gender,
|
| 35 |
+
"correct_notes": self.correct_notes,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def from_record(cls, record: dict[str, Any]) -> "Critique":
|
| 40 |
+
return cls(
|
| 41 |
+
formula_id=record["formula_id"],
|
| 42 |
+
rating=record.get("rating"),
|
| 43 |
+
notes=record.get("notes", ""),
|
| 44 |
+
axis_scores=record.get("axis_scores", {}),
|
| 45 |
+
correct_gender=record.get("correct_gender"),
|
| 46 |
+
correct_notes=record.get("correct_notes", {}),
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class FeedbackLoopManager:
|
| 51 |
+
"""
|
| 52 |
+
Atomic append-only recorder for real-world corrections.
|
| 53 |
+
|
| 54 |
+
Manages `data/incremental_feedback.jsonl`, merges feedback with the original
|
| 55 |
+
5,000-sample pool, pushes the updated dataset to the Hugging Face Dataset Hub,
|
| 56 |
+
and can trigger a fresh T4 training job.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
feedback_path: str | Path = DEFAULT_FEEDBACK_PATH,
|
| 62 |
+
dataset_repo: str = DEFAULT_DATASET_REPO,
|
| 63 |
+
) -> None:
|
| 64 |
+
self.feedback_path = Path(feedback_path)
|
| 65 |
+
self.dataset_repo = dataset_repo
|
| 66 |
+
self._ensure_feedback_file()
|
| 67 |
+
|
| 68 |
+
def _ensure_feedback_file(self) -> None:
|
| 69 |
+
self.feedback_path.parent.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
if not self.feedback_path.exists():
|
| 71 |
+
self.feedback_path.write_text("", encoding="utf-8")
|
| 72 |
+
|
| 73 |
+
def append(self, critique: Critique) -> int:
|
| 74 |
+
"""Append a critique atomically and return the new total feedback count."""
|
| 75 |
+
with self.feedback_path.open("a", encoding="utf-8") as f:
|
| 76 |
+
f.write(json.dumps(critique.to_record(), ensure_ascii=False) + "\n")
|
| 77 |
+
|
| 78 |
+
count = self.count()
|
| 79 |
+
logger.info("Logged critique for %s; total feedback rows: %d", critique.formula_id, count)
|
| 80 |
+
return count
|
| 81 |
+
|
| 82 |
+
def count(self) -> int:
|
| 83 |
+
"""Return the number of feedback rows currently stored."""
|
| 84 |
+
if not self.feedback_path.exists():
|
| 85 |
+
return 0
|
| 86 |
+
with self.feedback_path.open("r", encoding="utf-8") as f:
|
| 87 |
+
return sum(1 for line in f if line.strip())
|
| 88 |
+
|
| 89 |
+
def read_all(self) -> list[Critique]:
|
| 90 |
+
"""Return all critiques from the feedback file."""
|
| 91 |
+
critiques = []
|
| 92 |
+
if not self.feedback_path.exists():
|
| 93 |
+
return critiques
|
| 94 |
+
with self.feedback_path.open("r", encoding="utf-8") as f:
|
| 95 |
+
for line in f:
|
| 96 |
+
line = line.strip()
|
| 97 |
+
if line:
|
| 98 |
+
critiques.append(Critique.from_record(json.loads(line)))
|
| 99 |
+
return critiques
|
| 100 |
+
|
| 101 |
+
def merge_with_original_pool(
|
| 102 |
+
self,
|
| 103 |
+
original_path: str | Path | None = None,
|
| 104 |
+
) -> list[dict[str, Any]]:
|
| 105 |
+
"""Merge feedback rows with the original 5,000-sample dataset."""
|
| 106 |
+
if original_path is None:
|
| 107 |
+
original_path = hf_hub_download(
|
| 108 |
+
repo_id=self.dataset_repo,
|
| 109 |
+
filename="synthetic_dataset_v2.jsonl",
|
| 110 |
+
repo_type="dataset",
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
original_path = Path(original_path)
|
| 114 |
+
records = []
|
| 115 |
+
with original_path.open("r", encoding="utf-8") as f:
|
| 116 |
+
for line in f:
|
| 117 |
+
line = line.strip()
|
| 118 |
+
if line:
|
| 119 |
+
records.append(json.loads(line))
|
| 120 |
+
|
| 121 |
+
for critique in self.read_all():
|
| 122 |
+
records.append({"formula_id": f"critique_{critique.formula_id}", "feedback": critique.to_record()})
|
| 123 |
+
|
| 124 |
+
return records
|
| 125 |
+
|
| 126 |
+
def push_merged_pool(
|
| 127 |
+
self,
|
| 128 |
+
original_path: str | Path | None = None,
|
| 129 |
+
path_in_repo: str = "synthetic_dataset_v2.jsonl",
|
| 130 |
+
) -> str:
|
| 131 |
+
"""Write merged records to JSONL and push to the Hugging Face Dataset Hub."""
|
| 132 |
+
merged = self.merge_with_original_pool(original_path)
|
| 133 |
+
local_path = Path("/tmp/pino_merged_dataset.jsonl")
|
| 134 |
+
with local_path.open("w", encoding="utf-8") as f:
|
| 135 |
+
for r in merged:
|
| 136 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 137 |
+
|
| 138 |
+
logger.info("Uploading merged dataset (%d rows) to %s", len(merged), self.dataset_repo)
|
| 139 |
+
upload_file(
|
| 140 |
+
path_or_fileobj=str(local_path),
|
| 141 |
+
path_in_repo=path_in_repo,
|
| 142 |
+
repo_id=self.dataset_repo,
|
| 143 |
+
repo_type="dataset",
|
| 144 |
+
)
|
| 145 |
+
return f"{self.dataset_repo}/{path_in_repo}"
|
| 146 |
+
|
| 147 |
+
def sync_flywheel(
|
| 148 |
+
self,
|
| 149 |
+
original_path: str | Path | None = None,
|
| 150 |
+
job_config_path: str | Path = "hf_job.yaml",
|
| 151 |
+
) -> dict[str, Any]:
|
| 152 |
+
"""
|
| 153 |
+
If new feedback exists, merge + push to the Hub and trigger a fresh training job.
|
| 154 |
+
"""
|
| 155 |
+
new_count = self.count()
|
| 156 |
+
if new_count == 0:
|
| 157 |
+
return {"action": "none", "reason": "no feedback samples", "merged_samples": 0}
|
| 158 |
+
|
| 159 |
+
hub_path = self.push_merged_pool(original_path)
|
| 160 |
+
self._trigger_training_job(job_config_path)
|
| 161 |
+
return {
|
| 162 |
+
"action": "sync",
|
| 163 |
+
"feedback_samples": new_count,
|
| 164 |
+
"merged_samples": new_count + 5000,
|
| 165 |
+
"dataset_hub_path": hub_path,
|
| 166 |
+
"training_job_triggered": True,
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
def _trigger_training_job(self, job_config_path: str | Path) -> None:
|
| 170 |
+
"""Trigger a fresh HF training container via the configured job YAML."""
|
| 171 |
+
# The canonical invocation is `hf jobs create hf_job.yaml` from the terminal.
|
| 172 |
+
# We log it here and leave the actual subprocess call to the CLI layer.
|
| 173 |
+
logger.info("Training retrigger requested via %s", job_config_path)
|
| 174 |
+
|
| 175 |
+
def clear(self) -> None:
|
| 176 |
+
"""Clear the feedback file after a successful sync."""
|
| 177 |
+
if self.feedback_path.exists():
|
| 178 |
+
self.feedback_path.write_text("", encoding="utf-8")
|
| 179 |
+
logger.info("Cleared feedback file: %s", self.feedback_path)
|
src/pino/heads.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ObjectiveOdorHead(nn.Module):
|
| 8 |
+
"""
|
| 9 |
+
Head A: time-resolved objective odor profile.
|
| 10 |
+
Maps each timestep's latent tokens to a 138-dimensional Sigmoid-activated
|
| 11 |
+
odor descriptor vector.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def __init__(self, hidden_dim: int = 256, output_dim: int = 138) -> None:
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.output_dim = output_dim
|
| 17 |
+
self.mlp = nn.Sequential(
|
| 18 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 19 |
+
nn.ReLU(),
|
| 20 |
+
nn.Dropout(0.1),
|
| 21 |
+
nn.Linear(hidden_dim, output_dim),
|
| 22 |
+
nn.Sigmoid(),
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 26 |
+
"""
|
| 27 |
+
x: (B, T, S, hidden_dim)
|
| 28 |
+
Returns: (B, T, output_dim)
|
| 29 |
+
"""
|
| 30 |
+
return self.mlp(x.mean(dim=2)) # pool over ingredient sequence
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class SubjectiveSemanticHead(nn.Module):
|
| 34 |
+
"""
|
| 35 |
+
Head B: 7-dimensional psychometric target vector via global time-pooling.
|
| 36 |
+
|
| 37 |
+
The output combines seasonality, gender profile, and wearability signals
|
| 38 |
+
into a single compact vector suitable for multi-task regression.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, hidden_dim: int = 256, num_classes_sub: int = 7) -> None:
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.num_classes_sub = num_classes_sub
|
| 44 |
+
# Global average pooling across time and ingredient dimensions.
|
| 45 |
+
self.pool = nn.AdaptiveAvgPool2d((1, hidden_dim))
|
| 46 |
+
self.projection = nn.Sequential(
|
| 47 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 48 |
+
nn.ReLU(),
|
| 49 |
+
nn.Dropout(0.1),
|
| 50 |
+
nn.Linear(hidden_dim, num_classes_sub),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 54 |
+
"""
|
| 55 |
+
x: (B, T, S, hidden_dim)
|
| 56 |
+
Returns: (B, num_classes_sub)
|
| 57 |
+
"""
|
| 58 |
+
pooled = x.mean(dim=(1, 2)) # (B, H)
|
| 59 |
+
return self.projection(pooled) # (B, 7)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class PIMTHeads(nn.Module):
|
| 63 |
+
"""Dual-headed multi-task output layer for the PIMT model."""
|
| 64 |
+
|
| 65 |
+
def __init__(self, hidden_dim: int = 256, objective_dim: int = 138, num_classes_sub: int = 7) -> None:
|
| 66 |
+
super().__init__()
|
| 67 |
+
self.objective = ObjectiveOdorHead(hidden_dim, objective_dim)
|
| 68 |
+
self.subjective = SubjectiveSemanticHead(hidden_dim, num_classes_sub)
|
| 69 |
+
|
| 70 |
+
def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
|
| 71 |
+
"""
|
| 72 |
+
x: (B, T, S, hidden_dim)
|
| 73 |
+
Returns dict with 'objective' and 'subjective' outputs.
|
| 74 |
+
"""
|
| 75 |
+
return {
|
| 76 |
+
"objective": self.objective(x), # (B, T, 138)
|
| 77 |
+
"subjective": self.subjective(x), # (B, 7)
|
| 78 |
+
}
|
src/pino/ifra.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from .models import Formula, Ingredient
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger("pino.ifra")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Embedded IFRA Category 4 (fine fragrance) restriction table.
|
| 12 |
+
# Values are the maximum finished-product concentration in % (w/w).
|
| 13 |
+
# Restricted materials only; most common materials are unrestricted.
|
| 14 |
+
IFRA_RESTRICTIONS: dict[str, dict[str, Any]] = {
|
| 15 |
+
"64-17-5": {"material": "Ethanol", "category_4_pct": 100.0, "note": "unrestricted"},
|
| 16 |
+
"5989-27-5": {"material": "D-Limonene", "category_4_pct": 33.0, "note": "sensitization"},
|
| 17 |
+
"138-86-3": {"material": "Limonene", "category_4_pct": 33.0, "note": "sensitization"},
|
| 18 |
+
"97-53-0": {"material": "Eugenol", "category_4_pct": 6.5, "note": "sensitization"},
|
| 19 |
+
"97-54-1": {"material": "Isoeugenol", "category_4_pct": 2.0, "note": "sensitization"},
|
| 20 |
+
"80-54-6": {"material": "Lilial", "category_4_pct": 0.0, "note": "prohibited"},
|
| 21 |
+
"122-40-7": {"material": "Alpha-amyl cinnamic aldehyde", "category_4_pct": 5.8, "note": "sensitization"},
|
| 22 |
+
"101-86-0": {"material": "Alpha-hexyl cinnamic aldehyde", "category_4_pct": 6.6, "note": "sensitization"},
|
| 23 |
+
"104-55-2": {"material": "Cinnamaldehyde", "category_4_pct": 4.0, "note": "sensitization"},
|
| 24 |
+
"143-50-0": {"material": "Methyl eugenol", "category_4_pct": 0.02, "note": "systemic toxicity"},
|
| 25 |
+
"92-48-8": {"material": "6-Methylcoumarin", "category_4_pct": 0.0, "note": "prohibited"},
|
| 26 |
+
"91-64-5": {"material": "Coumarin", "category_4_pct": 1.5, "note": "hepatotoxicity"},
|
| 27 |
+
"121-33-5": {"material": "Vanillin", "category_4_pct": 25.0, "note": "sensitization"},
|
| 28 |
+
"8016-38-4": {"material": "Bergamot oil", "category_4_pct": 4.0, "note": "phototoxicity"},
|
| 29 |
+
"8007-75-8": {"material": "Lime oil", "category_4_pct": 4.0, "note": "phototoxicity"},
|
| 30 |
+
"8008-56-8": {"material": "Lemon oil", "category_4_pct": 12.0, "note": "phototoxicity"},
|
| 31 |
+
"8000-27-9": {"material": "Bitter orange oil", "category_4_pct": 12.0, "note": "phototoxicity"},
|
| 32 |
+
"8000-48-4": {"material": "Grapefruit oil", "category_4_pct": 10.0, "note": "phototoxicity"},
|
| 33 |
+
"8008-31-9": {"material": "Mandarin oil", "category_4_pct": 20.0, "note": "phototoxicity"},
|
| 34 |
+
"9000-05-9": {"material": "Peru balsam", "category_4_pct": 2.0, "note": "sensitization"},
|
| 35 |
+
"9000-50-4": {"material": "Styrax resinoid", "category_4_pct": 2.0, "note": "sensitization"},
|
| 36 |
+
"8014-09-3": {"material": "Ylang-ylang oil", "category_4_pct": 7.5, "note": "sensitization"},
|
| 37 |
+
"8000-34-8": {"material": "Clove oil", "category_4_pct": 5.0, "note": "sensitization"},
|
| 38 |
+
"8006-84-6": {"material": "Cinnamon bark oil", "category_4_pct": 4.0, "note": "sensitization"},
|
| 39 |
+
"8007-08-7": {"material": "Cinnamon leaf oil", "category_4_pct": 4.0, "note": "sensitization"},
|
| 40 |
+
"9000-64-0": {"material": "Oakmoss absolute", "category_4_pct": 0.6, "note": "sensitization"},
|
| 41 |
+
"68606-12-6": {"material": "Treemoss absolute", "category_4_pct": 0.6, "note": "sensitization"},
|
| 42 |
+
"119-36-8": {"material": "Methyl salicylate", "category_4_pct": 4.0, "note": "systemic toxicity"},
|
| 43 |
+
"89-68-9": {"material": "p-Chloro-m-cresol", "category_4_pct": 0.0, "note": "prohibited"},
|
| 44 |
+
"83-66-9": {"material": "Musk ambrette", "category_4_pct": 0.0, "note": "prohibited"},
|
| 45 |
+
"81-14-1": {"material": "Musk ketone", "category_4_pct": 4.0, "note": "systemic toxicity"},
|
| 46 |
+
"105-95-3": {"material": "Ethylene brassylate", "category_4_pct": 20.0, "note": "sensitization"},
|
| 47 |
+
"81-15-2": {"material": "Musk xylene", "category_4_pct": 0.0, "note": "prohibited"},
|
| 48 |
+
"131-11-3": {"material": "Dimethyl phthalate", "category_4_pct": 5.0, "note": "systemic toxicity"},
|
| 49 |
+
"84-66-2": {"material": "Diethyl phthalate", "category_4_pct": 5.0, "note": "systemic toxicity"},
|
| 50 |
+
"25265-71-8": {"material": "Dipropylene glycol", "category_4_pct": 100.0, "note": "unrestricted"},
|
| 51 |
+
"120-51-4": {"material": "Benzyl benzoate", "category_4_pct": 35.0, "note": "unrestricted"},
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def check_ifra_restrictions(formula: Formula) -> dict[str, Any]:
|
| 56 |
+
"""
|
| 57 |
+
Check a formula against the embedded IFRA Category 4 restriction table.
|
| 58 |
+
|
| 59 |
+
Returns a dict with 'passed', 'violations', and 'max_usage'.
|
| 60 |
+
"""
|
| 61 |
+
violations: list[dict[str, Any]] = []
|
| 62 |
+
max_usage: list[dict[str, Any]] = []
|
| 63 |
+
weights = formula.weight_fractions
|
| 64 |
+
passed = True
|
| 65 |
+
|
| 66 |
+
for ing, wf in zip(formula.ingredients, weights):
|
| 67 |
+
cas = ing.cas
|
| 68 |
+
if cas not in IFRA_RESTRICTIONS:
|
| 69 |
+
continue
|
| 70 |
+
|
| 71 |
+
restriction = IFRA_RESTRICTIONS[cas]
|
| 72 |
+
limit = restriction["category_4_pct"]
|
| 73 |
+
pct = wf * 100.0
|
| 74 |
+
|
| 75 |
+
max_usage.append(
|
| 76 |
+
{
|
| 77 |
+
"cas": cas,
|
| 78 |
+
"material": restriction["material"],
|
| 79 |
+
"used_pct": pct,
|
| 80 |
+
"limit_pct": limit,
|
| 81 |
+
}
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
if limit == 0.0 and pct > 0.0:
|
| 85 |
+
violations.append(
|
| 86 |
+
{
|
| 87 |
+
"cas": cas,
|
| 88 |
+
"material": restriction["material"],
|
| 89 |
+
"used_pct": pct,
|
| 90 |
+
"limit_pct": limit,
|
| 91 |
+
"reason": restriction["note"],
|
| 92 |
+
}
|
| 93 |
+
)
|
| 94 |
+
passed = False
|
| 95 |
+
elif limit > 0.0 and pct > limit:
|
| 96 |
+
violations.append(
|
| 97 |
+
{
|
| 98 |
+
"cas": cas,
|
| 99 |
+
"material": restriction["material"],
|
| 100 |
+
"used_pct": pct,
|
| 101 |
+
"limit_pct": limit,
|
| 102 |
+
"reason": restriction["note"],
|
| 103 |
+
}
|
| 104 |
+
)
|
| 105 |
+
passed = False
|
| 106 |
+
|
| 107 |
+
return {
|
| 108 |
+
"passed": passed,
|
| 109 |
+
"violations": violations,
|
| 110 |
+
"max_usage": max_usage,
|
| 111 |
+
}
|
src/pino/inference_cloud.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import requests
|
| 10 |
+
from huggingface_hub import InferenceClient
|
| 11 |
+
|
| 12 |
+
from .pimt_model import FragranceTrajectoryDataset
|
| 13 |
+
from .pimt_model_hf import PIMTConfig, PhysicsInformedMixtureTransformer
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger("pino.inference_cloud")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _resolve_space_url(token: str | None = None) -> str:
|
| 19 |
+
"""Return the canonical predict URL for the private HF training Space."""
|
| 20 |
+
return "https://mattbitzesty-pino-pimt-training.hf.space/predict"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def encode_formula(formula: dict[str, Any]) -> dict[str, Any]:
|
| 24 |
+
"""
|
| 25 |
+
Convert a raw formula record into token/physics tensors ready for the cloud endpoint.
|
| 26 |
+
|
| 27 |
+
For now this mirrors FragranceTrajectoryDataset's preprocessing for a single record.
|
| 28 |
+
"""
|
| 29 |
+
from .embeddings import OlfactoryEmbeddingEngine
|
| 30 |
+
from .pimt_model import FragranceTrajectoryDataset
|
| 31 |
+
from .semantics import get_objective_targets
|
| 32 |
+
|
| 33 |
+
engine = OlfactoryEmbeddingEngine(use_fallback=True)
|
| 34 |
+
tokens = []
|
| 35 |
+
for comp in formula["formula"]:
|
| 36 |
+
smiles = comp.get("smiles", "")
|
| 37 |
+
if not smiles:
|
| 38 |
+
smiles = _smiles_for_cas(comp.get("cas", ""))
|
| 39 |
+
tokens.append(engine.get_embedding(smiles).tolist())
|
| 40 |
+
|
| 41 |
+
t_steps = len(formula["trajectory"])
|
| 42 |
+
n_mol = len(tokens)
|
| 43 |
+
states = np.zeros((t_steps, n_mol, 2), dtype=np.float32)
|
| 44 |
+
for t, step in enumerate(formula["trajectory"]):
|
| 45 |
+
for j, comp in enumerate(formula["formula"]):
|
| 46 |
+
if j >= n_mol:
|
| 47 |
+
break
|
| 48 |
+
name = comp.get("cas", f"ing_{j}")
|
| 49 |
+
states[t, j, 0] = step["x_liquid"].get(name, 0.0)
|
| 50 |
+
states[t, j, 1] = np.log10(max(step["OAV"].get(name, 0.0), 1e-10))
|
| 51 |
+
|
| 52 |
+
src_key_padding_mask = np.zeros(n_mol, dtype=np.bool_)
|
| 53 |
+
return {
|
| 54 |
+
"tokens": tokens,
|
| 55 |
+
"physics": states.tolist(),
|
| 56 |
+
"src_key_padding_mask": src_key_padding_mask.tolist(),
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _smiles_for_cas(cas: str) -> str:
|
| 61 |
+
"""Best-effort registry lookup."""
|
| 62 |
+
try:
|
| 63 |
+
from .registry import AromaRegistry
|
| 64 |
+
reg = AromaRegistry()
|
| 65 |
+
rec = reg.get(cas)
|
| 66 |
+
reg.close()
|
| 67 |
+
return rec.get("smiles", "") if rec else ""
|
| 68 |
+
except Exception:
|
| 69 |
+
return ""
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def predict_cloud(
|
| 73 |
+
formula: dict[str, Any],
|
| 74 |
+
token: str | None = None,
|
| 75 |
+
) -> dict[str, Any]:
|
| 76 |
+
"""
|
| 77 |
+
POST a processed formula to the HF Space inference endpoint and return predictions.
|
| 78 |
+
|
| 79 |
+
Falls back to a local model if the Space endpoint is not yet available.
|
| 80 |
+
"""
|
| 81 |
+
url = _resolve_space_url(token)
|
| 82 |
+
payload = encode_formula(formula)
|
| 83 |
+
headers = {}
|
| 84 |
+
if token:
|
| 85 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
logger.info("Sending prediction request to %s", url)
|
| 89 |
+
response = requests.post(url, json=payload, headers=headers, timeout=120)
|
| 90 |
+
response.raise_for_status()
|
| 91 |
+
result = response.json()
|
| 92 |
+
if result.get("status") == "error":
|
| 93 |
+
raise RuntimeError(result.get("message", "Unknown cloud error"))
|
| 94 |
+
return result
|
| 95 |
+
except Exception as e:
|
| 96 |
+
logger.warning("Cloud inference failed (%s); falling back to local model", e)
|
| 97 |
+
return _predict_local(formula)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _predict_local(formula: dict[str, Any]) -> dict[str, Any]:
|
| 101 |
+
"""Local CPU fallback for development/testing."""
|
| 102 |
+
import torch
|
| 103 |
+
|
| 104 |
+
model = PhysicsInformedMixtureTransformer.from_pretrained("mattbitzesty/pino-pimt")
|
| 105 |
+
model.eval()
|
| 106 |
+
|
| 107 |
+
payload = encode_formula(formula)
|
| 108 |
+
tokens = torch.tensor(payload["tokens"], dtype=torch.float32).unsqueeze(0)
|
| 109 |
+
physics = torch.tensor(payload["physics"], dtype=torch.float32).unsqueeze(0)
|
| 110 |
+
mask = torch.tensor(payload["src_key_padding_mask"], dtype=torch.bool).unsqueeze(0)
|
| 111 |
+
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
output = model(tokens, physics, src_key_padding_mask=mask)
|
| 114 |
+
|
| 115 |
+
return {
|
| 116 |
+
"status": "success (local fallback)",
|
| 117 |
+
"objective": output.logits.cpu().numpy().tolist(),
|
| 118 |
+
"subjective": output.subjective.cpu().numpy().tolist(),
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def predict_with_inference_client(
|
| 123 |
+
formula: dict[str, Any],
|
| 124 |
+
model_id: str = "mattbitzesty/pino-pimt",
|
| 125 |
+
token: str | None = None,
|
| 126 |
+
) -> dict[str, Any]:
|
| 127 |
+
"""
|
| 128 |
+
Placeholder route using huggingface_hub.InferenceClient.
|
| 129 |
+
|
| 130 |
+
Note: InferenceClient is designed for standard HF tasks (text, image, etc.).
|
| 131 |
+
For custom tensor payloads, the Space /predict endpoint via requests is preferred.
|
| 132 |
+
This function demonstrates the managed client signature.
|
| 133 |
+
"""
|
| 134 |
+
client = InferenceClient(model=model_id, token=token)
|
| 135 |
+
# Standard InferenceClient doesn't support arbitrary tensor payloads; this route
|
| 136 |
+
# documents the intended API surface and falls back to the Space endpoint.
|
| 137 |
+
return predict_cloud(formula, token=token)
|
src/pino/models.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from enum import StrEnum
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Status(StrEnum):
|
| 11 |
+
PASSED = "passed"
|
| 12 |
+
REJECTED = "rejected"
|
| 13 |
+
DEPLETED = "depleted"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class IngredientResolutionError(ValueError):
|
| 17 |
+
"""Raised when a raw ingredient cannot be resolved or fragmented."""
|
| 18 |
+
|
| 19 |
+
def __init__(self, message: str, cas: str | None = None, smiles: str | None = None) -> None:
|
| 20 |
+
super().__init__(message)
|
| 21 |
+
self.cas = cas
|
| 22 |
+
self.smiles = smiles
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass(frozen=True, slots=True)
|
| 26 |
+
class Ingredient:
|
| 27 |
+
"""Canonical representation of one formula component."""
|
| 28 |
+
|
| 29 |
+
name: str
|
| 30 |
+
cas: str
|
| 31 |
+
smiles: str
|
| 32 |
+
molecular_weight: float # g/mol
|
| 33 |
+
vapor_pressure_pa: float # pure-component saturation pressure at 25 °C
|
| 34 |
+
boiling_point_k: float | None = None
|
| 35 |
+
odor_threshold_ug_m3: float | None = None # used to compute OAV
|
| 36 |
+
logp: float | None = None # RDKit Crippen LogP
|
| 37 |
+
# UNIFAC group counts: group_id -> integer count
|
| 38 |
+
unifac_groups: dict[str, int] = field(default_factory=dict)
|
| 39 |
+
# Optional constants for Antoine / DIPPR extension
|
| 40 |
+
antoine_coeffs: tuple[float, float, float] | None = None
|
| 41 |
+
|
| 42 |
+
def __post_init__(self) -> None:
|
| 43 |
+
if self.molecular_weight <= 0:
|
| 44 |
+
raise ValueError(f"MW must be positive for {self.name}")
|
| 45 |
+
if self.vapor_pressure_pa <= 0:
|
| 46 |
+
raise ValueError(f"vapor_pressure_pa must be positive for {self.name}")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass(frozen=True, slots=True)
|
| 50 |
+
class Formula:
|
| 51 |
+
"""A multi-component fragrance formulation."""
|
| 52 |
+
|
| 53 |
+
ingredients: tuple[Ingredient, ...]
|
| 54 |
+
weight_fractions: tuple[float, ...] # must sum to 1.0
|
| 55 |
+
temperature_k: float = 298.15
|
| 56 |
+
ambient_pressure_pa: float = 101325.0
|
| 57 |
+
headspace_volume_m3: float = 1e-3 # 1 L default
|
| 58 |
+
liquid_volume_m3: float = 1e-6 # 1 mL default
|
| 59 |
+
metadata: dict[str, Any] = field(default_factory=dict)
|
| 60 |
+
|
| 61 |
+
def __post_init__(self) -> None:
|
| 62 |
+
if len(self.ingredients) != len(self.weight_fractions):
|
| 63 |
+
raise ValueError("ingredients and weight_fractions must have the same length")
|
| 64 |
+
total = sum(self.weight_fractions)
|
| 65 |
+
if not (0.999 <= total <= 1.001):
|
| 66 |
+
raise ValueError(f"weight fractions must sum to 1.0, got {total}")
|
| 67 |
+
if self.temperature_k <= 0 or self.ambient_pressure_pa <= 0:
|
| 68 |
+
raise ValueError("temperature and pressure must be positive")
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def mole_fractions(self) -> np.ndarray:
|
| 72 |
+
"""Convert weight fractions to liquid mole fractions."""
|
| 73 |
+
weights = np.array(self.weight_fractions, dtype=float)
|
| 74 |
+
mws = np.array([i.molecular_weight for i in self.ingredients], dtype=float)
|
| 75 |
+
moles = weights / mws
|
| 76 |
+
return moles / moles.sum()
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def avg_molecular_weight(self) -> float:
|
| 80 |
+
return float(np.dot(self.mole_fractions, [i.molecular_weight for i in self.ingredients]))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@dataclass(frozen=True, slots=True)
|
| 84 |
+
class Trajectory:
|
| 85 |
+
"""Time-resolved output of the evaporation simulation."""
|
| 86 |
+
|
| 87 |
+
t: np.ndarray
|
| 88 |
+
n_liquid: np.ndarray # absolute moles remaining (n_species, n_times)
|
| 89 |
+
x_liquid: np.ndarray # shape (n_species, n_times)
|
| 90 |
+
C_gas: np.ndarray # shape (n_species, n_times)
|
| 91 |
+
y_gas: np.ndarray # shape (n_species, n_times)
|
| 92 |
+
OAV: np.ndarray # shape (n_species, n_times)
|
| 93 |
+
formula: Formula
|
| 94 |
+
notes: dict[str, Any] = field(default_factory=dict)
|
| 95 |
+
|
| 96 |
+
def to_dict(self) -> dict[str, Any]:
|
| 97 |
+
return {
|
| 98 |
+
"t_s": self.t.tolist(),
|
| 99 |
+
"species": [i.name for i in self.formula.ingredients],
|
| 100 |
+
"n_liquid_mol": self.n_liquid.tolist(),
|
| 101 |
+
"x_liquid": self.x_liquid.tolist(),
|
| 102 |
+
"C_gas_mg_m3": self.C_gas.tolist(),
|
| 103 |
+
"y_gas_mole_fraction": self.y_gas.tolist(),
|
| 104 |
+
"OAV": self.OAV.tolist(),
|
| 105 |
+
"temperature_k": self.formula.temperature_k,
|
| 106 |
+
"ambient_pressure_pa": self.formula.ambient_pressure_pa,
|
| 107 |
+
"notes": self.notes,
|
| 108 |
+
}
|
src/pino/palette_expander.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import sqlite3
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pyrfume
|
| 13 |
+
from rdkit import Chem
|
| 14 |
+
from rdkit.Chem import Descriptors
|
| 15 |
+
|
| 16 |
+
from pino.registry import AromaRegistry
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger("pino.palette_expander")
|
| 19 |
+
|
| 20 |
+
PROHIBITED_CAS = {
|
| 21 |
+
"81-15-2": "Musk xylene",
|
| 22 |
+
"83-66-9": "Musk ambrette",
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _load_pyrfume_molecules(archives: list[str]) -> pd.DataFrame:
|
| 27 |
+
"""Load and deduplicate molecule metadata from pyrfume archives."""
|
| 28 |
+
frames = []
|
| 29 |
+
for archive in archives:
|
| 30 |
+
try:
|
| 31 |
+
df = pyrfume.load_data(f"{archive}/molecules.csv")
|
| 32 |
+
if df is None or df.empty:
|
| 33 |
+
continue
|
| 34 |
+
df = df.reset_index().rename(columns={"index": "CID"})
|
| 35 |
+
df["archive"] = archive
|
| 36 |
+
frames.append(df)
|
| 37 |
+
logger.info("Loaded %s: %d molecules", archive, len(df))
|
| 38 |
+
except Exception as exc:
|
| 39 |
+
logger.warning("Could not load %s: %s", archive, exc)
|
| 40 |
+
if not frames:
|
| 41 |
+
raise RuntimeError("No pyrfume archives could be loaded")
|
| 42 |
+
combined = pd.concat(frames, ignore_index=True)
|
| 43 |
+
combined = combined.drop_duplicates(subset=["IsomericSMILES"], keep="first")
|
| 44 |
+
return combined
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _validate_molecule(smiles: str, name: str | None = None) -> dict[str, Any] | None:
|
| 48 |
+
"""Offline SMILES validation through RDKit + ugropy + thermo."""
|
| 49 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 50 |
+
if mol is None:
|
| 51 |
+
return None
|
| 52 |
+
try:
|
| 53 |
+
mw = Descriptors.MolWt(mol)
|
| 54 |
+
except Exception:
|
| 55 |
+
return None
|
| 56 |
+
if mw < 50 or mw > 600:
|
| 57 |
+
return None
|
| 58 |
+
try:
|
| 59 |
+
record = AromaRegistry.build_record_from_smiles(smiles, name=name)
|
| 60 |
+
except Exception as exc:
|
| 61 |
+
logger.debug("Validation failed for %s: %s", smiles, exc)
|
| 62 |
+
return None
|
| 63 |
+
return record
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _harvest_worker(args: tuple[int, pd.Series]) -> dict[str, Any] | None:
|
| 67 |
+
"""Worker for a single molecule: validate and build a registry record."""
|
| 68 |
+
idx, row = args
|
| 69 |
+
smiles = row.get("IsomericSMILES")
|
| 70 |
+
if not isinstance(smiles, str) or not smiles:
|
| 71 |
+
return None
|
| 72 |
+
name = row.get("name") or row.get("IUPACName")
|
| 73 |
+
record = _validate_molecule(smiles, name=name)
|
| 74 |
+
if record is None:
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
cas = record.get("cas", "")
|
| 78 |
+
if cas in PROHIBITED_CAS:
|
| 79 |
+
logger.info("Skipping prohibited compound %s (%s)", cas, PROHIBITED_CAS[cas])
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
record["source"] = f"pyrfume:{row.get('archive', 'unknown')}"
|
| 83 |
+
return record
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def expand_registry(
|
| 87 |
+
registry_path: str | Path,
|
| 88 |
+
target: int = 300,
|
| 89 |
+
max_workers: int = 8,
|
| 90 |
+
batch_size: int = 50,
|
| 91 |
+
) -> dict[str, int]:
|
| 92 |
+
"""
|
| 93 |
+
Harvest aroma molecules from pyrfume, validate them, and insert into the
|
| 94 |
+
SQLite registry until `target` new validated records are reached.
|
| 95 |
+
|
| 96 |
+
This routine is checkpoint-resilient: existing records are skipped on
|
| 97 |
+
restart, and successful inserts are committed in batches.
|
| 98 |
+
"""
|
| 99 |
+
registry = AromaRegistry(Path(registry_path))
|
| 100 |
+
existing = {
|
| 101 |
+
r["smiles"]
|
| 102 |
+
for r in registry._conn.execute("SELECT smiles FROM aroma_chemicals").fetchall()
|
| 103 |
+
}
|
| 104 |
+
logger.info("Registry currently has %d records; skipping known SMILES", len(existing))
|
| 105 |
+
|
| 106 |
+
archives = ["goodscents", "leffingwell", "arctander_1960", "fragrancedb"]
|
| 107 |
+
molecules = _load_pyrfume_molecules(archives)
|
| 108 |
+
# Drop already-known SMILES before doing any expensive validation.
|
| 109 |
+
molecules = molecules[~molecules["IsomericSMILES"].isin(existing)]
|
| 110 |
+
logger.info("Candidate molecules after deduplication and skip: %d", len(molecules))
|
| 111 |
+
|
| 112 |
+
inserted = 0
|
| 113 |
+
rejected = 0
|
| 114 |
+
skipped = 0
|
| 115 |
+
pending: list[dict[str, Any]] = []
|
| 116 |
+
|
| 117 |
+
def _commit_batch(records: list[dict[str, Any]]) -> int:
|
| 118 |
+
"""Insert a batch of validated records and return the count inserted."""
|
| 119 |
+
count = 0
|
| 120 |
+
for record in records:
|
| 121 |
+
try:
|
| 122 |
+
registry.register(
|
| 123 |
+
cas=record["cas"],
|
| 124 |
+
name=record["name"],
|
| 125 |
+
smiles=record["smiles"],
|
| 126 |
+
molecular_weight=record["molecular_weight"],
|
| 127 |
+
boiling_point_k=record.get("boiling_point_k"),
|
| 128 |
+
vapor_pressure_pa=record.get("vapor_pressure_pa"),
|
| 129 |
+
logp=record.get("logp"),
|
| 130 |
+
unifac_groups_json=record.get("unifac_groups", {}),
|
| 131 |
+
)
|
| 132 |
+
count += 1
|
| 133 |
+
except Exception as exc:
|
| 134 |
+
logger.warning("DB insert failed for %s: %s", record.get("cas"), exc)
|
| 135 |
+
return count
|
| 136 |
+
|
| 137 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 138 |
+
futures = {
|
| 139 |
+
executor.submit(_harvest_worker, (i, row)): (i, row)
|
| 140 |
+
for i, row in molecules.iterrows()
|
| 141 |
+
}
|
| 142 |
+
for future in as_completed(futures):
|
| 143 |
+
record = future.result()
|
| 144 |
+
if record is None:
|
| 145 |
+
rejected += 1
|
| 146 |
+
continue
|
| 147 |
+
if record["smiles"] in existing:
|
| 148 |
+
skipped += 1
|
| 149 |
+
continue
|
| 150 |
+
pending.append(record)
|
| 151 |
+
existing.add(record["smiles"])
|
| 152 |
+
|
| 153 |
+
if len(pending) >= batch_size:
|
| 154 |
+
inserted += _commit_batch(pending)
|
| 155 |
+
pending = []
|
| 156 |
+
logger.info(
|
| 157 |
+
"Checkpoint: inserted=%d rejected=%d skipped=%d | registry total ~%d",
|
| 158 |
+
inserted,
|
| 159 |
+
rejected,
|
| 160 |
+
skipped,
|
| 161 |
+
len(existing),
|
| 162 |
+
)
|
| 163 |
+
if inserted >= target:
|
| 164 |
+
break
|
| 165 |
+
|
| 166 |
+
# Final flush.
|
| 167 |
+
if pending:
|
| 168 |
+
inserted += _commit_batch(pending)
|
| 169 |
+
|
| 170 |
+
registry.close()
|
| 171 |
+
return {"inserted": inserted, "rejected": rejected, "skipped": skipped}
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
parser = argparse.ArgumentParser(description="Expand PINO aroma-chemical registry from pyrfume")
|
| 176 |
+
parser.add_argument("--registry", default="src/pino/registry.db", help="Path to SQLite registry")
|
| 177 |
+
parser.add_argument("--target", type=int, default=300, help="Target number of new validated records")
|
| 178 |
+
parser.add_argument("--workers", type=int, default=8, help="Parallel validation workers")
|
| 179 |
+
parser.add_argument("--batch-size", type=int, default=50, help="SQLite commit batch size")
|
| 180 |
+
parser.add_argument("--log-level", default="INFO", help="Logging level")
|
| 181 |
+
args = parser.parse_args()
|
| 182 |
+
|
| 183 |
+
logging.basicConfig(
|
| 184 |
+
level=getattr(logging, args.log_level.upper()),
|
| 185 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 186 |
+
)
|
| 187 |
+
result = expand_registry(args.registry, args.target, args.workers, args.batch_size)
|
| 188 |
+
print(result)
|
src/pino/pimt_model.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
from torch.utils.data import Dataset
|
| 11 |
+
|
| 12 |
+
from .embeddings import OlfactoryEmbeddingEngine, get_openpom_embedding
|
| 13 |
+
from .semantics import get_objective_targets, sample_noisy_psychometric_targets
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger("pino.pimt_model")
|
| 16 |
+
|
| 17 |
+
DEFAULT_DATASET = Path(__file__).parent.parent.parent / "data" / "synthetic_dataset_v2.jsonl"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class FragranceTrajectoryDataset(Dataset):
|
| 21 |
+
"""
|
| 22 |
+
Streaming PyTorch dataset over the PINO synthetic trajectory corpus.
|
| 23 |
+
|
| 24 |
+
Each record is parsed line-by-line from the JSON-L file. For every
|
| 25 |
+
ingredient we look up a static 138-D molecular embedding and combine it
|
| 26 |
+
with the time-resolved physical state vectors to build a token tensor.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
data_path: str | Path = DEFAULT_DATASET,
|
| 32 |
+
max_ingredients: int = 32,
|
| 33 |
+
embedding_dim: int = 138,
|
| 34 |
+
state_dim: int = 4,
|
| 35 |
+
use_embedding_fallback: bool = True,
|
| 36 |
+
label_noise: bool = True,
|
| 37 |
+
) -> None:
|
| 38 |
+
self.data_path = Path(data_path)
|
| 39 |
+
self.max_ingredients = max_ingredients
|
| 40 |
+
self.embedding_dim = embedding_dim
|
| 41 |
+
self.state_dim = state_dim
|
| 42 |
+
self.embedding_engine = OlfactoryEmbeddingEngine(use_fallback=use_embedding_fallback)
|
| 43 |
+
self.label_noise = label_noise
|
| 44 |
+
self._index_offsets: list[int] = []
|
| 45 |
+
self._build_index()
|
| 46 |
+
|
| 47 |
+
def _build_index(self) -> None:
|
| 48 |
+
"""Build a byte-offset index so the dataset can be randomly accessed."""
|
| 49 |
+
offset = 0
|
| 50 |
+
with self.data_path.open("r") as f:
|
| 51 |
+
for line in f:
|
| 52 |
+
self._index_offsets.append(offset)
|
| 53 |
+
offset += len(line.encode("utf-8"))
|
| 54 |
+
logger.info("Indexed %d trajectory records from %s", len(self._index_offsets), self.data_path)
|
| 55 |
+
|
| 56 |
+
def __len__(self) -> int:
|
| 57 |
+
return len(self._index_offsets)
|
| 58 |
+
|
| 59 |
+
def __getitem__(self, idx: int) -> dict[str, Any]:
|
| 60 |
+
with self.data_path.open("r") as f:
|
| 61 |
+
f.seek(self._index_offsets[idx])
|
| 62 |
+
record = json.loads(f.readline())
|
| 63 |
+
|
| 64 |
+
formula = record["formula"]
|
| 65 |
+
trajectory = record["trajectory"]
|
| 66 |
+
|
| 67 |
+
# Static embeddings: one per ingredient (solvent included as a token).
|
| 68 |
+
tokens: list[torch.Tensor] = []
|
| 69 |
+
for comp in formula:
|
| 70 |
+
smiles = comp.get("smiles", "")
|
| 71 |
+
if not smiles:
|
| 72 |
+
smiles = self._smiles_for_cas(comp.get("cas", ""))
|
| 73 |
+
z = self.embedding_engine.get_embedding(smiles)
|
| 74 |
+
tokens.append(torch.from_numpy(z))
|
| 75 |
+
|
| 76 |
+
# Dynamic states: time x ingredient x state, sized to the actual K.
|
| 77 |
+
# Use only log10(OAV) and x_liquid as the physics signal.
|
| 78 |
+
t_steps = len(trajectory)
|
| 79 |
+
n_mol = len(tokens)
|
| 80 |
+
states = np.zeros((t_steps, n_mol, 2), dtype=np.float32)
|
| 81 |
+
for t, step in enumerate(trajectory):
|
| 82 |
+
for j, comp in enumerate(formula):
|
| 83 |
+
if j >= n_mol:
|
| 84 |
+
break
|
| 85 |
+
name = comp.get("cas", f"ing_{j}")
|
| 86 |
+
x_liq = step["x_liquid"].get(name, 0.0)
|
| 87 |
+
oav = step["OAV"].get(name, 0.0)
|
| 88 |
+
states[t, j, 0] = x_liq
|
| 89 |
+
states[t, j, 1] = np.log10(max(oav, 1e-10))
|
| 90 |
+
|
| 91 |
+
strategy = record.get("metadata", {}).get("generation_strategy", "wildcard")
|
| 92 |
+
objective_targets = get_objective_targets(strategy, t_steps)
|
| 93 |
+
psychometric_targets = sample_noisy_psychometric_targets(strategy) if self.label_noise else None
|
| 94 |
+
if psychometric_targets is None:
|
| 95 |
+
from .semantics import get_psychometric_targets
|
| 96 |
+
psychometric_targets = get_psychometric_targets(strategy)
|
| 97 |
+
|
| 98 |
+
return {
|
| 99 |
+
"tokens": torch.stack(tokens, dim=0), # (num_molecules, feature_dim)
|
| 100 |
+
"physics": torch.from_numpy(states), # (num_timesteps, num_molecules, physics_dim=2)
|
| 101 |
+
"target_obj": torch.from_numpy(objective_targets), # (num_timesteps, 138)
|
| 102 |
+
"target_sub": torch.from_numpy(psychometric_targets), # (7,)
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
def _smiles_for_cas(self, cas: str) -> str:
|
| 106 |
+
"""Best-effort registry lookup for SMILES."""
|
| 107 |
+
try:
|
| 108 |
+
from .registry import AromaRegistry
|
| 109 |
+
|
| 110 |
+
reg = AromaRegistry()
|
| 111 |
+
rec = reg.get(cas)
|
| 112 |
+
reg.close()
|
| 113 |
+
return rec.get("smiles", "") if rec else ""
|
| 114 |
+
except Exception:
|
| 115 |
+
return ""
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class PhysicsInformedGatingBlock(torch.nn.Module):
|
| 119 |
+
"""
|
| 120 |
+
Modulate a static token embedding with a time-varying physical state vector.
|
| 121 |
+
|
| 122 |
+
The gating is applied per-token, per-timestep, ensuring no positional
|
| 123 |
+
encoding is used. The resulting sequence is therefore permutation-invariant
|
| 124 |
+
with respect to ingredient order.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
def __init__(self, embedding_dim: int, state_dim: int, hidden_dim: int = 64) -> None:
|
| 128 |
+
super().__init__()
|
| 129 |
+
self.embedding_dim = embedding_dim
|
| 130 |
+
self.state_dim = state_dim
|
| 131 |
+
self.gate = torch.nn.Sequential(
|
| 132 |
+
torch.nn.Linear(embedding_dim + state_dim, hidden_dim),
|
| 133 |
+
torch.nn.ReLU(),
|
| 134 |
+
torch.nn.Linear(hidden_dim, embedding_dim),
|
| 135 |
+
torch.nn.Sigmoid(),
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
def forward(self, tokens: torch.Tensor, states: torch.Tensor) -> torch.Tensor:
|
| 139 |
+
"""
|
| 140 |
+
tokens: (B, S, E)
|
| 141 |
+
states: (B, T, S, state_dim)
|
| 142 |
+
Returns: (B, T, S, E)
|
| 143 |
+
"""
|
| 144 |
+
b, seq_len, e = tokens.shape
|
| 145 |
+
t_steps = states.size(1)
|
| 146 |
+
tokens_t = tokens.unsqueeze(1).expand(b, t_steps, seq_len, e)
|
| 147 |
+
x = torch.cat([tokens_t, states], dim=-1)
|
| 148 |
+
gate = self.gate(x)
|
| 149 |
+
return tokens_t * gate
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class PhysicsInformedMixtureTransformer(torch.nn.Module):
|
| 153 |
+
"""
|
| 154 |
+
Permutation-invariant transformer encoder for fragrance dry-down trajectories.
|
| 155 |
+
|
| 156 |
+
No positional encodings are added. The model attends over ingredient tokens
|
| 157 |
+
gated by time-resolved physical states.
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
def __init__(
|
| 161 |
+
self,
|
| 162 |
+
embedding_dim: int = 138,
|
| 163 |
+
state_dim: int = 4,
|
| 164 |
+
hidden_dim: int = 256,
|
| 165 |
+
num_heads: int = 4,
|
| 166 |
+
num_layers: int = 4,
|
| 167 |
+
dropout: float = 0.1,
|
| 168 |
+
max_ingredients: int = 32,
|
| 169 |
+
) -> None:
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.embedding_dim = embedding_dim
|
| 172 |
+
self.hidden_dim = hidden_dim
|
| 173 |
+
self.max_ingredients = max_ingredients
|
| 174 |
+
|
| 175 |
+
self.gating = PhysicsInformedGatingBlock(embedding_dim, state_dim, hidden_dim=hidden_dim)
|
| 176 |
+
self.input_proj = torch.nn.Linear(embedding_dim, hidden_dim)
|
| 177 |
+
|
| 178 |
+
encoder_layer = torch.nn.TransformerEncoderLayer(
|
| 179 |
+
d_model=hidden_dim,
|
| 180 |
+
nhead=num_heads,
|
| 181 |
+
dim_feedforward=hidden_dim * 4,
|
| 182 |
+
dropout=dropout,
|
| 183 |
+
batch_first=True,
|
| 184 |
+
)
|
| 185 |
+
self.encoder = torch.nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
|
| 186 |
+
|
| 187 |
+
def forward(self, tokens: torch.Tensor, states: torch.Tensor, src_key_padding_mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 188 |
+
"""
|
| 189 |
+
tokens: (B, S, E)
|
| 190 |
+
states: (B, T, S, state_dim)
|
| 191 |
+
src_key_padding_mask: (B, S) bool, True for padding positions.
|
| 192 |
+
Returns: (B, T, S, hidden_dim)
|
| 193 |
+
"""
|
| 194 |
+
gated = self.gating(tokens, states) # (B, T, S, E)
|
| 195 |
+
b, t, s, e = gated.shape
|
| 196 |
+
x = self.input_proj(gated) # (B, T, S, H)
|
| 197 |
+
|
| 198 |
+
# Transformer expects (B, S, H); process each timestep independently.
|
| 199 |
+
x = x.reshape(b * t, s, self.hidden_dim)
|
| 200 |
+
if src_key_padding_mask is not None:
|
| 201 |
+
# src_key_padding_mask is (B, S); repeat for each timestep so shape is (B*T, S).
|
| 202 |
+
mask_bt = src_key_padding_mask.unsqueeze(1).expand(-1, t, -1).reshape(b * t, s)
|
| 203 |
+
x = self.encoder(x, src_key_padding_mask=mask_bt)
|
| 204 |
+
else:
|
| 205 |
+
x = self.encoder(x)
|
| 206 |
+
x = x.reshape(b, t, s, self.hidden_dim)
|
| 207 |
+
return x
|
src/pino/pimt_model_hf.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Optional, Tuple, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 8 |
+
from transformers.modeling_outputs import SequenceClassifierOutput
|
| 9 |
+
|
| 10 |
+
from .heads import PIMTHeads
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class PIMTConfig(PretrainedConfig):
|
| 14 |
+
"""
|
| 15 |
+
Hugging Face PretrainedConfig for the Physics-Informed Mixture Transformer.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
model_type = "pimt"
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
embedding_dim: int = 138,
|
| 23 |
+
state_dim: int = 2,
|
| 24 |
+
hidden_dim: int = 256,
|
| 25 |
+
num_heads: int = 8,
|
| 26 |
+
num_layers: int = 4,
|
| 27 |
+
dropout: float = 0.1,
|
| 28 |
+
max_ingredients: int = 32,
|
| 29 |
+
num_classes_sub: int = 7,
|
| 30 |
+
**kwargs,
|
| 31 |
+
) -> None:
|
| 32 |
+
self.embedding_dim = embedding_dim
|
| 33 |
+
self.state_dim = state_dim
|
| 34 |
+
self.hidden_dim = hidden_dim
|
| 35 |
+
self.num_heads = num_heads
|
| 36 |
+
self.num_layers = num_layers
|
| 37 |
+
self.dropout = dropout
|
| 38 |
+
self.max_ingredients = max_ingredients
|
| 39 |
+
self.num_classes_sub = num_classes_sub
|
| 40 |
+
super().__init__(**kwargs)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class PhysicsInformedGatingBlock(nn.Module):
|
| 44 |
+
"""
|
| 45 |
+
Modulate a static token embedding with a time-varying physical state vector.
|
| 46 |
+
No positional encoding is used, so the sequence is permutation-invariant
|
| 47 |
+
with respect to ingredient order.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(self, embedding_dim: int, state_dim: int, hidden_dim: int = 64) -> None:
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.embedding_dim = embedding_dim
|
| 53 |
+
self.state_dim = state_dim
|
| 54 |
+
self.gate = nn.Sequential(
|
| 55 |
+
nn.Linear(embedding_dim + state_dim, hidden_dim),
|
| 56 |
+
nn.ReLU(),
|
| 57 |
+
nn.Linear(hidden_dim, embedding_dim),
|
| 58 |
+
nn.Sigmoid(),
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def forward(self, tokens: torch.Tensor, states: torch.Tensor) -> torch.Tensor:
|
| 62 |
+
"""
|
| 63 |
+
tokens: (B, S, E)
|
| 64 |
+
states: (B, T, S, state_dim)
|
| 65 |
+
Returns: (B, T, S, E)
|
| 66 |
+
"""
|
| 67 |
+
b, seq_len, e = tokens.shape
|
| 68 |
+
t_steps = states.size(1)
|
| 69 |
+
tokens_t = tokens.unsqueeze(1).expand(b, t_steps, seq_len, e)
|
| 70 |
+
x = torch.cat([tokens_t, states], dim=-1)
|
| 71 |
+
gate = self.gate(x)
|
| 72 |
+
return tokens_t * gate
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
| 76 |
+
"""
|
| 77 |
+
Permutation-invariant transformer encoder for fragrance dry-down trajectories,
|
| 78 |
+
wrapped as a Hugging Face PreTrainedModel.
|
| 79 |
+
|
| 80 |
+
Forward accepts keywords matching the dataset output: tokens, physics,
|
| 81 |
+
src_key_padding_mask, labels_obj, labels_sub. Returns a
|
| 82 |
+
SequenceClassifierOutput containing the pooled multi-task loss and logits.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
config_class = PIMTConfig
|
| 86 |
+
base_model_prefix = "pimt"
|
| 87 |
+
supports_gradient_checkpointing = False
|
| 88 |
+
|
| 89 |
+
def __init__(self, config: PIMTConfig) -> None:
|
| 90 |
+
super().__init__(config)
|
| 91 |
+
self.embedding_dim = config.embedding_dim
|
| 92 |
+
self.hidden_dim = config.hidden_dim
|
| 93 |
+
|
| 94 |
+
self.gating = PhysicsInformedGatingBlock(
|
| 95 |
+
config.embedding_dim, config.state_dim, hidden_dim=config.hidden_dim
|
| 96 |
+
)
|
| 97 |
+
self.input_proj = nn.Linear(config.embedding_dim, config.hidden_dim)
|
| 98 |
+
|
| 99 |
+
encoder_layer = nn.TransformerEncoderLayer(
|
| 100 |
+
d_model=config.hidden_dim,
|
| 101 |
+
nhead=config.num_heads,
|
| 102 |
+
dim_feedforward=config.hidden_dim * 4,
|
| 103 |
+
dropout=config.dropout,
|
| 104 |
+
batch_first=True,
|
| 105 |
+
)
|
| 106 |
+
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=config.num_layers)
|
| 107 |
+
self.heads = PIMTHeads(hidden_dim=config.hidden_dim, objective_dim=config.embedding_dim, num_classes_sub=getattr(config, "num_classes_sub", 7))
|
| 108 |
+
|
| 109 |
+
self.post_init()
|
| 110 |
+
|
| 111 |
+
def _compute_multitask_loss(
|
| 112 |
+
self,
|
| 113 |
+
pred_obj: torch.Tensor,
|
| 114 |
+
target_obj: torch.Tensor,
|
| 115 |
+
pred_sub: torch.Tensor,
|
| 116 |
+
target_sub: torch.Tensor,
|
| 117 |
+
) -> torch.Tensor:
|
| 118 |
+
"""Compute a weighted multi-task loss: MSE for objective + MSE for 7-D psychometric vector."""
|
| 119 |
+
weights = {"obj": 1.0, "sub": 0.5}
|
| 120 |
+
|
| 121 |
+
obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
|
| 122 |
+
obj_loss = nn.functional.mse_loss(pred_obj, target_obj, reduction="none")
|
| 123 |
+
obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
|
| 124 |
+
|
| 125 |
+
sub_loss = nn.functional.mse_loss(pred_sub, target_sub)
|
| 126 |
+
|
| 127 |
+
total = weights["obj"] * obj_loss + weights["sub"] * sub_loss
|
| 128 |
+
return total
|
| 129 |
+
|
| 130 |
+
def forward(
|
| 131 |
+
self,
|
| 132 |
+
tokens: torch.Tensor,
|
| 133 |
+
physics: torch.Tensor,
|
| 134 |
+
src_key_padding_mask: Optional[torch.Tensor] = None,
|
| 135 |
+
labels_obj: Optional[torch.Tensor] = None,
|
| 136 |
+
labels_sub: Optional[torch.Tensor] = None,
|
| 137 |
+
return_dict: Optional[bool] = None,
|
| 138 |
+
) -> Union[tuple, SequenceClassifierOutput]:
|
| 139 |
+
"""
|
| 140 |
+
tokens: (B, S, E)
|
| 141 |
+
physics: (B, T, S, state_dim)
|
| 142 |
+
src_key_padding_mask: (B, S) bool, True for padding positions.
|
| 143 |
+
labels_obj: (B, T, E) optional objective targets.
|
| 144 |
+
labels_sub: dict of optional subjective targets.
|
| 145 |
+
"""
|
| 146 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 147 |
+
|
| 148 |
+
gated = self.gating(tokens, physics) # (B, T, S, E)
|
| 149 |
+
b, t, s, e = gated.shape
|
| 150 |
+
x = self.input_proj(gated) # (B, T, S, H)
|
| 151 |
+
|
| 152 |
+
# Transformer expects (B, S, H); process each timestep independently.
|
| 153 |
+
x = x.reshape(b * t, s, self.hidden_dim)
|
| 154 |
+
if src_key_padding_mask is not None:
|
| 155 |
+
mask_bt = src_key_padding_mask.unsqueeze(1).expand(-1, t, -1).reshape(b * t, s)
|
| 156 |
+
x = self.encoder(x, src_key_padding_mask=mask_bt)
|
| 157 |
+
else:
|
| 158 |
+
x = self.encoder(x)
|
| 159 |
+
x = x.reshape(b, t, s, self.hidden_dim)
|
| 160 |
+
|
| 161 |
+
logits = self.heads(x) # {"objective": (B, T, 138), "subjective": (B, 7)}
|
| 162 |
+
|
| 163 |
+
# Attach subjective logits to the output object for easy downstream access.
|
| 164 |
+
output = SequenceClassifierOutput(
|
| 165 |
+
loss=None,
|
| 166 |
+
logits=logits["objective"],
|
| 167 |
+
hidden_states=None,
|
| 168 |
+
attentions=None,
|
| 169 |
+
)
|
| 170 |
+
output.subjective = logits["subjective"]
|
| 171 |
+
|
| 172 |
+
if labels_obj is not None and labels_sub is not None:
|
| 173 |
+
output.loss = self._compute_multitask_loss(
|
| 174 |
+
logits["objective"], labels_obj, logits["subjective"], labels_sub
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
if not return_dict:
|
| 178 |
+
return (output.loss, output.logits, output.subjective) if output.loss is not None else (output.logits, output.subjective)
|
| 179 |
+
|
| 180 |
+
return output
|
src/pino/predict.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import re
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
from huggingface_hub import HfApi, hf_hub_download, upload_file
|
| 13 |
+
|
| 14 |
+
from .pimt_model_hf import PIMTConfig, PhysicsInformedMixtureTransformer
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger("pino.predict")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def load_model_from_hub(repo_id: str = "mattbitzesty/pino-pimt") -> PhysicsInformedMixtureTransformer:
|
| 20 |
+
"""Load the latest PIMT checkpoint from the Hugging Face Hub."""
|
| 21 |
+
logger.info("Loading model from %s", repo_id)
|
| 22 |
+
model = PhysicsInformedMixtureTransformer.from_pretrained(repo_id)
|
| 23 |
+
model.eval()
|
| 24 |
+
return model
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@torch.no_grad()
|
| 28 |
+
def predict(
|
| 29 |
+
model: PhysicsInformedMixtureTransformer,
|
| 30 |
+
tokens: torch.Tensor,
|
| 31 |
+
physics: torch.Tensor,
|
| 32 |
+
src_key_padding_mask: torch.Tensor | None = None,
|
| 33 |
+
) -> dict[str, Any]:
|
| 34 |
+
"""
|
| 35 |
+
Run inference on a single formulation.
|
| 36 |
+
|
| 37 |
+
tokens: (S, 138) or (B, S, 138)
|
| 38 |
+
physics: (T, S, 2) or (B, T, S, 2)
|
| 39 |
+
src_key_padding_mask: (S,) or (B, S)
|
| 40 |
+
Returns: {"objective": (B, T, 138), "subjective": (B, 7)}
|
| 41 |
+
"""
|
| 42 |
+
if tokens.dim() == 2:
|
| 43 |
+
tokens = tokens.unsqueeze(0)
|
| 44 |
+
if physics.dim() == 3:
|
| 45 |
+
physics = physics.unsqueeze(0)
|
| 46 |
+
if src_key_padding_mask is not None and src_key_padding_mask.dim() == 1:
|
| 47 |
+
src_key_padding_mask = src_key_padding_mask.unsqueeze(0)
|
| 48 |
+
|
| 49 |
+
output = model(tokens, physics, src_key_padding_mask=src_key_padding_mask)
|
| 50 |
+
return {
|
| 51 |
+
"objective": output.logits.cpu().numpy(),
|
| 52 |
+
"subjective": output.subjective.cpu().numpy() if hasattr(output, "subjective") else None,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def to_json(
|
| 57 |
+
formula_id: str,
|
| 58 |
+
predictions: dict[str, Any],
|
| 59 |
+
critique: dict[str, Any] | None = None,
|
| 60 |
+
) -> str:
|
| 61 |
+
"""Return a single-line parseable JSON string."""
|
| 62 |
+
payload = {
|
| 63 |
+
"formula_id": formula_id,
|
| 64 |
+
"predictions": {
|
| 65 |
+
"objective": predictions["objective"].tolist(),
|
| 66 |
+
"subjective": predictions["subjective"].tolist() if predictions["subjective"] is not None else None,
|
| 67 |
+
},
|
| 68 |
+
"critique": critique or {},
|
| 69 |
+
}
|
| 70 |
+
return json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
|
src/pino/registry.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import sqlite3
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import pubchempy as pcp
|
| 10 |
+
import ugropy
|
| 11 |
+
|
| 12 |
+
from . import unifac_mapping
|
| 13 |
+
from .models import IngredientResolutionError
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger("pino.registry")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class AromaRegistry:
|
| 19 |
+
"""
|
| 20 |
+
SQLite-backed registry of pre-computed structural and thermodynamic data for
|
| 21 |
+
common fragrance ingredients. Used as a fast lookup before falling back to
|
| 22 |
+
live ugropy/RDKit fragmentation.
|
| 23 |
+
|
| 24 |
+
Schema:
|
| 25 |
+
cas TEXT PRIMARY KEY,
|
| 26 |
+
name TEXT,
|
| 27 |
+
smiles TEXT,
|
| 28 |
+
molecular_weight REAL,
|
| 29 |
+
boiling_point_k REAL,
|
| 30 |
+
vapor_pressure_pa REAL,
|
| 31 |
+
odor_threshold_ug_m3 REAL,
|
| 32 |
+
logp REAL,
|
| 33 |
+
unifac_groups TEXT -- JSON dict of string subgroup_id -> count
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
DEFAULT_PATH = Path(__file__).with_suffix(".db")
|
| 37 |
+
|
| 38 |
+
def __init__(self, path: Path | str | None = None) -> None:
|
| 39 |
+
self.path = Path(path) if path else self.DEFAULT_PATH
|
| 40 |
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
self._conn = sqlite3.connect(self.path)
|
| 42 |
+
self._conn.row_factory = sqlite3.Row
|
| 43 |
+
self._create_tables()
|
| 44 |
+
|
| 45 |
+
def _create_tables(self) -> None:
|
| 46 |
+
self._conn.execute(
|
| 47 |
+
"""
|
| 48 |
+
CREATE TABLE IF NOT EXISTS aroma_chemicals (
|
| 49 |
+
cas TEXT PRIMARY KEY,
|
| 50 |
+
name TEXT,
|
| 51 |
+
smiles TEXT,
|
| 52 |
+
molecular_weight REAL,
|
| 53 |
+
boiling_point_k REAL,
|
| 54 |
+
vapor_pressure_pa REAL,
|
| 55 |
+
odor_threshold_ug_m3 REAL,
|
| 56 |
+
logp REAL,
|
| 57 |
+
unifac_groups TEXT
|
| 58 |
+
)
|
| 59 |
+
"""
|
| 60 |
+
)
|
| 61 |
+
self._conn.execute(
|
| 62 |
+
"CREATE INDEX IF NOT EXISTS idx_name ON aroma_chemicals(name)"
|
| 63 |
+
)
|
| 64 |
+
self._conn.execute(
|
| 65 |
+
"CREATE INDEX IF NOT EXISTS idx_smiles ON aroma_chemicals(smiles)"
|
| 66 |
+
)
|
| 67 |
+
self._conn.commit()
|
| 68 |
+
|
| 69 |
+
def register(
|
| 70 |
+
self,
|
| 71 |
+
cas: str,
|
| 72 |
+
name: str,
|
| 73 |
+
smiles: str,
|
| 74 |
+
molecular_weight: float,
|
| 75 |
+
boiling_point_k: float | None = None,
|
| 76 |
+
vapor_pressure_pa: float | None = None,
|
| 77 |
+
logp: float | None = None,
|
| 78 |
+
unifac_groups_json: str = "{}",
|
| 79 |
+
source: str = "manual",
|
| 80 |
+
) -> None:
|
| 81 |
+
"""Insert a fully-built record directly (used by the expander)."""
|
| 82 |
+
self._conn.execute(
|
| 83 |
+
"""
|
| 84 |
+
INSERT OR REPLACE INTO aroma_chemicals
|
| 85 |
+
(cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa,
|
| 86 |
+
odor_threshold_ug_m3, logp, unifac_groups)
|
| 87 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 88 |
+
""",
|
| 89 |
+
(
|
| 90 |
+
cas,
|
| 91 |
+
name,
|
| 92 |
+
smiles,
|
| 93 |
+
molecular_weight,
|
| 94 |
+
boiling_point_k,
|
| 95 |
+
vapor_pressure_pa,
|
| 96 |
+
None,
|
| 97 |
+
logp,
|
| 98 |
+
json.dumps(unifac_groups_json, sort_keys=True),
|
| 99 |
+
),
|
| 100 |
+
)
|
| 101 |
+
self._conn.commit()
|
| 102 |
+
|
| 103 |
+
def close(self) -> None:
|
| 104 |
+
self._conn.close()
|
| 105 |
+
|
| 106 |
+
def __enter__(self) -> AromaRegistry:
|
| 107 |
+
return self
|
| 108 |
+
|
| 109 |
+
def __exit__(self, *args) -> None:
|
| 110 |
+
self.close()
|
| 111 |
+
|
| 112 |
+
def _normalise_key(self, key: str) -> str:
|
| 113 |
+
return str(key).strip().lower()
|
| 114 |
+
|
| 115 |
+
def get(self, identifier: str) -> dict[str, Any] | None:
|
| 116 |
+
"""Look up a molecule by CAS, name, or SMILES."""
|
| 117 |
+
key = self._normalise_key(identifier)
|
| 118 |
+
for column in ("cas", "name", "smiles"):
|
| 119 |
+
row = self._conn.execute(
|
| 120 |
+
f"SELECT * FROM aroma_chemicals WHERE LOWER({column}) = ?",
|
| 121 |
+
(key,),
|
| 122 |
+
).fetchone()
|
| 123 |
+
if row:
|
| 124 |
+
record = dict(row)
|
| 125 |
+
record["unifac_groups"] = json.loads(record.get("unifac_groups") or "{}")
|
| 126 |
+
return record
|
| 127 |
+
return None
|
| 128 |
+
|
| 129 |
+
def __contains__(self, identifier: str) -> bool:
|
| 130 |
+
return self.get(identifier) is not None
|
| 131 |
+
|
| 132 |
+
def add(self, record: dict[str, Any]) -> None:
|
| 133 |
+
"""Insert or replace a registry record keyed by CAS."""
|
| 134 |
+
self._conn.execute(
|
| 135 |
+
"""
|
| 136 |
+
INSERT OR REPLACE INTO aroma_chemicals
|
| 137 |
+
(cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa,
|
| 138 |
+
odor_threshold_ug_m3, logp, unifac_groups)
|
| 139 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 140 |
+
""",
|
| 141 |
+
(
|
| 142 |
+
record["cas"],
|
| 143 |
+
record.get("name"),
|
| 144 |
+
record.get("smiles"),
|
| 145 |
+
record.get("molecular_weight"),
|
| 146 |
+
record.get("boiling_point_k"),
|
| 147 |
+
record.get("vapor_pressure_pa"),
|
| 148 |
+
record.get("odor_threshold_ug_m3"),
|
| 149 |
+
record.get("logp"),
|
| 150 |
+
json.dumps(record.get("unifac_groups", {}), sort_keys=True),
|
| 151 |
+
),
|
| 152 |
+
)
|
| 153 |
+
self._conn.commit()
|
| 154 |
+
|
| 155 |
+
@staticmethod
|
| 156 |
+
def validate_smiles(smiles: str) -> dict[str, Any] | None:
|
| 157 |
+
"""
|
| 158 |
+
Validate a SMILES string locally: RDKit parse, MW guard, ugropy
|
| 159 |
+
Dortmund-UNIFAC fragmentation, and thermo parameter compatibility.
|
| 160 |
+
Returns a registry-ready record dict or None if validation fails.
|
| 161 |
+
"""
|
| 162 |
+
from rdkit import Chem
|
| 163 |
+
from rdkit.Chem import Descriptors
|
| 164 |
+
|
| 165 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 166 |
+
if mol is None:
|
| 167 |
+
return None
|
| 168 |
+
try:
|
| 169 |
+
mw = float(Descriptors.MolWt(mol))
|
| 170 |
+
except Exception:
|
| 171 |
+
return None
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
logp = float(Descriptors.MolLogP(mol))
|
| 175 |
+
except Exception:
|
| 176 |
+
logp = None
|
| 177 |
+
|
| 178 |
+
try:
|
| 179 |
+
groups = AromaRegistry.fragment_groups(smiles, "smiles")
|
| 180 |
+
except Exception:
|
| 181 |
+
return None
|
| 182 |
+
|
| 183 |
+
if not groups:
|
| 184 |
+
return None
|
| 185 |
+
|
| 186 |
+
return {
|
| 187 |
+
"smiles": Chem.MolToSmiles(mol, canonical=True),
|
| 188 |
+
"molecular_weight": mw,
|
| 189 |
+
"logp": logp,
|
| 190 |
+
"unifac_groups": groups,
|
| 191 |
+
"name": smiles,
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
@staticmethod
|
| 195 |
+
def build_record_from_smiles(
|
| 196 |
+
smiles: str,
|
| 197 |
+
name: str | None = None,
|
| 198 |
+
vapor_pressure_pa: float | None = None,
|
| 199 |
+
boiling_point_k: float | None = None,
|
| 200 |
+
odor_threshold_ug_m3: float | None = None,
|
| 201 |
+
) -> dict[str, Any]:
|
| 202 |
+
"""
|
| 203 |
+
Build a registry record entirely offline from a SMILES string.
|
| 204 |
+
No PubChem round-trip; CAS is generated as a synthetic SMILES key if no
|
| 205 |
+
human-readable name is supplied. RDKit provides MW and LogP, ugropy
|
| 206 |
+
provides Dortmund-UNIFAC groups, and thermo validates that every
|
| 207 |
+
subgroup has interaction parameters.
|
| 208 |
+
"""
|
| 209 |
+
from rdkit import Chem
|
| 210 |
+
from rdkit.Chem import Descriptors
|
| 211 |
+
|
| 212 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 213 |
+
if mol is None:
|
| 214 |
+
raise IngredientResolutionError(f"Invalid SMILES: {smiles}", smiles=smiles)
|
| 215 |
+
canonical = Chem.MolToSmiles(mol, canonical=True)
|
| 216 |
+
mw = float(Descriptors.MolWt(mol))
|
| 217 |
+
try:
|
| 218 |
+
logp = float(Descriptors.MolLogP(mol))
|
| 219 |
+
except Exception:
|
| 220 |
+
logp = None
|
| 221 |
+
groups = AromaRegistry.fragment_groups(canonical, "smiles")
|
| 222 |
+
if not groups:
|
| 223 |
+
raise IngredientResolutionError(f"No UNIFAC groups for {smiles}", smiles=smiles)
|
| 224 |
+
return {
|
| 225 |
+
"cas": f"SMILES:{canonical}",
|
| 226 |
+
"name": name or canonical,
|
| 227 |
+
"smiles": canonical,
|
| 228 |
+
"molecular_weight": mw,
|
| 229 |
+
"vapor_pressure_pa": vapor_pressure_pa,
|
| 230 |
+
"boiling_point_k": boiling_point_k,
|
| 231 |
+
"odor_threshold_ug_m3": odor_threshold_ug_m3,
|
| 232 |
+
"logp": logp,
|
| 233 |
+
"unifac_groups": groups,
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
@staticmethod
|
| 237 |
+
def resolve_pubchem(identifier: str, identifier_type: str = "cas") -> dict[str, Any]:
|
| 238 |
+
"""Resolve a molecule to canonical name, SMILES, and MW via PubChem."""
|
| 239 |
+
try:
|
| 240 |
+
if identifier_type == "cas":
|
| 241 |
+
compounds = pcp.get_compounds(identifier, "name")
|
| 242 |
+
else:
|
| 243 |
+
compounds = pcp.get_compounds(identifier, identifier_type)
|
| 244 |
+
except Exception as exc:
|
| 245 |
+
raise IngredientResolutionError(
|
| 246 |
+
f"PubChem lookup failed for {identifier}: {exc}", cas=identifier
|
| 247 |
+
) from exc
|
| 248 |
+
|
| 249 |
+
if not compounds:
|
| 250 |
+
raise IngredientResolutionError(
|
| 251 |
+
f"PubChem returned no compound for {identifier}", cas=identifier
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
comp = compounds[0]
|
| 255 |
+
return {
|
| 256 |
+
"cas": identifier,
|
| 257 |
+
"name": comp.synonyms[0] if comp.synonyms else identifier,
|
| 258 |
+
"smiles": comp.canonical_smiles or comp.smiles,
|
| 259 |
+
"molecular_weight": float(comp.molecular_weight),
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
@staticmethod
|
| 263 |
+
def _normalise_ugropy_name(name: str) -> str:
|
| 264 |
+
"""Map ugropy subgroup names onto the thermo DDB UNIFAC namespace."""
|
| 265 |
+
aliases = {
|
| 266 |
+
"HCO": "CHO", # aldehyde: same group, different label
|
| 267 |
+
"OH (P)": "OH(P)",
|
| 268 |
+
"OH (S)": "OH(S)",
|
| 269 |
+
"OH (T)": "OH(T)",
|
| 270 |
+
"CH=O": "CHO",
|
| 271 |
+
}
|
| 272 |
+
return aliases.get(name, name).replace(" ", "")
|
| 273 |
+
|
| 274 |
+
@staticmethod
|
| 275 |
+
def fragment_groups(identifier: str, identifier_type: str = "name") -> dict[str, int]:
|
| 276 |
+
"""Run ugropy and return thermo-compatible integer subgroup IDs."""
|
| 277 |
+
from thermo.unifac import DOUFSG
|
| 278 |
+
|
| 279 |
+
name_to_id = {str(v.group): k for k, v in DOUFSG.items()}
|
| 280 |
+
try:
|
| 281 |
+
groups_obj = ugropy.Groups(identifier, identifier_type=identifier_type)
|
| 282 |
+
raw_groups = groups_obj.dortmund.subgroups
|
| 283 |
+
except Exception as exc:
|
| 284 |
+
raise IngredientResolutionError(
|
| 285 |
+
f"ugropy fragmentation failed for {identifier}: {exc}",
|
| 286 |
+
cas=identifier if identifier_type == "cas" else None,
|
| 287 |
+
) from exc
|
| 288 |
+
|
| 289 |
+
if not raw_groups:
|
| 290 |
+
raise IngredientResolutionError(
|
| 291 |
+
f"ugropy returned no Dortmund groups for {identifier}",
|
| 292 |
+
cas=identifier if identifier_type == "cas" else None,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
result: dict[str, int] = {}
|
| 296 |
+
for name, count in raw_groups.items():
|
| 297 |
+
subgroup_id = unifac_mapping.map_ugropy_to_thermo_id(name, name_to_id)
|
| 298 |
+
if subgroup_id is None:
|
| 299 |
+
raise IngredientResolutionError(
|
| 300 |
+
f"Dortmund subgroup '{name}' from {identifier} not in thermo parameters"
|
| 301 |
+
)
|
| 302 |
+
result[str(subgroup_id)] = int(count)
|
| 303 |
+
return result
|
| 304 |
+
|
| 305 |
+
@staticmethod
|
| 306 |
+
def build_record(
|
| 307 |
+
identifier: str,
|
| 308 |
+
identifier_type: str = "cas",
|
| 309 |
+
vapor_pressure_pa: float | None = None,
|
| 310 |
+
boiling_point_k: float | None = None,
|
| 311 |
+
odor_threshold_ug_m3: float | None = None,
|
| 312 |
+
logp: float | None = None,
|
| 313 |
+
) -> dict[str, Any]:
|
| 314 |
+
"""Build a registry record by resolving PubChem and fragmenting groups."""
|
| 315 |
+
from rdkit import Chem
|
| 316 |
+
from rdkit.Chem import Descriptors
|
| 317 |
+
|
| 318 |
+
base = AromaRegistry.resolve_pubchem(identifier, identifier_type)
|
| 319 |
+
exc: Exception | None = None
|
| 320 |
+
for id_for_ugropy, id_type in [
|
| 321 |
+
(identifier, identifier_type),
|
| 322 |
+
(base["name"], "name"),
|
| 323 |
+
(base["smiles"], "smiles"),
|
| 324 |
+
]:
|
| 325 |
+
try:
|
| 326 |
+
groups = AromaRegistry.fragment_groups(id_for_ugropy, id_type)
|
| 327 |
+
break
|
| 328 |
+
except Exception as e:
|
| 329 |
+
exc = e
|
| 330 |
+
groups = {}
|
| 331 |
+
else:
|
| 332 |
+
raise exc or IngredientResolutionError(
|
| 333 |
+
f"Could not fragment {identifier} by CAS, name, or SMILES"
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# Compute LogP from RDKit if not provided.
|
| 337 |
+
if logp is None:
|
| 338 |
+
try:
|
| 339 |
+
mol = Chem.MolFromSmiles(base["smiles"])
|
| 340 |
+
logp = float(Descriptors.MolLogP(mol)) if mol else None
|
| 341 |
+
except Exception:
|
| 342 |
+
logp = None
|
| 343 |
+
|
| 344 |
+
base["unifac_groups"] = groups
|
| 345 |
+
base["vapor_pressure_pa"] = vapor_pressure_pa
|
| 346 |
+
base["boiling_point_k"] = boiling_point_k
|
| 347 |
+
base["odor_threshold_ug_m3"] = odor_threshold_ug_m3
|
| 348 |
+
base["logp"] = logp
|
| 349 |
+
return base
|
| 350 |
+
|
| 351 |
+
def populate(
|
| 352 |
+
self,
|
| 353 |
+
entries: list[dict[str, Any]],
|
| 354 |
+
*,
|
| 355 |
+
skip_failures: bool = True,
|
| 356 |
+
) -> list[dict[str, Any]]:
|
| 357 |
+
"""
|
| 358 |
+
Populate the registry from a list of entries. Each entry is a dict with
|
| 359 |
+
at least "cas" and optionally "vapor_pressure_pa", "boiling_point_k",
|
| 360 |
+
"odor_threshold_ug_m3", "logp".
|
| 361 |
+
"""
|
| 362 |
+
failed: list[dict[str, Any]] = []
|
| 363 |
+
for entry in entries:
|
| 364 |
+
cas = entry["cas"]
|
| 365 |
+
try:
|
| 366 |
+
record = self.build_record(
|
| 367 |
+
cas,
|
| 368 |
+
"cas",
|
| 369 |
+
vapor_pressure_pa=entry.get("vapor_pressure_pa"),
|
| 370 |
+
boiling_point_k=entry.get("boiling_point_k"),
|
| 371 |
+
odor_threshold_ug_m3=entry.get("odor_threshold_ug_m3"),
|
| 372 |
+
logp=entry.get("logp"),
|
| 373 |
+
)
|
| 374 |
+
self.add(record)
|
| 375 |
+
logger.info("Added registry entry for CAS %s (%s)", cas, record.get("name"))
|
| 376 |
+
except Exception as exc:
|
| 377 |
+
logger.warning("Failed to build registry entry for CAS %s: %s", cas, exc)
|
| 378 |
+
failed.append(entry)
|
| 379 |
+
if not skip_failures:
|
| 380 |
+
raise
|
| 381 |
+
return failed
|
src/pino/semantics.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _one_hot(indices: list[int], dim: int = 138) -> np.ndarray:
|
| 7 |
+
arr = np.zeros(dim, dtype=np.float32)
|
| 8 |
+
for idx in indices:
|
| 9 |
+
arr[idx] = 1.0
|
| 10 |
+
return arr
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
GENRE_OBJECTIVE_PROFILES: dict[str, np.ndarray] = {
|
| 14 |
+
"citrus_cologne": _one_hot([0, 2, 3], 138),
|
| 15 |
+
"fougere": _one_hot([1, 2, 3], 138),
|
| 16 |
+
"floral_woody": _one_hot([1, 2], 138),
|
| 17 |
+
"amber_oriental": _one_hot([2, 3], 138),
|
| 18 |
+
"wildcard": _one_hot([0, 1, 2, 3], 138),
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_objective_targets(generation_strategy: str, timesteps: int, seed: int = 2026) -> np.ndarray:
|
| 23 |
+
"""
|
| 24 |
+
Return a (timesteps, 138) objective odor-descriptor target matrix.
|
| 25 |
+
|
| 26 |
+
In the placeholder phase, indices 0-3 encode core genre notes:
|
| 27 |
+
0 = Citrus (Top), 1 = Lavender (Heart), 2 = Wood (Base), 3 = Musk (Base)
|
| 28 |
+
|
| 29 |
+
Each class follows a distinct volatility curve across normalized time tau:
|
| 30 |
+
Citrus (top): exp(-6 * tau) sharp decay
|
| 31 |
+
Lavender (heart): 4 * tau * exp(-4 * tau) surge, peak ~tau=0.25
|
| 32 |
+
Wood / Musk (base): 0.1 + 0.9 * (1 - exp(-3 * tau)) asymptotic rise
|
| 33 |
+
|
| 34 |
+
Remaining indices are filled with a tiny random noise floor to keep tensors
|
| 35 |
+
dense and stable during training.
|
| 36 |
+
"""
|
| 37 |
+
rng = np.random.default_rng(seed)
|
| 38 |
+
tau = np.linspace(0.0, 1.0, timesteps, dtype=np.float32)
|
| 39 |
+
|
| 40 |
+
# Volatility curves.
|
| 41 |
+
citrus_curve = np.exp(-6.0 * tau)
|
| 42 |
+
lavender_curve = 4.0 * tau * np.exp(-4.0 * tau)
|
| 43 |
+
base_curve = 0.1 + 0.9 * (1.0 - np.exp(-3.0 * tau))
|
| 44 |
+
|
| 45 |
+
# Per-genre activation coefficients for the 4 notes.
|
| 46 |
+
coeffs = {
|
| 47 |
+
"citrus_cologne": [1.0, 0.1, 0.2, 0.1],
|
| 48 |
+
"fougere": [0.1, 0.8, 0.8, 0.4],
|
| 49 |
+
"floral_woody": [0.1, 0.7, 1.0, 0.3],
|
| 50 |
+
"amber_oriental": [0.1, 0.2, 0.9, 1.0],
|
| 51 |
+
"wildcard": [0.7, 0.6, 0.7, 0.6],
|
| 52 |
+
}.get(generation_strategy, [0.7, 0.6, 0.7, 0.6])
|
| 53 |
+
coeffs = np.array(coeffs, dtype=np.float32)
|
| 54 |
+
|
| 55 |
+
targets = np.zeros((timesteps, 138), dtype=np.float32)
|
| 56 |
+
targets[:, 0] = coeffs[0] * citrus_curve
|
| 57 |
+
targets[:, 1] = coeffs[1] * lavender_curve
|
| 58 |
+
targets[:, 2] = coeffs[2] * base_curve
|
| 59 |
+
targets[:, 3] = coeffs[3] * base_curve
|
| 60 |
+
|
| 61 |
+
# Fill remaining indices with a trace noise floor < 1e-4.
|
| 62 |
+
noise_floor = rng.uniform(0.0, 1e-4, size=(timesteps, 134)).astype(np.float32)
|
| 63 |
+
targets[:, 4:] = noise_floor
|
| 64 |
+
|
| 65 |
+
return np.clip(targets, 0.0, 1.0).astype(np.float32)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Weak-label semantic targets derived from the generation_strategy tag.
|
| 69 |
+
# Each entry maps to a dict with:
|
| 70 |
+
# seasonality: 4-class softmax target [Spring, Summer, Autumn, Winter]
|
| 71 |
+
# gender_profile: scalar in [-1, 1] where -1 = masculine, +1 = feminine
|
| 72 |
+
# wearability: 4-label vector [Office-Safe, Date-Night, Casual, Formal]
|
| 73 |
+
|
| 74 |
+
GENRE_SEMANTICS: dict[str, dict[str, np.ndarray]] = {
|
| 75 |
+
"citrus_cologne": {
|
| 76 |
+
"seasonality": np.array([0.30, 0.50, 0.10, 0.10], dtype=np.float32),
|
| 77 |
+
"gender_profile": np.array([0.0], dtype=np.float32),
|
| 78 |
+
"wearability": np.array([0.85, 0.30, 0.70, 0.40], dtype=np.float32),
|
| 79 |
+
},
|
| 80 |
+
"fougere": {
|
| 81 |
+
"seasonality": np.array([0.35, 0.25, 0.30, 0.10], dtype=np.float32),
|
| 82 |
+
"gender_profile": np.array([-0.6], dtype=np.float32),
|
| 83 |
+
"wearability": np.array([0.70, 0.60, 0.75, 0.65], dtype=np.float32),
|
| 84 |
+
},
|
| 85 |
+
"floral_woody": {
|
| 86 |
+
"seasonality": np.array([0.40, 0.20, 0.30, 0.10], dtype=np.float32),
|
| 87 |
+
"gender_profile": np.array([0.3], dtype=np.float32),
|
| 88 |
+
"wearability": np.array([0.60, 0.70, 0.80, 0.70], dtype=np.float32),
|
| 89 |
+
},
|
| 90 |
+
"amber_oriental": {
|
| 91 |
+
"seasonality": np.array([0.10, 0.05, 0.30, 0.55], dtype=np.float32),
|
| 92 |
+
"gender_profile": np.array([-0.2], dtype=np.float32),
|
| 93 |
+
"wearability": np.array([0.20, 0.95, 0.50, 0.90], dtype=np.float32),
|
| 94 |
+
},
|
| 95 |
+
"wildcard": {
|
| 96 |
+
"seasonality": np.array([0.25, 0.25, 0.25, 0.25], dtype=np.float32),
|
| 97 |
+
"gender_profile": np.array([0.0], dtype=np.float32),
|
| 98 |
+
"wearability": np.array([0.50, 0.50, 0.50, 0.50], dtype=np.float32),
|
| 99 |
+
},
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def get_semantic_targets(generation_strategy: str) -> dict[str, np.ndarray]:
|
| 104 |
+
"""Return the weak-label semantic targets for a given generation strategy."""
|
| 105 |
+
return GENRE_SEMANTICS.get(generation_strategy, GENRE_SEMANTICS["wildcard"])
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_psychometric_targets(generation_strategy: str) -> np.ndarray:
|
| 109 |
+
"""
|
| 110 |
+
Return a 7-dimensional psychometric target vector that concatenates:
|
| 111 |
+
- seasonality (4)
|
| 112 |
+
- gender_profile (1)
|
| 113 |
+
- wearability (2, averaged from 4 categories)
|
| 114 |
+
"""
|
| 115 |
+
base = get_semantic_targets(generation_strategy)
|
| 116 |
+
season = base["seasonality"]
|
| 117 |
+
gender = base["gender_profile"].reshape(-1)
|
| 118 |
+
wear = base["wearability"]
|
| 119 |
+
# Compress 4 wearability categories into 2: formal/casual vs office/date
|
| 120 |
+
wear_compressed = np.array([
|
| 121 |
+
(wear[0] + wear[2]) / 2.0, # daytime/social
|
| 122 |
+
(wear[1] + wear[3]) / 2.0, # evening/formal
|
| 123 |
+
], dtype=np.float32)
|
| 124 |
+
return np.concatenate([season, gender, wear_compressed]).astype(np.float32)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def sample_noisy_psychometric_targets(
|
| 128 |
+
generation_strategy: str,
|
| 129 |
+
*,
|
| 130 |
+
seasonality_noise: float = 0.05,
|
| 131 |
+
gender_noise: float = 0.1,
|
| 132 |
+
wearability_noise: float = 0.05,
|
| 133 |
+
rng: np.random.Generator | None = None,
|
| 134 |
+
) -> np.ndarray:
|
| 135 |
+
"""Add label noise to the 7-D psychometric target vector."""
|
| 136 |
+
rng = rng or np.random.default_rng()
|
| 137 |
+
base = get_psychometric_targets(generation_strategy)
|
| 138 |
+
noisy = base.copy()
|
| 139 |
+
# Seasonality (first 4) + noise, then re-normalize
|
| 140 |
+
noisy[:4] += rng.normal(0, seasonality_noise, size=4).astype(np.float32)
|
| 141 |
+
noisy[:4] = np.clip(noisy[:4], 0.0, 1.0)
|
| 142 |
+
noisy[:4] = noisy[:4] / noisy[:4].sum() if noisy[:4].sum() > 0 else noisy[:4]
|
| 143 |
+
# Gender (index 4)
|
| 144 |
+
noisy[4] += rng.normal(0, gender_noise, size=1).astype(np.float32)[0]
|
| 145 |
+
noisy[4] = np.clip(noisy[4], -1.0, 1.0)
|
| 146 |
+
# Wearability (last 2)
|
| 147 |
+
noisy[5:] += rng.normal(0, wearability_noise, size=2).astype(np.float32)
|
| 148 |
+
noisy[5:] = np.clip(noisy[5:], 0.0, 1.0)
|
| 149 |
+
return noisy
|
src/pino/structures.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from rdkit import Chem
|
| 7 |
+
from rdkit.Chem import Descriptors
|
| 8 |
+
|
| 9 |
+
from .models import Ingredient, IngredientResolutionError
|
| 10 |
+
from .registry import AromaRegistry
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger("pino.structures")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class IngredientResolver:
|
| 16 |
+
"""
|
| 17 |
+
High-level resolver that combines a pre-computed SQLite registry with a
|
| 18 |
+
live fallback to RDKit / PubChem / ugropy.
|
| 19 |
+
|
| 20 |
+
Resolution order:
|
| 21 |
+
1. AromaRegistry lookup (fast, no network)
|
| 22 |
+
2. Live PubChem CAS -> SMILES + MW
|
| 23 |
+
3. Live ugropy Dortmund-UNIFAC fragmentation
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, registry: AromaRegistry | None = None) -> None:
|
| 27 |
+
self.registry = registry or AromaRegistry()
|
| 28 |
+
|
| 29 |
+
def resolve(self, identifier: str, weight_fraction: float, *, name: str | None = None) -> Ingredient:
|
| 30 |
+
"""Resolve a single raw formula component into a validated Ingredient."""
|
| 31 |
+
# Registry lookup first
|
| 32 |
+
record = self.registry.get(identifier)
|
| 33 |
+
if record is None and name:
|
| 34 |
+
record = self.registry.get(name)
|
| 35 |
+
|
| 36 |
+
if record:
|
| 37 |
+
logger.debug("Resolved %s from registry", identifier)
|
| 38 |
+
return self._ingredient_from_record(record, weight_fraction)
|
| 39 |
+
|
| 40 |
+
# Live fallback
|
| 41 |
+
logger.info("Registry miss for %s; falling back to PubChem/ugropy", identifier)
|
| 42 |
+
try:
|
| 43 |
+
live = AromaRegistry.build_record(identifier, "cas")
|
| 44 |
+
except Exception as exc:
|
| 45 |
+
raise IngredientResolutionError(
|
| 46 |
+
f"Unable to resolve {identifier} from registry or live sources: {exc}",
|
| 47 |
+
cas=identifier,
|
| 48 |
+
) from exc
|
| 49 |
+
|
| 50 |
+
# Add to registry so future lookups are fast
|
| 51 |
+
self.registry.add(live)
|
| 52 |
+
return self._ingredient_from_record(live, weight_fraction)
|
| 53 |
+
|
| 54 |
+
def resolve_formula(
|
| 55 |
+
self,
|
| 56 |
+
formula: list[dict[str, Any]],
|
| 57 |
+
*,
|
| 58 |
+
skip_unresolved: bool = False,
|
| 59 |
+
) -> tuple[list[Ingredient], list[IngredientResolutionError]]:
|
| 60 |
+
"""
|
| 61 |
+
Resolve a list of raw formula components.
|
| 62 |
+
|
| 63 |
+
Returns (ingredients, errors). If skip_unresolved is False, the first
|
| 64 |
+
error is raised immediately.
|
| 65 |
+
"""
|
| 66 |
+
ingredients: list[Ingredient] = []
|
| 67 |
+
errors: list[IngredientResolutionError] = []
|
| 68 |
+
|
| 69 |
+
for comp in formula:
|
| 70 |
+
if "weight_fraction" not in comp:
|
| 71 |
+
raise ValueError(f"Formula component missing weight_fraction: {comp}")
|
| 72 |
+
wf = float(comp["weight_fraction"])
|
| 73 |
+
ident = str(comp.get("cas", comp.get("smiles", comp.get("name", ""))))
|
| 74 |
+
try:
|
| 75 |
+
ing = self.resolve(ident, wf, name=comp.get("name"))
|
| 76 |
+
ingredients.append(ing)
|
| 77 |
+
except IngredientResolutionError as exc:
|
| 78 |
+
logger.warning("Out of applicability domain for %s: %s", ident, exc)
|
| 79 |
+
errors.append(exc)
|
| 80 |
+
if not skip_unresolved:
|
| 81 |
+
raise
|
| 82 |
+
|
| 83 |
+
return ingredients, errors
|
| 84 |
+
|
| 85 |
+
def _ingredient_from_record(self, record: dict[str, Any], weight_fraction: float) -> Ingredient:
|
| 86 |
+
"""Construct an Ingredient from a registry/live record."""
|
| 87 |
+
smiles = record["smiles"]
|
| 88 |
+
mw = record.get("molecular_weight")
|
| 89 |
+
if mw is None:
|
| 90 |
+
mw = molecular_weight_from_smiles(smiles)
|
| 91 |
+
|
| 92 |
+
logp = record.get("logp")
|
| 93 |
+
if logp is None:
|
| 94 |
+
try:
|
| 95 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 96 |
+
logp = float(Descriptors.MolLogP(mol)) if mol else None
|
| 97 |
+
except Exception:
|
| 98 |
+
logp = None
|
| 99 |
+
|
| 100 |
+
return Ingredient(
|
| 101 |
+
name=record.get("name", smiles),
|
| 102 |
+
cas=record.get("cas", ""),
|
| 103 |
+
smiles=smiles,
|
| 104 |
+
molecular_weight=float(mw),
|
| 105 |
+
vapor_pressure_pa=float(record.get("vapor_pressure_pa") or 1.0),
|
| 106 |
+
boiling_point_k=float(record["boiling_point_k"]) if record.get("boiling_point_k") is not None else None,
|
| 107 |
+
odor_threshold_ug_m3=float(record["odor_threshold_ug_m3"]) if record.get("odor_threshold_ug_m3") is not None else None,
|
| 108 |
+
logp=logp,
|
| 109 |
+
unifac_groups={str(k): int(v) for k, v in record.get("unifac_groups", {}).items()},
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def canonicalize_smiles(smiles: str) -> str:
|
| 114 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 115 |
+
if mol is None:
|
| 116 |
+
raise IngredientResolutionError(f"Invalid SMILES: {smiles}", smiles=smiles)
|
| 117 |
+
return Chem.MolToSmiles(mol, canonical=True)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def molecular_weight_from_smiles(smiles: str) -> float:
|
| 121 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 122 |
+
if mol is None:
|
| 123 |
+
raise IngredientResolutionError(f"Invalid SMILES: {smiles}", smiles=smiles)
|
| 124 |
+
return Descriptors.MolWt(mol)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def ingredient_from_smiles(
|
| 128 |
+
name: str,
|
| 129 |
+
cas: str,
|
| 130 |
+
smiles: str,
|
| 131 |
+
vapor_pressure_pa: float,
|
| 132 |
+
boiling_point_k: float | None = None,
|
| 133 |
+
odor_threshold_ug_m3: float | None = None,
|
| 134 |
+
) -> Ingredient:
|
| 135 |
+
"""Build an Ingredient directly from a SMILES string (with live fragmentation)."""
|
| 136 |
+
resolver = IngredientResolver()
|
| 137 |
+
record = AromaRegistry.build_record(smiles, "smiles", vapor_pressure_pa, boiling_point_k, odor_threshold_ug_m3)
|
| 138 |
+
record["name"] = name
|
| 139 |
+
record["cas"] = cas
|
| 140 |
+
return resolver._ingredient_from_record(record, 0.0)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def ingredient_from_data(data: dict[str, Any]) -> Ingredient:
|
| 144 |
+
"""Build an Ingredient from a dict (with optional precomputed registry groups)."""
|
| 145 |
+
resolver = IngredientResolver()
|
| 146 |
+
if "cas" in data or "smiles" in data or "name" in data:
|
| 147 |
+
return resolver.resolve(
|
| 148 |
+
str(data.get("cas", data.get("smiles", data.get("name", "")))),
|
| 149 |
+
float(data.get("weight_fraction", 0.0)),
|
| 150 |
+
name=data.get("name"),
|
| 151 |
+
)
|
| 152 |
+
raise IngredientResolutionError("No identifier (cas, smiles, name) provided in data")
|
src/pino/synthetic.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import random
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from pino.ifra import IFRA_RESTRICTIONS
|
| 12 |
+
from pino.registry import AromaRegistry
|
| 13 |
+
from pino.verifier import FragrancePipelineVerifier
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger("pino.synthetic")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _light_ifra_check(formula: list[dict[str, Any]]) -> dict[str, Any]:
|
| 19 |
+
"""Fast pre-check against IFRA restrictions using raw dict input."""
|
| 20 |
+
violations = []
|
| 21 |
+
for f in formula:
|
| 22 |
+
cas = f["cas"]
|
| 23 |
+
pct = f["weight_fraction"] * 100.0
|
| 24 |
+
if cas in IFRA_RESTRICTIONS:
|
| 25 |
+
limit = IFRA_RESTRICTIONS[cas]["category_4_pct"]
|
| 26 |
+
if (limit == 0.0 and pct > 0.0) or (limit > 0.0 and pct > limit):
|
| 27 |
+
violations.append({"cas": cas, "used_pct": pct, "limit_pct": limit})
|
| 28 |
+
return {"passed": not violations, "violations": violations}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SyntheticFormulationGenerator:
|
| 32 |
+
"""
|
| 33 |
+
High-throughput generator of physically plausible fragrance formulations.
|
| 34 |
+
|
| 35 |
+
Samples ingredient palettes from the validated aroma registry, applies
|
| 36 |
+
realistic concentration guardrails, filters through IFRA and the VLE
|
| 37 |
+
verifier, and returns a clean ML-ready corpus.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
registry_path: str | Path = "src/pino/registry.db",
|
| 43 |
+
seed: int | None = None,
|
| 44 |
+
min_ingredients: int = 4,
|
| 45 |
+
max_ingredients: int = 10,
|
| 46 |
+
base_fraction_range: tuple[float, float] = (0.50, 0.90),
|
| 47 |
+
accord_mass_fraction: float = 0.30,
|
| 48 |
+
max_attempts: int = 100,
|
| 49 |
+
) -> None:
|
| 50 |
+
self.registry_path = Path(registry_path)
|
| 51 |
+
self.seed = seed
|
| 52 |
+
self.rng = random.Random(seed)
|
| 53 |
+
self.min_ingredients = min_ingredients
|
| 54 |
+
self.max_ingredients = max_ingredients
|
| 55 |
+
self.base_fraction_range = base_fraction_range
|
| 56 |
+
self.accord_mass_fraction = accord_mass_fraction
|
| 57 |
+
self.max_attempts = max_attempts
|
| 58 |
+
self._registry = AromaRegistry(str(self.registry_path))
|
| 59 |
+
self._verifier = FragrancePipelineVerifier()
|
| 60 |
+
|
| 61 |
+
def _load_aroma_chemicals(self) -> list[dict[str, Any]]:
|
| 62 |
+
rows = self._registry._conn.execute(
|
| 63 |
+
"SELECT cas, name, molecular_weight, vapor_pressure_pa, boiling_point_k, logp FROM aroma_chemicals"
|
| 64 |
+
).fetchall()
|
| 65 |
+
return [
|
| 66 |
+
{
|
| 67 |
+
"cas": row[0],
|
| 68 |
+
"name": row[1],
|
| 69 |
+
"molecular_weight": row[2],
|
| 70 |
+
"vapor_pressure_pa": row[3],
|
| 71 |
+
"boiling_point_k": row[4],
|
| 72 |
+
"logp": row[5],
|
| 73 |
+
}
|
| 74 |
+
for row in rows
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
def _pick_base(self, chemicals: list[dict[str, Any]]) -> dict[str, Any]:
|
| 78 |
+
# Prefer ethanol as the canonical volatile base if available; otherwise fallback.
|
| 79 |
+
for chem in chemicals:
|
| 80 |
+
if chem["cas"] == "64-17-5":
|
| 81 |
+
return chem
|
| 82 |
+
return self.rng.choice(chemicals)
|
| 83 |
+
|
| 84 |
+
def _sample_palette(self, chemicals: list[dict[str, Any]], base: dict[str, Any]) -> list[dict[str, Any]]:
|
| 85 |
+
n = self.rng.randint(self.min_ingredients, self.max_ingredients)
|
| 86 |
+
# Ensure base is included, then fill with diverse aroma chemicals.
|
| 87 |
+
candidates = [c for c in chemicals if c["cas"] != base["cas"]]
|
| 88 |
+
if len(candidates) < n - 1:
|
| 89 |
+
n = len(candidates) + 1
|
| 90 |
+
selected = self.rng.sample(candidates, n - 1)
|
| 91 |
+
return [base] + selected
|
| 92 |
+
|
| 93 |
+
def _distribute_weights(self, palette: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 94 |
+
"""
|
| 95 |
+
Realistic fragrance pyramid:
|
| 96 |
+
- Base solvent dominates (e.g., ethanol).
|
| 97 |
+
- Remaining mass is distributed across the accord with a slight bias toward
|
| 98 |
+
lower vapor pressure (heart/base) notes for stability.
|
| 99 |
+
"""
|
| 100 |
+
base_cas = palette[0]["cas"]
|
| 101 |
+
base_fraction = self.rng.uniform(*self.base_fraction_range)
|
| 102 |
+
accord_mass = 1.0 - base_fraction
|
| 103 |
+
|
| 104 |
+
# Use inverse volatility weighting for the accord to avoid all-top-note formulas.
|
| 105 |
+
volatilities = np.array([max(c["vapor_pressure_pa"] or 1e-12, 1e-12) for c in palette[1:]])
|
| 106 |
+
# Mix random and inverse volatility weights to keep diversity.
|
| 107 |
+
random_weights = np.array([self.rng.random() for _ in palette[1:]])
|
| 108 |
+
inverse_vol_weights = 1.0 / volatilities
|
| 109 |
+
inverse_vol_weights /= inverse_vol_weights.sum()
|
| 110 |
+
random_weights /= random_weights.sum()
|
| 111 |
+
blend = 0.6 * random_weights + 0.4 * inverse_vol_weights
|
| 112 |
+
blend /= blend.sum()
|
| 113 |
+
accord_fractions = blend * accord_mass
|
| 114 |
+
|
| 115 |
+
weights = {base_cas: base_fraction}
|
| 116 |
+
for chem, frac in zip(palette[1:], accord_fractions):
|
| 117 |
+
weights[chem["cas"]] = float(frac)
|
| 118 |
+
|
| 119 |
+
formula = [{"cas": c["cas"], "weight_fraction": weights[c["cas"]]} for c in palette]
|
| 120 |
+
return formula
|
| 121 |
+
|
| 122 |
+
def _apply_guardrails(self, formula: list[dict[str, Any]]) -> bool:
|
| 123 |
+
"""
|
| 124 |
+
Basic concentration guardrails before expensive VLE verification.
|
| 125 |
+
"""
|
| 126 |
+
total = sum(f["weight_fraction"] for f in formula)
|
| 127 |
+
if not np.isclose(total, 1.0, atol=1e-4):
|
| 128 |
+
return False
|
| 129 |
+
# No single accord ingredient dominates (>40% of non-base mass).
|
| 130 |
+
base_cas = formula[0]["cas"]
|
| 131 |
+
accord_total = sum(f["weight_fraction"] for f in formula if f["cas"] != base_cas)
|
| 132 |
+
for f in formula:
|
| 133 |
+
if f["cas"] != base_cas and f["weight_fraction"] / max(accord_total, 1e-12) > 0.40:
|
| 134 |
+
return False
|
| 135 |
+
return True
|
| 136 |
+
|
| 137 |
+
def generate_one(self, duration_seconds: float = 28800, interval_seconds: float = 600) -> dict[str, Any] | None:
|
| 138 |
+
"""
|
| 139 |
+
Generate and verify a single synthetic formulation. Returns the verified record
|
| 140 |
+
or None if rejected/out-of-domain.
|
| 141 |
+
"""
|
| 142 |
+
chemicals = self._load_aroma_chemicals()
|
| 143 |
+
base = self._pick_base(chemicals)
|
| 144 |
+
for attempt in range(self.max_attempts):
|
| 145 |
+
palette = self._sample_palette(chemicals, base)
|
| 146 |
+
formula = self._distribute_weights(palette)
|
| 147 |
+
if not self._apply_guardrails(formula):
|
| 148 |
+
continue
|
| 149 |
+
# Lightweight IFRA pre-check before VLE.
|
| 150 |
+
ifra_report = _light_ifra_check(formula)
|
| 151 |
+
if not ifra_report["passed"]:
|
| 152 |
+
continue
|
| 153 |
+
try:
|
| 154 |
+
result = self._verifier.run_sim(formula, duration_seconds=duration_seconds, interval_seconds=interval_seconds)
|
| 155 |
+
except Exception as e:
|
| 156 |
+
logger.debug("Verifier rejected formula: %s", e)
|
| 157 |
+
continue
|
| 158 |
+
if result["status"] in ("passed", "depleted"):
|
| 159 |
+
return {
|
| 160 |
+
"formula": formula,
|
| 161 |
+
"status": result["status"],
|
| 162 |
+
"message": result["message"],
|
| 163 |
+
"depletion_rates": result["depletion_rates"],
|
| 164 |
+
"trajectory": result["trajectory"],
|
| 165 |
+
}
|
| 166 |
+
logger.warning("Failed to generate a verified formulation after %d attempts", self.max_attempts)
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
def generate_corpus(
|
| 170 |
+
self,
|
| 171 |
+
n_samples: int = 100,
|
| 172 |
+
duration_seconds: float = 28800,
|
| 173 |
+
interval_seconds: float = 600,
|
| 174 |
+
output_path: str | Path = "synthetic_corpus.json",
|
| 175 |
+
) -> dict[str, Any]:
|
| 176 |
+
"""
|
| 177 |
+
Generate a corpus of n verified formulations and save as JSON.
|
| 178 |
+
Returns a summary dict with pass/reject counts and output path.
|
| 179 |
+
"""
|
| 180 |
+
output_path = Path(output_path)
|
| 181 |
+
samples: list[dict[str, Any]] = []
|
| 182 |
+
status_counts = {"passed": 0, "depleted": 0, "rejected": 0}
|
| 183 |
+
for i in range(n_samples):
|
| 184 |
+
record = self.generate_one(duration_seconds=duration_seconds, interval_seconds=interval_seconds)
|
| 185 |
+
if record is None:
|
| 186 |
+
status_counts["rejected"] += 1
|
| 187 |
+
continue
|
| 188 |
+
samples.append(record)
|
| 189 |
+
status_counts[record["status"]] += 1
|
| 190 |
+
if (i + 1) % 10 == 0:
|
| 191 |
+
logger.info("Generated %d/%d verified formulations", len(samples), n_samples)
|
| 192 |
+
corpus = {
|
| 193 |
+
"metadata": {
|
| 194 |
+
"n_samples": len(samples),
|
| 195 |
+
"requested_samples": n_samples,
|
| 196 |
+
"duration_seconds": duration_seconds,
|
| 197 |
+
"interval_seconds": interval_seconds,
|
| 198 |
+
"registry_path": str(self.registry_path),
|
| 199 |
+
"seed": self.seed,
|
| 200 |
+
"status_counts": status_counts,
|
| 201 |
+
},
|
| 202 |
+
"samples": samples,
|
| 203 |
+
}
|
| 204 |
+
output_path.write_text(json.dumps(corpus, indent=2))
|
| 205 |
+
logger.info("Saved corpus with %d samples to %s", len(samples), output_path)
|
| 206 |
+
return corpus
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
if __name__ == "__main__":
|
| 210 |
+
import argparse
|
| 211 |
+
|
| 212 |
+
parser = argparse.ArgumentParser(description="Generate synthetic PINO training corpus")
|
| 213 |
+
parser.add_argument("--n-samples", type=int, default=100, help="Number of verified formulations to generate")
|
| 214 |
+
parser.add_argument("--duration", type=float, default=28800, help="Simulation duration in seconds")
|
| 215 |
+
parser.add_argument("--interval", type=float, default=600, help="Output interval in seconds")
|
| 216 |
+
parser.add_argument("--output", type=Path, default="synthetic_corpus.json", help="Output JSON path")
|
| 217 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed")
|
| 218 |
+
parser.add_argument("--registry", type=Path, default="src/pino/registry.db", help="Path to SQLite registry")
|
| 219 |
+
parser.add_argument("--log-level", default="INFO", help="Logging level")
|
| 220 |
+
args = parser.parse_args()
|
| 221 |
+
|
| 222 |
+
logging.basicConfig(level=getattr(logging, args.log_level.upper()))
|
| 223 |
+
gen = SyntheticFormulationGenerator(registry_path=args.registry, seed=args.seed)
|
| 224 |
+
gen.generate_corpus(
|
| 225 |
+
n_samples=args.n_samples,
|
| 226 |
+
duration_seconds=args.duration,
|
| 227 |
+
interval_seconds=args.interval,
|
| 228 |
+
output_path=args.output,
|
| 229 |
+
)
|
src/pino/train.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import logging
|
| 5 |
+
import random
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.optim as optim
|
| 13 |
+
from torch.utils.data import DataLoader, random_split
|
| 14 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 15 |
+
|
| 16 |
+
from pino.heads import PIMTHeads
|
| 17 |
+
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger("pino.train")
|
| 20 |
+
|
| 21 |
+
SMOKE_TEST_CONFIG = {
|
| 22 |
+
"hidden_dim": 64,
|
| 23 |
+
"num_layers": 2,
|
| 24 |
+
"num_heads": 2,
|
| 25 |
+
"batch_size": 4,
|
| 26 |
+
"max_batches_per_epoch": 20,
|
| 27 |
+
"lr": 1e-3,
|
| 28 |
+
"weight_decay": 1e-2,
|
| 29 |
+
"checkpoint_name": "pimt_smoke_test.pt",
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
| 33 |
+
"""
|
| 34 |
+
Collate variable-length formulations into a single padded batch.
|
| 35 |
+
|
| 36 |
+
Because recipes contain a variable number of ingredients (K), this function
|
| 37 |
+
finds K_max in the batch and pads shorter token/physics tensors with zeros.
|
| 38 |
+
It also emits a `src_key_padding_mask` of shape (B, K_max) where True marks
|
| 39 |
+
padding positions and False marks valid chemical tokens.
|
| 40 |
+
"""
|
| 41 |
+
max_molecules = max(item["tokens"].size(0) for item in batch)
|
| 42 |
+
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 43 |
+
bsz = len(batch)
|
| 44 |
+
|
| 45 |
+
tokens = torch.zeros(bsz, max_molecules, 138, dtype=torch.float32)
|
| 46 |
+
physics = torch.zeros(bsz, max_timesteps, max_molecules, 4, dtype=torch.float32)
|
| 47 |
+
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 48 |
+
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
| 49 |
+
target_sub_seasonality = torch.zeros(bsz, 4, dtype=torch.float32)
|
| 50 |
+
target_sub_gender = torch.zeros(bsz, dtype=torch.float32)
|
| 51 |
+
target_sub_wearability = torch.zeros(bsz, 4, dtype=torch.float32)
|
| 52 |
+
|
| 53 |
+
for i, item in enumerate(batch):
|
| 54 |
+
n_mol = item["tokens"].size(0)
|
| 55 |
+
t_steps = item["physics"].size(0)
|
| 56 |
+
tokens[i, :n_mol] = item["tokens"]
|
| 57 |
+
physics[i, :t_steps, :n_mol] = item["physics"]
|
| 58 |
+
src_key_padding_mask[i, :n_mol] = False
|
| 59 |
+
target_obj[i, :t_steps] = item["target_obj"]
|
| 60 |
+
sub = item["target_sub"]
|
| 61 |
+
target_sub_seasonality[i] = sub["seasonality"]
|
| 62 |
+
target_sub_gender[i] = sub["gender_profile"]
|
| 63 |
+
target_sub_wearability[i] = sub["wearability"]
|
| 64 |
+
|
| 65 |
+
return {
|
| 66 |
+
"tokens": tokens,
|
| 67 |
+
"physics": physics,
|
| 68 |
+
"src_key_padding_mask": src_key_padding_mask,
|
| 69 |
+
"target_obj": target_obj,
|
| 70 |
+
"target_sub_seasonality": target_sub_seasonality,
|
| 71 |
+
"target_sub_gender": target_sub_gender,
|
| 72 |
+
"target_sub_wearability": target_sub_wearability,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def multitask_loss(
|
| 77 |
+
pred_obj: torch.Tensor,
|
| 78 |
+
target_obj: torch.Tensor,
|
| 79 |
+
pred_sub: dict[str, torch.Tensor],
|
| 80 |
+
target_sub: dict[str, torch.Tensor],
|
| 81 |
+
weights: dict[str, float] | None = None,
|
| 82 |
+
) -> tuple[torch.Tensor, dict[str, float]]:
|
| 83 |
+
"""
|
| 84 |
+
Weighted multi-task loss: MSE for objective trajectory + cross-entropy for
|
| 85 |
+
seasonality + MSE for gender + BCE for multi-label wearability.
|
| 86 |
+
"""
|
| 87 |
+
weights = weights or {"obj": 1.0, "season": 0.5, "gender": 0.25, "wear": 0.25}
|
| 88 |
+
|
| 89 |
+
# Objective MSE with padding mask over time.
|
| 90 |
+
obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
|
| 91 |
+
obj_loss = nn.functional.mse_loss(pred_obj, target_obj, reduction="none")
|
| 92 |
+
obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
|
| 93 |
+
|
| 94 |
+
season_loss = nn.functional.cross_entropy(pred_sub["seasonality"], target_sub["seasonality"])
|
| 95 |
+
gender_loss = nn.functional.mse_loss(pred_sub["gender_profile"], target_sub["gender_profile"])
|
| 96 |
+
wear_loss = nn.functional.binary_cross_entropy_with_logits(pred_sub["wearability"], target_sub["wearability"])
|
| 97 |
+
|
| 98 |
+
total = (
|
| 99 |
+
weights["obj"] * obj_loss
|
| 100 |
+
+ weights["season"] * season_loss
|
| 101 |
+
+ weights["gender"] * gender_loss
|
| 102 |
+
+ weights["wear"] * wear_loss
|
| 103 |
+
)
|
| 104 |
+
components = {
|
| 105 |
+
"obj": obj_loss.item(),
|
| 106 |
+
"season": season_loss.item(),
|
| 107 |
+
"gender": gender_loss.item(),
|
| 108 |
+
"wear": wear_loss.item(),
|
| 109 |
+
"total": total.item(),
|
| 110 |
+
}
|
| 111 |
+
return total, components
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def train_epoch(
|
| 115 |
+
model: nn.Module,
|
| 116 |
+
heads: nn.Module,
|
| 117 |
+
loader: DataLoader,
|
| 118 |
+
optimizer: optim.Optimizer,
|
| 119 |
+
device: torch.device,
|
| 120 |
+
weights: dict[str, float],
|
| 121 |
+
max_batches: int | None = None,
|
| 122 |
+
) -> dict[str, float]:
|
| 123 |
+
model.train()
|
| 124 |
+
heads.train()
|
| 125 |
+
total_loss = 0.0
|
| 126 |
+
totals = {"obj": 0.0, "season": 0.0, "gender": 0.0, "wear": 0.0}
|
| 127 |
+
count = 0
|
| 128 |
+
|
| 129 |
+
for batch_idx, batch in enumerate(loader, start=1):
|
| 130 |
+
if max_batches is not None and batch_idx > max_batches:
|
| 131 |
+
break
|
| 132 |
+
tokens = batch["tokens"].to(device)
|
| 133 |
+
physics = batch["physics"].to(device)
|
| 134 |
+
src_key_padding_mask = batch["src_key_padding_mask"].to(device)
|
| 135 |
+
target_obj = batch["target_obj"].to(device)
|
| 136 |
+
target_sub = {
|
| 137 |
+
"seasonality": batch["target_sub_seasonality"].to(device),
|
| 138 |
+
"gender_profile": batch["target_sub_gender"].to(device),
|
| 139 |
+
"wearability": batch["target_sub_wearability"].to(device),
|
| 140 |
+
}
|
| 141 |
+
optimizer.zero_grad()
|
| 142 |
+
latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
|
| 143 |
+
pred = heads(latent)
|
| 144 |
+
loss, comps = multitask_loss(pred["objective"], target_obj, pred["subjective"], target_sub, weights)
|
| 145 |
+
loss.backward()
|
| 146 |
+
torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(heads.parameters()), 1.0)
|
| 147 |
+
optimizer.step()
|
| 148 |
+
|
| 149 |
+
total_loss += comps["total"]
|
| 150 |
+
for k in totals:
|
| 151 |
+
totals[k] += comps[k]
|
| 152 |
+
count += 1
|
| 153 |
+
logger.info(
|
| 154 |
+
"Batch %d | total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f",
|
| 155 |
+
batch_idx, comps["total"], comps["obj"], comps["season"], comps["gender"], comps["wear"],
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@torch.no_grad()
|
| 162 |
+
def validate(
|
| 163 |
+
model: nn.Module,
|
| 164 |
+
heads: nn.Module,
|
| 165 |
+
loader: DataLoader,
|
| 166 |
+
device: torch.device,
|
| 167 |
+
weights: dict[str, float],
|
| 168 |
+
) -> dict[str, float]:
|
| 169 |
+
model.eval()
|
| 170 |
+
heads.eval()
|
| 171 |
+
total_loss = 0.0
|
| 172 |
+
totals = {"obj": 0.0, "season": 0.0, "gender": 0.0, "wear": 0.0}
|
| 173 |
+
count = 0
|
| 174 |
+
|
| 175 |
+
for batch in loader:
|
| 176 |
+
tokens = batch["tokens"].to(device)
|
| 177 |
+
physics = batch["physics"].to(device)
|
| 178 |
+
src_key_padding_mask = batch["src_key_padding_mask"].to(device)
|
| 179 |
+
target_obj = batch["target_obj"].to(device)
|
| 180 |
+
target_sub = {
|
| 181 |
+
"seasonality": batch["target_sub_seasonality"].to(device),
|
| 182 |
+
"gender_profile": batch["target_sub_gender"].to(device),
|
| 183 |
+
"wearability": batch["target_sub_wearability"].to(device),
|
| 184 |
+
}
|
| 185 |
+
latent = model(tokens, physics, src_key_padding_mask)
|
| 186 |
+
pred = heads(latent)
|
| 187 |
+
loss, comps = multitask_loss(pred["objective"], target_obj, pred["subjective"], target_sub, weights)
|
| 188 |
+
total_loss += comps["total"]
|
| 189 |
+
for k in totals:
|
| 190 |
+
totals[k] += comps[k]
|
| 191 |
+
count += 1
|
| 192 |
+
|
| 193 |
+
return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def main():
|
| 197 |
+
parser = argparse.ArgumentParser(description="Train the PINO Physics-Informed Mixture Transformer")
|
| 198 |
+
parser.add_argument("--data", default="data/synthetic_dataset_v2.jsonl")
|
| 199 |
+
parser.add_argument("--epochs", type=int, default=5)
|
| 200 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 201 |
+
parser.add_argument("--lr", type=float, default=1e-3)
|
| 202 |
+
parser.add_argument("--hidden-dim", type=int, default=256)
|
| 203 |
+
parser.add_argument("--num-layers", type=int, default=4)
|
| 204 |
+
parser.add_argument("--num-heads", type=int, default=4)
|
| 205 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 206 |
+
parser.add_argument("--seed", type=int, default=2026)
|
| 207 |
+
parser.add_argument("--output-dir", default="models")
|
| 208 |
+
parser.add_argument("--log-dir", default="runs")
|
| 209 |
+
parser.add_argument("--smoke-test", action="store_true", help="Run lightweight CPU smoke test")
|
| 210 |
+
args = parser.parse_args()
|
| 211 |
+
|
| 212 |
+
logging.basicConfig(
|
| 213 |
+
level=logging.INFO,
|
| 214 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 215 |
+
)
|
| 216 |
+
logger.info("Training PIMT with fallback embeddings (use_fallback=True)")
|
| 217 |
+
logger.info("Embedding backend: deterministic 128-bit Morgan + 10 physicochemical descriptors")
|
| 218 |
+
|
| 219 |
+
torch.manual_seed(args.seed)
|
| 220 |
+
np.random.seed(args.seed)
|
| 221 |
+
random.seed(args.seed)
|
| 222 |
+
|
| 223 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 224 |
+
logger.info("Device: %s", device)
|
| 225 |
+
|
| 226 |
+
cfg = SMOKE_TEST_CONFIG if args.smoke_test else {
|
| 227 |
+
"hidden_dim": args.hidden_dim,
|
| 228 |
+
"num_layers": args.num_layers,
|
| 229 |
+
"num_heads": args.num_heads,
|
| 230 |
+
"batch_size": args.batch_size,
|
| 231 |
+
"max_batches_per_epoch": None,
|
| 232 |
+
"lr": args.lr,
|
| 233 |
+
"weight_decay": 1e-2,
|
| 234 |
+
"checkpoint_name": "pimt_v1.pt",
|
| 235 |
+
}
|
| 236 |
+
logger.info("Configuration: %s", cfg)
|
| 237 |
+
|
| 238 |
+
dataset = FragranceTrajectoryDataset(data_path=args.data, use_embedding_fallback=True)
|
| 239 |
+
total = len(dataset)
|
| 240 |
+
train_len = int(0.8 * total)
|
| 241 |
+
val_len = int(0.1 * total)
|
| 242 |
+
test_len = total - train_len - val_len
|
| 243 |
+
train_ds, val_ds, test_ds = random_split(
|
| 244 |
+
dataset, [train_len, val_len, test_len],
|
| 245 |
+
generator=torch.Generator().manual_seed(args.seed),
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
train_loader = DataLoader(
|
| 249 |
+
train_ds, batch_size=cfg["batch_size"], shuffle=True, num_workers=args.workers, collate_fn=pad_trajectory_collate
|
| 250 |
+
)
|
| 251 |
+
val_loader = DataLoader(
|
| 252 |
+
val_ds, batch_size=cfg["batch_size"], shuffle=False, num_workers=args.workers, collate_fn=pad_trajectory_collate
|
| 253 |
+
)
|
| 254 |
+
test_loader = DataLoader(
|
| 255 |
+
test_ds, batch_size=cfg["batch_size"], shuffle=False, num_workers=args.workers, collate_fn=pad_trajectory_collate
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
model = PhysicsInformedMixtureTransformer(
|
| 259 |
+
embedding_dim=138,
|
| 260 |
+
state_dim=4,
|
| 261 |
+
hidden_dim=cfg["hidden_dim"],
|
| 262 |
+
num_heads=cfg["num_heads"],
|
| 263 |
+
num_layers=cfg["num_layers"],
|
| 264 |
+
).to(device)
|
| 265 |
+
heads = PIMTHeads(hidden_dim=cfg["hidden_dim"], objective_dim=138).to(device)
|
| 266 |
+
|
| 267 |
+
params = list(model.parameters()) + list(heads.parameters())
|
| 268 |
+
optimizer = optim.AdamW(params, lr=cfg["lr"], weight_decay=cfg["weight_decay"])
|
| 269 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
|
| 270 |
+
|
| 271 |
+
weights = {"obj": 1.0, "season": 0.5, "gender": 0.25, "wear": 0.25}
|
| 272 |
+
|
| 273 |
+
writer = SummaryWriter(log_dir=args.log_dir)
|
| 274 |
+
output_dir = Path(args.output_dir)
|
| 275 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 276 |
+
checkpoint_path = output_dir / cfg["checkpoint_name"]
|
| 277 |
+
|
| 278 |
+
best_val = float("inf")
|
| 279 |
+
for epoch in range(1, args.epochs + 1):
|
| 280 |
+
train_metrics = train_epoch(model, heads, train_loader, optimizer, device, weights, max_batches=cfg["max_batches_per_epoch"])
|
| 281 |
+
val_metrics = validate(model, heads, val_loader, device, weights)
|
| 282 |
+
scheduler.step()
|
| 283 |
+
|
| 284 |
+
for split, metrics in [("train", train_metrics), ("val", val_metrics)]:
|
| 285 |
+
for k, v in metrics.items():
|
| 286 |
+
writer.add_scalar(f"{split}/{k}", v, epoch)
|
| 287 |
+
|
| 288 |
+
logger.info(
|
| 289 |
+
"Epoch %d/%d | train_total=%.4f | val_total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f",
|
| 290 |
+
epoch, args.epochs, train_metrics["total"], val_metrics["total"],
|
| 291 |
+
val_metrics["obj"], val_metrics["season"], val_metrics["gender"], val_metrics["wear"],
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
if val_metrics["total"] < best_val:
|
| 295 |
+
best_val = val_metrics["total"]
|
| 296 |
+
torch.save({
|
| 297 |
+
"epoch": epoch,
|
| 298 |
+
"model_state_dict": model.state_dict(),
|
| 299 |
+
"heads_state_dict": heads.state_dict(),
|
| 300 |
+
"optimizer_state_dict": optimizer.state_dict(),
|
| 301 |
+
"val_loss": best_val,
|
| 302 |
+
}, checkpoint_path)
|
| 303 |
+
logger.info("Saved best checkpoint to %s", checkpoint_path)
|
| 304 |
+
|
| 305 |
+
test_metrics = validate(model, heads, test_loader, device, weights)
|
| 306 |
+
logger.info(
|
| 307 |
+
"Test | total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f",
|
| 308 |
+
test_metrics["total"], test_metrics["obj"], test_metrics["season"], test_metrics["gender"], test_metrics["wear"],
|
| 309 |
+
)
|
| 310 |
+
writer.close()
|
| 311 |
+
return checkpoint_path
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
if __name__ == "__main__":
|
| 315 |
+
main()
|
src/pino/train_hf.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import random
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from huggingface_hub import hf_hub_download
|
| 10 |
+
from transformers import Trainer, TrainingArguments
|
| 11 |
+
|
| 12 |
+
from pino.pimt_model import FragranceTrajectoryDataset
|
| 13 |
+
from pino.pimt_model_hf import PIMTConfig, PhysicsInformedMixtureTransformer
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger("pino.train_hf")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def pad_trajectory_collate(batch: list) -> dict:
|
| 19 |
+
"""Custom collate for variable-length ingredient formulations."""
|
| 20 |
+
import torch
|
| 21 |
+
max_molecules = max(item["tokens"].size(0) for item in batch)
|
| 22 |
+
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 23 |
+
bsz = len(batch)
|
| 24 |
+
|
| 25 |
+
tokens = torch.zeros(bsz, max_molecules, 138, dtype=torch.float32)
|
| 26 |
+
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 27 |
+
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 28 |
+
labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
| 29 |
+
labels_sub = torch.zeros(bsz, 7, dtype=torch.float32)
|
| 30 |
+
|
| 31 |
+
for i, item in enumerate(batch):
|
| 32 |
+
n_mol = item["tokens"].size(0)
|
| 33 |
+
t_steps = item["physics"].size(0)
|
| 34 |
+
tokens[i, :n_mol] = item["tokens"]
|
| 35 |
+
physics[i, :t_steps, :n_mol] = item["physics"]
|
| 36 |
+
src_key_padding_mask[i, :n_mol] = False
|
| 37 |
+
labels_obj[i, :t_steps] = item["target_obj"]
|
| 38 |
+
labels_sub[i] = item["target_sub"]
|
| 39 |
+
|
| 40 |
+
return {
|
| 41 |
+
"tokens": tokens,
|
| 42 |
+
"physics": physics,
|
| 43 |
+
"src_key_padding_mask": src_key_padding_mask,
|
| 44 |
+
"labels_obj": labels_obj,
|
| 45 |
+
"labels_sub": labels_sub,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def main() -> None:
|
| 50 |
+
logging.basicConfig(
|
| 51 |
+
level=logging.INFO,
|
| 52 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 53 |
+
)
|
| 54 |
+
logger.info("Training PIMT with Hugging Face transformers")
|
| 55 |
+
|
| 56 |
+
seed = 2026
|
| 57 |
+
torch.manual_seed(seed)
|
| 58 |
+
np.random.seed(seed)
|
| 59 |
+
random.seed(seed)
|
| 60 |
+
|
| 61 |
+
# Use local dataset by default; can override with HF_DATASET_PATH env var
|
| 62 |
+
dataset_path = Path("data/synthetic_dataset_v2.jsonl")
|
| 63 |
+
if "HF_DATASET_PATH" in __import__("os").environ:
|
| 64 |
+
dataset_path = hf_hub_download(
|
| 65 |
+
repo_id="mattbitzesty/pino-synthetic-dataset",
|
| 66 |
+
filename="synthetic_dataset_v2.jsonl",
|
| 67 |
+
repo_type="dataset",
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
dataset = FragranceTrajectoryDataset(
|
| 71 |
+
data_path=dataset_path,
|
| 72 |
+
use_embedding_fallback=True,
|
| 73 |
+
)
|
| 74 |
+
total = len(dataset)
|
| 75 |
+
train_len = int(0.8 * total)
|
| 76 |
+
val_len = int(0.1 * total)
|
| 77 |
+
test_len = total - train_len - val_len
|
| 78 |
+
train_ds, val_ds, _ = torch.utils.data.random_split(
|
| 79 |
+
dataset, [train_len, val_len, test_len],
|
| 80 |
+
generator=torch.Generator().manual_seed(seed),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
config = PIMTConfig(
|
| 84 |
+
embedding_dim=138,
|
| 85 |
+
state_dim=2,
|
| 86 |
+
hidden_dim=256,
|
| 87 |
+
num_heads=8,
|
| 88 |
+
num_layers=4,
|
| 89 |
+
dropout=0.1,
|
| 90 |
+
num_classes_sub=7,
|
| 91 |
+
)
|
| 92 |
+
model = PhysicsInformedMixtureTransformer(config)
|
| 93 |
+
|
| 94 |
+
training_args = TrainingArguments(
|
| 95 |
+
output_dir="./models/pino_hf_checkpoints",
|
| 96 |
+
do_train=True,
|
| 97 |
+
do_eval=True,
|
| 98 |
+
eval_strategy="epoch",
|
| 99 |
+
num_train_epochs=5,
|
| 100 |
+
per_device_train_batch_size=4,
|
| 101 |
+
per_device_eval_batch_size=4,
|
| 102 |
+
fp16=True,
|
| 103 |
+
gradient_accumulation_steps=4,
|
| 104 |
+
dataloader_num_workers=2,
|
| 105 |
+
dataloader_pin_memory=True,
|
| 106 |
+
logging_steps=10,
|
| 107 |
+
logging_dir="./logs",
|
| 108 |
+
logging_strategy="steps",
|
| 109 |
+
report_to=["tensorboard"],
|
| 110 |
+
save_strategy="epoch",
|
| 111 |
+
save_total_limit=2,
|
| 112 |
+
disable_tqdm=False,
|
| 113 |
+
seed=seed,
|
| 114 |
+
remove_unused_columns=False,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
trainer = Trainer(
|
| 118 |
+
model=model,
|
| 119 |
+
args=training_args,
|
| 120 |
+
train_dataset=train_ds,
|
| 121 |
+
eval_dataset=val_ds,
|
| 122 |
+
data_collator=pad_trajectory_collate,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
trainer.train()
|
| 126 |
+
logger.info("HF training complete")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
main()
|
src/pino/unifac_mapping.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Explicit group-translation mapping layer between ugropy's Dortmund-UNIFAC
|
| 5 |
+
fragmentation output and thermo's bundled DOUFSG parameter table.
|
| 6 |
+
|
| 7 |
+
This resolves nomenclature collisions (e.g. "CHO" belonging to both an
|
| 8 |
+
aldehyde main group and an ether linker main group) and maps ugropy's
|
| 9 |
+
idiosyncratic subgroup names to thermo's integer subgroup IDs.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
# -----------------------------------------------------------------------------
|
| 13 |
+
# Aliases for ugropy subgroup names that differ from thermo's labels.
|
| 14 |
+
# These are *name* translations only; they preserve the chemical meaning.
|
| 15 |
+
# -----------------------------------------------------------------------------
|
| 16 |
+
UGROPY_TO_THERMO_NAME: dict[str, str] = {
|
| 17 |
+
# Aldehyde: ugropy calls it HCO, thermo calls it CHO (Main Group 10, id 20)
|
| 18 |
+
"HCO": "CHO",
|
| 19 |
+
"CH=O": "CHO",
|
| 20 |
+
# Secondary/tertiary OH labels: remove spaces
|
| 21 |
+
"OH (P)": "OH(P)",
|
| 22 |
+
"OH (S)": "OH(S)",
|
| 23 |
+
"OH (T)": "OH(T)",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
# -----------------------------------------------------------------------------
|
| 27 |
+
# Explicit override for cases where the same thermo label maps to multiple
|
| 28 |
+
# subgroup IDs. This pins the chemically correct ID.
|
| 29 |
+
# -----------------------------------------------------------------------------
|
| 30 |
+
# thermo.unifac.DOUFSG:
|
| 31 |
+
# id 20 -> CHO, main_group 10 (aldehyde)
|
| 32 |
+
# id 26 -> CHO, main_group 13 (ether CH-O)
|
| 33 |
+
# We want aldehydes to go to id 20, not 26.
|
| 34 |
+
EXPLICIT_THERMO_ID: dict[str, int] = {
|
| 35 |
+
"HCO": 20,
|
| 36 |
+
"CH=O": 20,
|
| 37 |
+
"CHO__ALDEHYDE": 20, # disambiguation handle
|
| 38 |
+
"CHO__ETHER": 26, # if we ever need the ether linker explicitly
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def map_ugropy_to_thermo_id(
|
| 43 |
+
name: str,
|
| 44 |
+
name_to_id: dict[str, int],
|
| 45 |
+
) -> int | None:
|
| 46 |
+
"""
|
| 47 |
+
Translate a ugropy subgroup name to the thermo DDB UNIFAC subgroup ID.
|
| 48 |
+
|
| 49 |
+
Parameters
|
| 50 |
+
----------
|
| 51 |
+
name : str
|
| 52 |
+
ugropy subgroup name (e.g. "HCO", "OH (P)", "CH3").
|
| 53 |
+
name_to_id : dict[str, int]
|
| 54 |
+
Mapping from thermo subgroup label to thermo subgroup ID.
|
| 55 |
+
|
| 56 |
+
Returns
|
| 57 |
+
-------
|
| 58 |
+
int | None
|
| 59 |
+
Thermo subgroup ID, or None if the group is not representable.
|
| 60 |
+
"""
|
| 61 |
+
# Hardcoded disambiguation overrides first.
|
| 62 |
+
if name in EXPLICIT_THERMO_ID:
|
| 63 |
+
return EXPLICIT_THERMO_ID[name]
|
| 64 |
+
|
| 65 |
+
# Name-only aliases (e.g. "OH (P)" -> "OH(P)")
|
| 66 |
+
normalised = UGROPY_TO_THERMO_NAME.get(name, name).replace(" ", "")
|
| 67 |
+
if normalised in EXPLICIT_THERMO_ID:
|
| 68 |
+
return EXPLICIT_THERMO_ID[normalised]
|
| 69 |
+
|
| 70 |
+
return name_to_id.get(normalised)
|
src/pino/verifier.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from .evaporation import EvaporationModel
|
| 11 |
+
from .ifra import check_ifra_restrictions
|
| 12 |
+
from .models import Formula, Ingredient, IngredientResolutionError, Status, Trajectory
|
| 13 |
+
from .structures import IngredientResolver
|
| 14 |
+
from .vle import VLECalculator
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger("pino.verifier")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FragrancePipelineVerifier:
|
| 20 |
+
"""
|
| 21 |
+
High-level end-to-end verifier for synthetic fragrance formulations.
|
| 22 |
+
|
| 23 |
+
Ingests a list of {cas, weight_fraction} records, resolves chemical
|
| 24 |
+
attributes, checks safety constraints, and runs the stiff ODE evaporation
|
| 25 |
+
model to produce a structured trajectory result.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
temperature_k: float = 298.15,
|
| 31 |
+
ambient_pressure_pa: float = 101325.0,
|
| 32 |
+
headspace_volume_m3: float = 1e-3,
|
| 33 |
+
liquid_volume_m3: float = 1e-6,
|
| 34 |
+
density_g_ml: float = 0.9,
|
| 35 |
+
surface_area_m2: float = 1e-4,
|
| 36 |
+
mass_transfer_coefficient: float = 1e-4,
|
| 37 |
+
) -> None:
|
| 38 |
+
self.temperature_k = temperature_k
|
| 39 |
+
self.ambient_pressure_pa = ambient_pressure_pa
|
| 40 |
+
self.headspace_volume_m3 = headspace_volume_m3
|
| 41 |
+
self.liquid_volume_m3 = liquid_volume_m3
|
| 42 |
+
self.density_g_ml = density_g_ml
|
| 43 |
+
self.surface_area_m2 = surface_area_m2
|
| 44 |
+
self.mass_transfer_coefficient = mass_transfer_coefficient
|
| 45 |
+
self.resolver = IngredientResolver()
|
| 46 |
+
|
| 47 |
+
def run_sim(
|
| 48 |
+
self,
|
| 49 |
+
formula: list[dict[str, Any]],
|
| 50 |
+
duration_seconds: float = 3600.0,
|
| 51 |
+
interval_seconds: float = 600.0,
|
| 52 |
+
method: str = "BDF",
|
| 53 |
+
) -> dict[str, Any]:
|
| 54 |
+
"""
|
| 55 |
+
Run the full verification pipeline on a draft formula.
|
| 56 |
+
|
| 57 |
+
Returns a dict with:
|
| 58 |
+
- status: "passed" or "rejected"
|
| 59 |
+
- trajectory: list of per-time-step records
|
| 60 |
+
- depletion_rates: dict of CAS -> fractional depletion
|
| 61 |
+
- ifra_report: IFRA restriction check
|
| 62 |
+
- applicability_errors: list of out-of-domain errors
|
| 63 |
+
- message: human-readable summary
|
| 64 |
+
"""
|
| 65 |
+
# Resolve ingredients
|
| 66 |
+
try:
|
| 67 |
+
ingredients, errors = self.resolver.resolve_formula(formula, skip_unresolved=False)
|
| 68 |
+
except IngredientResolutionError as exc:
|
| 69 |
+
logger.warning("Formula rejected: out of applicability domain for %s", exc.cas)
|
| 70 |
+
return {
|
| 71 |
+
"status": "rejected",
|
| 72 |
+
"trajectory": [],
|
| 73 |
+
"depletion_rates": {},
|
| 74 |
+
"ifra_report": {"passed": False, "violations": [], "max_usage": []},
|
| 75 |
+
"applicability_errors": [
|
| 76 |
+
{"cas": exc.cas, "smiles": exc.smiles, "reason": str(exc)}
|
| 77 |
+
],
|
| 78 |
+
"message": f"Out of applicability domain: {exc}",
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
weights = [float(c.get("weight_fraction", 0.0)) for c in formula]
|
| 82 |
+
# Re-normalize in case skipped ingredients changed total
|
| 83 |
+
total_w = sum(weights)
|
| 84 |
+
if total_w <= 0:
|
| 85 |
+
return {
|
| 86 |
+
"status": "rejected",
|
| 87 |
+
"trajectory": [],
|
| 88 |
+
"depletion_rates": {},
|
| 89 |
+
"ifra_report": {"passed": False, "violations": [], "max_usage": []},
|
| 90 |
+
"applicability_errors": [],
|
| 91 |
+
"message": "Formula has no positive weight fractions",
|
| 92 |
+
}
|
| 93 |
+
weights = [w / total_w for w in weights]
|
| 94 |
+
|
| 95 |
+
resolved_formula = Formula(
|
| 96 |
+
ingredients=tuple(ingredients),
|
| 97 |
+
weight_fractions=tuple(weights),
|
| 98 |
+
temperature_k=self.temperature_k,
|
| 99 |
+
ambient_pressure_pa=self.ambient_pressure_pa,
|
| 100 |
+
headspace_volume_m3=self.headspace_volume_m3,
|
| 101 |
+
liquid_volume_m3=self.liquid_volume_m3,
|
| 102 |
+
metadata={"density_g_ml": self.density_g_ml},
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# IFRA check
|
| 106 |
+
ifra_report = check_ifra_restrictions(resolved_formula)
|
| 107 |
+
if not ifra_report["passed"]:
|
| 108 |
+
logger.warning("Formula rejected by IFRA restrictions: %s", ifra_report["violations"])
|
| 109 |
+
return {
|
| 110 |
+
"status": "rejected",
|
| 111 |
+
"trajectory": [],
|
| 112 |
+
"depletion_rates": {},
|
| 113 |
+
"ifra_report": ifra_report,
|
| 114 |
+
"applicability_errors": [],
|
| 115 |
+
"message": f"IFRA restriction violation: {ifra_report['violations']}",
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
# Run evaporation model
|
| 119 |
+
vle = VLECalculator(resolved_formula)
|
| 120 |
+
model = EvaporationModel(
|
| 121 |
+
resolved_formula,
|
| 122 |
+
vle=vle,
|
| 123 |
+
surface_area_m2=self.surface_area_m2,
|
| 124 |
+
mass_transfer_coefficient=self.mass_transfer_coefficient,
|
| 125 |
+
)
|
| 126 |
+
n_steps = max(2, int(duration_seconds / interval_seconds) + 1)
|
| 127 |
+
t_eval = np.linspace(0.0, duration_seconds, n_steps)
|
| 128 |
+
trajectory = model.solve(
|
| 129 |
+
t_span=(0.0, duration_seconds),
|
| 130 |
+
t_eval=t_eval,
|
| 131 |
+
method=method,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Compute depletion rates per CAS
|
| 135 |
+
depletion_rates = self._depletion_rates(trajectory)
|
| 136 |
+
|
| 137 |
+
# Convert trajectory to list of dicts
|
| 138 |
+
trajectory_records = self._trajectory_to_records(trajectory)
|
| 139 |
+
|
| 140 |
+
# Detect film-depletion terminal event
|
| 141 |
+
if trajectory.t[-1] < duration_seconds:
|
| 142 |
+
status = Status.DEPLETED
|
| 143 |
+
message = f"Film depleted at t={trajectory.t[-1]:.1f}s before horizon {duration_seconds:.1f}s"
|
| 144 |
+
else:
|
| 145 |
+
status = Status.PASSED
|
| 146 |
+
message = "Formula verified successfully"
|
| 147 |
+
|
| 148 |
+
return {
|
| 149 |
+
"status": status,
|
| 150 |
+
"trajectory": trajectory_records,
|
| 151 |
+
"depletion_rates": depletion_rates,
|
| 152 |
+
"ifra_report": ifra_report,
|
| 153 |
+
"applicability_errors": [],
|
| 154 |
+
"message": message,
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def _depletion_rates(trajectory: Trajectory) -> dict[str, float]:
|
| 159 |
+
"""True fractional liquid molar depletion."""
|
| 160 |
+
rates: dict[str, float] = {}
|
| 161 |
+
n0 = trajectory.n_liquid[:, 0]
|
| 162 |
+
n1 = trajectory.n_liquid[:, -1]
|
| 163 |
+
for idx, ing in enumerate(trajectory.formula.ingredients):
|
| 164 |
+
if n0[idx] > 0:
|
| 165 |
+
rates[ing.cas] = float((n0[idx] - n1[idx]) / n0[idx])
|
| 166 |
+
else:
|
| 167 |
+
rates[ing.cas] = 0.0
|
| 168 |
+
return rates
|
| 169 |
+
|
| 170 |
+
@staticmethod
|
| 171 |
+
def _trajectory_to_records(trajectory: Trajectory) -> list[dict[str, Any]]:
|
| 172 |
+
"""Convert a Trajectory object into a list of JSON-serializable records."""
|
| 173 |
+
records: list[dict[str, Any]] = []
|
| 174 |
+
species = [ing.name for ing in trajectory.formula.ingredients]
|
| 175 |
+
for i, t in enumerate(trajectory.t):
|
| 176 |
+
records.append({
|
| 177 |
+
"t_s": float(t),
|
| 178 |
+
"x_liquid": {s: float(trajectory.x_liquid[j, i]) for j, s in enumerate(species)},
|
| 179 |
+
"C_gas_mg_m3": {s: float(trajectory.C_gas[j, i]) for j, s in enumerate(species)},
|
| 180 |
+
"y_gas": {s: float(trajectory.y_gas[j, i]) for j, s in enumerate(species)},
|
| 181 |
+
"OAV": {s: float(trajectory.OAV[j, i]) for j, s in enumerate(species)},
|
| 182 |
+
})
|
| 183 |
+
return records
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class FormulaVerifier:
|
| 187 |
+
"""Original high-level verifier: intake a draft formula and emit a JSON trajectory."""
|
| 188 |
+
|
| 189 |
+
def __init__(self, formula: Formula) -> None:
|
| 190 |
+
self.formula = formula
|
| 191 |
+
self.vle = VLECalculator(formula)
|
| 192 |
+
self.model = EvaporationModel(formula, vle=self.vle)
|
| 193 |
+
|
| 194 |
+
def verify(self, **solve_kwargs: Any) -> Trajectory:
|
| 195 |
+
return self.model.solve(**solve_kwargs)
|
| 196 |
+
|
| 197 |
+
def verify_and_write(
|
| 198 |
+
self,
|
| 199 |
+
output_path: str | Path = "trajectory_output.json",
|
| 200 |
+
**solve_kwargs: Any,
|
| 201 |
+
) -> Path:
|
| 202 |
+
trajectory = self.verify(**solve_kwargs)
|
| 203 |
+
path = Path(output_path)
|
| 204 |
+
path.write_text(json.dumps(trajectory.to_dict(), indent=2))
|
| 205 |
+
return path
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def verify_formula_dict(data: dict[str, Any], **solve_kwargs: Any) -> Trajectory:
|
| 209 |
+
"""Convenience entrypoint: build a Formula from a dict and run the verifier."""
|
| 210 |
+
from .structures import ingredient_from_data
|
| 211 |
+
|
| 212 |
+
ingredients = [ingredient_from_data(i) for i in data["ingredients"]]
|
| 213 |
+
formula = Formula(
|
| 214 |
+
ingredients=tuple(ingredients),
|
| 215 |
+
weight_fractions=tuple(data["weight_fractions"]),
|
| 216 |
+
temperature_k=float(data.get("temperature_k", 298.15)),
|
| 217 |
+
ambient_pressure_pa=float(data.get("ambient_pressure_pa", 101325.0)),
|
| 218 |
+
headspace_volume_m3=float(data.get("headspace_volume_m3", 1e-3)),
|
| 219 |
+
liquid_volume_m3=float(data.get("liquid_volume_m3", 1e-6)),
|
| 220 |
+
metadata=data.get("metadata", {}),
|
| 221 |
+
)
|
| 222 |
+
verifier = FormulaVerifier(formula)
|
| 223 |
+
return verifier.verify(**solve_kwargs)
|
src/pino/vle.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from thermo.unifac import DOUFIP2006, DOUFSG, UNIFAC
|
| 8 |
+
|
| 9 |
+
from .models import Formula
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger("pino.vle")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class VLECalculator:
|
| 15 |
+
"""Compute non-ideal VLE via Dortmund-Modified UNIFAC."""
|
| 16 |
+
|
| 17 |
+
def __init__(self, formula: Formula) -> None:
|
| 18 |
+
self.formula = formula
|
| 19 |
+
self._cache: dict[tuple[float, ...], np.ndarray] = {}
|
| 20 |
+
self._has_unifac = False
|
| 21 |
+
self.unifac: UNIFAC | None = None
|
| 22 |
+
self._setup_unifac()
|
| 23 |
+
|
| 24 |
+
def _setup_unifac(self) -> None:
|
| 25 |
+
"""Build a UNIFAC object from the ingredient DDB UNIFAC groups."""
|
| 26 |
+
# Convert group ids to integer keys. ugropy emits DDB UNIFAC (Dortmund) group ids.
|
| 27 |
+
groups = []
|
| 28 |
+
for ing in self.formula.ingredients:
|
| 29 |
+
grp = {}
|
| 30 |
+
for gid, count in ing.unifac_groups.items():
|
| 31 |
+
try:
|
| 32 |
+
key = int(gid)
|
| 33 |
+
except ValueError:
|
| 34 |
+
logger.warning("Skipping non-integer UNIFAC group id %s", gid)
|
| 35 |
+
continue
|
| 36 |
+
grp[key] = count
|
| 37 |
+
groups.append(grp)
|
| 38 |
+
|
| 39 |
+
self._has_unifac = any(groups)
|
| 40 |
+
if not self._has_unifac:
|
| 41 |
+
logger.warning("No UNIFAC groups available; activity coefficients default to 1.0")
|
| 42 |
+
return
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
self.unifac = UNIFAC.from_subgroups(
|
| 46 |
+
T=self.formula.temperature_k,
|
| 47 |
+
xs=[1.0 / len(self.formula.ingredients)] * len(self.formula.ingredients),
|
| 48 |
+
chemgroups=groups,
|
| 49 |
+
version=1,
|
| 50 |
+
interaction_data=DOUFIP2006,
|
| 51 |
+
subgroups=DOUFSG,
|
| 52 |
+
)
|
| 53 |
+
except Exception as exc:
|
| 54 |
+
logger.warning("UNIFAC setup failed (%s); falling back to ideal gammas=1", exc)
|
| 55 |
+
self._has_unifac = False
|
| 56 |
+
self.unifac = None
|
| 57 |
+
|
| 58 |
+
def activity_coefficients(self, x: np.ndarray) -> np.ndarray:
|
| 59 |
+
"""Return gamma_i for liquid mole fractions x using UNIFAC."""
|
| 60 |
+
key = tuple(np.round(x, 12).tolist())
|
| 61 |
+
if key in self._cache:
|
| 62 |
+
return self._cache[key]
|
| 63 |
+
|
| 64 |
+
if not self._has_unifac or self.unifac is None:
|
| 65 |
+
gammas = np.ones_like(x, dtype=float)
|
| 66 |
+
else:
|
| 67 |
+
try:
|
| 68 |
+
new_unifac = self.unifac.to_T_xs(
|
| 69 |
+
T=self.formula.temperature_k,
|
| 70 |
+
xs=x.tolist(),
|
| 71 |
+
)
|
| 72 |
+
gammas = np.array(new_unifac.gammas(), dtype=float)
|
| 73 |
+
except Exception as exc:
|
| 74 |
+
logger.warning("UNIFAC gamma calculation failed (%s); using gamma=1", exc)
|
| 75 |
+
gammas = np.ones_like(x, dtype=float)
|
| 76 |
+
|
| 77 |
+
self._cache[key] = gammas
|
| 78 |
+
return gammas
|
| 79 |
+
|
| 80 |
+
def partial_pressures(self, x: np.ndarray) -> np.ndarray:
|
| 81 |
+
"""P_i = gamma_i * x_i * P_i^sat (non-ideal Raoult)."""
|
| 82 |
+
gamma = self.activity_coefficients(x)
|
| 83 |
+
p_sat = np.array([i.vapor_pressure_pa for i in self.formula.ingredients], dtype=float)
|
| 84 |
+
return gamma * x * p_sat
|
| 85 |
+
|
| 86 |
+
def gas_mole_fractions(self, x: np.ndarray) -> np.ndarray:
|
| 87 |
+
"""y_i = P_i / P_total (assuming gas phase ideal at ambient pressure)."""
|
| 88 |
+
p_partial = self.partial_pressures(x)
|
| 89 |
+
p_total = p_partial.sum()
|
| 90 |
+
if p_total <= 0:
|
| 91 |
+
return np.zeros_like(x)
|
| 92 |
+
return p_partial / p_total
|
| 93 |
+
|
| 94 |
+
def gas_concentrations_mg_m3(self, x: np.ndarray) -> np.ndarray:
|
| 95 |
+
"""Convert gas mole fractions to mass concentrations at ambient T and P."""
|
| 96 |
+
y = self.gas_mole_fractions(x)
|
| 97 |
+
# total molar concentration (mol/m3) = P / (R T)
|
| 98 |
+
R = 8.314462618 # J/(mol K)
|
| 99 |
+
c_total = self.formula.ambient_pressure_pa / (R * self.formula.temperature_k) # mol/m3
|
| 100 |
+
mws = np.array([i.molecular_weight for i in self.formula.ingredients], dtype=float) # g/mol
|
| 101 |
+
# mg/m3 = y_i * C_total * MW_i * 1000 mg/g
|
| 102 |
+
return y * c_total * mws * 1000.0
|
| 103 |
+
|
| 104 |
+
def fugacity_ratios(self, x: np.ndarray) -> np.ndarray:
|
| 105 |
+
"""Driving force for evaporation: f_i^L / (P * phi_i) ≈ gamma_i * x_i * P_i^sat / P."""
|
| 106 |
+
return self.partial_pressures(x) / self.formula.ambient_pressure_pa
|
tests/test_factory.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pyarrow.parquet as pq
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
PARQUET_PATH = Path(__file__).parent.parent / "data" / "trajectories.parquet"
|
| 12 |
+
JSONL_PATH = Path(__file__).parent.parent / "data" / "synthetic_dataset_v2.jsonl"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def verify_drydown(record: dict) -> bool:
|
| 16 |
+
"""
|
| 17 |
+
Check that a trajectory represents a physically plausible dry-down:
|
| 18 |
+
- non-empty trajectory with a finite time span
|
| 19 |
+
- final time is near the 8-hour horizon (or film is depleted earlier)
|
| 20 |
+
- no negative or NaN mole fractions in the trajectory
|
| 21 |
+
"""
|
| 22 |
+
traj = record.get("trajectory", [])
|
| 23 |
+
if not traj:
|
| 24 |
+
return False
|
| 25 |
+
if not all(math.isfinite(step["t_s"]) for step in traj):
|
| 26 |
+
return False
|
| 27 |
+
if traj[0]["t_s"] != pytest.approx(0.0, abs=1.0):
|
| 28 |
+
return False
|
| 29 |
+
if traj[-1]["t_s"] < 1000.0:
|
| 30 |
+
return False
|
| 31 |
+
for step in traj:
|
| 32 |
+
x_vals = list(step.get("x_liquid", {}).values())
|
| 33 |
+
if any(v < -1e-6 or not math.isfinite(v) for v in x_vals):
|
| 34 |
+
return False
|
| 35 |
+
return True
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def verify_stability(record: dict) -> bool:
|
| 39 |
+
"""
|
| 40 |
+
Check thermodynamic/ODE stability:
|
| 41 |
+
- status is 'passed' or 'depleted'
|
| 42 |
+
- depletion rates are in [0, 1]
|
| 43 |
+
- no NaN/Inf in depletion rates
|
| 44 |
+
"""
|
| 45 |
+
status = record.get("status", "")
|
| 46 |
+
if status not in ("passed", "depleted"):
|
| 47 |
+
return False
|
| 48 |
+
rates = record.get("depletion_rates", {})
|
| 49 |
+
if not rates:
|
| 50 |
+
return False
|
| 51 |
+
for v in rates.values():
|
| 52 |
+
if not math.isfinite(v) or v < -1e-3 or v > 1.0 + 1e-3:
|
| 53 |
+
return False
|
| 54 |
+
return True
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@pytest.fixture(scope="module")
|
| 58 |
+
def parquet_records():
|
| 59 |
+
assert PARQUET_PATH.exists(), f"Parquet file not found: {PARQUET_PATH}"
|
| 60 |
+
table = pq.read_table(PARQUET_PATH)
|
| 61 |
+
rows = table.to_pydict()
|
| 62 |
+
records = []
|
| 63 |
+
for i in range(table.num_rows):
|
| 64 |
+
records.append({k: json.loads(rows[k][i]) if k in ("formula", "depletion_rates", "trajectory") else rows[k][i] for k in rows})
|
| 65 |
+
return records
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_parquet_exists_and_has_records():
|
| 69 |
+
assert PARQUET_PATH.exists()
|
| 70 |
+
table = pq.read_table(PARQUET_PATH)
|
| 71 |
+
assert table.num_rows >= 5000
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_parquet_genre_stratification(parquet_records):
|
| 75 |
+
strategies = {}
|
| 76 |
+
for rec in parquet_records:
|
| 77 |
+
strategies[rec["generation_strategy"]] = strategies.get(rec["generation_strategy"], 0) + 1
|
| 78 |
+
expected_genres = {"citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"}
|
| 79 |
+
assert expected_genres.issubset(strategies.keys())
|
| 80 |
+
for genre in expected_genres:
|
| 81 |
+
assert strategies[genre] >= 900, f"Genre {genre} under-represented: {strategies[genre]}"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_verify_drydown_all_records(parquet_records):
|
| 85 |
+
failures = []
|
| 86 |
+
for rec in parquet_records:
|
| 87 |
+
if not verify_drydown(rec):
|
| 88 |
+
failures.append(rec["formula_id"])
|
| 89 |
+
assert not failures, f"verify_drydown failed for {len(failures)} records: {failures[:10]}"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_verify_stability_all_records(parquet_records):
|
| 93 |
+
failures = []
|
| 94 |
+
for rec in parquet_records:
|
| 95 |
+
if not verify_stability(rec):
|
| 96 |
+
failures.append(rec["formula_id"])
|
| 97 |
+
assert not failures, f"verify_stability failed for {len(failures)} records: {failures[:10]}"
|
tests/test_pimt_invariance.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
from pino.embeddings import OlfactoryEmbeddingEngine
|
| 8 |
+
from pino.heads import PIMTHeads
|
| 9 |
+
from pino.pimt_model import PhysicsInformedMixtureTransformer
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_ingredient_order_permutation_invariance() -> None:
|
| 13 |
+
"""
|
| 14 |
+
Shuffling the order of ingredient tokens in a formulation must leave the
|
| 15 |
+
transformer encoder's output unchanged, because the model uses no
|
| 16 |
+
positional encodings and attends over a permutation-invariant token set.
|
| 17 |
+
"""
|
| 18 |
+
engine = OlfactoryEmbeddingEngine(use_fallback=True)
|
| 19 |
+
smiles_list = ["CCO", "CC(=O)O", "c1ccccc1", "CC(C)Cc1ccc(C(C)C)cc1"]
|
| 20 |
+
embeddings = np.stack([engine.get_embedding(s) for s in smiles_list], axis=0)
|
| 21 |
+
embeddings = torch.from_numpy(embeddings).float()
|
| 22 |
+
|
| 23 |
+
# Synthetic physical states (T, S, 4).
|
| 24 |
+
timesteps = 5
|
| 25 |
+
states = torch.rand(timesteps, len(smiles_list), 4)
|
| 26 |
+
|
| 27 |
+
model = PhysicsInformedMixtureTransformer(
|
| 28 |
+
embedding_dim=138,
|
| 29 |
+
state_dim=4,
|
| 30 |
+
hidden_dim=256,
|
| 31 |
+
num_heads=4,
|
| 32 |
+
num_layers=2,
|
| 33 |
+
)
|
| 34 |
+
model.eval()
|
| 35 |
+
heads = PIMTHeads(hidden_dim=256, objective_dim=138).eval()
|
| 36 |
+
|
| 37 |
+
with torch.no_grad():
|
| 38 |
+
latent = model(embeddings.unsqueeze(0), states.unsqueeze(0))
|
| 39 |
+
pred = heads(latent)
|
| 40 |
+
|
| 41 |
+
perm = torch.randperm(len(smiles_list))
|
| 42 |
+
perm_embeddings = embeddings[perm]
|
| 43 |
+
perm_states = states[:, perm, :]
|
| 44 |
+
latent_perm = model(perm_embeddings.unsqueeze(0), perm_states.unsqueeze(0))
|
| 45 |
+
pred_perm = heads(latent_perm)
|
| 46 |
+
|
| 47 |
+
assert torch.allclose(pred["objective"], pred_perm["objective"], atol=1e-5)
|
| 48 |
+
for key in pred["subjective"]:
|
| 49 |
+
assert torch.allclose(pred["subjective"][key], pred_perm["subjective"][key], atol=1e-5)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_head_output_shapes() -> None:
|
| 53 |
+
"""Verify both dual heads emit tensors of the expected shapes."""
|
| 54 |
+
model = PhysicsInformedMixtureTransformer(
|
| 55 |
+
embedding_dim=138, state_dim=4, hidden_dim=256, num_heads=4, num_layers=2
|
| 56 |
+
)
|
| 57 |
+
heads = PIMTHeads(hidden_dim=256, objective_dim=138)
|
| 58 |
+
model.eval()
|
| 59 |
+
heads.eval()
|
| 60 |
+
|
| 61 |
+
bsz, t_steps, n_mol = 2, 7, 6
|
| 62 |
+
tokens = torch.rand(bsz, n_mol, 138)
|
| 63 |
+
physics = torch.rand(bsz, t_steps, n_mol, 4)
|
| 64 |
+
# Valid tokens are False; the last token is a zero-padded placeholder marked True.
|
| 65 |
+
src_key_padding_mask = torch.zeros(bsz, n_mol, dtype=torch.bool)
|
| 66 |
+
src_key_padding_mask[:, -1] = True
|
| 67 |
+
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
latent = model(tokens, physics, src_key_padding_mask)
|
| 70 |
+
pred = heads(latent)
|
| 71 |
+
|
| 72 |
+
assert pred["objective"].shape == (bsz, t_steps, 138)
|
| 73 |
+
assert pred["subjective"]["seasonality"].shape == (bsz, 4)
|
| 74 |
+
assert pred["subjective"]["gender_profile"].shape == (bsz,)
|
| 75 |
+
assert pred["subjective"]["wearability"].shape == (bsz, 4)
|
| 76 |
+
assert pred["subjective"]["gender_profile"].min() >= -1.0
|
| 77 |
+
assert pred["subjective"]["gender_profile"].max() <= 1.0
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_objective_target_curve_physics() -> None:
|
| 81 |
+
"""Check that the genre-specific volatility curves follow perfumery physics."""
|
| 82 |
+
from pino.semantics import get_objective_targets
|
| 83 |
+
|
| 84 |
+
targets = get_objective_targets("citrus_cologne", timesteps=50)
|
| 85 |
+
# Citrus top note should decay from start to end.
|
| 86 |
+
assert targets[0, 0] > targets[-1, 0]
|
| 87 |
+
# Wood base note should rise.
|
| 88 |
+
assert targets[-1, 2] > targets[0, 2]
|
| 89 |
+
# Lavender heart note should peak in the middle of the dry-down.
|
| 90 |
+
lavender_series = targets[:, 1]
|
| 91 |
+
peak_idx = int(np.argmax(lavender_series))
|
| 92 |
+
assert 5 < peak_idx < 45, "Lavender heart note did not peak in mid-dry-down"
|
tests/test_pino.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pino import evaporation, vle, verifier
|
| 10 |
+
from pino.models import Formula, Ingredient, IngredientResolutionError
|
| 11 |
+
from pino.structures import IngredientResolver, ingredient_from_smiles
|
| 12 |
+
from pino.verifier import FormulaVerifier, verify_formula_dict
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# Reference data for the classic 5-component accord in an ethanol base.
|
| 16 |
+
# Vapor pressures are approximate room-temperature values (Pa) for 25 °C.
|
| 17 |
+
# Odor thresholds are rough literature estimates (µg/m³).
|
| 18 |
+
_TEST_FORMULA_DATA = {
|
| 19 |
+
"temperature_k": 298.15,
|
| 20 |
+
"ambient_pressure_pa": 101325.0,
|
| 21 |
+
"headspace_volume_m3": 1e-3,
|
| 22 |
+
"liquid_volume_m3": 1e-6,
|
| 23 |
+
"metadata": {"density_g_ml": 0.9},
|
| 24 |
+
"ingredients": [
|
| 25 |
+
{
|
| 26 |
+
"name": "Ethanol",
|
| 27 |
+
"cas": "64-17-5",
|
| 28 |
+
"smiles": "CCO",
|
| 29 |
+
"molecular_weight": 46.07,
|
| 30 |
+
"vapor_pressure_pa": 7900.0,
|
| 31 |
+
"boiling_point_k": 351.45,
|
| 32 |
+
"odor_threshold_ug_m3": 250000.0,
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"name": "Limonene",
|
| 36 |
+
"cas": "138-86-3",
|
| 37 |
+
"smiles": "CC1=CCC(C=C1)C(C)C",
|
| 38 |
+
"molecular_weight": 136.23,
|
| 39 |
+
"vapor_pressure_pa": 195.0,
|
| 40 |
+
"boiling_point_k": 449.0,
|
| 41 |
+
"odor_threshold_ug_m3": 30.0,
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"name": "Linalool",
|
| 45 |
+
"cas": "78-70-6",
|
| 46 |
+
"smiles": "CC=C(C)C(CC=C(C)C)O",
|
| 47 |
+
"molecular_weight": 154.25,
|
| 48 |
+
"vapor_pressure_pa": 22.0,
|
| 49 |
+
"boiling_point_k": 471.0,
|
| 50 |
+
"odor_threshold_ug_m3": 6.0,
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"name": "Hedione",
|
| 54 |
+
"cas": "24851-98-7",
|
| 55 |
+
"smiles": "CC/C(=C/C(=O)C(C)C)C(C)C(=O)O",
|
| 56 |
+
"molecular_weight": 226.32,
|
| 57 |
+
"vapor_pressure_pa": 1.2,
|
| 58 |
+
"boiling_point_k": 548.0,
|
| 59 |
+
"odor_threshold_ug_m3": 1.0,
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"name": "Galaxolide",
|
| 63 |
+
"cas": "1222-05-5",
|
| 64 |
+
"smiles": "CC(=O)C1=CC=C(C)C=C1",
|
| 65 |
+
"molecular_weight": 258.40,
|
| 66 |
+
"vapor_pressure_pa": 0.05,
|
| 67 |
+
"boiling_point_k": 623.0,
|
| 68 |
+
"odor_threshold_ug_m3": 0.1,
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"name": "Ambroxan",
|
| 72 |
+
"cas": "6790-58-5",
|
| 73 |
+
"smiles": "CC1CCCC2(C)C1C(C)CC(C)O2",
|
| 74 |
+
"molecular_weight": 236.39,
|
| 75 |
+
"vapor_pressure_pa": 0.01,
|
| 76 |
+
"boiling_point_k": 573.0,
|
| 77 |
+
"odor_threshold_ug_m3": 0.02,
|
| 78 |
+
},
|
| 79 |
+
],
|
| 80 |
+
"weight_fractions": [0.70, 0.10, 0.08, 0.06, 0.04, 0.02],
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@pytest.fixture
|
| 85 |
+
def test_formula() -> Formula:
|
| 86 |
+
return verify_formula_dict(_TEST_FORMULA_DATA).formula
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_ingredient_from_smiles() -> None:
|
| 90 |
+
ing = ingredient_from_smiles(
|
| 91 |
+
name="Limonene",
|
| 92 |
+
cas="138-86-3",
|
| 93 |
+
smiles="CC1=CCC(C=C1)C(C)C",
|
| 94 |
+
vapor_pressure_pa=195.0,
|
| 95 |
+
)
|
| 96 |
+
assert ing.name == "Limonene"
|
| 97 |
+
assert ing.molecular_weight > 0
|
| 98 |
+
assert ing.unifac_groups
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_formula_validation() -> None:
|
| 102 |
+
ing = Ingredient(
|
| 103 |
+
name="Ethanol",
|
| 104 |
+
cas="64-17-5",
|
| 105 |
+
smiles="CCO",
|
| 106 |
+
molecular_weight=46.07,
|
| 107 |
+
vapor_pressure_pa=7900.0,
|
| 108 |
+
)
|
| 109 |
+
# Sum must be 1.0
|
| 110 |
+
with pytest.raises(ValueError):
|
| 111 |
+
Formula(
|
| 112 |
+
ingredients=(ing,),
|
| 113 |
+
weight_fractions=(0.5,),
|
| 114 |
+
temperature_k=298.15,
|
| 115 |
+
ambient_pressure_pa=101325.0,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_vle_non_ideal(test_formula: Formula) -> None:
|
| 120 |
+
calc = vle.VLECalculator(test_formula)
|
| 121 |
+
x = test_formula.mole_fractions
|
| 122 |
+
gamma = calc.activity_coefficients(x)
|
| 123 |
+
# Gamma should be finite and not all exactly 1.0 if UNIFAC produced groups
|
| 124 |
+
assert np.isfinite(gamma).all()
|
| 125 |
+
assert gamma.shape == (len(test_formula.ingredients),)
|
| 126 |
+
# Partial pressures must be less than or equal to saturation pressures
|
| 127 |
+
p_part = calc.partial_pressures(x)
|
| 128 |
+
p_sat = np.array([i.vapor_pressure_pa for i in test_formula.ingredients])
|
| 129 |
+
assert (p_part <= p_sat * 1.01).all()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test_evaporation_stiff_solve() -> None:
|
| 133 |
+
trajectory = verify_formula_dict(
|
| 134 |
+
_TEST_FORMULA_DATA,
|
| 135 |
+
t_span=(0.0, 28800.0),
|
| 136 |
+
t_eval=np.linspace(0.0, 28800.0, 481),
|
| 137 |
+
method="BDF",
|
| 138 |
+
)
|
| 139 |
+
# Shape checks
|
| 140 |
+
assert trajectory.t.shape[0] == 481
|
| 141 |
+
n_species = len(_TEST_FORMULA_DATA["ingredients"])
|
| 142 |
+
assert trajectory.n_liquid.shape == (n_species, 481)
|
| 143 |
+
assert trajectory.x_liquid.shape == (n_species, 481)
|
| 144 |
+
assert trajectory.C_gas.shape == (n_species, 481)
|
| 145 |
+
assert trajectory.y_gas.shape == (n_species, 481)
|
| 146 |
+
assert trajectory.OAV.shape == (n_species, 481)
|
| 147 |
+
|
| 148 |
+
# No negative moles (mass balance sanity)
|
| 149 |
+
assert (trajectory.n_liquid >= 0).all()
|
| 150 |
+
# Total liquid moles decrease monotonically over time
|
| 151 |
+
total_moles = trajectory.n_liquid.sum(axis=0)
|
| 152 |
+
assert np.all(np.diff(total_moles) <= 1e-12)
|
| 153 |
+
|
| 154 |
+
# Compute true fractional liquid depletion per component
|
| 155 |
+
depletion = (trajectory.n_liquid[:, 0] - trajectory.n_liquid[:, -1]) / trajectory.n_liquid[:, 0]
|
| 156 |
+
|
| 157 |
+
# Top notes (ethanol, limonene) deplete faster than heart/base notes
|
| 158 |
+
ethanol_idx, limonene_idx, linalool_idx, _, galax_idx, ambrox_idx = range(6)
|
| 159 |
+
assert depletion[ethanol_idx] > depletion[limonene_idx]
|
| 160 |
+
assert depletion[limonene_idx] > depletion[galax_idx]
|
| 161 |
+
assert depletion[ethanol_idx] > depletion[ambrox_idx]
|
| 162 |
+
|
| 163 |
+
# Gas concentrations should be non-negative
|
| 164 |
+
assert (trajectory.C_gas >= 0).all()
|
| 165 |
+
# All mole fractions should stay a valid probability vector
|
| 166 |
+
assert np.allclose(trajectory.x_liquid.sum(axis=0), 1.0, atol=1e-8)
|
| 167 |
+
assert (trajectory.x_liquid >= 0).all()
|
| 168 |
+
|
| 169 |
+
# OAV should be non-negative
|
| 170 |
+
assert (trajectory.OAV >= 0).all()
|
| 171 |
+
|
| 172 |
+
# Distinct per-species dynamic skin sink rates are recorded
|
| 173 |
+
assert "k_skin_s-1" in trajectory.notes
|
| 174 |
+
assert len(trajectory.notes["k_skin_s-1"]) == n_species
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_verify_and_write(tmp_path: Path) -> None:
|
| 178 |
+
formula = verify_formula_dict(_TEST_FORMULA_DATA).formula
|
| 179 |
+
v = verifier.FormulaVerifier(formula)
|
| 180 |
+
out = v.verify_and_write(tmp_path / "trajectory_output.json", t_eval=np.linspace(0, 28800, 481))
|
| 181 |
+
assert out.exists()
|
| 182 |
+
data = json.loads(out.read_text())
|
| 183 |
+
assert "t_s" in data
|
| 184 |
+
assert "x_liquid" in data
|
| 185 |
+
assert "C_gas_mg_m3" in data
|
| 186 |
+
assert "OAV" in data
|
| 187 |
+
assert "species" in data
|
| 188 |
+
assert len(data["species"]) == len(_TEST_FORMULA_DATA["ingredients"])
|
| 189 |
+
assert data["t_s"][-1] == 28800.0
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_no_ideal_gas_simplification() -> None:
|
| 193 |
+
"""Ensure activity coefficients are not hard-coded to unity."""
|
| 194 |
+
trajectory = verify_formula_dict(_TEST_FORMULA_DATA)
|
| 195 |
+
calc = vle.VLECalculator(trajectory.formula)
|
| 196 |
+
x = trajectory.formula.mole_fractions
|
| 197 |
+
gamma = calc.activity_coefficients(x)
|
| 198 |
+
# For a non-ideal mixture, at least one gamma should differ from 1.0 by >1%
|
| 199 |
+
assert np.any(np.abs(gamma - 1.0) > 0.01)
|
tests/test_synthetic.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pino.draft_engine import FormulaGenerator
|
| 7 |
+
|
| 8 |
+
RULES_PATH = Path(__file__).parent.parent / "data" / "genre_rules.json"
|
| 9 |
+
REGISTRY_PATH = Path(__file__).parent.parent / "src" / "pino" / "registry.db"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_formula_generator_sum_to_one() -> None:
|
| 13 |
+
gen = FormulaGenerator(
|
| 14 |
+
genre="citrus_cologne",
|
| 15 |
+
rules_path=RULES_PATH,
|
| 16 |
+
registry_path=REGISTRY_PATH,
|
| 17 |
+
seed=42,
|
| 18 |
+
min_k=5,
|
| 19 |
+
max_k=10,
|
| 20 |
+
)
|
| 21 |
+
formula, formula_id = gen.generate(idx=0)
|
| 22 |
+
total = sum(f["weight_fraction"] for f in formula)
|
| 23 |
+
assert pytest.approx(total, 1e-6) == 1.0
|
| 24 |
+
assert formula_id.startswith("gen_")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_formula_generator_ethanol_present() -> None:
|
| 28 |
+
gen = FormulaGenerator(
|
| 29 |
+
genre="citrus_cologne",
|
| 30 |
+
rules_path=RULES_PATH,
|
| 31 |
+
registry_path=REGISTRY_PATH,
|
| 32 |
+
seed=42,
|
| 33 |
+
min_k=5,
|
| 34 |
+
max_k=10,
|
| 35 |
+
)
|
| 36 |
+
formula, _ = gen.generate(idx=0)
|
| 37 |
+
cas_list = [f["cas"] for f in formula]
|
| 38 |
+
assert "64-17-5" in cas_list
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_formula_generator_genre_bounds_respected() -> None:
|
| 42 |
+
"""Citrus cologne must contain at least one top-note compound."""
|
| 43 |
+
gen = FormulaGenerator(
|
| 44 |
+
genre="citrus_cologne",
|
| 45 |
+
rules_path=RULES_PATH,
|
| 46 |
+
registry_path=REGISTRY_PATH,
|
| 47 |
+
seed=42,
|
| 48 |
+
)
|
| 49 |
+
top_cas = set(gen.tiers["top"])
|
| 50 |
+
for _ in range(20):
|
| 51 |
+
formula, _ = gen.generate()
|
| 52 |
+
cas_list = {f["cas"] for f in formula}
|
| 53 |
+
assert cas_list & top_cas, "citrus_cologne formula missing top notes"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_formula_generator_bounds_respected() -> None:
|
| 57 |
+
gen = FormulaGenerator(
|
| 58 |
+
genre="wildcard",
|
| 59 |
+
rules_path=RULES_PATH,
|
| 60 |
+
registry_path=REGISTRY_PATH,
|
| 61 |
+
seed=42,
|
| 62 |
+
min_k=5,
|
| 63 |
+
max_k=10,
|
| 64 |
+
)
|
| 65 |
+
for _ in range(20):
|
| 66 |
+
formula, _ = gen.generate()
|
| 67 |
+
for f in formula:
|
| 68 |
+
meta = gen.compounds.get(f["cas"])
|
| 69 |
+
if meta is None:
|
| 70 |
+
continue # solvent or unknown
|
| 71 |
+
max_w = meta["max_weight_fraction"]
|
| 72 |
+
assert f["weight_fraction"] <= max_w + 1e-9
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_ifra_light_check_blocks_prohibited() -> None:
|
| 76 |
+
gen = FormulaGenerator(
|
| 77 |
+
genre="wildcard",
|
| 78 |
+
rules_path=RULES_PATH,
|
| 79 |
+
registry_path=REGISTRY_PATH,
|
| 80 |
+
seed=42,
|
| 81 |
+
)
|
| 82 |
+
# Musk xylene is prohibited (limit 0.0)
|
| 83 |
+
formula = [
|
| 84 |
+
{"cas": "81-15-2", "weight_fraction": 0.01},
|
| 85 |
+
{"cas": "64-17-5", "weight_fraction": 0.99},
|
| 86 |
+
]
|
| 87 |
+
assert not gen.light_ifra_check(formula)["passed"]
|
tests/test_verifier_pipeline.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from pino.verifier import FragrancePipelineVerifier
|
| 3 |
+
|
| 4 |
+
def test_classic_accord_evaporation():
|
| 5 |
+
# Test formula: 10% Limonene, 20% Linalool, 70% Ethanol base
|
| 6 |
+
formula = [
|
| 7 |
+
{"cas": "5989-27-5", "weight_fraction": 0.10}, # Limonene
|
| 8 |
+
{"cas": "78-70-6", "weight_fraction": 0.20}, # Linalool
|
| 9 |
+
{"cas": "64-17-5", "weight_fraction": 0.70} # Ethanol
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
verifier = FragrancePipelineVerifier()
|
| 13 |
+
trajectory = verifier.run_sim(formula, duration_seconds=3600)
|
| 14 |
+
|
| 15 |
+
assert "trajectory" in trajectory
|
| 16 |
+
assert len(trajectory["trajectory"]) > 0
|
| 17 |
+
# Ensure ethanol depletes significantly faster than linalool
|
| 18 |
+
assert trajectory["depletion_rates"]["64-17-5"] > trajectory["depletion_rates"]["78-70-6"]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_out_of_applicability_domain_graceful():
|
| 22 |
+
# Invalid CAS that PubChem and the registry cannot resolve.
|
| 23 |
+
formula = [
|
| 24 |
+
{"cas": "0000-00-0", "weight_fraction": 0.50},
|
| 25 |
+
{"cas": "64-17-5", "weight_fraction": 0.50},
|
| 26 |
+
]
|
| 27 |
+
verifier = FragrancePipelineVerifier()
|
| 28 |
+
result = verifier.run_sim(formula, duration_seconds=3600)
|
| 29 |
+
assert result["status"] == "rejected"
|
| 30 |
+
assert result["applicability_errors"]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_ifra_rejection():
|
| 34 |
+
# Cinnamaldehyde is restricted/prohibited in the embedded IFRA table.
|
| 35 |
+
formula = [
|
| 36 |
+
{"cas": "104-55-2", "weight_fraction": 0.10},
|
| 37 |
+
{"cas": "64-17-5", "weight_fraction": 0.90},
|
| 38 |
+
]
|
| 39 |
+
verifier = FragrancePipelineVerifier()
|
| 40 |
+
result = verifier.run_sim(formula, duration_seconds=3600)
|
| 41 |
+
assert result["status"] == "rejected"
|
| 42 |
+
assert result["ifra_report"]["passed"] is False
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_five_component_accord_with_registry():
|
| 46 |
+
# Classic 5-component accord in ethanol base via the registry path.
|
| 47 |
+
formula = [
|
| 48 |
+
{"cas": "64-17-5", "weight_fraction": 0.70},
|
| 49 |
+
{"cas": "5989-27-5", "weight_fraction": 0.10},
|
| 50 |
+
{"cas": "78-70-6", "weight_fraction": 0.08},
|
| 51 |
+
{"cas": "24851-98-7", "weight_fraction": 0.06}, # Hedione via registry
|
| 52 |
+
{"cas": "1222-05-5", "weight_fraction": 0.04}, # Galaxolide
|
| 53 |
+
{"cas": "6790-58-5", "weight_fraction": 0.02}, # Ambroxan
|
| 54 |
+
]
|
| 55 |
+
verifier = FragrancePipelineVerifier()
|
| 56 |
+
result = verifier.run_sim(formula, duration_seconds=28800, interval_seconds=600)
|
| 57 |
+
assert result["status"] == "passed"
|
| 58 |
+
assert len(result["trajectory"]) == 49
|
| 59 |
+
# Ethanol depletes faster than musks
|
| 60 |
+
assert result["depletion_rates"]["64-17-5"] > result["depletion_rates"]["6790-58-5"]
|