perf(embeddings): implement write-through SQLite cache for 3D shape features
Browse files- OlfactoryEmbeddingEngine now queries AromaRegistry first, computes missing 3D
features once, and writes them back to the SQLite DB permanently.
- Empty/placeholder SMILES short-circuit to zero fallback without invoking RDKit.
- Mute RDKit C++ logger to eliminate warning spam during training.
- src/pino/embeddings.py +71 -51
src/pino/embeddings.py
CHANGED
|
@@ -4,9 +4,10 @@ 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 |
from .thermo.geometry import extract_3d_shape_features
|
| 11 |
from .thermo.naturals import OPENPOM_DIM, SHAPE_DIM, resolve_natural_oil_vectors
|
| 12 |
|
|
@@ -15,31 +16,28 @@ logger = logging.getLogger("pino.embeddings")
|
|
| 15 |
STRUCTURAL_DIM = OPENPOM_DIM # 138
|
| 16 |
COMBINED_DIM = STRUCTURAL_DIM + SHAPE_DIM # 145
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
from .registry import AromaRegistry
|
| 22 |
-
|
| 23 |
-
return AromaRegistry()
|
| 24 |
|
| 25 |
|
| 26 |
class OlfactoryEmbeddingEngine:
|
| 27 |
"""
|
| 28 |
-
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 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,6 +46,15 @@ class OlfactoryEmbeddingEngine:
|
|
| 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)
|
|
@@ -57,44 +64,40 @@ class OlfactoryEmbeddingEngine:
|
|
| 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 |
-
|
| 61 |
-
bare_cas = cas
|
| 62 |
-
if cas and cas.startswith("NATURAL:"):
|
| 63 |
-
bare_cas = cas.split(":", 1)[1]
|
| 64 |
|
| 65 |
-
#
|
| 66 |
-
if
|
| 67 |
try:
|
| 68 |
-
|
| 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",
|
| 74 |
|
| 75 |
# Natural oils may be resolvable from a constituent blend even if no SMILES.
|
| 76 |
-
if
|
| 77 |
try:
|
| 78 |
-
|
| 79 |
-
|
| 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",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 93 |
fpgen = AllChem.GetMorganGenerator(radius=2, fpSize=128)
|
| 94 |
fp_bitvect = fpgen.GetFingerprint(mol)
|
| 95 |
fp_array = np.array(fp_bitvect, dtype=np.float32)
|
| 96 |
except AttributeError:
|
| 97 |
-
# Legacy fallback for older environments.
|
| 98 |
fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=128)
|
| 99 |
fp_array = np.array(fp, dtype=np.float32)
|
| 100 |
|
|
@@ -114,37 +117,54 @@ class OlfactoryEmbeddingEngine:
|
|
| 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 |
-
|
| 119 |
-
|
| 120 |
-
bare_cas = cas.split(":", 1)[1]
|
| 121 |
|
| 122 |
-
|
|
|
|
| 123 |
try:
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
| 128 |
except Exception as exc:
|
| 129 |
-
logger.debug("Registry lookup failed for %s: %s",
|
| 130 |
|
| 131 |
-
# Natural
|
| 132 |
-
if
|
| 133 |
try:
|
| 134 |
-
|
| 135 |
-
|
| 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",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 147 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
def _compute_real_openpom(self, smiles: str) -> np.ndarray:
|
| 150 |
raise NotImplementedError("Real OpenPOM model not yet loaded")
|
|
|
|
| 4 |
from typing import Any
|
| 5 |
|
| 6 |
import numpy as np
|
| 7 |
+
from rdkit import Chem, RDLogger
|
| 8 |
from rdkit.Chem import AllChem, Descriptors
|
| 9 |
|
| 10 |
+
from .registry import AromaRegistry
|
| 11 |
from .thermo.geometry import extract_3d_shape_features
|
| 12 |
from .thermo.naturals import OPENPOM_DIM, SHAPE_DIM, resolve_natural_oil_vectors
|
| 13 |
|
|
|
|
| 16 |
STRUCTURAL_DIM = OPENPOM_DIM # 138
|
| 17 |
COMBINED_DIM = STRUCTURAL_DIM + SHAPE_DIM # 145
|
| 18 |
|
| 19 |
+
# Mute RDKit's internal C++ warning streams globally.
|
| 20 |
+
rd_logger = RDLogger.logger()
|
| 21 |
+
rd_logger.setLevel(RDLogger.CRITICAL)
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
class OlfactoryEmbeddingEngine:
|
| 25 |
"""
|
| 26 |
+
Write-through cached embedding engine for 145-D olfactory molecule tokens.
|
| 27 |
|
| 28 |
+
Reads OpenPOM structural vectors and 3D shape features from the SQLite
|
| 29 |
+
AromaRegistry. If 3D features are missing and a valid SMILES is provided, it
|
| 30 |
+
computes them once, writes them back to the database permanently, and
|
| 31 |
+
returns them. Empty or invalid inputs short-circuit to a zero fallback
|
| 32 |
+
without invoking RDKit.
|
|
|
|
| 33 |
"""
|
| 34 |
|
| 35 |
+
def __init__(self, use_fallback: bool = True) -> None:
|
| 36 |
self.use_fallback = use_fallback
|
| 37 |
self.structural_dim = STRUCTURAL_DIM
|
| 38 |
self.shape_dim = SHAPE_DIM
|
| 39 |
self.embedding_dim = COMBINED_DIM
|
| 40 |
+
self.registry = AromaRegistry()
|
| 41 |
if not self.use_fallback:
|
| 42 |
self._initialize_real_openpom()
|
| 43 |
|
|
|
|
| 46 |
logger.warning("Real OpenPOM model not available; enabling fallback automatically")
|
| 47 |
self.use_fallback = True
|
| 48 |
|
| 49 |
+
def _normalized_cas(self, cas: str | None) -> str:
|
| 50 |
+
return str(cas).replace("NATURAL:", "").strip() if cas else ""
|
| 51 |
+
|
| 52 |
+
def _is_valid_smiles(self, smiles: str) -> bool:
|
| 53 |
+
if not smiles or not isinstance(smiles, str):
|
| 54 |
+
return False
|
| 55 |
+
s = smiles.strip()
|
| 56 |
+
return bool(s) and s != "None" and not s.startswith("SMILES:") and not s.startswith("NATURAL:")
|
| 57 |
+
|
| 58 |
def get_embedding(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 59 |
"""Main entry point. Returns a 145-dimensional float32 array."""
|
| 60 |
structural = self._compute_structural_embedding(smiles, cas)
|
|
|
|
| 64 |
return combined / norm if norm > 0 else combined
|
| 65 |
|
| 66 |
def _compute_structural_embedding(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 67 |
+
normalized_cas = self._normalized_cas(cas)
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
# 1. Query the live SQLite cache first.
|
| 70 |
+
if normalized_cas:
|
| 71 |
try:
|
| 72 |
+
record = self.registry.get(normalized_cas)
|
|
|
|
| 73 |
if record and record.get("openpom_embedding"):
|
| 74 |
return np.asarray(record["openpom_embedding"], dtype=np.float32)
|
| 75 |
except Exception as exc:
|
| 76 |
+
logger.debug("Registry lookup failed for %s: %s", normalized_cas, exc)
|
| 77 |
|
| 78 |
# Natural oils may be resolvable from a constituent blend even if no SMILES.
|
| 79 |
+
if normalized_cas and (normalized_cas.startswith("8") or normalized_cas.startswith("6") or normalized_cas.startswith("9")):
|
| 80 |
try:
|
| 81 |
+
all_records = self.registry.all_records()
|
| 82 |
+
openpom, _ = resolve_natural_oil_vectors(normalized_cas, all_records)
|
|
|
|
| 83 |
if any(openpom):
|
| 84 |
return np.asarray(openpom, dtype=np.float32)
|
| 85 |
except Exception as exc:
|
| 86 |
+
logger.debug("Natural oil resolution failed for %s: %s", normalized_cas, exc)
|
| 87 |
+
|
| 88 |
+
# 2. Fallback: compute a deterministic 128-bit Morgan + 10 physicochemical descriptors.
|
| 89 |
+
if not self._is_valid_smiles(smiles):
|
| 90 |
+
return np.zeros(self.structural_dim, dtype=np.float32)
|
| 91 |
|
| 92 |
mol = Chem.MolFromSmiles(smiles)
|
| 93 |
if not mol:
|
|
|
|
| 94 |
return np.zeros(self.structural_dim, dtype=np.float32)
|
| 95 |
|
| 96 |
try:
|
|
|
|
| 97 |
fpgen = AllChem.GetMorganGenerator(radius=2, fpSize=128)
|
| 98 |
fp_bitvect = fpgen.GetFingerprint(mol)
|
| 99 |
fp_array = np.array(fp_bitvect, dtype=np.float32)
|
| 100 |
except AttributeError:
|
|
|
|
| 101 |
fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=128)
|
| 102 |
fp_array = np.array(fp, dtype=np.float32)
|
| 103 |
|
|
|
|
| 117 |
return np.concatenate([fp_array, physchem]).astype(np.float32)
|
| 118 |
|
| 119 |
def _compute_shape_features(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 120 |
+
"""Fetch cached 3D shape features or compute them on the fly and write through."""
|
| 121 |
+
normalized_cas = self._normalized_cas(cas)
|
| 122 |
+
zero_shape = np.zeros(self.shape_dim, dtype=np.float32)
|
|
|
|
| 123 |
|
| 124 |
+
# 1. Query the live SQLite cache.
|
| 125 |
+
if normalized_cas:
|
| 126 |
try:
|
| 127 |
+
record = self.registry.get(normalized_cas)
|
| 128 |
+
if record:
|
| 129 |
+
shape_3d = record.get("shape_3d_features")
|
| 130 |
+
if shape_3d and any(v != 0.0 for v in shape_3d):
|
| 131 |
+
return np.asarray(shape_3d, dtype=np.float32)
|
| 132 |
except Exception as exc:
|
| 133 |
+
logger.debug("Registry lookup failed for %s: %s", normalized_cas, exc)
|
| 134 |
|
| 135 |
+
# Natural oils may be resolvable from a constituent blend.
|
| 136 |
+
if normalized_cas and (normalized_cas.startswith("8") or normalized_cas.startswith("6") or normalized_cas.startswith("9")):
|
| 137 |
try:
|
| 138 |
+
all_records = self.registry.all_records()
|
| 139 |
+
_, shape = resolve_natural_oil_vectors(normalized_cas, all_records)
|
|
|
|
| 140 |
if any(shape):
|
| 141 |
return np.asarray(shape, dtype=np.float32)
|
| 142 |
except Exception as exc:
|
| 143 |
+
logger.debug("Natural oil shape resolution failed for %s: %s", normalized_cas, exc)
|
| 144 |
+
|
| 145 |
+
# 2. String guardrail: invalid/empty SMILES short-circuit to zero fallback.
|
| 146 |
+
if not self._is_valid_smiles(smiles):
|
| 147 |
+
return zero_shape
|
| 148 |
|
| 149 |
+
# 3. Just-In-Time compute 3D features exactly once.
|
| 150 |
try:
|
| 151 |
features = extract_3d_shape_features(smiles)
|
|
|
|
| 152 |
except Exception as exc:
|
| 153 |
+
logger.debug("3D shape feature extraction failed for %s: %s", smiles, exc)
|
| 154 |
+
return zero_shape
|
| 155 |
+
|
| 156 |
+
shape_3d_vec = list(features)
|
| 157 |
+
if any(v != 0.0 for v in shape_3d_vec):
|
| 158 |
+
# 4. Write through to the persistent SQLite cache.
|
| 159 |
+
if normalized_cas:
|
| 160 |
+
try:
|
| 161 |
+
record = self.registry.get(normalized_cas) or {"cas": normalized_cas}
|
| 162 |
+
record["shape_3d_features"] = shape_3d_vec
|
| 163 |
+
self.registry.add(record)
|
| 164 |
+
except Exception as exc:
|
| 165 |
+
logger.debug("Failed to persist 3D features for %s: %s", normalized_cas, exc)
|
| 166 |
+
|
| 167 |
+
return np.asarray(shape_3d_vec, dtype=np.float32)
|
| 168 |
|
| 169 |
def _compute_real_openpom(self, smiles: str) -> np.ndarray:
|
| 170 |
raise NotImplementedError("Real OpenPOM model not yet loaded")
|