Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

scores.py 7.6 KB

You have to be logged in to leave a comment. Sign In
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
  1. from typing import Any, Dict, List, Optional
  2. import numpy as np
  3. from rdkit import Chem
  4. from rdkit.Chem import AllChem, DataStructs
  5. from molbart.utils import smiles_utils
  6. class BaseScore:
  7. """
  8. Base scoring class.
  9. """
  10. scorer_name = "base"
  11. def __init__(self, **kwargs: Any):
  12. return
  13. def __call__(self, sampled_smiles: List[List[str]], target_smiles: Optional[List[str]] = None) -> Dict[str, float]:
  14. return self._score_sampled_smiles(sampled_smiles, target_smiles)
  15. def __repr__(self):
  16. repr_name = self.scorer_name
  17. return repr_name
  18. def _score_sampled_smiles(
  19. self, sampled_smiles: List[List[str]], target_smiles: Optional[List[str]] = None
  20. ) -> Dict[str, Any]:
  21. """Scoring function which should be implemented in each new Score class."""
  22. raise NotImplementedError("self._score_sampled_smiles() needs to be implemented for every scoring class.")
  23. class FractionInvalidScore(BaseScore):
  24. """
  25. Scoring using fraction of invalid of all or top-1 SMILES.
  26. """
  27. scorer_name = "fraction_invalid"
  28. def __init__(self, only_top1: bool = False):
  29. """
  30. Args:
  31. only_top1: If True, will only compute fraction of invalid top-1 SMILES,
  32. otherwise fraction invalid is over all generated SMILES.
  33. """
  34. super().__init__()
  35. self.only_top1 = only_top1
  36. def _score_sampled_smiles(
  37. self, sampled_smiles: List[List[str]], target_smiles: Optional[List[str]] = None
  38. ) -> Dict[str, float]:
  39. """Computing fraction of invalid SMILES."""
  40. if self.only_top1:
  41. is_valid = [
  42. bool(Chem.MolFromSmiles(top_k_smiles[0])) if len(top_k_smiles) > 0 else False
  43. for top_k_smiles in sampled_smiles
  44. ]
  45. else:
  46. is_valid = []
  47. for top_k_smiles in sampled_smiles:
  48. for smiles in top_k_smiles:
  49. is_valid.append(bool(Chem.MolFromSmiles(smiles)))
  50. fraction_invalid = 1 - (sum(is_valid) / len(is_valid))
  51. return {self.scorer_name: fraction_invalid}
  52. class FractionUniqueScore(BaseScore):
  53. """
  54. Scoring using the fraction of uniquely sampled SMILES among the top-N sampled SMILES.
  55. """
  56. scorer_name = "fraction_unique"
  57. def __init__(self, canonicalized: bool = False, only_valid: bool=True):
  58. """
  59. Args:
  60. canonicalized: whether the sampled_smiles and target_smiles are
  61. been canonicalized.
  62. only_valid: whether to only consider valid SMILES yielding molecules.
  63. """
  64. super().__init__()
  65. self._canonicalized = canonicalized
  66. self._only_valid = only_valid
  67. def _score_sampled_smiles(
  68. self, sampled_smiles: List[List[str]], target_smiles: Optional[List[str]] = None
  69. ) -> Dict[str, float]:
  70. """Computing fraction of unique top-N SMILES."""
  71. n_samples = len(sampled_smiles)
  72. n_beams = len(sampled_smiles[0])
  73. n_unique_total = 0
  74. for top_k in sampled_smiles:
  75. if not self._canonicalized:
  76. if self._only_valid:
  77. top_k = [smiles_utils.inchi_key(smiles) for smiles in top_k if Chem.MolFromSmiles(smiles)]
  78. else:
  79. top_k = [smiles_utils.inchi_key(smiles) for smiles in top_k]
  80. elif self._only_valid:
  81. top_k = [smiles for smiles in top_k if Chem.MolFromSmiles(smiles)]
  82. n_unique = len(set(top_k))
  83. n_unique_total += n_unique
  84. fraction_unique = n_unique_total / (n_beams * n_samples)
  85. return {self.scorer_name: fraction_unique}
  86. class TanimotoSimilarityScore(BaseScore):
  87. """
  88. Scoring using the Tanomoto similarity of the top-1 sampled SMILES and the target
  89. SMILES.
  90. """
  91. scorer_name = "top1_tanimoto_similarity"
  92. def __init__(self, statistics="mean"):
  93. """
  94. Args:
  95. return_strategy: ["mean", "median", "all"], returns the average similarity or
  96. all similarities.
  97. """
  98. super().__init__()
  99. if statistics not in ["mean", "median", "all"]:
  100. raise ValueError(f"'statistics' should be either 'mean', 'median' or 'all'," f" not {statistics}")
  101. self._statistics = statistics
  102. self._stat_fcn = {"mean": np.mean, "median": np.median}
  103. def _get_statistics(self, similarities: np.ndarray) -> float:
  104. if self._statistics == "all":
  105. return [similarities]
  106. similarities = similarities[~np.isnan(similarities)]
  107. return self._stat_fcn[self._statistics](similarities)
  108. def _score_sampled_smiles(
  109. self, sampled_smiles: List[List[str]], target_smiles: Optional[List[str]] = None
  110. ) -> Dict[str, Any]:
  111. """
  112. Compute similarities of ECPF4 fingerprints of target and top-1 sampled molecules.
  113. """
  114. target_molecules = [Chem.MolFromSmiles(smiles) for smiles in target_smiles]
  115. sampled_molecules = [
  116. Chem.MolFromSmiles(smiles_list[0]) if len(smiles_list) > 0 else None for smiles_list in sampled_smiles
  117. ]
  118. n_samples = len(target_molecules)
  119. similarities = np.nan * np.ones(n_samples)
  120. counter = 0
  121. for sampled_mol, target_mol in zip(sampled_molecules, target_molecules):
  122. if not sampled_mol or not target_mol:
  123. counter += 1
  124. continue
  125. fp1 = AllChem.GetMorganFingerprint(sampled_mol, 2)
  126. fp2 = AllChem.GetMorganFingerprint(target_mol, 2)
  127. similarities[counter] = DataStructs.TanimotoSimilarity(fp1, fp2) # Tanimoto similarity = Jaccard similarity
  128. counter += 1
  129. return {self.scorer_name: self._get_statistics(similarities)}
  130. class TopKAccuracyScore(BaseScore):
  131. scorer_name = "top_k_accuracy"
  132. def __init__(
  133. self,
  134. top_ks: np.ndarray = np.array([1, 3, 5, 10, 20, 30, 40, 50]),
  135. canonicalized: bool = False,
  136. ):
  137. """
  138. Args:
  139. top_ks: a list of top-Ks to compute accuracy for.
  140. canonicalized: whether the sampled_smiles and target_smiles are
  141. been canonicalized.
  142. """
  143. super().__init__()
  144. self._top_ks = top_ks
  145. self._canonicalized = canonicalized
  146. def _is_in_set(self, sampled_smiles: List[List[str]], target_smiles: List[str], k: int) -> np.ndarray:
  147. if not self._canonicalized:
  148. target_smiles = [smiles_utils.canonicalize_smiles(smiles) for smiles in target_smiles]
  149. sampled_smiles = [
  150. [smiles_utils.canonicalize_smiles(smiles) for smiles in smiles_list] for smiles_list in sampled_smiles
  151. ]
  152. is_in_set = [
  153. tgt_smi in sampled_smi[0:k] if len(sampled_smi[0:k]) > 0 else False
  154. for sampled_smi, tgt_smi in zip(sampled_smiles, target_smiles)
  155. ]
  156. return is_in_set
  157. def _score_sampled_smiles(self, sampled_smiles: List[List[str]], target_smiles: List[str]) -> Dict[str, float]:
  158. n_beams = np.max(np.array([1, np.max(np.asarray([len(smiles) for smiles in sampled_smiles]))]))
  159. top_ks = self._top_ks[self._top_ks <= n_beams]
  160. columns = []
  161. is_in_set = np.zeros((len(sampled_smiles), len(top_ks)), dtype=bool)
  162. for i_k, k in enumerate(top_ks):
  163. columns.append(f"accuracy_top_{k}")
  164. is_in_set[:, i_k] = self._is_in_set(sampled_smiles, target_smiles, k)
  165. is_in_set = np.cumsum(is_in_set, axis=1)
  166. top_n_accuracy = np.mean(is_in_set > 0, axis=0)
  167. if max(top_ks) == 1:
  168. return {"accuracy": top_n_accuracy[0]}
  169. scores = {col: accuracy for col, accuracy in zip(columns, top_n_accuracy)}
  170. return scores
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...