forked from wengong-jin/multiobj-rationale
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproperties.py
More file actions
executable file
·183 lines (146 loc) · 5.67 KB
/
Copy pathproperties.py
File metadata and controls
executable file
·183 lines (146 loc) · 5.67 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
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
#!/usr/bin/env python
from __future__ import print_function, division
import numpy as np
from rdkit import Chem
from rdkit import rdBase
from rdkit.Chem import AllChem
from rdkit import DataStructs
import rdkit.Chem.QED as QED
import scripts.sascorer as sascorer
import os
import pickle
from chemprop.train import predict
from chemprop.data import MoleculeDataset
from chemprop.data.utils import get_data, get_data_from_smiles
from chemprop.utils import load_args, load_checkpoint, load_scalers
rdBase.DisableLog('rdApp.error')
class gsk3_model():
"""Scores based on an ECFP classifier for activity."""
kwargs = ["clf_path"]
clf_path = 'data/gsk3/gsk3.pkl'
def __init__(self):
with open(self.clf_path, "rb") as f:
self.clf = pickle.load(f)
def __call__(self, smiles_list):
fps = []
mask = []
for i,smiles in enumerate(smiles_list):
mol = Chem.MolFromSmiles(smiles)
mask.append( int(mol is not None) )
fp = gsk3_model.fingerprints_from_mol(mol) if mol else np.zeros((1, 2048))
fps.append(fp)
fps = np.concatenate(fps, axis=0)
scores = self.clf.predict_proba(fps)[:, 1]
scores = scores * np.array(mask)
return np.float32(scores)
@classmethod
def fingerprints_from_mol(cls, mol): # use ECFP4
features_vec = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048)
features = np.zeros((1,))
DataStructs.ConvertToNumpyArray(features_vec, features)
return features.reshape(1, -1)
class jnk3_model():
"""Scores based on an ECFP classifier for activity."""
kwargs = ["clf_path"]
clf_path = 'data/jnk3/jnk3.pkl'
def __init__(self):
with open(self.clf_path, "rb") as f:
self.clf = pickle.load(f)
def __call__(self, smiles_list):
fps = []
mask = []
for i,smiles in enumerate(smiles_list):
mol = Chem.MolFromSmiles(smiles)
mask.append( int(mol is not None) )
fp = jnk3_model.fingerprints_from_mol(mol) if mol else np.zeros((1, 2048))
fps.append(fp)
fps = np.concatenate(fps, axis=0)
scores = self.clf.predict_proba(fps)[:, 1]
scores = scores * np.array(mask)
return np.float32(scores)
@classmethod
def fingerprints_from_mol(cls, mol): # use ECFP4
features_vec = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048)
features = np.zeros((1,))
DataStructs.ConvertToNumpyArray(features_vec, features)
return features.reshape(1, -1)
class qed_func():
def __call__(self, smiles_list):
scores = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
if mol is None:
scores.append(0)
else:
scores.append(QED.qed(mol))
return np.float32(scores)
class sa_func():
def __call__(self, smiles_list):
scores = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
if mol is None:
scores.append(100)
else:
scores.append(sascorer.calculateScore(mol))
return np.float32(scores)
class chemprop_model():
def __init__(self, checkpoint_dir):
self.checkpoints = []
for root, _, files in os.walk(checkpoint_dir):
for fname in files:
if fname.endswith('.pt'):
fname = os.path.join(root, fname)
self.scaler, self.features_scaler = load_scalers(fname)
self.train_args = load_args(fname)
model = load_checkpoint(fname, cuda=True)
self.checkpoints.append(model)
def __call__(self, smiles, batch_size=500):
test_data = get_data_from_smiles(smiles=smiles, skip_invalid_smiles=False, args=self.train_args)
valid_indices = [i for i in range(len(test_data)) if test_data[i].mol is not None]
full_data = test_data
test_data = MoleculeDataset([test_data[i] for i in valid_indices])
if self.train_args.features_scaling:
test_data.normalize_features(self.features_scaler)
sum_preds = np.zeros((len(test_data), 1))
for model in self.checkpoints:
model_preds = predict(
model=model,
data=test_data,
batch_size=batch_size,
scaler=self.scaler
)
sum_preds += np.array(model_preds)
# Ensemble predictions
avg_preds = sum_preds / len(self.checkpoints)
avg_preds = avg_preds.squeeze(-1).tolist()
# Put zero for invalid smiles
full_preds = [0.0] * len(full_data)
for i, si in enumerate(valid_indices):
full_preds[si] = avg_preds[i]
return np.array(full_preds, dtype=np.float32)
def get_scoring_function(prop_name):
"""Function that initializes and returns a scoring function by name"""
if prop_name == 'jnk3':
return jnk3_model()
elif prop_name == 'gsk3':
return gsk3_model()
elif prop_name == 'qed':
return qed_func()
elif prop_name == 'sa':
return sa_func()
else:
return chemprop_model(prop_name)
if __name__ == "__main__":
import sys
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--prop', required=True)
args = parser.parse_args()
funcs = [get_scoring_function(prop) for prop in args.prop.split(',')]
data = [line.split()[:2] for line in sys.stdin]
all_x, all_y = zip(*data)
props = [func(all_y) for func in funcs]
col_list = [all_x, all_y] + props
for tup in zip(*col_list):
print(*tup)