| 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: |
| |
| 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 |
|
|