-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnofeedback.py
More file actions
151 lines (135 loc) · 5.11 KB
/
Copy pathnofeedback.py
File metadata and controls
151 lines (135 loc) · 5.11 KB
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
import openai
import jsonlines
import time
import pandas as pd
import numpy as np
import random
import json
import sys
import os
from rdkit.Chem import rdMolDescriptors as rdmd
# Set up your API key and model parameters
#model_engine = 'gpt-3.5-turbo' # You can choose a different model if desired
model_engine = 'text-davinci-003'
temperature = 0.3
num_generations = 10
import openai
import jsonlines
import time
import subprocess
import re
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import RDConfig
from rdkit.Chem import QED
sys.path.append(os.path.join(RDConfig.RDContribDir, 'SA_Score'))
import sascorer
directory_path = './LMLF/'
target_file_path = './LMLF/one-box/drd2.jsonl'
output_file_path = ''
target_molecules = []
target_labels = []
data = []
for i in range(1, num_generations):
new_molecules = []
num_molecules = 20
print("iteration", i)
with jsonlines.open(target_file_path) as reader:
for line in reader:
if "\n" not in line:
target_molecules.append(line['smiles'])
target_labels.append(line['label'])
unique_molecules = set()
for _ in range(num_molecules):
target_index = random.randint(0, len(target_molecules) - 1)
target_mol = target_molecules[target_index]
target_label = target_labels[target_index]
print("target, label", target_mol, target_label)
# message = [{"role":"user", "content":f'Generating only SMILES strings, Generate a novel valid molecule similar to {target_mol} that is {target_label}-class'}]
# response = openai.ChatCompletion.create(
# model = "gpt-3.5-turbo",
# messages = message,
# max_tokens=60,
# temperature=0.7,
# n=1,
# stop=None,
# timeout=60
# )
# new_mol = response.choices[0]
prompt = f'Generate a novel valid molecule similar to {target_mol} that is {target_label}-class and do not generate any English text'
response = openai.Completion.create(
engine=model_engine,
prompt=prompt,
max_tokens=60,
temperature=0.7,
n=1,
stop=None,
timeout=20
)
new_mol = response.choices[0].text.strip()
print("new mol", new_mol)
try:
mol = Chem.MolFromSmiles(new_mol)
if mol is not None and mol not in unique_molecules:
#sanitized_mol = Chem.SanitizeMol(mol)
new_molecules.append(mol)
#print("new molecules", new_mol)
print("new_molecules", new_molecules)
except Exception as e:
print(f"SMILES Parse Error: {e}. Skipping molecule: {new_mol}")
docking_scores = []
for mol in new_molecules:
docking_score = calculate_docking_score(mol)
print("docking score", docking_score)
docking_scores.append(docking_score)
labels = []
mw_threshold = 700
logp_threshold = 5
radscore_threshold = 5
new_target_molecules = []
mols = []
for mol in new_molecules:
print("mol", Chem.MolToSmiles(mol))
try:
smiles = Chem.MolToSmiles(mol)
if smiles not in unique_molecules:
unique_molecules.add(smiles)
mw = rdkit.Chem.Descriptors.MolWt(mol)
logp = rdkit.Chem.Descriptors.MolLogP(mol)
sas = sascorer.calculateScore(mol)
print(mw, logp, sas, )
if (
200 <= mw <= mw_threshold
and logp <= logp_threshold
and sas <= radscore_threshold
):
labels.append('1')
new_target_molecules.append({'smiles': smiles, 'label': '1'})
#mols.append(Chem.MolToSmiles(mol))
else:
labels.append('0')
else:
print("skipping duplicate molecules")
except Exception as e:
print(f"Molecular Property Calculation Error: {e}. Skipping molecule.")
data.extend(list(zip(unique_molecules, labels)))
print("data", data)
#with jsonlines.open(target_file_path, mode='a') as writer:
# writer.write('\\n')
# writer.write_all(new_target_molecules)
with jsonlines.open(target_file_path, mode='a') as writer:
# writer.write("\\n")
for molecule in new_target_molecules:
writer.write(molecule)
writer.write('\n')
# with open(target_file_path, mode='a') as outfile:
# for hostDict in target_file_path:
# json.dump(hostDict, outfile)
# outfile.write('\n')
df = pd.DataFrame(data, columns=['Molecule', 'Label'])
df.to_csv(output_file_path, index=False)
# Print and analyze the results
print(f'generation {i}:')
print('generated molecules:')
print(data)