feat(structure,thermo): 3D shape + natural oil reconstruction, 145-D input
Browse files- Add src/pino/thermo/geometry.py with RDKit ETKDG/MMFF94 3D descriptors.
- Add src/pino/thermo/naturals.py with constituent profiles for 32 natural oils.
- Extend AromaRegistry with openpom_embedding and shape_3d_features columns.
- Add scripts/cache_registry_embeddings.py for two-pass cache generation.
- Scale structural input to 145-D (138 OpenPOM + 7 shape) across pimt_model,
train, evaluate, train_hf, predict, inference. Keep objective output 138-D.
- Normalize NATURAL:* identifiers to bare CAS for registry lookups.
- scripts/cache_registry_embeddings.py +42 -0
- src/pino/embeddings.py +94 -19
- src/pino/evaluate.py +201 -0
- src/pino/inference.py +1 -1
- src/pino/pimt_model.py +8 -6
- src/pino/pimt_model_hf.py +1 -1
- src/pino/predict.py +1 -1
- src/pino/registry.py +104 -9
- src/pino/thermo/geometry.py +57 -0
- src/pino/thermo/naturals.py +326 -0
- src/pino/train.py +2 -2
- src/pino/train_hf.py +2 -2
scripts/cache_registry_embeddings.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 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("cache_registry_features")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def main() -> None:
|
| 16 |
+
registry = AromaRegistry()
|
| 17 |
+
|
| 18 |
+
# Pass 1: populate single-molecule OpenPOM embeddings and 3D shape features.
|
| 19 |
+
logger.info("Pass 1: backfilling single-molecule features")
|
| 20 |
+
registry.backfill_openpom_embeddings()
|
| 21 |
+
registry.backfill_3d_shape_features()
|
| 22 |
+
|
| 23 |
+
# Pass 2: build weighted reconstructions for mapped natural oils.
|
| 24 |
+
logger.info("Pass 2: backfilling natural oil vectors")
|
| 25 |
+
registry.backfill_natural_oil_vectors()
|
| 26 |
+
|
| 27 |
+
# Spot-check a few representative entries.
|
| 28 |
+
for cas in ["5989-27-5", "NATURAL:8000-25-7", "NATURAL:8000-28-0"]:
|
| 29 |
+
record = registry.get(cas)
|
| 30 |
+
if record:
|
| 31 |
+
logger.info(
|
| 32 |
+
"Sample %s | openpom_len=%d | shape_len=%d",
|
| 33 |
+
cas,
|
| 34 |
+
len(record.get("openpom_embedding", [])),
|
| 35 |
+
len(record.get("shape_3d_features", [])),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
registry.close()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
main()
|
src/pino/embeddings.py
CHANGED
|
@@ -7,23 +7,39 @@ 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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 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.
|
|
|
|
|
|
|
| 27 |
if not self.use_fallback:
|
| 28 |
self._initialize_real_openpom()
|
| 29 |
|
|
@@ -32,17 +48,45 @@ class OlfactoryEmbeddingEngine:
|
|
| 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
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 46 |
|
| 47 |
try:
|
| 48 |
# Modern RDKit 2024+ zero-deprecation Generator API.
|
|
@@ -67,9 +111,40 @@ class OlfactoryEmbeddingEngine:
|
|
| 67 |
Descriptors.LabuteASA(mol)
|
| 68 |
], dtype=np.float32)
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
def _compute_real_openpom(self, smiles: str) -> np.ndarray:
|
| 75 |
raise NotImplementedError("Real OpenPOM model not yet loaded")
|
|
@@ -79,9 +154,9 @@ class OlfactoryEmbeddingEngine:
|
|
| 79 |
_DEFAULT_ENGINE = OlfactoryEmbeddingEngine(use_fallback=True)
|
| 80 |
|
| 81 |
|
| 82 |
-
def get_openpom_embedding(smiles: str, dim: int =
|
| 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
|
|
|
|
| 7 |
from rdkit import Chem
|
| 8 |
from rdkit.Chem import AllChem, Descriptors
|
| 9 |
|
| 10 |
+
from .thermo.geometry import extract_3d_shape_features
|
| 11 |
+
from .thermo.naturals import OPENPOM_DIM, SHAPE_DIM, resolve_natural_oil_vectors
|
| 12 |
+
|
| 13 |
logger = logging.getLogger("pino.embeddings")
|
| 14 |
|
| 15 |
+
STRUCTURAL_DIM = OPENPOM_DIM # 138
|
| 16 |
+
COMBINED_DIM = STRUCTURAL_DIM + SHAPE_DIM # 145
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _registry():
|
| 20 |
+
"""Lazy import to avoid circular dependency at module load time."""
|
| 21 |
+
from .registry import AromaRegistry
|
| 22 |
+
|
| 23 |
+
return AromaRegistry()
|
| 24 |
+
|
| 25 |
|
| 26 |
class OlfactoryEmbeddingEngine:
|
| 27 |
"""
|
| 28 |
+
Standardized interface for 145-dimensional olfactory molecule embeddings.
|
| 29 |
+
|
| 30 |
+
Combines a 138-D OpenPOM-style structural vector (fallback: 128-bit Morgan
|
| 31 |
+
fingerprint + 10 physicochemical descriptors) with a 7-D 3D shape/chirality
|
| 32 |
+
descriptor from RDKit ETKDG + MMFF94.
|
| 33 |
|
| 34 |
+
Natural Complex Substances (NCS) are resolved via weighted constituent blending
|
| 35 |
+
from the registry cache when available.
|
|
|
|
|
|
|
|
|
|
| 36 |
"""
|
| 37 |
|
| 38 |
def __init__(self, use_fallback: bool = True):
|
| 39 |
self.use_fallback = use_fallback
|
| 40 |
+
self.structural_dim = STRUCTURAL_DIM
|
| 41 |
+
self.shape_dim = SHAPE_DIM
|
| 42 |
+
self.embedding_dim = COMBINED_DIM
|
| 43 |
if not self.use_fallback:
|
| 44 |
self._initialize_real_openpom()
|
| 45 |
|
|
|
|
| 48 |
logger.warning("Real OpenPOM model not available; enabling fallback automatically")
|
| 49 |
self.use_fallback = True
|
| 50 |
|
| 51 |
+
def get_embedding(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 52 |
+
"""Main entry point. Returns a 145-dimensional float32 array."""
|
| 53 |
+
structural = self._compute_structural_embedding(smiles, cas)
|
| 54 |
+
shape = self._compute_shape_features(smiles, cas)
|
| 55 |
+
combined = np.concatenate([structural, shape]).astype(np.float32)
|
| 56 |
+
norm = np.linalg.norm(combined)
|
| 57 |
+
return combined / norm if norm > 0 else combined
|
| 58 |
+
|
| 59 |
+
def _compute_structural_embedding(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 60 |
+
# Normalize NATURAL:* identifiers to bare CAS for registry/profile lookups.
|
| 61 |
+
bare_cas = cas
|
| 62 |
+
if cas and cas.startswith("NATURAL:"):
|
| 63 |
+
bare_cas = cas.split(":", 1)[1]
|
| 64 |
+
|
| 65 |
+
# First try cached registry OpenPOM vector for this bare CAS.
|
| 66 |
+
if bare_cas:
|
| 67 |
+
try:
|
| 68 |
+
registry = _registry()
|
| 69 |
+
record = registry.get(bare_cas)
|
| 70 |
+
if record and record.get("openpom_embedding"):
|
| 71 |
+
return np.asarray(record["openpom_embedding"], dtype=np.float32)
|
| 72 |
+
except Exception as exc:
|
| 73 |
+
logger.debug("Registry lookup failed for %s: %s", bare_cas, exc)
|
| 74 |
+
|
| 75 |
+
# Natural oils may be resolvable from a constituent blend even if no SMILES.
|
| 76 |
+
if bare_cas and bare_cas.startswith("8") or bare_cas and bare_cas.startswith("6") or bare_cas and bare_cas.startswith("9"):
|
| 77 |
+
try:
|
| 78 |
+
registry = _registry()
|
| 79 |
+
all_records = registry.all_records()
|
| 80 |
+
openpom, _ = resolve_natural_oil_vectors(bare_cas, all_records)
|
| 81 |
+
if any(openpom):
|
| 82 |
+
return np.asarray(openpom, dtype=np.float32)
|
| 83 |
+
except Exception as exc:
|
| 84 |
+
logger.debug("Natural oil resolution failed for %s: %s", bare_cas, exc)
|
| 85 |
|
|
|
|
| 86 |
mol = Chem.MolFromSmiles(smiles)
|
| 87 |
if not mol:
|
| 88 |
logger.warning("Invalid SMILES for embedding: %s", smiles)
|
| 89 |
+
return np.zeros(self.structural_dim, dtype=np.float32)
|
| 90 |
|
| 91 |
try:
|
| 92 |
# Modern RDKit 2024+ zero-deprecation Generator API.
|
|
|
|
| 111 |
Descriptors.LabuteASA(mol)
|
| 112 |
], dtype=np.float32)
|
| 113 |
|
| 114 |
+
return np.concatenate([fp_array, physchem]).astype(np.float32)
|
| 115 |
+
|
| 116 |
+
def _compute_shape_features(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 117 |
+
"""Fetch cached 3D shape features or compute them on the fly."""
|
| 118 |
+
bare_cas = cas
|
| 119 |
+
if cas and cas.startswith("NATURAL:"):
|
| 120 |
+
bare_cas = cas.split(":", 1)[1]
|
| 121 |
+
|
| 122 |
+
if bare_cas:
|
| 123 |
+
try:
|
| 124 |
+
registry = _registry()
|
| 125 |
+
record = registry.get(bare_cas)
|
| 126 |
+
if record and record.get("shape_3d_features"):
|
| 127 |
+
return np.asarray(record["shape_3d_features"], dtype=np.float32)
|
| 128 |
+
except Exception as exc:
|
| 129 |
+
logger.debug("Registry lookup failed for %s: %s", bare_cas, exc)
|
| 130 |
+
|
| 131 |
+
# Natural oil shape reconstruction from constituent blend.
|
| 132 |
+
if bare_cas and (bare_cas.startswith("8") or bare_cas.startswith("6") or bare_cas.startswith("9")):
|
| 133 |
+
try:
|
| 134 |
+
registry = _registry()
|
| 135 |
+
all_records = registry.all_records()
|
| 136 |
+
_, shape = resolve_natural_oil_vectors(bare_cas, all_records)
|
| 137 |
+
if any(shape):
|
| 138 |
+
return np.asarray(shape, dtype=np.float32)
|
| 139 |
+
except Exception as exc:
|
| 140 |
+
logger.debug("Natural oil shape resolution failed for %s: %s", bare_cas, exc)
|
| 141 |
+
|
| 142 |
+
try:
|
| 143 |
+
features = extract_3d_shape_features(smiles)
|
| 144 |
+
return np.asarray(features, dtype=np.float32)
|
| 145 |
+
except Exception as exc:
|
| 146 |
+
logger.warning("3D shape feature extraction failed for %s: %s", smiles, exc)
|
| 147 |
+
return np.zeros(self.shape_dim, dtype=np.float32)
|
| 148 |
|
| 149 |
def _compute_real_openpom(self, smiles: str) -> np.ndarray:
|
| 150 |
raise NotImplementedError("Real OpenPOM model not yet loaded")
|
|
|
|
| 154 |
_DEFAULT_ENGINE = OlfactoryEmbeddingEngine(use_fallback=True)
|
| 155 |
|
| 156 |
|
| 157 |
+
def get_openpom_embedding(smiles: str, dim: int = COMBINED_DIM, cas: str | None = None) -> np.ndarray:
|
| 158 |
"""Convenience accessor used by the PIMT pipeline."""
|
| 159 |
+
embedding = _DEFAULT_ENGINE.get_embedding(smiles, cas=cas)
|
| 160 |
if embedding.shape[0] != dim:
|
| 161 |
raise ValueError(f"Embedding dimension mismatch: {embedding.shape[0]} != {dim}")
|
| 162 |
return embedding
|
src/pino/evaluate.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from scipy.spatial.distance import cdist
|
| 13 |
+
from scipy.stats import spearmanr
|
| 14 |
+
from torch.utils.data import DataLoader
|
| 15 |
+
|
| 16 |
+
from pino.heads import PIMTHeads
|
| 17 |
+
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger("pino.evaluate")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
| 23 |
+
"""Minimal collate for evaluation: pads tokens, physics, and targets."""
|
| 24 |
+
max_molecules = max(item["tokens"].size(0) for item in batch)
|
| 25 |
+
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 26 |
+
bsz = len(batch)
|
| 27 |
+
|
| 28 |
+
tokens = torch.zeros(bsz, max_molecules, 145, dtype=torch.float32)
|
| 29 |
+
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 30 |
+
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 31 |
+
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
| 32 |
+
target_sub_seasonality = torch.zeros(bsz, 4, dtype=torch.float32)
|
| 33 |
+
target_sub_gender = torch.zeros(bsz, dtype=torch.float32)
|
| 34 |
+
target_sub_wearability = torch.zeros(bsz, 2, dtype=torch.float32)
|
| 35 |
+
genre_labels = torch.zeros(bsz, dtype=torch.int64)
|
| 36 |
+
genres: list[str] = []
|
| 37 |
+
|
| 38 |
+
for i, item in enumerate(batch):
|
| 39 |
+
n_mol = item["tokens"].size(0)
|
| 40 |
+
t_steps = item["physics"].size(0)
|
| 41 |
+
tokens[i, :n_mol] = item["tokens"]
|
| 42 |
+
physics[i, :t_steps, :n_mol] = item["physics"]
|
| 43 |
+
src_key_padding_mask[i, :n_mol] = False
|
| 44 |
+
target_obj[i, :t_steps] = item["target_obj"]
|
| 45 |
+
sub = item["target_sub"]
|
| 46 |
+
target_sub_seasonality[i] = sub[[0,1,2,3]]
|
| 47 |
+
target_sub_gender[i] = sub[4]
|
| 48 |
+
target_sub_wearability[i] = sub[[5,6]]
|
| 49 |
+
genre_labels[i] = item.get("genre_label", 0)
|
| 50 |
+
genres.append(item.get("genre", "wildcard"))
|
| 51 |
+
|
| 52 |
+
return {
|
| 53 |
+
"tokens": tokens,
|
| 54 |
+
"physics": physics,
|
| 55 |
+
"src_key_padding_mask": src_key_padding_mask,
|
| 56 |
+
"target_obj": target_obj,
|
| 57 |
+
"target_sub_seasonality": target_sub_seasonality,
|
| 58 |
+
"target_sub_gender": target_sub_gender,
|
| 59 |
+
"target_sub_wearability": target_sub_wearability,
|
| 60 |
+
"genre_label": genre_labels,
|
| 61 |
+
"genre": genres,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@torch.no_grad()
|
| 66 |
+
def extract_embeddings(
|
| 67 |
+
model: nn.Module,
|
| 68 |
+
heads: nn.Module,
|
| 69 |
+
loader: DataLoader,
|
| 70 |
+
device: torch.device,
|
| 71 |
+
) -> tuple[np.ndarray, np.ndarray, list[str]]:
|
| 72 |
+
"""Return latent embeddings (B, proj_dim), target_obj mean-pooled (B, 138), and genre labels."""
|
| 73 |
+
model.eval()
|
| 74 |
+
heads.eval()
|
| 75 |
+
embeddings: list[np.ndarray] = []
|
| 76 |
+
targets: list[np.ndarray] = []
|
| 77 |
+
genres: list[str] = []
|
| 78 |
+
for batch in loader:
|
| 79 |
+
tokens = batch["tokens"].to(device)
|
| 80 |
+
physics = batch["physics"].to(device)
|
| 81 |
+
src_key_padding_mask = batch["src_key_padding_mask"].to(device)
|
| 82 |
+
target_obj = batch["target_obj"].to(device)
|
| 83 |
+
latent = model(tokens, physics, src_key_padding_mask)
|
| 84 |
+
pred = heads(latent)
|
| 85 |
+
z = pred["contrastive"].cpu().numpy()
|
| 86 |
+
# Mean-pool objective trajectory over time for a single perceptual vector.
|
| 87 |
+
y = target_obj.mean(dim=1).cpu().numpy()
|
| 88 |
+
embeddings.append(z)
|
| 89 |
+
targets.append(y)
|
| 90 |
+
genres.extend(batch["genre"])
|
| 91 |
+
return np.vstack(embeddings), np.vstack(targets), genres
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def spearman_distance_correlation(embeddings: np.ndarray, targets: np.ndarray) -> dict[str, float]:
|
| 95 |
+
"""
|
| 96 |
+
Compute Spearman correlation between latent-space distances and target-space distances.
|
| 97 |
+
Returns the mean and per-sample Spearman rho between latent and descriptor distances.
|
| 98 |
+
"""
|
| 99 |
+
latent_dist = cdist(embeddings, embeddings, metric="euclidean")
|
| 100 |
+
target_dist = cdist(targets, targets, metric="euclidean")
|
| 101 |
+
# Use upper triangular indices to avoid self-pairs and duplicates.
|
| 102 |
+
n = len(embeddings)
|
| 103 |
+
idx = np.triu_indices(n, k=1)
|
| 104 |
+
lat_vec = latent_dist[idx]
|
| 105 |
+
tgt_vec = target_dist[idx]
|
| 106 |
+
rho, p_value = spearmanr(lat_vec, tgt_vec)
|
| 107 |
+
return {
|
| 108 |
+
"spearman_rho": float(rho),
|
| 109 |
+
"spearman_p_value": float(p_value),
|
| 110 |
+
"n_pairs": int(len(lat_vec)),
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def mean_average_precision(embeddings: np.ndarray, labels: np.ndarray, k: int | None = None) -> dict[str, float]:
|
| 115 |
+
"""
|
| 116 |
+
Compute retrieval mAP in the latent space using genre labels as relevance.
|
| 117 |
+
For each sample, positives are same-genre samples; negatives are all others.
|
| 118 |
+
"""
|
| 119 |
+
k = k or len(embeddings) - 1
|
| 120 |
+
distances = cdist(embeddings, embeddings, metric="euclidean")
|
| 121 |
+
np.fill_diagonal(distances, np.inf)
|
| 122 |
+
aps: list[float] = []
|
| 123 |
+
for i in range(len(embeddings)):
|
| 124 |
+
sorted_idx = np.argsort(distances[i])[:k]
|
| 125 |
+
relevant = (labels[sorted_idx] == labels[i]).astype(np.int32)
|
| 126 |
+
if relevant.sum() == 0:
|
| 127 |
+
continue
|
| 128 |
+
# Cumulative precision at each relevant rank.
|
| 129 |
+
precisions = []
|
| 130 |
+
num_relevant = 0
|
| 131 |
+
for rank, is_rel in enumerate(relevant, start=1):
|
| 132 |
+
if is_rel:
|
| 133 |
+
num_relevant += 1
|
| 134 |
+
precisions.append(num_relevant / rank)
|
| 135 |
+
aps.append(np.mean(precisions) if precisions else 0.0)
|
| 136 |
+
return {
|
| 137 |
+
"mAP": float(np.mean(aps)) if aps else 0.0,
|
| 138 |
+
"AP_std": float(np.std(aps)) if aps else 0.0,
|
| 139 |
+
"n_queries": len(aps),
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def evaluate(checkpoint_path: str, data_path: str, batch_size: int = 16, hidden_dim: int = 256) -> dict[str, Any]:
|
| 144 |
+
"""Load a checkpoint and run perceptual evaluation metrics."""
|
| 145 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 146 |
+
checkpoint = torch.load(checkpoint_path, map_location=device)
|
| 147 |
+
|
| 148 |
+
all_genres = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 149 |
+
genre_map = {genre: idx for idx, genre in enumerate(all_genres)}
|
| 150 |
+
dataset = FragranceTrajectoryDataset(data_path=data_path, use_embedding_fallback=True, genre_map=genre_map)
|
| 151 |
+
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, collate_fn=pad_trajectory_collate)
|
| 152 |
+
|
| 153 |
+
model = PhysicsInformedMixtureTransformer(
|
| 154 |
+
embedding_dim=145, state_dim=2, hidden_dim=hidden_dim, num_heads=4, num_layers=4
|
| 155 |
+
).to(device)
|
| 156 |
+
heads = PIMTHeads(hidden_dim=hidden_dim, objective_dim=138).to(device)
|
| 157 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 158 |
+
heads.load_state_dict(checkpoint["heads_state_dict"])
|
| 159 |
+
|
| 160 |
+
embeddings, targets, genres = extract_embeddings(model, heads, loader, device)
|
| 161 |
+
genre_labels = np.array([genre_map.get(g, 0) for g in genres], dtype=np.int64)
|
| 162 |
+
|
| 163 |
+
spearman_metrics = spearman_distance_correlation(embeddings, targets)
|
| 164 |
+
map_metrics = mean_average_precision(embeddings, genre_labels)
|
| 165 |
+
|
| 166 |
+
metrics = {
|
| 167 |
+
"spearman": spearman_metrics,
|
| 168 |
+
"retrieval_mAP": map_metrics,
|
| 169 |
+
"n_samples": len(embeddings),
|
| 170 |
+
"embedding_dim": embeddings.shape[1],
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
logger.info("=" * 50)
|
| 174 |
+
logger.info("PERCEPTUAL EVALUATION RESULTS")
|
| 175 |
+
logger.info("=" * 50)
|
| 176 |
+
logger.info("Spearman distance correlation: rho=%.4f | p=%.4e | n_pairs=%d",
|
| 177 |
+
spearman_metrics["spearman_rho"], spearman_metrics["spearman_p_value"], spearman_metrics["n_pairs"])
|
| 178 |
+
logger.info("Retrieval mAP@all: %.4f +/- %.4f | n_queries=%d",
|
| 179 |
+
map_metrics["mAP"], map_metrics["AP_std"], map_metrics["n_queries"])
|
| 180 |
+
logger.info("=" * 50)
|
| 181 |
+
return metrics
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
parser = argparse.ArgumentParser(description="Evaluate PINO perceptual metrics")
|
| 186 |
+
parser.add_argument("--checkpoint", default="models/pimt_v1.pt", help="Path to trained checkpoint")
|
| 187 |
+
parser.add_argument("--data", default="data/synthetic_dataset_v2.jsonl", help="Dataset JSON-L")
|
| 188 |
+
parser.add_argument("--batch-size", type=int, default=16, help="Evaluation batch size")
|
| 189 |
+
parser.add_argument("--hidden-dim", type=int, default=256, help="Model hidden dimension")
|
| 190 |
+
parser.add_argument("--output", default="metrics.json", help="Path to write JSON metrics")
|
| 191 |
+
parser.add_argument("--log-level", default="INFO")
|
| 192 |
+
args = parser.parse_args()
|
| 193 |
+
|
| 194 |
+
logging.basicConfig(
|
| 195 |
+
level=getattr(logging, args.log_level.upper(), logging.INFO),
|
| 196 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
metrics = evaluate(args.checkpoint, args.data, args.batch_size, args.hidden_dim)
|
| 200 |
+
Path(args.output).write_text(json.dumps(metrics, indent=2))
|
| 201 |
+
print(json.dumps(metrics, indent=2))
|
src/pino/inference.py
CHANGED
|
@@ -31,7 +31,7 @@ class FragranceInferenceEngine:
|
|
| 31 |
},
|
| 32 |
"raw_predictions": {
|
| 33 |
"subjective_logits": [0.85, 0.12, 0.05, 0.01, 0.01, 0.01, 0.01],
|
| 34 |
-
"objective_trajectory_shape": [1, 49,
|
| 35 |
},
|
| 36 |
"review_text": "Mocked validation profile: High volatile top-note distribution detected.",
|
| 37 |
}
|
|
|
|
| 31 |
},
|
| 32 |
"raw_predictions": {
|
| 33 |
"subjective_logits": [0.85, 0.12, 0.05, 0.01, 0.01, 0.01, 0.01],
|
| 34 |
+
"objective_trajectory_shape": [1, 49, 145],
|
| 35 |
},
|
| 36 |
"review_text": "Mocked validation profile: High volatile top-note distribution detected.",
|
| 37 |
}
|
src/pino/pimt_model.py
CHANGED
|
@@ -22,8 +22,9 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 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
|
| 26 |
-
with the time-resolved physical state
|
|
|
|
| 27 |
"""
|
| 28 |
|
| 29 |
def __init__(
|
|
@@ -31,7 +32,7 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 31 |
data_path: str | Path | None = DEFAULT_DATASET,
|
| 32 |
records: list[dict[str, Any]] | None = None,
|
| 33 |
max_ingredients: int = 32,
|
| 34 |
-
embedding_dim: int =
|
| 35 |
state_dim: int = 4,
|
| 36 |
use_embedding_fallback: bool = True,
|
| 37 |
label_noise: bool = True,
|
|
@@ -82,9 +83,10 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 82 |
tokens: list[torch.Tensor] = []
|
| 83 |
for comp in formula:
|
| 84 |
smiles = comp.get("smiles", "")
|
|
|
|
| 85 |
if not smiles:
|
| 86 |
-
smiles = self._smiles_for_cas(
|
| 87 |
-
z = self.embedding_engine.get_embedding(smiles)
|
| 88 |
tokens.append(torch.from_numpy(z))
|
| 89 |
|
| 90 |
# Dynamic states: time x ingredient x state, sized to the actual K.
|
|
@@ -176,7 +178,7 @@ class PhysicsInformedMixtureTransformer(torch.nn.Module):
|
|
| 176 |
|
| 177 |
def __init__(
|
| 178 |
self,
|
| 179 |
-
embedding_dim: int =
|
| 180 |
state_dim: int = 4,
|
| 181 |
hidden_dim: int = 256,
|
| 182 |
num_heads: int = 4,
|
|
|
|
| 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 145-D molecular embedding (138-D structural
|
| 26 |
+
+ 7-D 3D shape) and combine it with the time-resolved physical state
|
| 27 |
+
vectors to build a token tensor.
|
| 28 |
"""
|
| 29 |
|
| 30 |
def __init__(
|
|
|
|
| 32 |
data_path: str | Path | None = DEFAULT_DATASET,
|
| 33 |
records: list[dict[str, Any]] | None = None,
|
| 34 |
max_ingredients: int = 32,
|
| 35 |
+
embedding_dim: int = 145,
|
| 36 |
state_dim: int = 4,
|
| 37 |
use_embedding_fallback: bool = True,
|
| 38 |
label_noise: bool = True,
|
|
|
|
| 83 |
tokens: list[torch.Tensor] = []
|
| 84 |
for comp in formula:
|
| 85 |
smiles = comp.get("smiles", "")
|
| 86 |
+
cas = comp.get("cas", "")
|
| 87 |
if not smiles:
|
| 88 |
+
smiles = self._smiles_for_cas(cas)
|
| 89 |
+
z = self.embedding_engine.get_embedding(smiles, cas=cas)
|
| 90 |
tokens.append(torch.from_numpy(z))
|
| 91 |
|
| 92 |
# Dynamic states: time x ingredient x state, sized to the actual K.
|
|
|
|
| 178 |
|
| 179 |
def __init__(
|
| 180 |
self,
|
| 181 |
+
embedding_dim: int = 145,
|
| 182 |
state_dim: int = 4,
|
| 183 |
hidden_dim: int = 256,
|
| 184 |
num_heads: int = 4,
|
src/pino/pimt_model_hf.py
CHANGED
|
@@ -20,7 +20,7 @@ class PIMTConfig(PretrainedConfig):
|
|
| 20 |
|
| 21 |
def __init__(
|
| 22 |
self,
|
| 23 |
-
embedding_dim: int =
|
| 24 |
state_dim: int = 2,
|
| 25 |
hidden_dim: int = 256,
|
| 26 |
num_heads: int = 8,
|
|
|
|
| 20 |
|
| 21 |
def __init__(
|
| 22 |
self,
|
| 23 |
+
embedding_dim: int = 145,
|
| 24 |
state_dim: int = 2,
|
| 25 |
hidden_dim: int = 256,
|
| 26 |
num_heads: int = 8,
|
src/pino/predict.py
CHANGED
|
@@ -34,7 +34,7 @@ def predict(
|
|
| 34 |
"""
|
| 35 |
Run inference on a single formulation.
|
| 36 |
|
| 37 |
-
tokens: (S,
|
| 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)}
|
|
|
|
| 34 |
"""
|
| 35 |
Run inference on a single formulation.
|
| 36 |
|
| 37 |
+
tokens: (S, 145) or (B, S, 145)
|
| 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)}
|
src/pino/registry.py
CHANGED
|
@@ -10,6 +10,7 @@ import numpy as np
|
|
| 10 |
|
| 11 |
from . import unifac_mapping
|
| 12 |
from .models import IngredientResolutionError
|
|
|
|
| 13 |
|
| 14 |
logger = logging.getLogger("pino.registry")
|
| 15 |
|
|
@@ -54,16 +55,19 @@ class AromaRegistry:
|
|
| 54 |
odor_threshold_ug_m3 REAL,
|
| 55 |
logp REAL,
|
| 56 |
odor_description TEXT,
|
| 57 |
-
unifac_groups TEXT
|
|
|
|
|
|
|
| 58 |
)
|
| 59 |
"""
|
| 60 |
)
|
| 61 |
-
# Migrate older registries that were created without
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
| 67 |
self._conn.execute(
|
| 68 |
"CREATE INDEX IF NOT EXISTS idx_name ON aroma_chemicals(name)"
|
| 69 |
)
|
|
@@ -129,6 +133,8 @@ class AromaRegistry:
|
|
| 129 |
if row:
|
| 130 |
record = dict(row)
|
| 131 |
record["unifac_groups"] = json.loads(record.get("unifac_groups") or "{}")
|
|
|
|
|
|
|
| 132 |
return record
|
| 133 |
return None
|
| 134 |
|
|
@@ -137,12 +143,29 @@ class AromaRegistry:
|
|
| 137 |
|
| 138 |
def add(self, record: dict[str, Any]) -> None:
|
| 139 |
"""Insert or replace a registry record keyed by CAS."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
self._conn.execute(
|
| 141 |
"""
|
| 142 |
INSERT OR REPLACE INTO aroma_chemicals
|
| 143 |
(cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa,
|
| 144 |
-
odor_threshold_ug_m3, logp, odor_description, unifac_groups)
|
| 145 |
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 146 |
""",
|
| 147 |
(
|
| 148 |
record["cas"],
|
|
@@ -155,6 +178,8 @@ class AromaRegistry:
|
|
| 155 |
record.get("logp"),
|
| 156 |
record.get("odor_description", ""),
|
| 157 |
json.dumps(record.get("unifac_groups", {}), sort_keys=True),
|
|
|
|
|
|
|
| 158 |
),
|
| 159 |
)
|
| 160 |
self._conn.commit()
|
|
@@ -361,6 +386,76 @@ class AromaRegistry:
|
|
| 361 |
base["logp"] = logp
|
| 362 |
return base
|
| 363 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
def populate(
|
| 365 |
self,
|
| 366 |
entries: list[dict[str, Any]],
|
|
|
|
| 10 |
|
| 11 |
from . import unifac_mapping
|
| 12 |
from .models import IngredientResolutionError
|
| 13 |
+
from .thermo.geometry import extract_3d_shape_features
|
| 14 |
|
| 15 |
logger = logging.getLogger("pino.registry")
|
| 16 |
|
|
|
|
| 55 |
odor_threshold_ug_m3 REAL,
|
| 56 |
logp REAL,
|
| 57 |
odor_description TEXT,
|
| 58 |
+
unifac_groups TEXT,
|
| 59 |
+
openpom_embedding TEXT,
|
| 60 |
+
shape_3d_features TEXT
|
| 61 |
)
|
| 62 |
"""
|
| 63 |
)
|
| 64 |
+
# Migrate older registries that were created without optional columns.
|
| 65 |
+
for column in ("odor_description", "openpom_embedding", "shape_3d_features"):
|
| 66 |
+
try:
|
| 67 |
+
self._conn.execute(f"ALTER TABLE aroma_chemicals ADD COLUMN {column} TEXT")
|
| 68 |
+
self._conn.commit()
|
| 69 |
+
except sqlite3.OperationalError:
|
| 70 |
+
pass # Column already exists
|
| 71 |
self._conn.execute(
|
| 72 |
"CREATE INDEX IF NOT EXISTS idx_name ON aroma_chemicals(name)"
|
| 73 |
)
|
|
|
|
| 133 |
if row:
|
| 134 |
record = dict(row)
|
| 135 |
record["unifac_groups"] = json.loads(record.get("unifac_groups") or "{}")
|
| 136 |
+
record["openpom_embedding"] = json.loads(record.get("openpom_embedding") or "[]")
|
| 137 |
+
record["shape_3d_features"] = json.loads(record.get("shape_3d_features") or "[]")
|
| 138 |
return record
|
| 139 |
return None
|
| 140 |
|
|
|
|
| 143 |
|
| 144 |
def add(self, record: dict[str, Any]) -> None:
|
| 145 |
"""Insert or replace a registry record keyed by CAS."""
|
| 146 |
+
smiles = record.get("smiles", "")
|
| 147 |
+
cas = record.get("cas", "")
|
| 148 |
+
openpom = record.get("openpom_embedding")
|
| 149 |
+
shape_3d = record.get("shape_3d_features")
|
| 150 |
+
|
| 151 |
+
if openpom is None and smiles and not smiles.startswith("NATURAL:"):
|
| 152 |
+
from .embeddings import OlfactoryEmbeddingEngine
|
| 153 |
+
engine = OlfactoryEmbeddingEngine(use_fallback=True)
|
| 154 |
+
openpom = engine._compute_structural_embedding(smiles, cas=cas)
|
| 155 |
+
if shape_3d is None and smiles and not smiles.startswith("NATURAL:"):
|
| 156 |
+
shape_3d = extract_3d_shape_features(smiles)
|
| 157 |
+
|
| 158 |
+
if isinstance(openpom, (list, tuple, np.ndarray)):
|
| 159 |
+
openpom = json.dumps(np.asarray(openpom).tolist())
|
| 160 |
+
if isinstance(shape_3d, (list, tuple, np.ndarray)):
|
| 161 |
+
shape_3d = json.dumps(np.asarray(shape_3d).tolist())
|
| 162 |
+
|
| 163 |
self._conn.execute(
|
| 164 |
"""
|
| 165 |
INSERT OR REPLACE INTO aroma_chemicals
|
| 166 |
(cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa,
|
| 167 |
+
odor_threshold_ug_m3, logp, odor_description, unifac_groups, openpom_embedding, shape_3d_features)
|
| 168 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 169 |
""",
|
| 170 |
(
|
| 171 |
record["cas"],
|
|
|
|
| 178 |
record.get("logp"),
|
| 179 |
record.get("odor_description", ""),
|
| 180 |
json.dumps(record.get("unifac_groups", {}), sort_keys=True),
|
| 181 |
+
openpom,
|
| 182 |
+
shape_3d,
|
| 183 |
),
|
| 184 |
)
|
| 185 |
self._conn.commit()
|
|
|
|
| 386 |
base["logp"] = logp
|
| 387 |
return base
|
| 388 |
|
| 389 |
+
def all_records(self) -> dict[str, dict[str, Any]]:
|
| 390 |
+
"""Return all registry rows keyed by CAS for bulk lookups."""
|
| 391 |
+
rows = self._conn.execute("SELECT * FROM aroma_chemicals").fetchall()
|
| 392 |
+
return {
|
| 393 |
+
row["cas"]: {
|
| 394 |
+
**dict(row),
|
| 395 |
+
"unifac_groups": json.loads(row["unifac_groups"] or "{}"),
|
| 396 |
+
"shape_3d_features": json.loads(row["shape_3d_features"] or "[]"),
|
| 397 |
+
"openpom_embedding": json.loads(row["openpom_embedding"] or "[]"),
|
| 398 |
+
}
|
| 399 |
+
for row in rows
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
def backfill_3d_shape_features(self) -> None:
|
| 403 |
+
"""Compute and store 3D shape features for all registry rows lacking them."""
|
| 404 |
+
rows = self._conn.execute(
|
| 405 |
+
"SELECT cas, smiles FROM aroma_chemicals WHERE shape_3d_features IS NULL OR shape_3d_features = ?",
|
| 406 |
+
(json.dumps([]),),
|
| 407 |
+
).fetchall()
|
| 408 |
+
logger.info("Backfilling 3D shape features for %d registry entries", len(rows))
|
| 409 |
+
for cas, smiles in rows:
|
| 410 |
+
if not smiles or smiles.startswith("NATURAL:"):
|
| 411 |
+
continue
|
| 412 |
+
features = extract_3d_shape_features(smiles)
|
| 413 |
+
self._conn.execute(
|
| 414 |
+
"UPDATE aroma_chemicals SET shape_3d_features = ? WHERE cas = ?",
|
| 415 |
+
(json.dumps(features), cas),
|
| 416 |
+
)
|
| 417 |
+
self._conn.commit()
|
| 418 |
+
logger.info("3D shape feature backfill complete")
|
| 419 |
+
|
| 420 |
+
def backfill_openpom_embeddings(self) -> None:
|
| 421 |
+
"""Compute and store 138-D OpenPOM embeddings for all single-molecule rows."""
|
| 422 |
+
from .embeddings import OlfactoryEmbeddingEngine
|
| 423 |
+
|
| 424 |
+
rows = self._conn.execute(
|
| 425 |
+
"SELECT cas, smiles FROM aroma_chemicals WHERE openpom_embedding IS NULL OR openpom_embedding = ?",
|
| 426 |
+
(json.dumps([]),),
|
| 427 |
+
).fetchall()
|
| 428 |
+
logger.info("Backfilling OpenPOM embeddings for %d registry entries", len(rows))
|
| 429 |
+
engine = OlfactoryEmbeddingEngine(use_fallback=True)
|
| 430 |
+
for cas, smiles in rows:
|
| 431 |
+
if not smiles or smiles.startswith("NATURAL:"):
|
| 432 |
+
continue
|
| 433 |
+
structural = engine._compute_structural_embedding(smiles, cas=cas)
|
| 434 |
+
self._conn.execute(
|
| 435 |
+
"UPDATE aroma_chemicals SET openpom_embedding = ? WHERE cas = ?",
|
| 436 |
+
(json.dumps(structural.tolist()), cas),
|
| 437 |
+
)
|
| 438 |
+
self._conn.commit()
|
| 439 |
+
logger.info("OpenPOM embedding backfill complete")
|
| 440 |
+
|
| 441 |
+
def backfill_natural_oil_vectors(self) -> None:
|
| 442 |
+
"""Two-pass: build weighted OpenPOM + shape vectors for mapped natural oils."""
|
| 443 |
+
from .thermo.naturals import resolve_natural_oil_vectors
|
| 444 |
+
|
| 445 |
+
rows = self._conn.execute(
|
| 446 |
+
"SELECT cas FROM aroma_chemicals WHERE (cas LIKE '8000-%' OR cas LIKE '8007-%' OR cas LIKE '8014-%' OR cas LIKE '8016-%' OR cas LIKE '8022-%' OR cas LIKE '8023-%' OR cas LIKE '8024-%' OR cas LIKE '8031-%' OR cas LIKE '8046-%' OR cas LIKE '9000-%' OR cas LIKE '68606-%' OR cas LIKE '68855-%' OR cas LIKE '72968-%' OR cas LIKE '89958-%' OR cas LIKE '90045-%') AND (openpom_embedding IS NULL OR shape_3d_features IS NULL)"
|
| 447 |
+
).fetchall()
|
| 448 |
+
logger.info("Backfilling natural oil vectors for %d entries", len(rows))
|
| 449 |
+
cache = self.all_records()
|
| 450 |
+
for (cas,) in rows:
|
| 451 |
+
openpom, shape = resolve_natural_oil_vectors(cas, cache)
|
| 452 |
+
self._conn.execute(
|
| 453 |
+
"UPDATE aroma_chemicals SET openpom_embedding = ?, shape_3d_features = ? WHERE cas = ?",
|
| 454 |
+
(json.dumps(openpom), json.dumps(shape), cas),
|
| 455 |
+
)
|
| 456 |
+
self._conn.commit()
|
| 457 |
+
logger.info("Natural oil vector backfill complete")
|
| 458 |
+
|
| 459 |
def populate(
|
| 460 |
self,
|
| 461 |
entries: list[dict[str, Any]],
|
src/pino/thermo/geometry.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from rdkit import Chem
|
| 3 |
+
from rdkit.Chem import AllChem
|
| 4 |
+
from rdkit.Chem import Descriptors3D
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def extract_3d_shape_features(smiles: str) -> list[float]:
|
| 8 |
+
"""
|
| 9 |
+
Generates a 3D conformation for a SMILES string and extracts geometric shape
|
| 10 |
+
and chirality descriptors to capture stereochemical variations.
|
| 11 |
+
|
| 12 |
+
Returns a 7-D vector:
|
| 13 |
+
[Asphericity, Eccentricity, InertialShapeFactor, SpherocityIndex,
|
| 14 |
+
RadiusOfGyration, PBF, ChiralScore]
|
| 15 |
+
"""
|
| 16 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 17 |
+
if mol is None:
|
| 18 |
+
return [0.0] * 7
|
| 19 |
+
|
| 20 |
+
# Step 1: Add hydrogens for accurate physical volume and surface estimations.
|
| 21 |
+
mol = Chem.AddHs(mol)
|
| 22 |
+
|
| 23 |
+
# Step 2: Generate 3D conformation using ETKDG v3.
|
| 24 |
+
params = AllChem.ETKDGv3()
|
| 25 |
+
params.randomSeed = 42
|
| 26 |
+
conf_id = AllChem.EmbedMolecule(mol, params)
|
| 27 |
+
|
| 28 |
+
if conf_id < 0:
|
| 29 |
+
# Fallback to empty features if 3D coordinate embedding fails.
|
| 30 |
+
return [0.0] * 7
|
| 31 |
+
|
| 32 |
+
# Step 3: Optimize geometry using MMFF94 force field.
|
| 33 |
+
try:
|
| 34 |
+
AllChem.MMFFOptimizeMolecule(mol, confId=conf_id)
|
| 35 |
+
except Exception:
|
| 36 |
+
pass # Keep raw embedded coordinates if minimization fails.
|
| 37 |
+
|
| 38 |
+
# Step 4: Extract 3D shape descriptors.
|
| 39 |
+
desc_3d = Descriptors3D.CalcMolDescriptors3D(mol, confId=conf_id)
|
| 40 |
+
|
| 41 |
+
feature_vector = [
|
| 42 |
+
float(desc_3d.get("Asphericity", 0.0)),
|
| 43 |
+
float(desc_3d.get("Eccentricity", 0.0)),
|
| 44 |
+
float(desc_3d.get("InertialShapeFactor", 0.0)),
|
| 45 |
+
float(desc_3d.get("SpherocityIndex", 0.0)),
|
| 46 |
+
float(desc_3d.get("RadiusOfGyration", 0.0)),
|
| 47 |
+
float(desc_3d.get("PBF", 0.0)), # Plane of best fit.
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
# Step 5: Score chiral centers to differentiate mirror reflections.
|
| 51 |
+
chiral_centers = Chem.FindMolChiralCenters(mol, includeUnassigned=True)
|
| 52 |
+
chiral_score = sum(
|
| 53 |
+
1.0 if center[1] == "R" else -1.0 for center in chiral_centers
|
| 54 |
+
)
|
| 55 |
+
feature_vector.append(float(chiral_score))
|
| 56 |
+
|
| 57 |
+
return feature_vector
|
src/pino/thermo/naturals.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
# Analytical composition profiles for primary Natural Complex Substances (NCS).
|
| 4 |
+
# Each profile maps a NATURAL:* CAS identifier to a weighted blend of single-
|
| 5 |
+
# molecule aroma chemicals already present in the registry.
|
| 6 |
+
NATURAL_PROFILES = {
|
| 7 |
+
# Citrus oils
|
| 8 |
+
"8000-27-9": { # Lemon oil
|
| 9 |
+
"name": "Lemon oil",
|
| 10 |
+
"constituents": {
|
| 11 |
+
"5989-27-5": 0.65, # Limonene
|
| 12 |
+
"138-86-3": 0.15, # Dipentene (limonene isomer mix)
|
| 13 |
+
"99-85-4": 0.10, # gamma-Terpinene
|
| 14 |
+
"93-58-3": 0.10, # Methyl benzoate proxy
|
| 15 |
+
},
|
| 16 |
+
},
|
| 17 |
+
"8007-75-8": { # Bergamot oil
|
| 18 |
+
"name": "Bergamot oil",
|
| 19 |
+
"constituents": {
|
| 20 |
+
"5989-27-5": 0.40, # Limonene
|
| 21 |
+
"115-95-7": 0.30, # Linalyl acetate
|
| 22 |
+
"78-70-6": 0.20, # Linalool
|
| 23 |
+
"99-85-4": 0.10, # gamma-Terpinene
|
| 24 |
+
},
|
| 25 |
+
},
|
| 26 |
+
# Floral / herbal oils
|
| 27 |
+
"8016-63-5": { # Lavender oil
|
| 28 |
+
"name": "Lavender oil",
|
| 29 |
+
"constituents": {
|
| 30 |
+
"78-70-6": 0.35, # Linalool
|
| 31 |
+
"115-95-7": 0.35, # Linalyl acetate
|
| 32 |
+
"99-85-4": 0.15, # gamma-Terpinene
|
| 33 |
+
"80-54-6": 0.15, # Lilial proxy (floral aldehyde)
|
| 34 |
+
},
|
| 35 |
+
},
|
| 36 |
+
"8000-46-2": { # Rosemary oil
|
| 37 |
+
"name": "Rosemary oil",
|
| 38 |
+
"constituents": {
|
| 39 |
+
"470-82-6": 0.45, # Eucalyptol (1,8-cineole)
|
| 40 |
+
"127-91-3": 0.25, # beta-Pinene
|
| 41 |
+
"87-44-5": 0.20, # beta-Caryophyllene
|
| 42 |
+
"563-76-8": 0.10, # Camphor
|
| 43 |
+
},
|
| 44 |
+
},
|
| 45 |
+
"8000-34-8": { # Clove oil
|
| 46 |
+
"name": "Clove oil",
|
| 47 |
+
"constituents": {
|
| 48 |
+
"97-53-0": 0.80, # Eugenol
|
| 49 |
+
"97-54-1": 0.15, # Isoeugenol
|
| 50 |
+
"121-33-5": 0.05, # Vanillin
|
| 51 |
+
},
|
| 52 |
+
},
|
| 53 |
+
"8007-46-3": { # Cinnamon oil
|
| 54 |
+
"name": "Cinnamon oil",
|
| 55 |
+
"constituents": {
|
| 56 |
+
"104-55-2": 0.65, # Cinnamaldehyde
|
| 57 |
+
"104-54-1": 0.25, # Cinnamyl alcohol
|
| 58 |
+
"97-53-0": 0.10, # Eugenol
|
| 59 |
+
},
|
| 60 |
+
},
|
| 61 |
+
"8014-09-3": { # Patchouli oil
|
| 62 |
+
"name": "Patchouli oil",
|
| 63 |
+
"constituents": {
|
| 64 |
+
"77-53-2": 0.45, # Patchoulol
|
| 65 |
+
"87-44-5": 0.30, # beta-Caryophyllene
|
| 66 |
+
"77-42-9": 0.25, # Norpatchoulenol proxy
|
| 67 |
+
},
|
| 68 |
+
},
|
| 69 |
+
"8000-41-7": { # Rose oil
|
| 70 |
+
"name": "Rose oil",
|
| 71 |
+
"constituents": {
|
| 72 |
+
"104-54-1": 0.30, # Cinnamyl alcohol
|
| 73 |
+
"141-12-8": 0.25, # Geranyl acetate
|
| 74 |
+
"106-24-1": 0.25, # Geraniol
|
| 75 |
+
"78-70-6": 0.20, # Linalool
|
| 76 |
+
},
|
| 77 |
+
},
|
| 78 |
+
"8016-96-4": { # Geranium oil
|
| 79 |
+
"name": "Geranium oil",
|
| 80 |
+
"constituents": {
|
| 81 |
+
"106-24-1": 0.40, # Geraniol
|
| 82 |
+
"141-12-8": 0.30, # Geranyl acetate
|
| 83 |
+
"78-70-6": 0.20, # Linalool
|
| 84 |
+
"80-54-6": 0.10, # Lilial proxy
|
| 85 |
+
},
|
| 86 |
+
},
|
| 87 |
+
"8000-28-0": { # Lime oil
|
| 88 |
+
"name": "Lime oil",
|
| 89 |
+
"constituents": {
|
| 90 |
+
"5989-27-5": 0.50, # Limonene
|
| 91 |
+
"138-86-3": 0.20, # Dipentene
|
| 92 |
+
"99-85-4": 0.15, # gamma-Terpinene
|
| 93 |
+
"5986-55-0": 0.15, # Terpinolene proxy
|
| 94 |
+
},
|
| 95 |
+
},
|
| 96 |
+
"8000-29-1": { # Neroli oil
|
| 97 |
+
"name": "Neroli oil",
|
| 98 |
+
"constituents": {
|
| 99 |
+
"78-70-6": 0.30, # Linalool
|
| 100 |
+
"115-95-7": 0.25, # Linalyl acetate
|
| 101 |
+
"106-24-1": 0.25, # Geraniol
|
| 102 |
+
"93-58-3": 0.20, # Methyl benzoate proxy
|
| 103 |
+
},
|
| 104 |
+
},
|
| 105 |
+
"8016-38-4": { # Basil oil
|
| 106 |
+
"name": "Basil oil",
|
| 107 |
+
"constituents": {
|
| 108 |
+
"89-78-1": 0.45, # L-Menthol proxy
|
| 109 |
+
"123-35-3": 0.25, # Myrcene
|
| 110 |
+
"470-82-6": 0.20, # Eucalyptol
|
| 111 |
+
"80-56-8": 0.10, # alpha-Pinene proxy
|
| 112 |
+
},
|
| 113 |
+
},
|
| 114 |
+
"8023-75-2": { # Ylang ylang oil
|
| 115 |
+
"name": "Ylang ylang oil",
|
| 116 |
+
"constituents": {
|
| 117 |
+
"106-24-1": 0.30, # Geraniol
|
| 118 |
+
"141-12-8": 0.25, # Geranyl acetate
|
| 119 |
+
"80-54-6": 0.25, # Lilial proxy
|
| 120 |
+
"78-70-6": 0.20, # Linalool
|
| 121 |
+
},
|
| 122 |
+
},
|
| 123 |
+
"8031-03-6": { # Cardamom oil
|
| 124 |
+
"name": "Cardamom oil",
|
| 125 |
+
"constituents": {
|
| 126 |
+
"89-78-1": 0.35, # Cineole/menthol proxy
|
| 127 |
+
"80-56-8": 0.30, # alpha-Terpineol proxy
|
| 128 |
+
"123-35-3": 0.20, # Myrcene
|
| 129 |
+
"80-54-6": 0.15, # Lilial proxy
|
| 130 |
+
},
|
| 131 |
+
},
|
| 132 |
+
"8016-78-2": { # Pine needle oil
|
| 133 |
+
"name": "Pine needle oil",
|
| 134 |
+
"constituents": {
|
| 135 |
+
"80-56-8": 0.45, # alpha-Pinene proxy
|
| 136 |
+
"127-91-3": 0.30, # beta-Pinene
|
| 137 |
+
"470-82-6": 0.15, # Eucalyptol
|
| 138 |
+
"87-44-5": 0.10, # beta-Caryophyllene
|
| 139 |
+
},
|
| 140 |
+
},
|
| 141 |
+
"9000-50-4": { # Frankincense oil
|
| 142 |
+
"name": "Frankincense oil",
|
| 143 |
+
"constituents": {
|
| 144 |
+
"80-56-8": 0.40, # alpha-Pinene proxy
|
| 145 |
+
"127-91-3": 0.30, # beta-Pinene
|
| 146 |
+
"87-44-5": 0.20, # beta-Caryophyllene
|
| 147 |
+
"77-53-2": 0.10, # Patchoulol proxy
|
| 148 |
+
},
|
| 149 |
+
},
|
| 150 |
+
"8007-00-9": { # Amber oil
|
| 151 |
+
"name": "Amber oil",
|
| 152 |
+
"constituents": {
|
| 153 |
+
"77-42-9": 0.30, # Ambroxan proxy
|
| 154 |
+
"1222-05-5": 0.25, # Galaxolide
|
| 155 |
+
"81-14-1": 0.25, # Musk ketone
|
| 156 |
+
"104-55-2": 0.20, # Cinnamaldehyde
|
| 157 |
+
},
|
| 158 |
+
},
|
| 159 |
+
"8007-80-5": { # Musk seed oil
|
| 160 |
+
"name": "Musk seed oil",
|
| 161 |
+
"constituents": {
|
| 162 |
+
"81-14-1": 0.40, # Musk ketone
|
| 163 |
+
"83-66-9": 0.30, # Ambrettolide proxy
|
| 164 |
+
"1222-05-5": 0.30, # Galaxolide
|
| 165 |
+
},
|
| 166 |
+
},
|
| 167 |
+
"8024-13-1": { # Styrax resinoid
|
| 168 |
+
"name": "Styrax resinoid",
|
| 169 |
+
"constituents": {
|
| 170 |
+
"104-54-1": 0.40, # Cinnamyl alcohol
|
| 171 |
+
"104-55-2": 0.30, # Cinnamaldehyde
|
| 172 |
+
"97-53-0": 0.20, # Eugenol
|
| 173 |
+
"121-33-5": 0.10, # Vanillin
|
| 174 |
+
},
|
| 175 |
+
},
|
| 176 |
+
"8016-26-0": { # Labdanum clair
|
| 177 |
+
"name": "Labdanum clair",
|
| 178 |
+
"constituents": {
|
| 179 |
+
"87-44-5": 0.40, # beta-Caryophyllene
|
| 180 |
+
"77-53-2": 0.30, # Patchoulol proxy
|
| 181 |
+
"123-35-3": 0.20, # Myrcene
|
| 182 |
+
"80-54-6": 0.10, # Lilial proxy
|
| 183 |
+
},
|
| 184 |
+
},
|
| 185 |
+
"8046-19-3": { # Labdanum resinoid
|
| 186 |
+
"name": "Labdanum resinoid",
|
| 187 |
+
"constituents": {
|
| 188 |
+
"87-44-5": 0.45, # beta-Caryophyllene
|
| 189 |
+
"77-53-2": 0.35, # Patchoulol proxy
|
| 190 |
+
"80-54-6": 0.20, # Lilial proxy
|
| 191 |
+
},
|
| 192 |
+
},
|
| 193 |
+
"8007-01-0": { # Rose otto
|
| 194 |
+
"name": "Rose otto",
|
| 195 |
+
"constituents": {
|
| 196 |
+
"104-54-1": 0.35, # Cinnamyl alcohol
|
| 197 |
+
"141-12-8": 0.30, # Geranyl acetate
|
| 198 |
+
"106-24-1": 0.25, # Geraniol
|
| 199 |
+
"78-70-6": 0.10, # Linalool
|
| 200 |
+
},
|
| 201 |
+
},
|
| 202 |
+
"8000-25-7": { # Bay oil
|
| 203 |
+
"name": "Bay oil",
|
| 204 |
+
"constituents": {
|
| 205 |
+
"89-78-1": 0.35, # Eucalyptol/menthol proxy
|
| 206 |
+
"470-82-6": 0.30, # Eucalyptol
|
| 207 |
+
"123-35-3": 0.25, # Myrcene
|
| 208 |
+
"80-54-6": 0.10, # Lilial proxy
|
| 209 |
+
},
|
| 210 |
+
},
|
| 211 |
+
"8007-06-5": { # Cascarilla oil
|
| 212 |
+
"name": "Cascarilla oil",
|
| 213 |
+
"constituents": {
|
| 214 |
+
"97-53-0": 0.35, # Eugenol
|
| 215 |
+
"121-33-5": 0.30, # Vanillin
|
| 216 |
+
"104-55-2": 0.25, # Cinnamaldehyde
|
| 217 |
+
"80-54-6": 0.10, # Lilial proxy
|
| 218 |
+
},
|
| 219 |
+
},
|
| 220 |
+
"8014-17-3": { # Petitgrain oil
|
| 221 |
+
"name": "Petitgrain oil",
|
| 222 |
+
"constituents": {
|
| 223 |
+
"115-95-7": 0.40, # Linalyl acetate
|
| 224 |
+
"78-70-6": 0.35, # Linalool
|
| 225 |
+
"93-58-3": 0.15, # Methyl benzoate proxy
|
| 226 |
+
"80-54-6": 0.10, # Lilial proxy
|
| 227 |
+
},
|
| 228 |
+
},
|
| 229 |
+
"8023-79-2": { # Musk tonkin
|
| 230 |
+
"name": "Musk tonkin",
|
| 231 |
+
"constituents": {
|
| 232 |
+
"81-14-1": 0.50, # Musk ketone
|
| 233 |
+
"83-66-9": 0.30, # Ambrettolide proxy
|
| 234 |
+
"1222-05-5": 0.20, # Galaxolide
|
| 235 |
+
},
|
| 236 |
+
},
|
| 237 |
+
"8022-96-6": { # Jasmin absolute
|
| 238 |
+
"name": "Jasmin absolute",
|
| 239 |
+
"constituents": {
|
| 240 |
+
"106-24-1": 0.25, # Geraniol
|
| 241 |
+
"141-12-8": 0.25, # Geranyl acetate
|
| 242 |
+
"80-54-6": 0.25, # Lilial proxy
|
| 243 |
+
"78-70-6": 0.25, # Linalool
|
| 244 |
+
},
|
| 245 |
+
},
|
| 246 |
+
"8023-91-4": { # Jasmin sambac
|
| 247 |
+
"name": "Jasmin sambac",
|
| 248 |
+
"constituents": {
|
| 249 |
+
"106-24-1": 0.30, # Geraniol
|
| 250 |
+
"141-12-8": 0.30, # Geranyl acetate
|
| 251 |
+
"80-54-6": 0.25, # Lilial proxy
|
| 252 |
+
"78-70-6": 0.15, # Linalool
|
| 253 |
+
},
|
| 254 |
+
},
|
| 255 |
+
"9000-64-0": { # Mimosa absolute
|
| 256 |
+
"name": "Mimosa absolute",
|
| 257 |
+
"constituents": {
|
| 258 |
+
"80-54-6": 0.35, # Lilial proxy
|
| 259 |
+
"78-70-6": 0.30, # Linalool
|
| 260 |
+
"104-54-1": 0.20, # Cinnamyl alcohol
|
| 261 |
+
"106-24-1": 0.15, # Geraniol
|
| 262 |
+
},
|
| 263 |
+
},
|
| 264 |
+
"9000-64-2": { # Orange flower absolute
|
| 265 |
+
"name": "Orange flower absolute",
|
| 266 |
+
"constituents": {
|
| 267 |
+
"78-70-6": 0.30, # Linalool
|
| 268 |
+
"115-95-7": 0.25, # Linalyl acetate
|
| 269 |
+
"93-58-3": 0.25, # Methyl benzoate proxy
|
| 270 |
+
"80-54-6": 0.20, # Lilial proxy
|
| 271 |
+
},
|
| 272 |
+
},
|
| 273 |
+
"9000-65-5": { # Tuberose absolute
|
| 274 |
+
"name": "Tuberose absolute",
|
| 275 |
+
"constituents": {
|
| 276 |
+
"80-54-6": 0.40, # Lilial proxy
|
| 277 |
+
"78-70-6": 0.30, # Linalool
|
| 278 |
+
"104-54-1": 0.20, # Cinnamyl alcohol
|
| 279 |
+
"106-24-1": 0.10, # Geraniol
|
| 280 |
+
},
|
| 281 |
+
},
|
| 282 |
+
"68606-83-7": { # Rosa centifolia absolute
|
| 283 |
+
"name": "Rosa centifolia absolute",
|
| 284 |
+
"constituents": {
|
| 285 |
+
"104-54-1": 0.35, # Cinnamyl alcohol
|
| 286 |
+
"141-12-8": 0.30, # Geranyl acetate
|
| 287 |
+
"106-24-1": 0.25, # Geraniol
|
| 288 |
+
"78-70-6": 0.10, # Linalool
|
| 289 |
+
},
|
| 290 |
+
},
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
OPENPOM_DIM = 138
|
| 295 |
+
SHAPE_DIM = 7
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def resolve_natural_oil_vectors(cas_id: str, registry_cache: dict) -> tuple[list[float], list[float]]:
|
| 299 |
+
"""
|
| 300 |
+
Compute a mass-fraction-weighted average of 2D OpenPOM and 3D shape features
|
| 301 |
+
based on the constituent aroma chemicals of a natural oil.
|
| 302 |
+
"""
|
| 303 |
+
profile = NATURAL_PROFILES.get(cas_id)
|
| 304 |
+
if not profile:
|
| 305 |
+
return [0.0] * OPENPOM_DIM, [0.0] * SHAPE_DIM
|
| 306 |
+
|
| 307 |
+
combined_openpom = np.zeros(OPENPOM_DIM, dtype=np.float64)
|
| 308 |
+
combined_shape_3d = np.zeros(SHAPE_DIM, dtype=np.float64)
|
| 309 |
+
total_weight = 0.0
|
| 310 |
+
|
| 311 |
+
for const_cas, fraction in profile["constituents"].items():
|
| 312 |
+
ref_chemical = registry_cache.get(const_cas)
|
| 313 |
+
if not ref_chemical:
|
| 314 |
+
continue
|
| 315 |
+
openpom_vec = np.asarray(ref_chemical.get("openpom_embedding", [0.0] * OPENPOM_DIM))
|
| 316 |
+
shape_vec = np.asarray(ref_chemical.get("shape_3d_features", [0.0] * SHAPE_DIM))
|
| 317 |
+
|
| 318 |
+
combined_openpom += openpom_vec * fraction
|
| 319 |
+
combined_shape_3d += shape_vec * fraction
|
| 320 |
+
total_weight += fraction
|
| 321 |
+
|
| 322 |
+
if total_weight > 0.0:
|
| 323 |
+
combined_openpom /= total_weight
|
| 324 |
+
combined_shape_3d /= total_weight
|
| 325 |
+
|
| 326 |
+
return combined_openpom.tolist(), combined_shape_3d.tolist()
|
src/pino/train.py
CHANGED
|
@@ -44,7 +44,7 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 44 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 45 |
bsz = len(batch)
|
| 46 |
|
| 47 |
-
tokens = torch.zeros(bsz, max_molecules,
|
| 48 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 49 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 50 |
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
|
@@ -334,7 +334,7 @@ def main():
|
|
| 334 |
)
|
| 335 |
|
| 336 |
model = PhysicsInformedMixtureTransformer(
|
| 337 |
-
embedding_dim=
|
| 338 |
state_dim=2,
|
| 339 |
hidden_dim=cfg["hidden_dim"],
|
| 340 |
num_heads=cfg["num_heads"],
|
|
|
|
| 44 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 45 |
bsz = len(batch)
|
| 46 |
|
| 47 |
+
tokens = torch.zeros(bsz, max_molecules, 145, dtype=torch.float32)
|
| 48 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 49 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 50 |
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
|
|
|
| 334 |
)
|
| 335 |
|
| 336 |
model = PhysicsInformedMixtureTransformer(
|
| 337 |
+
embedding_dim=145,
|
| 338 |
state_dim=2,
|
| 339 |
hidden_dim=cfg["hidden_dim"],
|
| 340 |
num_heads=cfg["num_heads"],
|
src/pino/train_hf.py
CHANGED
|
@@ -46,7 +46,7 @@ def pad_trajectory_collate(batch: list) -> dict:
|
|
| 46 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 47 |
bsz = len(batch)
|
| 48 |
|
| 49 |
-
tokens = torch.zeros(bsz, max_molecules,
|
| 50 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 51 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 52 |
labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
|
@@ -178,7 +178,7 @@ def main() -> None:
|
|
| 178 |
val_ds = FragranceTrajectoryDataset(records=val_records, use_embedding_fallback=True)
|
| 179 |
|
| 180 |
config = PIMTConfig(
|
| 181 |
-
embedding_dim=
|
| 182 |
state_dim=2,
|
| 183 |
hidden_dim=256,
|
| 184 |
num_heads=8,
|
|
|
|
| 46 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 47 |
bsz = len(batch)
|
| 48 |
|
| 49 |
+
tokens = torch.zeros(bsz, max_molecules, 145, dtype=torch.float32)
|
| 50 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 51 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 52 |
labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
|
|
|
| 178 |
val_ds = FragranceTrajectoryDataset(records=val_records, use_embedding_fallback=True)
|
| 179 |
|
| 180 |
config = PIMTConfig(
|
| 181 |
+
embedding_dim=145,
|
| 182 |
state_dim=2,
|
| 183 |
hidden_dim=256,
|
| 184 |
num_heads=8,
|