Download code/src/lnpbench/featurize.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 8.05 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/src/lnpbench/featurize.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/src/lnpbench/featurize.py
-
curl -L -o featurize.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/src/lnpbench/featurize.py
8.05 kB
| """Molecular featurisation: fingerprints, RDKit descriptors, graphs, SMILES tokens. | |
| All featurisers are deterministic so that the cached tensors fully determine the | |
| numerical results of every experiment in the paper. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from typing import Dict, Iterable, List, Sequence, Tuple | |
| import numpy as np | |
| from rdkit import Chem, RDLogger | |
| from rdkit.Chem import Descriptors, rdFingerprintGenerator, rdMolDescriptors | |
| RDLogger.DisableLog("rdApp.*") | |
| MORGAN_BITS = 2048 | |
| MORGAN_RADIUS = 2 | |
| _MORGAN = rdFingerprintGenerator.GetMorganGenerator(radius=MORGAN_RADIUS, fpSize=MORGAN_BITS) | |
| # --------------------------------------------------------------------------- | |
| # Fingerprints and descriptors | |
| # --------------------------------------------------------------------------- | |
| def morgan_fp(smiles: str | None, n_bits: int = MORGAN_BITS) -> np.ndarray: | |
| out = np.zeros(n_bits, dtype=np.uint8) | |
| if not smiles: | |
| return out | |
| mol = Chem.MolFromSmiles(smiles) | |
| if mol is None: | |
| return out | |
| gen = _MORGAN if n_bits == MORGAN_BITS else rdFingerprintGenerator.GetMorganGenerator(radius=MORGAN_RADIUS, fpSize=n_bits) | |
| fp = gen.GetCountFingerprintAsNumPy(mol) | |
| out[:] = (fp > 0).astype(np.uint8) | |
| return out | |
| def maccs_keys(smiles: str | None) -> np.ndarray: | |
| out = np.zeros(167, dtype=np.uint8) | |
| if not smiles: | |
| return out | |
| mol = Chem.MolFromSmiles(smiles) | |
| if mol is None: | |
| return out | |
| from rdkit.Chem import MACCSkeys | |
| out[:] = np.asarray(MACCSkeys.GenMACCSKeys(mol), dtype=np.uint8) | |
| return out | |
| _DESC_NAMES: List[str] | None = None | |
| def descriptor_names() -> List[str]: | |
| global _DESC_NAMES | |
| if _DESC_NAMES is None: | |
| _DESC_NAMES = [name for name, _ in Descriptors._descList] | |
| return _DESC_NAMES | |
| def rdkit_descriptors(smiles: str | None) -> np.ndarray: | |
| """~210 RDKit 2D descriptors, NaN/inf replaced by 0.""" | |
| dim = len(descriptor_names()) | |
| out = np.zeros(dim, dtype=np.float32) | |
| if not smiles: | |
| return out | |
| mol = Chem.MolFromSmiles(smiles) | |
| if mol is None: | |
| return out | |
| for i, (_, fn) in enumerate(Descriptors._descList): | |
| try: | |
| v = fn(mol) | |
| if v is None: | |
| continue | |
| v = float(v) | |
| if np.isfinite(v): | |
| out[i] = v | |
| except Exception: | |
| continue | |
| return out | |
| def fragment_physchem(smiles: str | None) -> np.ndarray: | |
| """Compact, interpretable fragment-level descriptors (12 dims).""" | |
| out = np.zeros(12, dtype=np.float32) | |
| if not smiles: | |
| return out | |
| mol = Chem.MolFromSmiles(smiles) | |
| if mol is None: | |
| return out | |
| try: | |
| out[0] = Descriptors.MolWt(mol) / 500.0 | |
| out[1] = Descriptors.MolLogP(mol) / 5.0 | |
| out[2] = rdMolDescriptors.CalcTPSA(mol) / 100.0 | |
| out[3] = rdMolDescriptors.CalcNumHBD(mol) / 5.0 | |
| out[4] = rdMolDescriptors.CalcNumHBA(mol) / 10.0 | |
| out[5] = rdMolDescriptors.CalcNumRotatableBonds(mol) / 10.0 | |
| out[6] = rdMolDescriptors.CalcNumRings(mol) / 5.0 | |
| out[7] = rdMolDescriptors.CalcNumAromaticRings(mol) / 5.0 | |
| out[8] = sum(1 for a in mol.GetAtoms() if a.GetSymbol() == "N") / 5.0 | |
| out[9] = sum(1 for a in mol.GetAtoms() if a.GetSymbol() == "O") / 10.0 | |
| out[10] = rdMolDescriptors.CalcFractionCSP3(mol) | |
| out[11] = min(mol.GetNumHeavyAtoms(), 100) / 100.0 | |
| except Exception: | |
| pass | |
| return out | |
| # --------------------------------------------------------------------------- | |
| # Molecular graphs | |
| # --------------------------------------------------------------------------- | |
| ELEMENTS = ["C", "N", "O", "S", "F", "Cl", "Br", "I", "P", "Si", "B", "Se"] | |
| _DEGREES = 6 | |
| _CHARGES = 5 # -2..+2 | |
| _HYDROGENS = 5 # 0..4 | |
| _HYBRID = ["S", "SP", "SP2", "SP3", "SP3D", "SP3D2", "OTHER"] | |
| _CHIRAL = 4 | |
| _BOND_TYPES = 4 | |
| _STEREO = 6 | |
| def _one_hot(value: int, size: int) -> List[float]: | |
| vec = [0.0] * size | |
| if 0 <= value < size: | |
| vec[value] = 1.0 | |
| return vec | |
| def atom_features(atom: Chem.Atom) -> List[float]: | |
| symbol = atom.GetSymbol() | |
| feats: List[float] = _one_hot(ELEMENTS.index(symbol) if symbol in ELEMENTS else len(ELEMENTS), len(ELEMENTS) + 1) | |
| feats += _one_hot(atom.GetDegree(), _DEGREES) | |
| feats += _one_hot(atom.GetFormalCharge() + 2, _CHARGES) | |
| feats += _one_hot(atom.GetTotalNumHs(), _HYDROGENS) | |
| hyb = str(atom.GetHybridization()).split(".")[-1] | |
| feats += _one_hot(_HYBRID.index(hyb) if hyb in _HYBRID else len(_HYBRID) - 1, len(_HYBRID)) | |
| feats.append(1.0 if atom.GetIsAromatic() else 0.0) | |
| feats.append(1.0 if atom.IsInRing() else 0.0) | |
| feats += _one_hot(int(atom.GetChiralTag()), _CHIRAL) | |
| feats.append(atom.GetMass() / 100.0) | |
| return feats | |
| def bond_features(bond: Chem.Bond) -> List[float]: | |
| bt = bond.GetBondType() | |
| idx = { | |
| Chem.BondType.SINGLE: 0, | |
| Chem.BondType.DOUBLE: 1, | |
| Chem.BondType.TRIPLE: 2, | |
| Chem.BondType.AROMATIC: 3, | |
| }.get(bt, 0) | |
| feats: List[float] = _one_hot(idx, _BOND_TYPES) | |
| feats.append(1.0 if bond.GetIsConjugated() else 0.0) | |
| feats.append(1.0 if bond.IsInRing() else 0.0) | |
| feats += _one_hot(int(bond.GetStereo()), _STEREO) | |
| return feats | |
| ATOM_DIM = len(atom_features(Chem.MolFromSmiles("CC").GetAtomWithIdx(0))) | |
| BOND_DIM = len(bond_features(Chem.MolFromSmiles("CC").GetBondWithIdx(0))) | |
| def mol_to_graph(smiles: str, add_hydrogen: bool = False) -> Dict[str, np.ndarray]: | |
| mol = Chem.MolFromSmiles(smiles) if smiles else None | |
| if mol is None: | |
| return { | |
| "x": np.zeros((1, ATOM_DIM), dtype=np.float32), | |
| "edge_index": np.zeros((2, 0), dtype=np.int64), | |
| "edge_attr": np.zeros((0, BOND_DIM), dtype=np.float32), | |
| } | |
| if add_hydrogen: | |
| mol = Chem.AddHs(mol) | |
| x = np.asarray([atom_features(a) for a in mol.GetAtoms()], dtype=np.float32) | |
| src, dst, attr = [], [], [] | |
| for bond in mol.GetBonds(): | |
| i, j = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx() | |
| bf = bond_features(bond) | |
| src += [i, j] | |
| dst += [j, i] | |
| attr += [bf, bf] | |
| edge_index = np.asarray([src, dst], dtype=np.int64) if src else np.zeros((2, 0), dtype=np.int64) | |
| edge_attr = np.asarray(attr, dtype=np.float32) if attr else np.zeros((0, BOND_DIM), dtype=np.float32) | |
| return {"x": x, "edge_index": edge_index, "edge_attr": edge_attr} | |
| # --------------------------------------------------------------------------- | |
| # SMILES tokenisation (character level, carbon-chain preserving) | |
| # --------------------------------------------------------------------------- | |
| _SMILES_PATTERN = re.compile( | |
| r"(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>|\*|\$|%[0-9]{2}|[0-9])" | |
| ) | |
| PAD, UNK = 0, 1 | |
| def tokenize(smiles: str) -> List[str]: | |
| return _SMILES_PATTERN.findall(smiles) | |
| def build_vocab(smiles_list: Iterable[str]) -> Dict[str, int]: | |
| vocab = {"<pad>": PAD, "<unk>": UNK} | |
| for smi in smiles_list: | |
| for tok in tokenize(smi): | |
| if tok not in vocab: | |
| vocab[tok] = len(vocab) | |
| return vocab | |
| def encode_tokens(smiles: str, vocab: Dict[str, int], max_len: int) -> Tuple[np.ndarray, int]: | |
| toks = tokenize(smiles)[:max_len] | |
| ids = np.full(max_len, PAD, dtype=np.int64) | |
| for i, tok in enumerate(toks): | |
| ids[i] = vocab.get(tok, UNK) | |
| return ids, len(toks) | |
| # --------------------------------------------------------------------------- | |
| # Fragment helpers | |
| # --------------------------------------------------------------------------- | |
| def canonical(smiles: str | None) -> str | None: | |
| if not smiles: | |
| return None | |
| mol = Chem.MolFromSmiles(smiles) | |
| return Chem.MolToSmiles(mol) if mol is not None else None | |
| def unique_values(values: Sequence[str | None]) -> Tuple[List[str], Dict[str, int]]: | |
| """Return the sorted unique non-null values and their index mapping.""" | |
| uniq = sorted({v for v in values if v}) | |
| return uniq, {v: i for i, v in enumerate(uniq)} |