LNPBench / code /src /lnpbench /ontology.py
eduzrh's picture
LNPBench: code, caches, results and figures
dedf737 verified
Raw History Blame Contribute Delete
20.5 kB
"""Ontology / schema features for LNP formulations.
Motivation
----------
The 217 RDKit descriptors used elsewhere in this package describe the ionisable
lipid *as a whole*. They cannot say what role a functional group plays in the
lipid architecture: an ester in the linker and an ester at the end of a tail
both count as one ``fr_ester``. The schema layer below adds exactly that
missing information. Every substructure is assigned to a slot of the
formulation grammar
ionisable lipid := head + linker + tail x k
formulation := ionisable lipid + helper lipid
+ cholesterol + PEG lipid
and each slot is described by a small, fixed ontology of chemical classes.
On top of the slot ontologies we compute **cross-slot ratios** (charge per tail
carbon, ester density, hydrophilic/lipophilic balance, charge complementarity
between the ionisable lipid and the helper lipid, ...). These are quantities a
chemist reasons with and that no single-molecule descriptor vector contains.
Everything here is derived from structure only. No study label, no lipid
identifier and no fingerprint enters the block, so in principle it cannot act
as the study-identity shortcut documented in ``results/REPORT.md`` section 4.
That claim is not taken on faith: ``scripts/schema_audit.py`` measures how well
each candidate block predicts the study of origin, and the external-transfer
experiments report what the block is actually worth.
"""
from __future__ import annotations
from functools import lru_cache
from typing import Dict, List
import numpy as np
from rdkit import Chem, RDLogger
RDLogger.DisableLog("rdApp.*")
# ---------------------------------------------------------------------------
# SMARTS tables
# ---------------------------------------------------------------------------
# Functional groups that matter for lipid architecture. Deliberately small:
# the 217 RDKit descriptors already carry whole-molecule counts, so the point
# of this table is to be re-usable *per slot*, not to be exhaustive.
GROUP_SMARTS: Dict[str, str] = {
"amine_prim": "[NX3;H2;!$(N-C=O);!$(N-S=O);!$(N-N)]",
"amine_sec": "[NX3;H1;!$(N-C=O);!$(N-S=O);!$(N-N)]",
"amine_tert": "[NX3;H0;!$(N-C=O);!$(N-S=O);!$(N=*);!$(N#*);!$(N-N)]",
"quat_n": "[NX4+]",
"arom_n": "[n]",
"amide": "[NX3][CX3](=[OX1])",
"ester": "[#6][CX3](=[OX1])[OX2][#6]",
"carboxyl": "[CX3](=[OX1])[OX2H1]",
"carbonate": "[OX2][CX3](=[OX1])[OX2][#6]",
"carbamate": "[NX3][CX3](=[OX1])[OX2][#6]",
"ether": "[OD2]([#6])[#6]",
"hydroxyl": "[OX2H]",
"ketone": "[#6][CX3](=[OX1])[#6]",
"thioether": "[#16X2H0]([#6])[#6]",
"disulfide": "[#16X2H0][#16X2H0]",
"alkene": "[CX3]=[CX3]",
"alkyne": "[CX2]#[CX2]",
"epoxide": "[OX2r3]",
"phosphate": "[PX4](=[OX1])([OX1])[OX1]",
}
GROUP_NAMES: List[str] = list(GROUP_SMARTS)
# ring environments of a nitrogen -- these distinguish piperidine from
# piperazine from morpholine from an acyclic amine at a glance
RING_SMARTS: Dict[str, str] = {
"n6ring": "[NX3;R1]1[#6][#6][#6][#6][#6]1",
"n5ring": "[NX3;R1]1[#6][#6][#6][#6]1",
"n7ring": "[NX3;R1]1[#6][#6][#6][#6][#6][#6]1",
"morpholine": "[NX3;R1]1[#6][#6][OX2][#6][#6]1",
"piperazine": "[NX3;R1]1[#6][#6][NX3][#6][#6]1",
"imidazole": "c1cncn1",
"pyridine": "c1ccccn1",
"pyrrolidine": "[NX3;R1]1[#6][#6][#6][#6]1",
}
RING_NAMES: List[str] = list(RING_SMARTS)
# head-group ontology: one class per lipid, in priority order
HEAD_CLASSES = [
"none", # no nitrogen at all
"primary_amine",
"secondary_acyclic",
"secondary_ring",
"tertiary_acyclic",
"tertiary_ring",
"quaternary",
"aromatic_n",
"polyamine", # >= 2 nitrogen atoms, not fitting the above cleanly
]
# tail ontology: one class per tail slot
TAIL_CLASSES = [
"empty",
"saturated",
"monounsaturated",
"polyunsaturated",
"branched",
"ring_containing",
"heteroatom",
]
# helper-lipid ontology
HELPER_CLASSES = [
"none",
"phosphatidylcholine",
"phosphatidylethanolamine",
"phosphatidic_acid",
"cationic_lipid",
"neutral_dialkyl",
"sterol",
"peg_lipid",
"other",
]
@lru_cache(maxsize=1)
def _group_patterns():
return {k: Chem.MolFromSmarts(v) for k, v in GROUP_SMARTS.items()}
@lru_cache(maxsize=1)
def _ring_patterns():
return {k: Chem.MolFromSmarts(v) for k, v in RING_SMARTS.items()}
def _n_matches(mol, patt) -> int:
if patt is None or mol is None:
return 0
return len(mol.GetSubstructMatches(patt, uniquify=True))
def _group_counts(mol) -> np.ndarray:
pats = _group_patterns()
return np.asarray([_n_matches(mol, pats[k]) for k in GROUP_NAMES], dtype=np.float32)
def _ring_counts(mol) -> np.ndarray:
pats = _ring_patterns()
return np.asarray([_n_matches(mol, pats[k]) for k in RING_NAMES], dtype=np.float32)
def _chain_stats(mol) -> np.ndarray:
"""Carbon-chain topology: terminal carbons, branch points, longest chain."""
if mol is None or mol.GetNumAtoms() == 0:
return np.zeros(5, dtype=np.float32)
carbons = [a for a in mol.GetAtoms() if a.GetSymbol() == "C"]
n_c = len(carbons)
if n_c == 0:
return np.zeros(5, dtype=np.float32)
terminal = sum(1 for a in carbons if a.GetDegree() == 1)
branch = sum(1 for a in carbons if sum(1 for nb in a.GetNeighbors() if nb.GetSymbol() == "C") >= 3)
# longest carbon-only path, computed by BFS over the carbon subgraph
idx = {a.GetIdx(): i for i, a in enumerate(carbons)}
adj = {i: [] for i in range(n_c)}
for a in carbons:
i = idx[a.GetIdx()]
for nb in a.GetNeighbors():
if nb.GetSymbol() == "C":
adj[i].append(idx[nb.GetIdx()])
longest = 0
for start in range(n_c):
if len(adj[start]) > 2:
continue # only start from path ends/branch tips
seen = {start: 0}
stack = [start]
while stack:
u = stack.pop()
for v in adj[u]:
if v not in seen:
seen[v] = seen[u] + 1
stack.append(v)
if seen:
longest = max(longest, max(seen.values()) + 1)
return np.asarray([terminal, branch, longest, n_c, terminal / max(n_c, 1)], dtype=np.float32)# ---------------------------------------------------------------------------
# Slot ontologies
# ---------------------------------------------------------------------------
def _one_hot(i: int, n: int) -> np.ndarray:
v = np.zeros(n, dtype=np.float32)
if 0 <= i < n:
v[i] = 1.0
return v
HEAD_PREFIX_DIM = 12 # amine type (6) + type fractions (5) + multi-amine (1)
HEAD_TYPES = ["primary", "secondary", "tertiary", "quaternary", "aromatic", "none"]
def head_vector(smiles: str) -> np.ndarray:
"""Ontology vector for a head-group fragment.
The first release of this function assigned each head a single class in a
priority chain that put every poly-amine into one bucket; 79 % of LNPDB
formulations landed there, so the categorical part carried almost no
information. The encoding below replaces the chain with the *composition*
of the amine population: which type dominates, what the fractions are, and
whether more than one ionisable nitrogen is present.
"""
mol = Chem.MolFromSmiles(smiles) if isinstance(smiles, str) else None
g = _group_counts(mol) if mol is not None else np.zeros(len(GROUP_NAMES), dtype=np.float32)
r = _ring_counts(mol) if mol is not None else np.zeros(len(RING_NAMES), dtype=np.float32)
gd = dict(zip(GROUP_NAMES, g))
counts = np.asarray(
[gd["amine_prim"], gd["amine_sec"], gd["amine_tert"], gd["quat_n"], gd["arom_n"]],
dtype=np.float32,
)
n_n = float(counts.sum())
n_ionisable = float(counts[:4].sum())
if n_n > 0:
dom = int(np.argmax(counts))
frac = counts / n_n
else:
dom = 5
frac = np.zeros(5, dtype=np.float32)
multi = float((counts >= 1).sum() >= 2)
chem = np.asarray([
n_n, n_ionisable, gd["hydroxyl"], gd["ether"], gd["amide"],
gd["carboxyl"], gd["ester"], gd["ketone"], gd["alkene"], gd["alkyne"],
gd["quat_n"], gd["arom_n"],
], dtype=np.float32)
heavy = mol.GetNumHeavyAtoms() if mol is not None else 0
dens = np.asarray([n_ionisable / max(heavy, 1), gd["hydroxyl"] / max(heavy, 1)], dtype=np.float32)
return np.concatenate([_one_hot(dom, 6), frac, np.asarray([multi], dtype=np.float32),
r, chem, dens])
def linker_vector(smiles: str) -> np.ndarray:
mol = Chem.MolFromSmiles(smiles) if isinstance(smiles, str) else None
g = _group_counts(mol) if mol is not None else np.zeros(len(GROUP_NAMES), dtype=np.float32)
r = _ring_counts(mol) if mol is not None else np.zeros(len(RING_NAMES), dtype=np.float32)
gd = dict(zip(GROUP_NAMES, g))
# which of the three degradable linker chemistries is present
kind = np.asarray([
gd["ester"] >= 1, gd["ester"] >= 2, gd["amide"] >= 1,
gd["carbonate"] >= 1, gd["carbamate"] >= 1, gd["ether"] >= 1,
gd["disulfide"] >= 1, gd["ketone"] >= 1, gd["alkene"] >= 1,
float(np.sum(r) > 0),
], dtype=np.float32)
return np.concatenate([kind, g / 4.0, r])
def tail_vector(smiles: str) -> np.ndarray:
mol = Chem.MolFromSmiles(smiles) if isinstance(smiles, str) else None
if mol is None or mol.GetNumHeavyAtoms() == 0:
return np.zeros(len(TAIL_CLASSES) + 6, dtype=np.float32)
g = _group_counts(mol)
gd = dict(zip(GROUP_NAMES, g))
chain = _chain_stats(mol)
n_db = gd["alkene"] + gd["alkyne"]
hetero = gd["hydroxyl"] + gd["carboxyl"] + gd["ester"] + gd["ether"] + gd["amide"]
rings = float(Chem.GetSSSR(mol)[0] if False else mol.GetRingInfo().NumRings())
if hetero >= 1:
cls = 6
elif rings >= 1:
cls = 5
elif chain[1] >= 1:
cls = 4
elif n_db >= 2:
cls = 3
elif n_db == 1:
cls = 2
else:
cls = 1
extra = np.asarray([n_db, hetero, rings, chain[2], chain[0], chain[1]], dtype=np.float32)
return np.concatenate([_one_hot(cls, len(TAIL_CLASSES)), extra])
def helper_vector(smiles: str, slot: str) -> np.ndarray:
mol = Chem.MolFromSmiles(smiles) if isinstance(smiles, str) else None
if mol is None:
return np.zeros(len(HELPER_CLASSES) + 8, dtype=np.float32)
g = _group_counts(mol)
gd = dict(zip(GROUP_NAMES, g))
rings = mol.GetRingInfo().NumRings()
n_n = gd["amine_prim"] + gd["amine_sec"] + gd["amine_tert"] + gd["quat_n"] + gd["arom_n"]
if slot == "CHL":
cls = 6
elif slot == "PEG":
cls = 7
elif gd["phosphate"] >= 1 and gd["quat_n"] >= 1:
cls = 1
elif gd["phosphate"] >= 1 and gd["amine_prim"] >= 1:
cls = 2
elif gd["phosphate"] >= 1:
cls = 3
elif gd["quat_n"] >= 1 or gd["amine_tert"] >= 1:
cls = 4
elif n_n == 0 and gd["ester"] >= 2:
cls = 5
else:
cls = 8
# PEG chain length: number of ethylene-oxide repeats
eo = _n_matches(mol, Chem.MolFromSmarts("[OX2][CH2][CH2][OX2]"))
chem = np.asarray([
gd["phosphate"], gd["quat_n"], n_n, gd["ester"], eo,
rings, gd["hydroxyl"], mol.GetNumHeavyAtoms() / 50.0,
], dtype=np.float32)
return np.concatenate([_one_hot(cls, len(HELPER_CLASSES)), chem])# ---------------------------------------------------------------------------
# Cached per-molecule tables
# ---------------------------------------------------------------------------
def _cached_table(store, key: str, smiles: List[str], builder) -> np.ndarray:
attr = f"_onto_{key}"
tab = getattr(store, attr, None)
if tab is None:
if len(smiles) == 0:
# slots tail3 / tail4 are empty in this database; keep the layout
tab = np.zeros((0, len(builder(""))), dtype=np.float32)
else:
tab = np.stack([builder(s) for s in smiles]).astype(np.float32)
setattr(store, attr, tab)
return tab
def _il_schema_table(store) -> np.ndarray:
def build(s: str) -> np.ndarray:
mol = Chem.MolFromSmiles(s) if isinstance(s, str) else None
if mol is None:
return np.zeros(len(GROUP_NAMES) + len(RING_NAMES) + 5, dtype=np.float32)
return np.concatenate([_group_counts(mol), _ring_counts(mol), _chain_stats(mol)])
return _cached_table(store, "il", store.il_smiles, build)
def _head_table(store) -> np.ndarray:
return _cached_table(store, "head", store.frag["head"]["smiles"], head_vector)
def _linker_table(store) -> np.ndarray:
return _cached_table(store, "linker", store.frag["linker"]["smiles"], linker_vector)
def _tail_table(store, slot: str) -> np.ndarray:
return _cached_table(store, f"tail_{slot}", store.frag[slot]["smiles"], tail_vector)
def _helper_table(store, slot: str) -> np.ndarray:
return _cached_table(store, f"hlp_{slot}", store.frag[slot]["smiles"],
lambda s, _slot=slot: helper_vector(s, _slot))
def _slot_lookup(tab: np.ndarray, ids: np.ndarray, dim: int) -> np.ndarray:
out = np.zeros((len(ids), dim), dtype=np.float32)
ok = ids >= 0
if ok.any() and len(tab):
out[ok] = tab[np.clip(ids[ok], 0, len(tab) - 1)]
return out
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def schema_block(store, idx: np.ndarray, parts: str = "all") -> np.ndarray:
"""Ontology / schema matrix for the given sample rows.
``parts`` selects a subset so that ablations can attribute the effect:
* ``"il"`` whole-molecule functional-group ontology
* ``"slots"`` per-slot ontologies (head / linker / tails / helpers)
* ``"cross"`` cross-slot dimensionless ratios
* ``"all"`` everything (default)
"""
idx = np.asarray(idx)
n = len(idx)
il = store.il_id[idx]
blocks: List[np.ndarray] = []
il_tab = _il_schema_table(store)
il_feat = il_tab[il]
head_tab = _head_table(store)
head_dim = head_tab.shape[1]
head_ids = store.frag_ids[idx, 0]
head_feat = _slot_lookup(head_tab, head_ids, head_dim)
linker_tab = _linker_table(store)
linker_dim = linker_tab.shape[1]
linker_feat = _slot_lookup(linker_tab, store.frag_ids[idx, 1], linker_dim)
tail_slots = ["tail1", "tail2", "tail3", "tail4"]
tail_feats = []
for k, slot in enumerate(tail_slots, start=2):
tab = _tail_table(store, slot)
tab_dim = tab.shape[1]
tail_feats.append(_slot_lookup(tab, store.frag_ids[idx, k], tab_dim))
helper_feats = []
for k, slot in enumerate(["HL", "CHL", "PEG"]):
tab = _helper_table(store, slot)
tab_dim = tab.shape[1]
helper_feats.append(_slot_lookup(tab, store.helper_ids[idx, k], tab_dim))
if parts in ("il", "all"):
blocks.append(il_feat)
if parts in ("slots", "all"):
blocks.extend([head_feat, linker_feat] + tail_feats + helper_feats)
if parts in ("cross", "all"):
blocks.append(_cross_slot(store, idx, il_feat, head_feat, tail_feats,
helper_feats, il, n))
X = np.concatenate(blocks, axis=1) if blocks else np.zeros((n, 0), dtype=np.float32)
X = np.nan_to_num(X, nan=0.0, posinf=0.0, neginf=0.0)
return np.clip(X, -1e4, 1e4).astype(np.float64)
def _cross_slot(store, idx, il_feat, head_feat, tail_feats, helper_feats, il, n) -> np.ndarray:
"""Dimensionless ratios a chemist reasons with, which no single-molecule
descriptor vector contains (charge per tail carbon, ester density, charge
complementarity between the ionisable lipid and the helper, ...)."""
gi = {k: i for i, k in enumerate(GROUP_NAMES)}
n_ion = il_feat[:, [gi["amine_prim"], gi["amine_sec"], gi["amine_tert"], gi["quat_n"]]].sum(1)
n_ester = il_feat[:, gi["ester"]]
n_oh = il_feat[:, gi["hydroxyl"]]
n_ether = il_feat[:, gi["ether"]]
# chain stats sit after groups + rings in the il table
off = len(GROUP_NAMES) + len(RING_NAMES)
tail_c = il_feat[:, off + 3] # total carbon count
longest = il_feat[:, off + 2]
# tail vector layout: |TAIL_CLASSES| one-hot then
# [n_db, hetero, rings, longest, terminal, branch]
n_tails = np.zeros(n, dtype=np.float32)
tail_longest = np.zeros(n, dtype=np.float32)
for tf in tail_feats:
tail_longest = np.maximum(tail_longest, tf[:, len(TAIL_CLASSES) + 3])
n_tails += (tf.sum(1) > 0).astype(np.float32)
tail_carbons = np.where(tail_c > 0, tail_c, tail_longest)
# head layout: |type 6| + |fractions 5| + |multi 1| + |rings| + |chem| + |dens 2|
head_oh = head_feat[:, HEAD_PREFIX_DIM + len(RING_NAMES) + 12 + 1]
head_n = head_feat[:, HEAD_PREFIX_DIM + len(RING_NAMES) + 0]
peg_eo = helper_feats[2][:, len(HELPER_CLASSES) + 4]
hl_has_p = helper_feats[0][:, len(HELPER_CLASSES) + 0]
hl_quat = helper_feats[0][:, len(HELPER_CLASSES) + 1]
chl_present = (store.helper_ids[idx, 1] >= 0).astype(np.float32)
peg_present = (store.helper_ids[idx, 2] >= 0).astype(np.float32)
r = store.ratios[idx]
w_il, w_hl, w_chl, w_peg = r[:, 0], r[:, 1], r[:, 2], r[:, 3]
tpsa = store.il_desc[il, store.il_desc_names.index("TPSA")]
logp = store.il_desc[il, store.il_desc_names.index("MolLogP")]
mw = store.il_desc[il, store.il_desc_names.index("MolWt")]
feats = np.stack([
n_ion / (tail_carbons + 1.0), # charge per tail carbon
n_ester / (tail_carbons + 1.0), # ester density along the tails
n_ether / (tail_carbons + 1.0),
n_oh / (head_n + 1.0), # hydroxyls per head nitrogen
(head_oh + n_oh) / (tpsa / 30.0 + 1.0), # polar decoration per unit TPSA
tpsa / (np.abs(logp) + 1.0), # hydrophilic/lipophilic balance
tpsa / (mw / 100.0 + 1.0),
tail_carbons / (mw / 100.0 + 1.0),
longest / (tail_carbons + 1.0), # how much of the lipid is one chain
n_tails,
n_ion * chl_present, # charge delivered against a sterol
n_ion * w_chl,
peg_eo * w_peg * 100.0, # PEG surface coverage
peg_eo * chl_present,
hl_has_p * n_ion, # charge complementarity IL<->helper
hl_quat * n_ion,
w_il - w_hl, # envelope composition contrast
w_chl / (w_il + w_hl + 1e-3),
w_peg / (w_chl + 1e-3),
w_il * n_ion,
], axis=1).astype(np.float32)
return feats
SCHEMA_DIM_HINT = {
"il": len(GROUP_NAMES) + len(RING_NAMES) + 5,
}
# width used when the per-slot ontology vectors are packed into a single node
# tensor (the widest slot vector is the linker at 37)
ONTO_DIM = 48
N_ONTO_NODES = 10
def _assign_onto(out: np.ndarray, slot: int, tab: np.ndarray, ids: np.ndarray) -> None:
if len(tab) == 0:
return
d = min(tab.shape[1], ONTO_DIM)
ok = ids >= 0
if not ok.any():
return
vals = tab[np.clip(ids, 0, len(tab) - 1)]
out[ok, slot, :d] = vals[ok, :d]
def node_onto(store, idx: np.ndarray) -> np.ndarray:
"""(N, 10, ONTO_DIM) ontology attributes of the formulation-set nodes.
Node order matches ``models.set_base.N_NODES``: head, linker, tail1..4,
whole ionisable lipid, helper, cholesterol, PEG. Slots that do not exist
in a formulation stay at zero and are removed by the attention mask.
"""
idx = np.asarray(idx)
n = len(idx)
out = np.zeros((n, N_ONTO_NODES, ONTO_DIM), dtype=np.float32)
_assign_onto(out, 0, _head_table(store), store.frag_ids[idx, 0])
_assign_onto(out, 1, _linker_table(store), store.frag_ids[idx, 1])
for k, slot in enumerate(["tail1", "tail2", "tail3", "tail4"], start=2):
_assign_onto(out, k, _tail_table(store, slot), store.frag_ids[idx, k])
il_tab = _il_schema_table(store)
d = min(il_tab.shape[1], ONTO_DIM)
out[:, 6, :d] = il_tab[store.il_id[idx]][:, :d]
for k, slot in enumerate(["HL", "CHL", "PEG"], start=7):
_assign_onto(out, k, _helper_table(store, slot), store.helper_ids[idx, k - 7])
out = np.nan_to_num(out, nan=0.0, posinf=0.0, neginf=0.0)
return np.clip(out, -1e4, 1e4).astype(np.float32)