Upload evaluator.py with huggingface_hub
Browse files- evaluator.py +151 -0
evaluator.py
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math, os
|
2 |
+
import pickle
|
3 |
+
import os.path as op
|
4 |
+
import numpy as np
|
5 |
+
import pandas as pd
|
6 |
+
from joblib import dump, load, Parallel, delayed
|
7 |
+
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
|
8 |
+
from sklearn.metrics import mean_absolute_error, roc_auc_score
|
9 |
+
from sklearn.base import BaseEstimator
|
10 |
+
from tqdm import tqdm
|
11 |
+
|
12 |
+
from rdkit import Chem
|
13 |
+
from rdkit import rdBase
|
14 |
+
from rdkit.Chem import AllChem
|
15 |
+
from rdkit import DataStructs
|
16 |
+
from rdkit.Chem import rdMolDescriptors
|
17 |
+
rdBase.DisableLog('rdApp.error')
|
18 |
+
|
19 |
+
def process_smiles(smiles):
|
20 |
+
mol = Chem.MolFromSmiles(smiles)
|
21 |
+
if mol is not None:
|
22 |
+
return Evaluator.fingerprints_from_mol(mol), 1
|
23 |
+
return np.zeros((1, 2048)), 0
|
24 |
+
|
25 |
+
class Evaluator():
|
26 |
+
"""Scores based on an ECFP classifier."""
|
27 |
+
def __init__(self, model_path, task_name, n_jobs=2):
|
28 |
+
self.n_jobs = n_jobs
|
29 |
+
task_type = 'regression'
|
30 |
+
self.task_name = task_name
|
31 |
+
self.task_type = task_type
|
32 |
+
self.model_path = model_path
|
33 |
+
self.metric_func = roc_auc_score if 'classification' in self.task_type else mean_absolute_error
|
34 |
+
self.model = load(model_path)
|
35 |
+
|
36 |
+
def __call__(self, smiles_list):
|
37 |
+
fps = []
|
38 |
+
mask = []
|
39 |
+
for i,smiles in enumerate(smiles_list):
|
40 |
+
mol = Chem.MolFromSmiles(smiles)
|
41 |
+
mask.append( int(mol is not None) )
|
42 |
+
fp = Evaluator.fingerprints_from_mol(mol) if mol else np.zeros((1, 2048))
|
43 |
+
fps.append(fp)
|
44 |
+
|
45 |
+
fps = np.concatenate(fps, axis=0)
|
46 |
+
if 'classification' in self.task_type:
|
47 |
+
scores = self.model.predict_proba(fps)[:, 1]
|
48 |
+
else:
|
49 |
+
scores = self.model.predict(fps)
|
50 |
+
scores = scores * np.array(mask)
|
51 |
+
return np.float32(scores)
|
52 |
+
|
53 |
+
@classmethod
|
54 |
+
def fingerprints_from_mol(cls, mol): # use ECFP4
|
55 |
+
features_vec = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048)
|
56 |
+
features = np.zeros((1,))
|
57 |
+
DataStructs.ConvertToNumpyArray(features_vec, features)
|
58 |
+
return features.reshape(1, -1)
|
59 |
+
|
60 |
+
###### SAS Score ######
|
61 |
+
_fscores = None
|
62 |
+
|
63 |
+
def readFragmentScores(name='fpscores'):
|
64 |
+
import gzip
|
65 |
+
global _fscores
|
66 |
+
# generate the full path filename:
|
67 |
+
if name == "fpscores":
|
68 |
+
name = op.join(op.dirname(__file__), name)
|
69 |
+
data = pickle.load(gzip.open('%s.pkl.gz' % name))
|
70 |
+
outDict = {}
|
71 |
+
for i in data:
|
72 |
+
for j in range(1, len(i)):
|
73 |
+
outDict[i[j]] = float(i[0])
|
74 |
+
_fscores = outDict
|
75 |
+
|
76 |
+
def numBridgeheadsAndSpiro(mol, ri=None):
|
77 |
+
nSpiro = rdMolDescriptors.CalcNumSpiroAtoms(mol)
|
78 |
+
nBridgehead = rdMolDescriptors.CalcNumBridgeheadAtoms(mol)
|
79 |
+
return nBridgehead, nSpiro
|
80 |
+
|
81 |
+
def calculateSAS(smiles_list):
|
82 |
+
scores = []
|
83 |
+
for i, smiles in enumerate(smiles_list):
|
84 |
+
mol = Chem.MolFromSmiles(smiles)
|
85 |
+
score = calculateScore(mol)
|
86 |
+
scores.append(score)
|
87 |
+
return np.float32(scores)
|
88 |
+
|
89 |
+
def calculateScore(m):
|
90 |
+
if _fscores is None:
|
91 |
+
readFragmentScores()
|
92 |
+
|
93 |
+
# fragment score
|
94 |
+
fp = rdMolDescriptors.GetMorganFingerprint(m,
|
95 |
+
2) # <- 2 is the *radius* of the circular fingerprint
|
96 |
+
fps = fp.GetNonzeroElements()
|
97 |
+
score1 = 0.
|
98 |
+
nf = 0
|
99 |
+
for bitId, v in fps.items():
|
100 |
+
nf += v
|
101 |
+
sfp = bitId
|
102 |
+
score1 += _fscores.get(sfp, -4) * v
|
103 |
+
score1 /= nf
|
104 |
+
|
105 |
+
# features score
|
106 |
+
nAtoms = m.GetNumAtoms()
|
107 |
+
nChiralCenters = len(Chem.FindMolChiralCenters(m, includeUnassigned=True))
|
108 |
+
ri = m.GetRingInfo()
|
109 |
+
nBridgeheads, nSpiro = numBridgeheadsAndSpiro(m, ri)
|
110 |
+
nMacrocycles = 0
|
111 |
+
for x in ri.AtomRings():
|
112 |
+
if len(x) > 8:
|
113 |
+
nMacrocycles += 1
|
114 |
+
|
115 |
+
sizePenalty = nAtoms**1.005 - nAtoms
|
116 |
+
stereoPenalty = math.log10(nChiralCenters + 1)
|
117 |
+
spiroPenalty = math.log10(nSpiro + 1)
|
118 |
+
bridgePenalty = math.log10(nBridgeheads + 1)
|
119 |
+
macrocyclePenalty = 0.
|
120 |
+
# ---------------------------------------
|
121 |
+
# This differs from the paper, which defines:
|
122 |
+
# macrocyclePenalty = math.log10(nMacrocycles+1)
|
123 |
+
# This form generates better results when 2 or more macrocycles are present
|
124 |
+
if nMacrocycles > 0:
|
125 |
+
macrocyclePenalty = math.log10(2)
|
126 |
+
|
127 |
+
score2 = 0. - sizePenalty - stereoPenalty - spiroPenalty - bridgePenalty - macrocyclePenalty
|
128 |
+
|
129 |
+
# correction for the fingerprint density
|
130 |
+
# not in the original publication, added in version 1.1
|
131 |
+
# to make highly symmetrical molecules easier to synthetise
|
132 |
+
score3 = 0.
|
133 |
+
if nAtoms > len(fps):
|
134 |
+
score3 = math.log(float(nAtoms) / len(fps)) * .5
|
135 |
+
|
136 |
+
sascore = score1 + score2 + score3
|
137 |
+
|
138 |
+
# need to transform "raw" value into scale between 1 and 10
|
139 |
+
min = -4.0
|
140 |
+
max = 2.5
|
141 |
+
sascore = 11. - (sascore - min + 1) / (max - min) * 9.
|
142 |
+
# smooth the 10-end
|
143 |
+
if sascore > 8.:
|
144 |
+
sascore = 8. + math.log(sascore + 1. - 9.)
|
145 |
+
if sascore > 10.:
|
146 |
+
sascore = 10.0
|
147 |
+
elif sascore < 1.:
|
148 |
+
sascore = 1.0
|
149 |
+
|
150 |
+
return sascore
|
151 |
+
|