File size: 1,764 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
from __future__ import annotations

from pathlib import Path

from rdkit import Chem
from rdkit.Chem import AllChem


def _embed_3d_with_retries(mol: Chem.Mol) -> bool:
    """Try multiple RDKit embedding strategies to guarantee a 3D conformer."""
    attempts = []

    p1 = AllChem.ETKDGv3()
    p1.randomSeed = 42
    attempts.append(p1)

    p2 = AllChem.ETKDGv2()
    p2.randomSeed = 42
    attempts.append(p2)

    p3 = AllChem.ETKDGv3()
    p3.randomSeed = 42
    p3.useRandomCoords = True
    attempts.append(p3)

    for params in attempts:
        try:
            mol.RemoveAllConformers()
            status = AllChem.EmbedMolecule(mol, params)
            if int(status) != 0:
                continue
            if mol.GetNumConformers() == 0:
                continue
            try:
                AllChem.UFFOptimizeMolecule(mol, maxIters=300)
            except Exception:
                # Keep conformer if optimization fails.
                pass
            return bool(mol.GetConformer().Is3D())
        except Exception:
            continue
    return False


def prepare_ligand_sdf(ligand_id: str, smiles: str, out_path: str | Path) -> Path:
    """Prepare ligand SDF with optional 3D coordinates for docking."""
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        raise ValueError(f"Invalid SMILES for ligand {ligand_id}: {smiles}")
    mol = Chem.AddHs(mol)

    has_3d = _embed_3d_with_retries(mol)
    if not has_3d:
        raise ValueError(f"Failed to generate 3D conformer for ligand {ligand_id}")

    mol.SetProp("_Name", ligand_id)
    target = Path(out_path)
    target.parent.mkdir(parents=True, exist_ok=True)
    writer = Chem.SDWriter(str(target))
    writer.write(mol)
    writer.close()
    return target