-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsmiles_cor.py
1291 lines (1151 loc) · 46.8 KB
/
smiles_cor.py
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import os
import pandas as pd
import random
from chembl_structure_pipeline import standardizer
from rdkit.Chem import MolStandardize
from rdkit import Chem
import time
import torch
import torch.nn as nn
from torchtext.data import TabularDataset, Field, BucketIterator, Iterator
import random
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import random
from torch import optim
import numpy as np
import itertools
import time
import statistics
from rdkit.Chem import GraphDescriptors, Lipinski, AllChem
from rdkit.Chem.rdSLNParse import MolFromSLN
from rdkit.Chem.rdmolfiles import MolFromSmiles
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
import numpy as np
from rdkit import rdBase, Chem
import re
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
SEED = 42
random.seed(SEED)
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
##################################################################################################
##################################################################################################
# #
# THIS SCRIPT IS DIRECTLY ADAPTED FROM https://github.com/LindeSchoenmaker/SMILES-corrector #
# #
##################################################################################################
##################################################################################################
def is_smiles(array,
TRG,
reverse: bool,
return_output=False,
src=None,
src_field=None):
"""Turns predicted tokens within batch into smiles and evaluates their validity
Arguments:
array: Tensor with most probable token for each location for each sequence in batch
[trg len, batch size]
TRG: target field for getting tokens from vocab
reverse (bool): True if the target sequence is reversed
return_output (bool): True if output sequences and their validity should be saved
Returns:
df: dataframe with correct and incorrect sequences
valids: list with booleans that show if prediction was a valid SMILES (True) or invalid one (False)
smiless: list of the predicted smiles
"""
trg_field = TRG
valids = []
smiless = []
if return_output:
df = pd.DataFrame()
else:
df = None
batch_size = array.size(1)
# check if the first token should be removed, first token is zero because
# outputs initaliazed to all be zeros
if int((array[0, 0]).tolist()) == 0:
start = 1
else:
start = 0
# for each sequence in the batch
for i in range(0, batch_size):
# turns sequence from tensor to list skipps first row as this is not
# filled in in forward
sequence = (array[start:, i]).tolist()
# goes from embedded to tokens
trg_tokens = [trg_field.vocab.itos[int(t)] for t in sequence]
# print(trg_tokens)
# takes all tokens untill eos token, model would be faster if did this
# one step earlier, but then changes in vocab order would disrupt.
rev_tokens = list(
itertools.takewhile(lambda x: x != "<eos>", trg_tokens))
if reverse:
rev_tokens = rev_tokens[::-1]
smiles = "".join(rev_tokens)
# determine how many valid smiles are made
valid = True if MolFromSmiles(smiles) else False
valids.append(valid)
smiless.append(smiles)
if return_output:
if valid:
df.loc[i, "CORRECT"] = smiles
else:
df.loc[i, "INCORRECT"] = smiles
# add the original drugex outputs to the _de dataframe
if return_output and src is not None:
for i in range(0, batch_size):
# turns sequence from tensor to list skipps first row as this is
# <sos> for src
sequence = (src[1:, i]).tolist()
# goes from embedded to tokens
src_tokens = [src_field.vocab.itos[int(t)] for t in sequence]
# takes all tokens untill eos token, model would be faster if did
# this one step earlier, but then changes in vocab order would
# disrupt.
rev_tokens = list(
itertools.takewhile(lambda x: x != "<eos>", src_tokens))
smiles = "".join(rev_tokens)
df.loc[i, "ORIGINAL"] = smiles
return df, valids, smiless
def is_unchanged(array,
TRG,
reverse: bool,
return_output=False,
src=None,
src_field=None):
"""Checks is output is different from input
Arguments:
array: Tensor with most probable token for each location for each sequence in batch
[trg len, batch size]
TRG: target field for getting tokens from vocab
reverse (bool): True if the target sequence is reversed
return_output (bool): True if output sequences and their validity should be saved
Returns:
df: dataframe with correct and incorrect sequences
valids: list with booleans that show if prediction was a valid SMILES (True) or invalid one (False)
smiless: list of the predicted smiles
"""
trg_field = TRG
sources = []
batch_size = array.size(1)
unchanged = 0
# check if the first token should be removed, first token is zero because
# outputs initaliazed to all be zeros
if int((array[0, 0]).tolist()) == 0:
start = 1
else:
start = 0
for i in range(0, batch_size):
# turns sequence from tensor to list skipps first row as this is <sos>
# for src
sequence = (src[1:, i]).tolist()
# goes from embedded to tokens
src_tokens = [src_field.vocab.itos[int(t)] for t in sequence]
# takes all tokens untill eos token, model would be faster if did this
# one step earlier, but then changes in vocab order would disrupt.
rev_tokens = list(
itertools.takewhile(lambda x: x != "<eos>", src_tokens))
smiles = "".join(rev_tokens)
sources.append(smiles)
# for each sequence in the batch
for i in range(0, batch_size):
# turns sequence from tensor to list skipps first row as this is not
# filled in in forward
sequence = (array[start:, i]).tolist()
# goes from embedded to tokens
trg_tokens = [trg_field.vocab.itos[int(t)] for t in sequence]
# print(trg_tokens)
# takes all tokens untill eos token, model would be faster if did this
# one step earlier, but then changes in vocab order would disrupt.
rev_tokens = list(
itertools.takewhile(lambda x: x != "<eos>", trg_tokens))
if reverse:
rev_tokens = rev_tokens[::-1]
smiles = "".join(rev_tokens)
# determine how many valid smiles are made
valid = True if MolFromSmiles(smiles) else False
if not valid:
if smiles == sources[i]:
unchanged += 1
return unchanged
def molecule_reconstruction(array, TRG, reverse: bool, outputs):
"""Turns target tokens within batch into smiles and compares them to predicted output smiles
Arguments:
array: Tensor with target's token for each location for each sequence in batch
[trg len, batch size]
TRG: target field for getting tokens from vocab
reverse (bool): True if the target sequence is reversed
outputs: list of predicted SMILES sequences
Returns:
matches(int): number of total right molecules
"""
trg_field = TRG
matches = 0
targets = []
batch_size = array.size(1)
# for each sequence in the batch
for i in range(0, batch_size):
# turns sequence from tensor to list skipps first row as this is not
# filled in in forward
sequence = (array[1:, i]).tolist()
# goes from embedded to tokens
trg_tokens = [trg_field.vocab.itos[int(t)] for t in sequence]
# takes all tokens untill eos token, model would be faster if did this
# one step earlier, but then changes in vocab order would disrupt.
rev_tokens = list(
itertools.takewhile(lambda x: x != "<eos>", trg_tokens))
if reverse:
rev_tokens = rev_tokens[::-1]
smiles = "".join(rev_tokens)
targets.append(smiles)
for i in range(0, batch_size):
m = MolFromSmiles(targets[i])
p = MolFromSmiles(outputs[i])
if p is not None:
if m.HasSubstructMatch(p) and p.HasSubstructMatch(m):
matches += 1
return matches
def complexity_whitlock(mol: Chem.Mol, includeAllDescs=False):
"""
Complexity as defined in DOI:10.1021/jo9814546
S: complexity = 4*#rings + 2*#unsat + #hetatm + 2*#chiral
Other descriptors:
H: size = #bonds (Hydrogen atoms included)
G: S + H
Ratio: S / H
"""
mol_ = Chem.Mol(mol)
nrings = Lipinski.RingCount(mol_) - Lipinski.NumAromaticRings(mol_)
Chem.rdmolops.SetAromaticity(mol_)
unsat = sum(1 for bond in mol_.GetBonds()
if bond.GetBondTypeAsDouble() == 2)
hetatm = len(mol_.GetSubstructMatches(Chem.MolFromSmarts("[!#6]")))
AllChem.EmbedMolecule(mol_)
Chem.AssignAtomChiralTagsFromStructure(mol_)
chiral = len(Chem.FindMolChiralCenters(mol_))
S = 4 * nrings + 2 * unsat + hetatm + 2 * chiral
if not includeAllDescs:
return S
Chem.rdmolops.Kekulize(mol_)
mol_ = Chem.AddHs(mol_)
H = sum(bond.GetBondTypeAsDouble() for bond in mol_.GetBonds())
G = S + H
R = S / H
return {"WhitlockS": S, "WhitlockH": H, "WhitlockG": G, "WhitlockRatio": R}
def complexity_baronechanon(mol: Chem.Mol):
"""
Complexity as defined in DOI:10.1021/ci000145p
"""
mol_ = Chem.Mol(mol)
Chem.Kekulize(mol_)
Chem.RemoveStereochemistry(mol_)
mol_ = Chem.RemoveHs(mol_, updateExplicitCount=True)
degree, counts = 0, 0
for atom in mol_.GetAtoms():
degree += 3 * 2**(atom.GetExplicitValence() - atom.GetNumExplicitHs() -
1)
counts += 3 if atom.GetSymbol() == "C" else 6
ringterm = sum(map(lambda x: 6 * len(x), mol_.GetRingInfo().AtomRings()))
return degree + counts + ringterm
def calc_complexity(array,
TRG,
reverse,
valids,
complexity_function=GraphDescriptors.BertzCT):
"""Calculates the complexity of inputs that are not correct.
Arguments:
array: Tensor with target's token for each location for each sequence in batch
[trg len, batch size]
TRG: target field for getting tokens from vocab
reverse (bool): True if the target sequence is reversed
valids: list with booleans that show if prediction was a valid SMILES (True) or invalid one (False)
complexity_function: the type of complexity measure that will be used
GraphDescriptors.BertzCT
complexity_whitlock
complexity_baronechanon
Returns:
matches(int): mean of complexity values
"""
trg_field = TRG
sources = []
complexities = []
loc = torch.BoolTensor(valids)
# only keeps rows in batch size dimension where valid is false
array = array[:, loc == False]
# should check if this still works
# array = torch.transpose(array, 0, 1)
array_size = array.size(1)
for i in range(0, array_size):
# turns sequence from tensor to list skipps first row as this is not
# filled in in forward
sequence = (array[1:, i]).tolist()
# goes from embedded to tokens
trg_tokens = [trg_field.vocab.itos[int(t)] for t in sequence]
# takes all tokens untill eos token, model would be faster if did this
# one step earlier, but then changes in vocab order would disrupt.
rev_tokens = list(
itertools.takewhile(lambda x: x != "<eos>", trg_tokens))
if reverse:
rev_tokens = rev_tokens[::-1]
smiles = "".join(rev_tokens)
sources.append(smiles)
for source in sources:
try:
m = MolFromSmiles(source)
except BaseException:
m = MolFromSLN(source)
complexities.append(complexity_function(m))
if len(complexities) > 0:
mean = statistics.mean(complexities)
else:
mean = 0
return mean
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
class Convo:
"""Class for training and evaluating transformer and convolutional neural network
Methods
-------
train_model()
train model for initialized number of epochs
evaluate(return_output)
use model with validation loader (& optionally drugex loader) to get test loss & other metrics
translate(loader)
translate inputs from loader (different from evaluate in that no target sequence is used)
"""
def train_model(self):
optimizer = optim.Adam(self.parameters(), lr=self.lr)
log = open(f"{self.out}.log", "a")
best_error = np.inf
for epoch in range(self.epochs):
self.train()
start_time = time.time()
loss_train = 0
for i, batch in enumerate(self.loader_train):
optimizer.zero_grad()
# changed src,trg call to match with bentrevett
# src, trg = batch['src'], batch['trg']
trg = batch.trg
src = batch.src
output, attention = self(src, trg[:, :-1])
# feed the source and target into def forward to get the output
# Xuhan uses forward for this, with istrain = true
output_dim = output.shape[-1]
# changed
output = output.contiguous().view(-1, output_dim)
trg = trg[:, 1:].contiguous().view(-1)
# output = output[:,:,0]#.view(-1)
# output = output[1:].view(-1, output.shape[-1])
# trg = trg[1:].view(-1)
loss = nn.CrossEntropyLoss(
ignore_index=self.TRG.vocab.stoi[self.TRG.pad_token])
a, b = output.view(-1), trg.to(self.device).view(-1)
# changed
# loss = loss(output.view(0), trg.view(0).to(device))
loss = loss(output, trg)
loss.backward()
torch.nn.utils.clip_grad_norm_(self.parameters(), self.clip)
optimizer.step()
loss_train += loss.item()
# turned off for now, as not using voc so won't work, output is a tensor
# output = [(trg len - 1) * batch size, output dim]
# smiles, valid = is_valid_smiles(output, reversed)
# if valid:
# valids += 1
# smiless.append(smiles)
# added .dataset becaue len(iterator) gives len(self.dataset) /
# self.batch_size)
loss_train /= len(self.loader_train)
info = f"Epoch: {epoch+1:02} step: {i} loss_train: {loss_train:.4g}"
# model is used to generate trg based on src from the validation set to assess performance
# similar to Xuhan, although he doesn't use the if loop
if self.loader_valid is not None:
return_output = False
if epoch + 1 == self.epochs:
return_output = True
(
valids,
loss_valid,
valids_de,
df_output,
df_output_de,
right_molecules,
complexity,
unchanged,
unchanged_de,
) = self.evaluate(return_output)
reconstruction_error = 1 - right_molecules / len(
self.loader_valid.dataset)
error = 1 - valids / len(self.loader_valid.dataset)
complexity = complexity / len(self.loader_valid)
unchan = unchanged / (len(self.loader_valid.dataset) - valids)
info += f" loss_valid: {loss_valid:.4g} error_rate: {error:.4g} molecule_reconstruction_error_rate: {reconstruction_error:.4g} unchanged: {unchan:.4g} invalid_target_complexity: {complexity:.4g}"
if self.loader_drugex is not None:
error_de = 1 - valids_de / len(self.loader_drugex.dataset)
unchan_de = unchanged_de / (
len(self.loader_drugex.dataset) - valids_de)
info += f" error_rate_drugex: {error_de:.4g} unchanged_drugex: {unchan_de:.4g}"
if reconstruction_error < best_error:
torch.save(self.state_dict(), f"{self.out}.pkg")
best_error = reconstruction_error
last_save = epoch
else:
if epoch - last_save >= 10 and best_error != 1:
torch.save(self.state_dict(), f"{self.out}_last.pkg")
(
valids,
loss_valid,
valids_de,
df_output,
df_output_de,
right_molecules,
complexity,
unchanged,
unchanged_de,
) = self.evaluate(True)
end_time = time.time()
epoch_mins, epoch_secs = epoch_time(
start_time, end_time)
info += f" Time: {epoch_mins}m {epoch_secs}s"
break
elif error < best_error:
torch.save(self.state_dict(), f"{self.out}.pkg")
best_error = error
end_time = time.time()
epoch_mins, epoch_secs = epoch_time(start_time, end_time)
info += f" Time: {epoch_mins}m {epoch_secs}s"
torch.save(self.state_dict(), f"{self.out}_last.pkg")
log.close()
self.load_state_dict(torch.load(f"{self.out}.pkg"))
df_output.to_csv(f"{self.out}.csv", index=False)
df_output_de.to_csv(f"{self.out}_de.csv", index=False)
def evaluate(self, return_output):
self.eval()
test_loss = 0
df_output = pd.DataFrame()
df_output_de = pd.DataFrame()
valids = 0
valids_de = 0
unchanged = 0
unchanged_de = 0
right_molecules = 0
complexity = 0
with torch.no_grad():
for _, batch in enumerate(self.loader_valid):
trg = batch.trg
src = batch.src
output, attention = self.forward(src, trg[:, :-1])
pred_token = output.argmax(2)
array = torch.transpose(pred_token, 0, 1)
trg_trans = torch.transpose(trg, 0, 1)
output_dim = output.shape[-1]
output = output.contiguous().view(-1, output_dim)
trg = trg[:, 1:].contiguous().view(-1)
src_trans = torch.transpose(src, 0, 1)
df_batch, valid, smiless = is_smiles(
array, self.TRG, reverse=True, return_output=return_output)
unchanged += is_unchanged(
array,
self.TRG,
reverse=True,
return_output=return_output,
src=src_trans,
src_field=self.SRC,
)
matches = molecule_reconstruction(trg_trans,
self.TRG,
reverse=True,
outputs=smiless)
complexity += calc_complexity(trg_trans,
self.TRG,
reverse=True,
valids=valid)
if df_batch is not None:
df_output = pd.concat([df_output, df_batch],
ignore_index=True)
right_molecules += matches
valids += sum(valid)
# trg = trg[1:].view(-1)
# output, trg = output[1:].view(-1, output.shape[-1]), trg[1:].view(-1)
loss = nn.CrossEntropyLoss(
ignore_index=self.TRG.vocab.stoi[self.TRG.pad_token])
loss = loss(output, trg)
test_loss += loss.item()
if self.loader_drugex is not None:
for _, batch in enumerate(self.loader_drugex):
src = batch.src
output = self.translate_sentence(src, self.TRG,
self.device)
# checks the number of valid smiles
pred_token = output.argmax(2)
array = torch.transpose(pred_token, 0, 1)
src_trans = torch.transpose(src, 0, 1)
df_batch, valid, smiless = is_smiles(
array,
self.TRG,
reverse=True,
return_output=return_output,
src=src_trans,
src_field=self.SRC,
)
unchanged_de += is_unchanged(
array,
self.TRG,
reverse=True,
return_output=return_output,
src=src_trans,
src_field=self.SRC,
)
if df_batch is not None:
df_output_de = pd.concat([df_output_de, df_batch],
ignore_index=True)
valids_de += sum(valid)
return (
valids,
test_loss / len(self.loader_valid),
valids_de,
df_output,
df_output_de,
right_molecules,
complexity,
unchanged,
unchanged_de,
)
def translate(self, loader):
self.eval()
df_output_de = pd.DataFrame()
valids_de = 0
with torch.no_grad():
for _, batch in enumerate(loader):
src = batch.src
output = self.translate_sentence(src, self.TRG, self.device)
# checks the number of valid smiles
pred_token = output.argmax(2)
array = torch.transpose(pred_token, 0, 1)
src_trans = torch.transpose(src, 0, 1)
df_batch, valid, smiless = is_smiles(
array,
self.TRG,
reverse=True,
return_output=True,
src=src_trans,
src_field=self.SRC,
)
if df_batch is not None:
df_output_de = pd.concat([df_output_de, df_batch],
ignore_index=True)
valids_de += sum(valid)
return valids_de, df_output_de
class Encoder(nn.Module):
def __init__(self, input_dim, hid_dim, n_layers, n_heads, pf_dim, dropout,
max_length, device):
super().__init__()
self.device = device
self.tok_embedding = nn.Embedding(input_dim, hid_dim)
self.pos_embedding = nn.Embedding(max_length, hid_dim)
self.layers = nn.ModuleList([
EncoderLayer(hid_dim, n_heads, pf_dim, dropout, device)
for _ in range(n_layers)
])
self.dropout = nn.Dropout(dropout)
self.scale = torch.sqrt(torch.FloatTensor([hid_dim])).to(device)
def forward(self, src, src_mask):
# src = [batch size, src len]
# src_mask = [batch size, src len]
batch_size = src.shape[0]
src_len = src.shape[1]
pos = (torch.arange(0, src_len).unsqueeze(0).repeat(batch_size,
1).to(self.device))
# pos = [batch size, src len]
src = self.dropout((self.tok_embedding(src) * self.scale) +
self.pos_embedding(pos))
# src = [batch size, src len, hid dim]
for layer in self.layers:
src = layer(src, src_mask)
# src = [batch size, src len, hid dim]
return src
class EncoderLayer(nn.Module):
def __init__(self, hid_dim, n_heads, pf_dim, dropout, device):
super().__init__()
self.self_attn_layer_norm = nn.LayerNorm(hid_dim)
self.ff_layer_norm = nn.LayerNorm(hid_dim)
self.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads,
dropout, device)
self.positionwise_feedforward = PositionwiseFeedforwardLayer(
hid_dim, pf_dim, dropout)
self.dropout = nn.Dropout(dropout)
def forward(self, src, src_mask):
# src = [batch size, src len, hid dim]
# src_mask = [batch size, src len]
# self attention
_src, _ = self.self_attention(src, src, src, src_mask)
# dropout, residual connection and layer norm
src = self.self_attn_layer_norm(src + self.dropout(_src))
# src = [batch size, src len, hid dim]
# positionwise feedforward
_src = self.positionwise_feedforward(src)
# dropout, residual and layer norm
src = self.ff_layer_norm(src + self.dropout(_src))
# src = [batch size, src len, hid dim]
return src
class MultiHeadAttentionLayer(nn.Module):
def __init__(self, hid_dim, n_heads, dropout, device):
super().__init__()
assert hid_dim % n_heads == 0
self.hid_dim = hid_dim
self.n_heads = n_heads
self.head_dim = hid_dim // n_heads
self.fc_q = nn.Linear(hid_dim, hid_dim)
self.fc_k = nn.Linear(hid_dim, hid_dim)
self.fc_v = nn.Linear(hid_dim, hid_dim)
self.fc_o = nn.Linear(hid_dim, hid_dim)
self.dropout = nn.Dropout(dropout)
self.scale = torch.sqrt(torch.FloatTensor([self.head_dim])).to(device)
def forward(self, query, key, value, mask=None):
batch_size = query.shape[0]
# query = [batch size, query len, hid dim]
# key = [batch size, key len, hid dim]
# value = [batch size, value len, hid dim]
Q = self.fc_q(query)
K = self.fc_k(key)
V = self.fc_v(value)
# Q = [batch size, query len, hid dim]
# K = [batch size, key len, hid dim]
# V = [batch size, value len, hid dim]
Q = Q.view(batch_size, -1, self.n_heads,
self.head_dim).permute(0, 2, 1, 3)
K = K.view(batch_size, -1, self.n_heads,
self.head_dim).permute(0, 2, 1, 3)
V = V.view(batch_size, -1, self.n_heads,
self.head_dim).permute(0, 2, 1, 3)
# Q = [batch size, n heads, query len, head dim]
# K = [batch size, n heads, key len, head dim]
# V = [batch size, n heads, value len, head dim]
energy = torch.matmul(Q, K.permute(0, 1, 3, 2)) / self.scale
# energy = [batch size, n heads, query len, key len]
if mask is not None:
energy = energy.masked_fill(mask == 0, -1e10)
attention = torch.softmax(energy, dim=-1)
# attention = [batch size, n heads, query len, key len]
x = torch.matmul(self.dropout(attention), V)
# x = [batch size, n heads, query len, head dim]
x = x.permute(0, 2, 1, 3).contiguous()
# x = [batch size, query len, n heads, head dim]
x = x.view(batch_size, -1, self.hid_dim)
# x = [batch size, query len, hid dim]
x = self.fc_o(x)
# x = [batch size, query len, hid dim]
return x, attention
class PositionwiseFeedforwardLayer(nn.Module):
def __init__(self, hid_dim, pf_dim, dropout):
super().__init__()
self.fc_1 = nn.Linear(hid_dim, pf_dim)
self.fc_2 = nn.Linear(pf_dim, hid_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
# x = [batch size, seq len, hid dim]
x = self.dropout(torch.relu(self.fc_1(x)))
# x = [batch size, seq len, pf dim]
x = self.fc_2(x)
# x = [batch size, seq len, hid dim]
return x
class Decoder(nn.Module):
def __init__(
self,
output_dim,
hid_dim,
n_layers,
n_heads,
pf_dim,
dropout,
max_length,
device,
):
super().__init__()
self.device = device
self.tok_embedding = nn.Embedding(output_dim, hid_dim)
self.pos_embedding = nn.Embedding(max_length, hid_dim)
self.layers = nn.ModuleList([
DecoderLayer(hid_dim, n_heads, pf_dim, dropout, device)
for _ in range(n_layers)
])
self.fc_out = nn.Linear(hid_dim, output_dim)
self.dropout = nn.Dropout(dropout)
self.scale = torch.sqrt(torch.FloatTensor([hid_dim])).to(device)
def forward(self, trg, enc_src, trg_mask, src_mask):
# trg = [batch size, trg len]
# enc_src = [batch size, src len, hid dim]
# trg_mask = [batch size, trg len]
# src_mask = [batch size, src len]
batch_size = trg.shape[0]
trg_len = trg.shape[1]
pos = (torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size,
1).to(self.device))
# pos = [batch size, trg len]
trg = self.dropout((self.tok_embedding(trg) * self.scale) +
self.pos_embedding(pos))
# trg = [batch size, trg len, hid dim]
for layer in self.layers:
trg, attention = layer(trg, enc_src, trg_mask, src_mask)
# trg = [batch size, trg len, hid dim]
# attention = [batch size, n heads, trg len, src len]
output = self.fc_out(trg)
# output = [batch size, trg len, output dim]
return output, attention
class DecoderLayer(nn.Module):
def __init__(self, hid_dim, n_heads, pf_dim, dropout, device):
super().__init__()
self.self_attn_layer_norm = nn.LayerNorm(hid_dim)
self.enc_attn_layer_norm = nn.LayerNorm(hid_dim)
self.ff_layer_norm = nn.LayerNorm(hid_dim)
self.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads,
dropout, device)
self.encoder_attention = MultiHeadAttentionLayer(
hid_dim, n_heads, dropout, device)
self.positionwise_feedforward = PositionwiseFeedforwardLayer(
hid_dim, pf_dim, dropout)
self.dropout = nn.Dropout(dropout)
def forward(self, trg, enc_src, trg_mask, src_mask):
# trg = [batch size, trg len, hid dim]
# enc_src = [batch size, src len, hid dim]
# trg_mask = [batch size, trg len]
# src_mask = [batch size, src len]
# self attention
_trg, _ = self.self_attention(trg, trg, trg, trg_mask)
# dropout, residual connection and layer norm
trg = self.self_attn_layer_norm(trg + self.dropout(_trg))
# trg = [batch size, trg len, hid dim]
# encoder attention
_trg, attention = self.encoder_attention(trg, enc_src, enc_src,
src_mask)
# dropout, residual connection and layer norm
trg = self.enc_attn_layer_norm(trg + self.dropout(_trg))
# trg = [batch size, trg len, hid dim]
# positionwise feedforward
_trg = self.positionwise_feedforward(trg)
# dropout, residual and layer norm
trg = self.ff_layer_norm(trg + self.dropout(_trg))
# trg = [batch size, trg len, hid dim]
# attention = [batch size, n heads, trg len, src len]
return trg, attention
class Seq2Seq(nn.Module, Convo):
def __init__(
self,
encoder,
decoder,
src_pad_idx,
trg_pad_idx,
device,
loader_train: DataLoader,
out: str,
loader_valid=None,
loader_drugex=None,
epochs=100,
lr=0.0005,
clip=0.1,
reverse=True,
TRG=None,
SRC=None,
):
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.src_pad_idx = src_pad_idx
self.trg_pad_idx = trg_pad_idx
self.device = device
self.loader_train = loader_train
self.out = out
self.loader_valid = loader_valid
self.loader_drugex = loader_drugex
self.epochs = epochs
self.lr = lr
self.clip = clip
self.reverse = reverse
self.TRG = TRG
self.SRC = SRC
def make_src_mask(self, src):
# src = [batch size, src len]
src_mask = (src != self.src_pad_idx).unsqueeze(1).unsqueeze(2)
# src_mask = [batch size, 1, 1, src len]
return src_mask
def make_trg_mask(self, trg):
# trg = [batch size, trg len]
trg_pad_mask = (trg != self.trg_pad_idx).unsqueeze(1).unsqueeze(2)
# trg_pad_mask = [batch size, 1, 1, trg len]
trg_len = trg.shape[1]
trg_sub_mask = torch.tril(
torch.ones((trg_len, trg_len), device=self.device)).bool()
# trg_sub_mask = [trg len, trg len]
trg_mask = trg_pad_mask & trg_sub_mask
# trg_mask = [batch size, 1, trg len, trg len]
return trg_mask
def forward(self, src, trg):
# src = [batch size, src len]
# trg = [batch size, trg len]
src_mask = self.make_src_mask(src)
trg_mask = self.make_trg_mask(trg)
# src_mask = [batch size, 1, 1, src len]
# trg_mask = [batch size, 1, trg len, trg len]
enc_src = self.encoder(src, src_mask)
# enc_src = [batch size, src len, hid dim]
output, attention = self.decoder(trg, enc_src, trg_mask, src_mask)
# output = [batch size, trg len, output dim]
# attention = [batch size, n heads, trg len, src len]
return output, attention
def translate_sentence(self, src, trg_field, device, max_len=202):
self.eval()
src_mask = self.make_src_mask(src)
with torch.no_grad():
enc_src = self.encoder(src, src_mask)
trg_indexes = [trg_field.vocab.stoi[trg_field.init_token]]
batch_size = src.shape[0]
trg = torch.LongTensor(trg_indexes).unsqueeze(0).to(device)
trg = trg.repeat(batch_size, 1)
for i in range(max_len):
# turned model into self.
trg_mask = self.make_trg_mask(trg)
with torch.no_grad():
output, attention = self.decoder(trg, enc_src, trg_mask,
src_mask)
pred_tokens = output.argmax(2)[:, -1].unsqueeze(1)
trg = torch.cat((trg, pred_tokens), 1)
return output
def remove_floats(df: pd.DataFrame, subset: str):
"""Preprocessing step to remove any entries that are not strings"""
df_subset = df[subset]
df[subset] = df[subset].astype(str)
# only keep entries that stayed the same after applying astype str
df = df[df[subset] == df_subset].copy()
return df
def smi_tokenizer(smi: str, reverse=False) -> list:
"""
Tokenize a SMILES molecule
"""
pattern = r"(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])"
regex = re.compile(pattern)
# tokens = ['<sos>'] + [token for token in regex.findall(smi)] + ['<eos>']
tokens = [token for token in regex.findall(smi)]
# assert smi == ''.join(tokens[1:-1])
assert smi == "".join(tokens[:])
# try:
# assert smi == "".join(tokens[:])
# except:
# print(smi)
# print("".join(tokens[:]))
if reverse:
return tokens[::-1]
return tokens
def init_weights(m: nn.Module):
if hasattr(m, "weight") and m.weight.dim() > 1:
nn.init.xavier_uniform_(m.weight.data)
def count_parameters(model: nn.Module):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
def initialize_model(folder_out: str,
data_source: str,
error_source: str,
device: torch.device,
threshold: int,
epochs: int,
layers: int = 3,
batch_size: int = 16,
invalid_type: str = "all",
num_errors: int = 1,
validation_step=False):
"""Create encoder decoder models for specified model (currently only translator) & type of invalid SMILES
param data: collection of invalid, valid SMILES pairs
param invalid_smiles_path: path to previously generated invalid SMILES
param invalid_type: type of errors introduced into invalid SMILES
return:
"""
# set fields
SRC = Field(
tokenize=lambda x: smi_tokenizer(x),
init_token="<sos>",
eos_token="<eos>",
batch_first=True,
)
TRG = Field(
tokenize=lambda x: smi_tokenizer(x, reverse=True),
init_token="<sos>",
eos_token="<eos>",
batch_first=True,
)
if validation_step:
train, val = TabularDataset.splits(
path=f'{folder_out}errors/split/',
train=f"{data_source}_{invalid_type}_{num_errors}_errors_train.csv",
validation=
f"{data_source}_{invalid_type}_{num_errors}_errors_dev.csv",
format="CSV",
skip_header=False,
fields={
"ERROR": ("src", SRC),
"STD_SMILES": ("trg", TRG)
},
)
SRC.build_vocab(train, val, max_size=1000)
TRG.build_vocab(train, val, max_size=1000)
else:
train = TabularDataset(
path=
f'{folder_out}{data_source}_{invalid_type}_{num_errors}_errors.csv',
format="CSV",
skip_header=False,
fields={
"ERROR": ("src", SRC),
"STD_SMILES": ("trg", TRG)
},
)
SRC.build_vocab(train, max_size=1000)
TRG.build_vocab(train, max_size=1000)