| from __future__ import annotations |
|
|
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Dict, Iterable, List, Optional |
|
|
| import numpy as np |
| import pandas as pd |
| from rdkit import Chem |
| from rdkit.Chem import AllChem, Descriptors |
| from rdkit.Chem.rdFingerprintGenerator import GetMorganGenerator |
|
|
| from .graph_builders import build_ligand_graph |
| from .schemas import LigandEncoding |
|
|
|
|
| @dataclass |
| class LigandEncoderConfig: |
| radius: int = 2 |
| n_bits: int = 1024 |
| generate_3d: bool = False |
|
|
|
|
| class LigandEncoder: |
| """Encode ligands from SMILES/SDF into vectors and graph objects.""" |
|
|
| def __init__(self, config: Optional[LigandEncoderConfig] = None) -> None: |
| self.config = config or LigandEncoderConfig() |
| self._fp_gen = GetMorganGenerator(radius=self.config.radius, fpSize=self.config.n_bits) |
|
|
| def _mol_from_smiles(self, smiles: str): |
| mol = Chem.MolFromSmiles(smiles) |
| if mol is None: |
| raise ValueError(f"Invalid SMILES: {smiles}") |
| mol = Chem.AddHs(mol) |
| if self.config.generate_3d: |
| params = AllChem.ETKDGv3() |
| params.randomSeed = 42 |
| status = AllChem.EmbedMolecule(mol, params) |
| if status == 0: |
| AllChem.UFFOptimizeMolecule(mol) |
| return mol |
|
|
| def _fingerprint(self, mol) -> np.ndarray: |
| fp = self._fp_gen.GetFingerprint(mol) |
| return np.asarray(fp, dtype=float) |
|
|
| def _descriptors(self, mol) -> Dict[str, float]: |
| return { |
| "mw": float(Descriptors.MolWt(mol)), |
| "logp": float(Descriptors.MolLogP(mol)), |
| "hbd": float(Descriptors.NumHDonors(mol)), |
| "hba": float(Descriptors.NumHAcceptors(mol)), |
| "tpsa": float(Descriptors.TPSA(mol)), |
| "rot_bonds": float(Descriptors.NumRotatableBonds(mol)), |
| "ring_count": float(Descriptors.RingCount(mol)), |
| } |
|
|
| def encode_smiles(self, ligand_id: str, smiles: str) -> LigandEncoding: |
| mol = self._mol_from_smiles(smiles) |
| fp = self._fingerprint(mol) |
| desc = self._descriptors(mol) |
| graph = build_ligand_graph(mol) |
| desc_vec = np.asarray(list(desc.values()), dtype=float) |
| vector = np.concatenate([fp, desc_vec]) |
| prep = { |
| "canonical_smiles": Chem.MolToSmiles(Chem.RemoveHs(mol), canonical=True), |
| "formula": str(Descriptors.rdMolDescriptors.CalcMolFormula(mol)), |
| "mw": float(desc["mw"]), |
| } |
| return LigandEncoding( |
| ligand_id=ligand_id, |
| smiles=smiles, |
| fingerprint=fp, |
| descriptors=desc, |
| graph=graph, |
| vector=vector, |
| prep=prep, |
| ) |
|
|
| def encode_table(self, ligands: pd.DataFrame) -> List[LigandEncoding]: |
| rows = [] |
| for row in ligands.itertuples(index=False): |
| rows.append(self.encode_smiles(str(row.ligand_id), str(row.smiles))) |
| return rows |
|
|
| def encode_sdf(self, sdf_path: str | Path) -> List[LigandEncoding]: |
| suppl = Chem.SDMolSupplier(str(sdf_path), removeHs=False) |
| output: List[LigandEncoding] = [] |
| for idx, mol in enumerate(suppl): |
| if mol is None: |
| continue |
| mol_h = Chem.AddHs(Chem.RemoveHs(mol)) |
| lig_id = mol_h.GetProp("_Name") if mol_h.HasProp("_Name") else f"lig_{idx:04d}" |
| smiles = Chem.MolToSmiles(Chem.RemoveHs(mol_h), canonical=True) |
| fp = self._fingerprint(mol_h) |
| desc = self._descriptors(mol_h) |
| graph = build_ligand_graph(mol_h) |
| vector = np.concatenate([fp, np.asarray(list(desc.values()), dtype=float)]) |
| prep = { |
| "canonical_smiles": smiles, |
| "formula": str(Descriptors.rdMolDescriptors.CalcMolFormula(mol_h)), |
| "mw": float(desc["mw"]), |
| } |
| output.append( |
| LigandEncoding( |
| ligand_id=lig_id, |
| smiles=smiles, |
| fingerprint=fp, |
| descriptors=desc, |
| graph=graph, |
| vector=vector, |
| prep=prep, |
| ) |
| ) |
| return output |
|
|