File size: 4,246 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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