File size: 8,929 Bytes
fb8c550
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import asyncio
import logging
import os
import re
import shutil
import tempfile
import time
from typing import Any

import httpx

from app.tools.base import BaseTool

logger = logging.getLogger(__name__)

PDB_DOWNLOAD = "https://files.rcsb.org/download/{pdb_id}.pdb"
VINA_CMD = shutil.which("vina") or "/usr/local/bin/vina"


def _find_ligand_center(pdb_content: str) -> tuple[float, float, float] | None:
    """Find the geometric center of the largest HETATM ligand (non-water)."""
    het_atoms: list[list[tuple[float, float, float]]] = []
    current_het: list[tuple[float, float, float]] = []
    current_resname = ""
    for line in pdb_content.splitlines():
        if line.startswith("HETATM"):
            resname = line[17:20].strip()
            if resname == "HOH":
                continue
            try:
                x = float(line[30:38].strip())
                y = float(line[38:46].strip())
                z = float(line[46:54].strip())
            except ValueError:
                continue
            if resname != current_resname:
                if current_het:
                    het_atoms.append(current_het)
                current_het = [(x, y, z)]
                current_resname = resname
            else:
                current_het.append((x, y, z))
        elif line.startswith("ATOM") or line.startswith("TER"):
            if current_het:
                het_atoms.append(current_het)
                current_het = []
                current_resname = ""
    if current_het:
        het_atoms.append(current_het)

    if not het_atoms:
        return None

    largest = max(het_atoms, key=len)
    cx = sum(a[0] for a in largest) / len(largest)
    cy = sum(a[1] for a in largest) / len(largest)
    cz = sum(a[2] for a in largest) / len(largest)
    return cx, cy, cz


def _find_protein_center(pdb_content: str) -> tuple[float, float, float]:
    xs, ys, zs = [], [], []
    for line in pdb_content.splitlines():
        if line.startswith("ATOM") and len(line) >= 54:
            try:
                xs.append(float(line[30:38].strip()))
                ys.append(float(line[38:46].strip()))
                zs.append(float(line[46:54].strip()))
            except ValueError:
                continue
    if not xs:
        return 0.0, 0.0, 0.0
    return sum(xs) / len(xs), sum(ys) / len(ys), sum(zs) / len(zs)


def _clean_protein(pdb_content: str) -> str:
    """Keep only ATOM records (protein), strip HETATM, waters, ANISOU, CONECT."""
    lines: list[str] = []
    for line in pdb_content.splitlines():
        if line.startswith("ATOM") and len(line) >= 54:
            lines.append(line)
        elif line.startswith("TER"):
            lines.append(line)
        elif line.startswith("END"):
            lines.append(line)
    return "\n".join(lines)


def _parse_vina_pdbqt(pdbqt: str) -> list[dict[str, Any]]:
    """Parse Vina output PDBQT into individual pose dicts."""
    models = re.split(r"^MODEL\s+(\d+)", pdbqt, flags=re.MULTILINE)
    poses: list[dict[str, Any]] = []
    current_atoms: list[dict[str, Any]] = []
    current_model = 0

    for chunk in models:
        chunk = chunk.strip()
        if chunk.isdigit():
            current_model = int(chunk)
            current_atoms = []
        elif chunk and current_model > 0:
            for line in chunk.splitlines():
                if line.startswith("ATOM") or line.startswith("HETATM"):
                    try:
                        x = float(line[30:38].strip())
                        y = float(line[38:46].strip())
                        z = float(line[46:54].strip())
                        elem = line[76:78].strip()
                        current_atoms.append({"x": x, "y": y, "z": z, "element": elem})
                    except ValueError:
                        continue
            if current_atoms:
                energy_match = re.search(r"REMARK VINA RESULT:\s*([-\d.]+)", chunk)
                poses.append({
                    "model": current_model,
                    "atoms": len(current_atoms),
                    "affinity": float(energy_match.group(1)) if energy_match else None,
                })
                current_atoms = []
    return poses


class DockingTool(BaseTool):
    name = "docking"

    async def run(self, input: dict) -> dict:
        pdb_id = input.get("pdb_id", "").strip().upper()
        smiles = input.get("smiles", "").strip()

        if not pdb_id or not smiles:
            return {"error": "pdb_id and smiles are required"}

        tmpdir = tempfile.mkdtemp(prefix="docking_")
        try:
            # 1. Fetch PDB
            pdb_url = PDB_DOWNLOAD.format(pdb_id=pdb_id)
            async with httpx.AsyncClient(timeout=30) as client:
                r = await client.get(pdb_url)
                if r.status_code != 200:
                    return {"error": f"PDB {pdb_id} not found at RCSB"}
                pdb_content = r.text

            pdb_path = os.path.join(tmpdir, "protein.pdb")
            with open(pdb_path, "w") as f:
                f.write(pdb_content)

            # 2. Clean protein (strip waters, heteroatoms)
            cleaned = _clean_protein(pdb_content)
            clean_path = os.path.join(tmpdir, "cleaned.pdb")
            with open(clean_path, "w") as f:
                f.write(cleaned)

            # 3. Convert protein to PDBQT via obabel
            protein_pdbqt = os.path.join(tmpdir, "protein.pdbqt")
            proc = await asyncio.create_subprocess_exec(
                "obabel", clean_path, "-O", protein_pdbqt, "-xr",
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
            _, stderr = await proc.communicate()
            if proc.returncode != 0 or not os.path.exists(protein_pdbqt):
                err = stderr.decode() if stderr else "obabel failed"
                return {"error": f"Protein PDBQT preparation failed: {err}"}

            # 4. Convert SMILES to 3D PDBQT via obabel
            ligand_pdbqt = os.path.join(tmpdir, "ligand.pdbqt")
            proc = await asyncio.create_subprocess_exec(
                "obabel", f"-:{smiles}", "-O", ligand_pdbqt, "--gen3d", "-h",
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
            _, stderr = await proc.communicate()
            if proc.returncode != 0 or not os.path.exists(ligand_pdbqt):
                err = stderr.decode() if stderr else "obabel failed"
                return {"error": f"Ligand PDBQT preparation failed: {err}"}

            # 5. Determine binding site box
            center = _find_ligand_center(pdb_content)
            if center:
                cx, cy, cz = center
                sx = sy = sz = 20
            else:
                cx, cy, cz = _find_protein_center(pdb_content)
                sx = sy = sz = 30

            # 6. Run Vina
            out_pdbqt = os.path.join(tmpdir, "out.pdbqt")
            vina_cmd = await asyncio.create_subprocess_exec(
                VINA_CMD,
                "--receptor", protein_pdbqt,
                "--ligand", ligand_pdbqt,
                "--out", out_pdbqt,
                "--center_x", str(cx),
                "--center_y", str(cy),
                "--center_z", str(cz),
                "--size_x", str(sx),
                "--size_y", str(sy),
                "--size_z", str(sz),
                "--exhaustiveness", "8",
                "--num_modes", "9",
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
            try:
                stdout, stderr = await asyncio.wait_for(vina_cmd.communicate(), timeout=600)
            except asyncio.TimeoutError:
                vina_cmd.kill()
                await vina_cmd.communicate()
                return {"error": "Docking timed out after 10 minutes"}

            if vina_cmd.returncode != 0 or not os.path.exists(out_pdbqt):
                err = stderr.decode("utf-8", errors="replace")[:500] if stderr else ""
                return {"error": f"Vina failed (exit {vina_cmd.returncode}): {err}"}

            # 7. Parse results
            with open(out_pdbqt) as f:
                out_content = f.read()

            poses = _parse_vina_pdbqt(out_content)
            log = stdout.decode() if stdout else ""

            return {
                "pdb_id": pdb_id,
                "smiles": smiles,
                "poses": poses,
                "num_poses": len(poses),
                "box_center": {"x": cx, "y": cy, "z": cz},
                "box_size": {"x": sx, "y": sy, "z": sz},
                "vina_log": log[:2000],
                "from_cache": False,
            }

        except Exception as e:
            logger.exception("Docking run failed")
            return {"error": f"Docking failed: {e}"}
        finally:
            shutil.rmtree(tmpdir, ignore_errors=True)