Download code/src/lnpbench/cpp.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/src/lnpbench/cpp.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench@4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/src/lnpbench/cpp.py
-
curl -L -o cpp.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/src/lnpbench/cpp.py
11 kB
| """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 |