File size: 20,451 Bytes
27dc10f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import os
import subprocess
import tempfile
from typing import List, Tuple

import numpy as np
import rdkit.Chem as Chem
from meeko import MoleculePreparation, PDBQTMolecule, PDBQTWriterLegacy, RDKitMolCreate
from rdkit import RDLogger
from rdkit.Chem import rdDistGeom

from dataclasses import dataclass, field
from typing import List, Optional


class StrictDataClass:
    """
    A dataclass that raises an error if any field is created outside of the __init__ method.
    """

    def __setattr__(self, name, value):
        if hasattr(self, name) or name in self.__annotations__:
            super().__setattr__(name, value)
        else:
            raise AttributeError(
                f"'{type(self).__name__}' object has no attribute '{name}'."
                f" '{type(self).__name__}' is a StrictDataClass object."
                f" Attributes can only be defined in the class definition."
            )

@dataclass
class VinaConfig(StrictDataClass):
    opencl_binary_path: str = (
        "/lfs/skampere1/0/sttruong/cheapvs_llm/Vina-GPU-2.1/AutoDock-Vina-GPU-2.1"  # needed if you use VINA for rewards
    )
    vina_path: str = (
        "/lfs/skampere1/0/sttruong/cheapvs_llm/Vina-GPU-2.1/AutoDock-Vina-GPU-2.1/AutoDock-Vina-GPU-2-1"  # path to VINA executable, needed if you use VINA for rewards
    )
    target: str = "kras"  # kras, 2bm2

VINA = '/lfs/skampere1/0/sttruong/cheapvs_llm/Vina-GPU-2.1/AutoDock-Vina-GPU-2.1/AutoDock-Vina-GPU-2-1'

logger = RDLogger.logger()
RDLogger.DisableLog("rdApp.*")

def gpu_vina_installed(vina_path=VINA):
    if os.path.exists(vina_path):
        return True
    return False


def read_pdbqt(fn):
    """
    Read a pdbqt file and return the RDKit molecule object.

    Args:
        - fn (str): Path to the pdbqt file.

    Returns:
        - mol (rdkit.Chem.rdchem.Mol): RDKit molecule object.
    """
    pdbqt_mol = PDBQTMolecule.from_file(fn, is_dlg=False, skip_typing=True)
    rdkitmol_list = RDKitMolCreate.from_pdbqt_mol(pdbqt_mol)
    return rdkitmol_list[0]


def smile_to_conf(smile: str, n_tries=5) -> Chem.Mol:
    mol = Chem.MolFromSmiles(smile)
    if mol is None:
        return None
    Chem.SanitizeMol(mol)

    tries = 0
    while tries < n_tries:

        params = rdDistGeom.ETKDGv3()

        # set the parameters
        params.useSmallRingTorsions = True
        params.randomSeed = 0
        params.numThreads = 1

        # generate the conformer
        rdDistGeom.EmbedMolecule(mol, params)

        # add hydrogens
        mol = Chem.AddHs(mol, addCoords=True)

        if mol.GetNumConformers() > 0:
            return mol

        tries += 1

    print(f"Failed to generate conformer for {smile}")
    return mol


def mol_to_pdbqt(mol: Chem.Mol, pdbqt_file: str):

    preparator = MoleculePreparation()
    mol_setups = preparator.prepare(mol)

    for setup in mol_setups:
        pdbqt_string, is_ok, error_msg = PDBQTWriterLegacy.write_string(setup)
        if is_ok:
            with open(pdbqt_file, "w") as f:
                f.write(pdbqt_string)
            break
        else:
            print(f"Failed to write pdbqt file: {error_msg}")


def parse_affinty_from_pdbqt(pdbqt_file: str) -> float:
    with open(pdbqt_file, "r") as f:
        lines = f.readlines()
    for line in lines:
        if "REMARK VINA RESULT" in line:
            return float(line.split()[3])
    return None


script_dir = os.path.dirname(os.path.abspath(__file__))
repo_root = os.path.dirname(script_dir)
DATA_DIR = os.path.join(repo_root, "data/docking/")

TARGETS = {
    "2bm2": {
        "receptor": os.path.join(DATA_DIR, "2bm2/2bm2_protein.pdbqt"),
        "center_x": 40.415,
        "center_y": 110.986,
        "center_z": 82.673,
        "size_x": 30,
        "size_y": 30,
        "size_z": 30,
        "num_atoms": 30,
    },
    "kras": {
        "receptor": os.path.join(DATA_DIR, "kras/8azr.pdbqt"),
        "ref_ligand": os.path.join(DATA_DIR, "kras/8azr_ref_ligand.sdf"),
        "center_x": 21.466,
        "center_y": -0.650,
        "center_z": 5.028,
        "size_x": 18,
        "size_y": 18,
        "size_z": 18,
        "num_atoms": 32,
    },
    "trmd": {
        "receptor": os.path.join(DATA_DIR, "trmd/6qrd.pdbqt"),
        "center_x": 16.957,
        "center_y": 21.772,
        "center_z": 33.296,
        "size_x": 30,
        "size_y": 30,
        "size_z": 30,
        "num_atoms": 34,
    },
    'ACES_8dt5': {
        'center_x': 64.615,
        'center_y': 147.253,
        'center_z': 6.996,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/ACES_8dt5.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/ACES_8dt5.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'ACE_1uze': {
        'center_x': 40.638,
        'center_y': 35.471,
        'center_z': 46.563,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/ACE_1uze.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/ACE_1uze.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'ADRB2_4ldo': {
        'center_x': -1.346,
        'center_y': -12.351,
        'center_z': -48.586,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/ADRB2_4ldo.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/ADRB2_4ldo.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'AOFB_2c66': {
        'center_x': 52.765,
        'center_y': 154.112,
        'center_z': 26.269,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/AOFB_2c66.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/AOFB_2c66.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'BCL2_6o0k': {
        'center_x': -15.357,
        'center_y': 2.24,
        'center_z': -9.562,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/BCL2_6o0k.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/BCL2_6o0k.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'CAH2_5gmm': {
        'center_x': -0.223,
        'center_y': 6.554,
        'center_z': -47.066,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/CAH2_5gmm.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/CAH2_5gmm.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'CLTR1_6rz5': {
        'center_x': 12.835,
        'center_y': 8.127,
        'center_z': -13.658,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/CLTR1_6rz5.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/CLTR1_6rz5.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'DHPS_5u14': {
        'center_x': 70.928,
        'center_y': -0.17,
        'center_z': 101.575,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/DHPS_5u14.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/DHPS_5u14.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'DPP4_5y7k': {
        'center_x': 95.486,
        'center_y': -16.719,
        'center_z': 60.594,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/DPP4_5y7k.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/DPP4_5y7k.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'DYR_2w3a': {
        'center_x': 1.914,
        'center_y': 30.495,
        'center_z': -2.884,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/DYR_2w3a.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/DYR_2w3a.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'HDAC1_8voj': {
        'center_x': 171.994,
        'center_y': 205.147,
        'center_z': 153.834,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/HDAC1_8voj.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/HDAC1_8voj.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'HMDH_1hwk': {
        'center_x': 18.313,
        'center_y': 8.38,
        'center_z': 15.174,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/HMDH_1hwk.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/HMDH_1hwk.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'PARP1_8hlr': {
        'center_x': 11.147,
        'center_y': 4.004,
        'center_z': -9.104,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/PARP1_8hlr.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/PARP1_8hlr.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'PBPA_3udi': {
        'center_x': 34.097,
        'center_y': -0.694,
        'center_z': 12.515,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/PBPA_3udi.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/PBPA_3udi.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'PDE4A_3tvx': {
        'center_x': 43.495,
        'center_y': 16.644,
        'center_z': -24.574,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/PDE4A_3tvx.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/PDE4A_3tvx.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'PPARA_7bpz': {
        'center_x': 22.031,
        'center_y': 0.986,
        'center_z': 62.494,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/PPARA_7bpz.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/PPARA_7bpz.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'PPARG_5ugm': {
        'center_x': 25.979,
        'center_y': 64.86,
        'center_z': -29.332,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/PPARG_5ugm.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/PPARG_5ugm.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'SC6A4_6awp': {
        'center_x': 33.292,
        'center_y': 185.551,
        'center_z': 143.179,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/SC6A4_6awp.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/SC6A4_6awp.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
    'SRC_4mxo': {
        'center_x': 12.089,
        'center_y': -37.176,
        'center_z': -6.818,
        'receptor': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/proteins_pdbqt/SRC_4mxo.pdbqt',
        'ref_ligand': '/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/crystal_ligand/SRC_4mxo.pdb',
        'size_x': 25.0,
        'size_y': 25.0,
        'size_z': 25.0,
        "num_atoms": 34},
}


class QuickVina2GPU(object):

    def __init__(
        self,
        vina_path: str = VINA,
        target: str = None,
        target_pdbqt: str = None,
        reference_ligand: str = None,
        input_dir: str = None,
        out_dir: str = None,
        save_confs: bool = False,
        reward_scale_max: float = -1.0,
        reward_scale_min: float = -10.0,
        thread: int = 8000,
        print_time: bool = False,
        print_logs: bool = False,
    ):
        """
        Initializes the QuickVina2GPU class with configuration for running QuickVina 2 on GPU.

        Give either a code for a target or a PDBQT file.

        Args:
            - vina_path (str): Path to the Vina executable.
            - target (str, optional): Target identifier. Defaults to None.
            - target_pdbqt (str, optional): Path to the target PDBQT file. Defaults to None.
            - reference_ligand (str, optional): Path to the reference ligand file. Defaults to None.
            - input_dir (str, optional): Directory for input files. Defaults to a temporary directory.
            - out_dir (str, optional): Directory for output files. Defaults to None, will use input_dir + '_out'.
            - save_confs (bool, optional): Whether to save conformations. Defaults to False.
            - reward_scale_max (float, optional): Maximum reward scale. Defaults to -1.0.
            - reward_scale_min (float, optional): Minimum reward scale. Defaults to -10.0.
            - thread (int, optional): Number of threads to use. Defaults to 8000.
            - print_time (bool, optional): Whether to print execution time. Defaults to True.

        Raises:
        - ValueError: If the target is unknown.

        """
        self.vina_path = vina_path
        self.save_confs = save_confs
        self.thread = thread
        self.print_time = print_time
        self.print_logs = print_logs
        self.reward_scale_max = reward_scale_max
        self.reward_scale_min = reward_scale_min

        if target is None and target_pdbqt is None:
            raise ValueError("Either target or target_pdbqt must be provided")

        if input_dir is None:
            input_dir = '/lfs/skampere1/0/sttruong/cheapvs_llm/vina_dir'
            os.makedirs(input_dir, exist_ok=True)
        self.input_dir = input_dir
        self.out_dir = input_dir + "_out"

        if target in TARGETS:
            self.target_info = TARGETS[target]
        else:
            raise ValueError(f"Unknown target: {target}")

        for key, value in self.target_info.items():
            setattr(self, key, value)

    def _write_config_file(self):

        config = []
        config.append(f"receptor = {self.receptor}")
        config.append(f"ligand_directory = {self.input_dir}")
        config.append(f"opencl_binary_path = {VinaConfig.opencl_binary_path}")
        config.append(f"center_x = {self.center_x}")
        config.append(f"center_y = {self.center_y}")
        config.append(f"center_z = {self.center_z}")
        config.append(f"size_x = {self.size_x}")
        config.append(f"size_y = {self.size_y}")
        config.append(f"size_z = {self.size_z}")
        config.append(f"thread = {self.thread}")

        with open(os.path.join(self.input_dir, "config.txt"), "w") as f:
            f.write("\n".join(config))

    def _write_pdbqt_files(self, smiles: List[str]):

        # Convert smiles to mols
        mols = [smile_to_conf(smile) for smile in smiles]
        # Remove None
        # mols = [mol for mol in mols if mol is not None]

        # Write pdbqt files
        for i, mol in enumerate(mols):
            pdbqt_file = os.path.join(self.input_dir, f"input_{i}.pdbqt")
            try:
                mol_to_pdbqt(mol, pdbqt_file)
            except Exception as e:
                print(f"Failed to write pdbqt file: {e}")

    def _teardown(self):

        # Remove input files
        for file in os.listdir(self.input_dir):
            os.remove(os.path.join(self.input_dir, file))
        os.rmdir(self.input_dir)

        # Remove output files
        if os.path.exists(self.out_dir):
            for file in os.listdir(self.out_dir):
                os.remove(os.path.join(self.out_dir, file))
            os.rmdir(self.out_dir)

    def _run_vina(self):

        result = subprocess.run(
            [self.vina_path, "--config", os.path.join(self.input_dir, "config.txt")], capture_output=True, text=True, cwd=VinaConfig.opencl_binary_path 
        )
        if self.print_time:
            print(result.stdout.split("\n")[-2])
        if self.print_logs:
            print(result.stdout.split("\n"))

        if result.returncode != 0:
            print(f"Vina failed with return code {result.returncode}")
            print(result.stderr)
            return False

    def _parse_results(self):

        results = []
        failed = 0

        for i in range(self.batch_size):
            pdbqt_file = os.path.join(self.out_dir, f"input_{i}_out.pdbqt")
            if os.path.exists(pdbqt_file):
                affinity = parse_affinty_from_pdbqt(pdbqt_file)
            else:
                affinity = 0.0
                failed += 1
            results.append((affinity))

        if failed > 0:
            print(f"WARNING: Failed to calculate affinity for {failed}/{self.batch_size} molecules")

        return results

    def _parse_docked_poses(self):
        poses = []
        failed = 0

        for i in range(self.batch_size):
            pdbqt_file = os.path.join(self.out_dir, f"input_{i}_out.pdbqt")
            if os.path.exists(pdbqt_file):
                mol = read_pdbqt(pdbqt_file)
                poses.append(mol)
            else:
                poses.append(None)
                failed += 1

        if failed > 0:
            print(f"WARNING: Failed to read docked pdbqt files for {failed}/{self.batch_size} molecules")

        return poses

    def _check_outputs(self):
        if not os.path.exists(self.out_dir):
            return False
        return True

    def calculate_rewards(self, smiles: List[str]) -> List[Tuple[str, float]]:

        self.batch_size = len(smiles)
        # mols = [Chem.MolFromSmiles(smile) for smile in smiles]

        # Write input files, config file and run vina
        self._write_pdbqt_files(smiles)
        self._write_config_file()
        self._run_vina()

        # Parse results
        if self._check_outputs():
            affinties = self._parse_results()
        else:
            affinties = [0.0] * self.batch_size

        # Scale affinities to calculate rewards
        affinties = np.array(affinties)

        # print(
        #     f"AFFINITIES: mean={round(np.mean(affinties), 3 )}, std={round(np.std(affinties), 3)}, min={round(np.min(affinties), 3)}, max={round(np.max(affinties), 3)}"
        # )

        # Remove output files
        self._teardown()

        # return smiles, list(affinties), list(rewards)
        return smiles, list(affinties)

    def dock_mols(self, smiles: List[str]) -> List[Tuple[str, float]]:
        self.batch_size = len(smiles)

        # Write input files, config file and run vina
        self._write_pdbqt_files(smiles)
        self._write_config_file()
        self._run_vina()

        # Parse results
        affinties = self._parse_results()

        # Scale affinities to calculate rewards
        affinties = np.array(affinties)
        mols = self._parse_docked_poses()

        print(
            f"AFFINITIES: mean={round(np.mean(affinties), 3 )}, std={round(np.std(affinties), 3)}, min={round(np.min(affinties), 3)}, max={round(np.max(affinties), 3)}"
        )

        # Remove output files
        self._teardown()

        return mols, affinties


if __name__ == "__main__":

    # test
    smile = "Fc1cc2ccncc2cc1Br"
    mol = smile_to_conf(smile)

    pdbqt_file = "test.pdbqt"
    mol_to_pdbqt(mol, pdbqt_file)
    os.remove

    parse_affinty_from_pdbqt(pdbqt_file)

    # Test docking
    vina = QuickVina2GPU(vina_path=VINA, target="DPP4_5y7k")
    
    import pandas as pd
    df = pd.read_csv('/lfs/skampere1/0/sttruong/cheapvs_llm/20_targets/drugs_filtered/DPP4_HUMAN.csv')
    smiles_list = df['SMILES'].tolist()
    
    outs = vina.calculate_rewards(smiles_list)
    print(outs)