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graph_rdkit.py and the smiles2graph entry point so it
|
| 5 |
+
can be used from a flat HuggingFace repo (no `featurizer.` package path needed).
|
| 6 |
+
Depends only on numpy and rdkit.
|
| 7 |
+
|
| 8 |
+
The graph featurization (atom features, adjacency normalization, and the exact
|
| 9 |
+
`_process_mol` behavior) is reproduced verbatim from the training code so that
|
| 10 |
+
embeddings match the published weights. The only deviation: invalid SMILES raise
|
| 11 |
+
a ValueError instead of returning None, to avoid silently dropping rows.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from typing import Any, Optional, Union
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
from rdkit import Chem
|
| 18 |
+
from rdkit.Chem import AllChem
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Adjacency:
|
| 22 |
+
def __init__(self, mol: Chem.Mol):
|
| 23 |
+
self.num_atoms = mol.GetNumAtoms()
|
| 24 |
+
self.adj_mat = self._get_adjacency_matrix(mol)
|
| 25 |
+
|
| 26 |
+
def _get_adjacency_matrix(self, mol: Chem.Mol) -> np.ndarray:
|
| 27 |
+
return Chem.GetAdjacencyMatrix(mol)
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def id_adj_mat(self) -> np.ndarray:
|
| 31 |
+
return self.adj_mat + np.eye(self.num_atoms)
|
| 32 |
+
|
| 33 |
+
@property
|
| 34 |
+
def norm_id_adj_mat(self) -> np.ndarray:
|
| 35 |
+
id_adj_mat = self.id_adj_mat
|
| 36 |
+
return self._normalize_adj_mat(id_adj_mat)
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def norm_laplacian_mat(self) -> np.ndarray:
|
| 40 |
+
norm_adj_mat = self._normalize_adj_mat(self.adj_mat)
|
| 41 |
+
return np.eye(self.num_atoms) - norm_adj_mat
|
| 42 |
+
|
| 43 |
+
@staticmethod
|
| 44 |
+
def _normalize_adj_mat(adj_mat: Union[list, np.ndarray]) -> np.ndarray:
|
| 45 |
+
if isinstance(adj_mat, list):
|
| 46 |
+
adj_mat = np.array(adj_mat)
|
| 47 |
+
num_nodes = len(adj_mat)
|
| 48 |
+
node_deg = np.sum(adj_mat, axis=0)
|
| 49 |
+
node_deg = 1 / np.sqrt(node_deg)
|
| 50 |
+
node_deg = np.eye(num_nodes) * node_deg
|
| 51 |
+
return np.matmul(np.matmul(node_deg, adj_mat), node_deg)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class Nodes:
|
| 55 |
+
def __init__(self, mol: Chem.Mol):
|
| 56 |
+
self.node_feat = self._get_node_features(mol)
|
| 57 |
+
|
| 58 |
+
def _get_node_features(self, mol: Chem.Mol) -> np.ndarray:
|
| 59 |
+
return np.array([self._featurize_atom(a) for a in mol.GetAtoms()])
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def _featurize_atom(atom: Chem.Atom) -> np.ndarray:
|
| 63 |
+
results = (
|
| 64 |
+
Nodes.one_of_k_encoding(
|
| 65 |
+
atom.GetSymbol(),
|
| 66 |
+
["C", "N", "O", "S", "F", "Si", "P", "Cl", "Br", "Mg", "Na",
|
| 67 |
+
"Ca", "Fe", "As", "Al", "I", "B", "V", "K", "Tl", "Yb",
|
| 68 |
+
"Sb", "Sn", "Ag", "Pd", "Co", "Se", "Ti", "Zn", "H", "Li",
|
| 69 |
+
"Ge", "Cu", "Au", "Ni", "Cd", "In", "Mn", "Zr", "Cr", "Pt",
|
| 70 |
+
"Hg", "Pb", "Unknown"],
|
| 71 |
+
unk=True
|
| 72 |
+
)
|
| 73 |
+
+ Nodes.one_of_k_encoding(atom.GetDegree(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
|
| 74 |
+
+ Nodes.one_of_k_encoding(atom.GetTotalNumHs(), [0, 1, 2, 3, 4, 5, 6], unk=True)
|
| 75 |
+
+ [atom.GetFormalCharge()]
|
| 76 |
+
+ Nodes.one_of_k_encoding(
|
| 77 |
+
atom.GetHybridization(),
|
| 78 |
+
[Chem.rdchem.HybridizationType.SP,
|
| 79 |
+
Chem.rdchem.HybridizationType.SP2,
|
| 80 |
+
Chem.rdchem.HybridizationType.SP3,
|
| 81 |
+
Chem.rdchem.HybridizationType.SP3D,
|
| 82 |
+
Chem.rdchem.HybridizationType.SP3D2,
|
| 83 |
+
Chem.rdchem.HybridizationType.UNSPECIFIED],
|
| 84 |
+
unk=True
|
| 85 |
+
)
|
| 86 |
+
+ [atom.GetIsAromatic()]
|
| 87 |
+
+ Nodes.one_of_k_encoding(atom.GetNumExplicitHs(), [0, 1, 2, 3, 4], unk=True)
|
| 88 |
+
)
|
| 89 |
+
return np.array(results).reshape(-1)
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def one_of_k_encoding(x: Any, allowable_set: list, unk: bool = False) -> list:
|
| 93 |
+
if x not in allowable_set:
|
| 94 |
+
if unk:
|
| 95 |
+
x = allowable_set[-1]
|
| 96 |
+
else:
|
| 97 |
+
raise Exception(f"input {x} not in allowable set {allowable_set}")
|
| 98 |
+
return [x == s for s in allowable_set]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class MolGraph(Adjacency, Nodes):
|
| 102 |
+
def __init__(self, smiles: str, explicit_H: Optional[str] = None):
|
| 103 |
+
self.mol = Chem.MolFromSmiles(smiles)
|
| 104 |
+
self._process_mol(self.mol, explicit_H=explicit_H)
|
| 105 |
+
|
| 106 |
+
Adjacency.__init__(self, self.mol)
|
| 107 |
+
Nodes.__init__(self, self.mol)
|
| 108 |
+
|
| 109 |
+
@staticmethod
|
| 110 |
+
def _process_mol(mol: Chem.Mol, explicit_H: Optional[str] = None) -> Chem.Mol:
|
| 111 |
+
if explicit_H == "all":
|
| 112 |
+
mol = Chem.AddHs(mol)
|
| 113 |
+
elif explicit_H == "polar":
|
| 114 |
+
mol = Chem.AddHs(
|
| 115 |
+
mol,
|
| 116 |
+
onlyOnAtoms=[a.GetIdx() for a in mol.GetAtoms() if a.GetAtomicNum() in [7, 8, 15, 16]],
|
| 117 |
+
)
|
| 118 |
+
elif explicit_H is None:
|
| 119 |
+
mol = Chem.RemoveHs(mol)
|
| 120 |
+
else:
|
| 121 |
+
raise ValueError("Invalid value for explicit_H")
|
| 122 |
+
|
| 123 |
+
Chem.Kekulize(mol)
|
| 124 |
+
AllChem.Compute2DCoords(mol)
|
| 125 |
+
return mol
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def smiles2graph(smiles, adj_type="norm_id_adj_mat", explicit_H_node=None, **kwargs):
|
| 129 |
+
"""Convert a SMILES string to (adjacency_matrix, node_features).
|
| 130 |
+
|
| 131 |
+
Returns
|
| 132 |
+
-------
|
| 133 |
+
(np.ndarray, np.ndarray)
|
| 134 |
+
adj_mat of shape (n_atoms, n_atoms) and node_feat of shape (n_atoms, 75).
|
| 135 |
+
|
| 136 |
+
Raises
|
| 137 |
+
------
|
| 138 |
+
ValueError
|
| 139 |
+
If the SMILES cannot be parsed or featurized.
|
| 140 |
+
"""
|
| 141 |
+
try:
|
| 142 |
+
mol = MolGraph(smiles, explicit_H_node)
|
| 143 |
+
adj_mat = getattr(mol, adj_type)
|
| 144 |
+
node_feat = mol.node_feat
|
| 145 |
+
except Exception as exc:
|
| 146 |
+
raise ValueError(f"Could not featurize SMILES '{smiles}': {exc}") from exc
|
| 147 |
+
return adj_mat, node_feat
|