File size: 11,018 Bytes
d1988f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | """Conformer-based critical packing parameter (cCPP) surrogate.
LNPDB (Nature Communications 2026, Eqs. 1-7) defines the critical packing
parameter of an ionizable lipid from an all-atom MD bilayer
CPP_V = V / (a0 * lc), V = (1/3) pi lc (rh^2 + rh rt + rt^2), a0 = pi rh^2
CPP_Rg = Rg_tail / Rg_head
with ``rh`` the head-group radius, ``rt`` the radius of the *terminal* tail
atoms, and ``lc`` the head-tail centre-of-mass distance. A 1.5 us bilayer
costs 4.1-4.7 GPU-days, which is why LNPDB only reports CPP for 54 systems.
``cCPP`` evaluates the *same geometric construction* on a single ETKDGv3 +
MMFF94 conformer (milliseconds), which makes the physics available for all
12,845 ionizable lipids. Absolute values are not on the MD scale (a gas-phase
conformer is more extended than a lipid embedded in a bilayer); the descriptors
are therefore used after per-dataset standardisation, and their functional
validity is established empirically against the 34 stable LM_2019 bilayers
(see ``scripts/validate_ccpp.py``).
Region assignment
-----------------
1. Amine nitrogens (N with degree <= 3, not amide/sulfonamide) seed the head.
2. If LNPDB's parsed head SMILES is a valid substructure of the lipid, its
atoms are added to the seeds (94% match rate when present).
3. Head = atoms within ``head_radius`` bonds of a seed; tail = complement.
4. ``rt`` uses the distal ``terminal_frac`` of tail atoms, mirroring the
paper's "terminal tail atoms".
"""
from __future__ import annotations
import math
import zlib
from typing import Dict, List, Sequence, Tuple
import numpy as np
from rdkit import Chem, RDLogger
from rdkit.Chem import AllChem, Crippen, Descriptors, Descriptors3D, rdMolDescriptors
RDLogger.DisableLog("rdApp.*")
CPP_DIM = 16
_CPP_NAMES = [
"ccpp_v_neutral",
"ccpp_rg_neutral",
"ccpp_v_prot",
"ccpp_rg_prot",
"d_ccpp_v",
"d_ccpp_rg",
"asphericity",
"pmi1",
"inertial_shape",
"logp",
"tpsa_scaled",
"mw_scaled",
"rot_scaled",
"n_scaled",
"tail_carbons_scaled",
"frac_csp3",
]
def cpp_feature_names() -> List[str]:
return list(_CPP_NAMES)
# ---------------------------------------------------------------------------
# Region assignment
# ---------------------------------------------------------------------------
def _amide_like_nitrogen(mol: Chem.Mol, idx: int) -> bool:
for nb in mol.GetAtomWithIdx(idx).GetNeighbors():
if nb.GetSymbol() != "C":
continue
for bond in nb.GetBonds():
other = bond.GetOtherAtom(nb)
if other.GetIdx() == idx:
continue
if bond.GetBondType() == Chem.BondType.DOUBLE and other.GetSymbol() in {"O", "S"}:
return True
return False
def _amine_nitrogens(mol: Chem.Mol) -> List[int]:
out = []
for atom in mol.GetAtoms():
if atom.GetSymbol() != "N" or atom.GetDegree() > 3:
continue
if not _amide_like_nitrogen(mol, atom.GetIdx()):
out.append(atom.GetIdx())
return out
def _bfs_within(mol: Chem.Mol, seed: Sequence[int], radius: int) -> set[int]:
dist = {i: 0 for i in seed}
frontier = list(seed)
for _ in range(radius):
nxt = []
for i in frontier:
for nb in mol.GetAtomWithIdx(i).GetNeighbors():
j = nb.GetIdx()
if j not in dist:
dist[j] = dist[i] + 1
nxt.append(j)
frontier = nxt
if not frontier:
break
return set(dist)
def assign_regions(
mol: Chem.Mol, head_smiles: str | None = None, head_radius: int = 2
) -> Tuple[List[int], List[int]]:
"""Return (head_atom_indices, tail_atom_indices) over heavy atoms."""
seeds = _amine_nitrogens(mol)
if head_smiles:
frag = Chem.MolFromSmiles(head_smiles)
if frag is not None:
match = mol.GetSubstructMatch(frag)
if match:
seeds = sorted(set(seeds) | set(match))
if not seeds:
seeds = [0]
n = mol.GetNumAtoms()
head = _bfs_within(mol, seeds, head_radius)
tail = set(range(n)) - head
if len(tail) < 3:
head = _bfs_within(mol, seeds, 1)
tail = set(range(n)) - head
if len(tail) < 3:
head, tail = set(seeds), set(range(n)) - set(seeds)
return sorted(head), sorted(tail)
# ---------------------------------------------------------------------------
# Geometry
# ---------------------------------------------------------------------------
def _align_to_z(coords: np.ndarray, masses: np.ndarray, head: Sequence[int], tail: Sequence[int]):
def com(idx):
m = masses[list(idx)][:, None]
return (coords[list(idx)] * m).sum(axis=0) / (m.sum() + 1e-8)
r_head, r_tail = com(head), com(tail)
mid = 0.5 * (r_head + r_tail)
centered = coords - mid
v = r_head - r_tail
norm = np.linalg.norm(v)
if norm > 1e-8:
v = v / norm
z = np.array([0.0, 0.0, 1.0])
axis = np.cross(v, z)
if np.linalg.norm(axis) > 1e-8:
axis = axis / np.linalg.norm(axis)
angle = math.acos(float(np.clip(np.dot(v, z), -1.0, 1.0)))
K = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]])
R = np.eye(3) + math.sin(angle) * K + (1 - math.cos(angle)) * (K @ K)
centered = centered @ R.T
return centered, r_head - mid, r_tail - mid
def _rg(coords_xy: np.ndarray, masses: np.ndarray) -> float:
if len(coords_xy) == 0:
return 1e-3
return max(
math.sqrt(float((masses * (coords_xy ** 2).sum(axis=1)).sum() / (masses.sum() + 1e-8))), 1e-3
)
def _radius(coords_xy: np.ndarray) -> float:
if len(coords_xy) < 2:
return 0.5
d = np.linalg.norm(coords_xy[:, None, :] - coords_xy[None, :, :], axis=-1)
return max(0.5 * float(d.max()), 1e-3)
class _ConformerTimeout(Exception):
pass
def _alarm_handler(signum, frame): # pragma: no cover - signal path
raise _ConformerTimeout()
try:
import signal as _signal
_signal.signal(_signal.SIGALRM, _alarm_handler)
except Exception: # pragma: no cover - non-POSIX
_signal = None
def _deadline(seconds: float | None) -> None:
"""Bound the wall-clock time of a single conformer generation call."""
if _signal is None:
return
_signal.setitimer(_signal.ITIMER_REAL, 0.0 if seconds is None else float(seconds))
def _embed(smiles: str) -> Chem.Mol | None:
"""Embed a heavy-atom-only 3D conformer.
Hydrogens carry <1/6 of the molecular mass and contribute little to the
lateral radii, but they triple the number of embedding degrees of freedom.
Embedding heavy atoms only is ~15x faster and leaves the cCPP ranking
essentially unchanged (validated in ``scripts/validate_ccpp.py``).
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
seed = zlib.crc32(smiles.encode()) % (2 ** 31 - 1)
_deadline(1.5)
try:
ok = AllChem.EmbedMolecule(
mol, maxAttempts=1, randomSeed=seed, useRandomCoords=False,
useSmallRingTorsions=True, enforceChirality=True,
)
if ok != 0:
ok = AllChem.EmbedMolecule(
mol, maxAttempts=2, randomSeed=seed, useRandomCoords=True,
useSmallRingTorsions=True, enforceChirality=True,
)
except _ConformerTimeout:
return None
finally:
_deadline(None)
if ok != 0:
return None
try:
AllChem.MMFFOptimizeMolecule(mol, maxIters=80)
except Exception:
try:
AllChem.UFFOptimizeMolecule(mol, maxIters=80)
except Exception:
pass
return mol
def cpp_from_mol(
mol: Chem.Mol, head_smiles: str | None = None, head_radius: int = 2, terminal_frac: float = 0.3
) -> Dict[str, float]:
coords = mol.GetConformer().GetPositions().astype(np.float64)
masses = np.asarray([a.GetMass() for a in mol.GetAtoms()], dtype=np.float64)
heavy = Chem.RemoveHs(mol)
head, tail = assign_regions(heavy, head_smiles, head_radius)
aligned, rh_com, rt_com = _align_to_z(coords, masses, head, tail)
rad_head = _radius(aligned[head, :2])
rg_head = _rg(aligned[head, :2], masses[head])
rg_tail = _rg(aligned[tail, :2], masses[tail])
k = max(2, int(round(len(tail) * terminal_frac)))
z = aligned[tail, 2]
distal = np.argsort(z)[-k:]
rad_tail = _radius(aligned[np.asarray(tail)[distal], :2])
lc = max(float(np.linalg.norm(rh_com - rt_com)), 1e-3)
ratio = rad_tail / rad_head
cpp_v = (1.0 + ratio + ratio ** 2) / 3.0
return {
"cppv": float(cpp_v),
"cpprg": float(rg_tail / (rg_head + 1e-6)),
"rad_head": float(rad_head),
"rad_tail": float(rad_tail),
"lc": lc,
"n_tail": float(len(tail)),
"n_head": float(len(head)),
}
def compute_cpp_features(
smiles: str | None,
smiles_prot: str | None,
head_smiles: str | None = None,
head_radius: int = 2,
) -> np.ndarray:
"""16-dim physics vector; robust to embedding failures (returns zeros)."""
out = np.zeros(CPP_DIM, dtype=np.float32)
if not smiles:
return out
base = Chem.MolFromSmiles(smiles)
if base is None:
return out
if isinstance(head_smiles, float) or not isinstance(head_smiles, str):
head_smiles = None
try:
mol_n = _embed(smiles)
if mol_n is not None:
f = cpp_from_mol(mol_n, head_smiles, head_radius)
out[0], out[1] = f["cppv"], f["cpprg"]
out[14] = min(f["n_tail"], 60.0) / 60.0
out[6] = Descriptors3D.Asphericity(mol_n)
out[7] = Descriptors3D.PMI1(mol_n)
out[8] = Descriptors3D.InertialShapeFactor(mol_n)
mol_p = _embed(smiles_prot) if smiles_prot else None
if mol_p is not None:
f = cpp_from_mol(mol_p, head_smiles, head_radius)
out[2], out[3] = f["cppv"], f["cpprg"]
out[4] = out[0] - out[2]
out[5] = out[1] - out[3]
out[9] = Crippen.MolLogP(base)
out[10] = rdMolDescriptors.CalcTPSA(base) / 100.0
out[11] = Descriptors.MolWt(base) / 500.0
out[12] = rdMolDescriptors.CalcNumRotatableBonds(base) / 10.0
out[13] = sum(1 for a in base.GetAtoms() if a.GetSymbol() == "N") / 5.0
out[15] = rdMolDescriptors.CalcFractionCSP3(base)
except Exception:
pass
return np.nan_to_num(out, nan=0.0, posinf=0.0, neginf=0.0).astype(np.float32)
def mixture_cpp(ccpp: np.ndarray, molar_fractions: np.ndarray, mask: np.ndarray) -> float:
"""PEG-excluded molar-fraction weighted cCPP of a formulation."""
w = np.asarray(molar_fractions, dtype=np.float64) * np.asarray(mask, dtype=np.float64)
v = np.asarray(ccpp, dtype=np.float64) * np.asarray(mask, dtype=np.float64)
denom = w.sum()
return float((w * v).sum() / denom) if denom > 0 else 0.0 |