-
Notifications
You must be signed in to change notification settings - Fork 9
/
loader.py
executable file
·2011 lines (1765 loc) · 79.1 KB
/
loader.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 os
import torch
import pickle
import collections
import math
import pandas as pd
import numpy as np
import networkx as nx
import random
from rdkit import Chem
from rdkit.Chem import Descriptors
from rdkit.Chem import AllChem
from rdkit import DataStructs
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprintAsBitVect
from torch.utils import data
from torch_geometric.data import Data
from torch_geometric.data import InMemoryDataset
from torch_geometric.data import Batch
from itertools import repeat, product, chain
num_atom_type = 120 #including the extra mask tokens=119
num_chirality_tag = 3 # original =3. including the extra mask tokens=3
num_bond_type = 6 #including aromatic and self-loop edge, and extra masked tokens
num_bond_direction = 3 # original =3, inlcuding the extra mask tokens=3
# allowable node and edge features
allowable_features = {
'possible_atomic_num_list' : list(range(1, 119)),
'possible_formal_charge_list' : [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
'possible_chirality_list' : [
Chem.rdchem.ChiralType.CHI_UNSPECIFIED,
Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CW,
Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CCW,
Chem.rdchem.ChiralType.CHI_OTHER
],
'possible_hybridization_list' : [
Chem.rdchem.HybridizationType.S,
Chem.rdchem.HybridizationType.SP, Chem.rdchem.HybridizationType.SP2,
Chem.rdchem.HybridizationType.SP3, Chem.rdchem.HybridizationType.SP3D,
Chem.rdchem.HybridizationType.SP3D2, Chem.rdchem.HybridizationType.UNSPECIFIED
],
'possible_numH_list' : [0, 1, 2, 3, 4, 5, 6, 7, 8],
'possible_implicit_valence_list' : [0, 1, 2, 3, 4, 5, 6],
'possible_degree_list' : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'possible_bonds' : [
Chem.rdchem.BondType.SINGLE,
Chem.rdchem.BondType.DOUBLE,
Chem.rdchem.BondType.TRIPLE,
Chem.rdchem.BondType.AROMATIC
],
'possible_bond_dirs' : [ # only for double bond stereo information
Chem.rdchem.BondDir.NONE,
Chem.rdchem.BondDir.ENDUPRIGHT,
Chem.rdchem.BondDir.ENDDOWNRIGHT
]
}
def mol_to_graph_data_obj_simple(mol):
"""
Converts rdkit mol object to graph Data object required by the pytorch
geometric package. NB: Uses simplified atom and bond features, and represent
as indices
:param mol: rdkit mol object
:return: graph data object with the attributes: x, edge_index, edge_attr
"""
# atoms
num_atom_features = 2 # atom type, chirality tag
atom_features_list = []
for atom in mol.GetAtoms():
atom_feature = [allowable_features['possible_atomic_num_list'].index(
atom.GetAtomicNum())] + [allowable_features[
'possible_chirality_list'].index(atom.GetChiralTag())]
atom_features_list.append(atom_feature)
x = torch.tensor(np.array(atom_features_list), dtype=torch.long)
# bonds
num_bond_features = 2 # bond type, bond direction
if len(mol.GetBonds()) > 0: # mol has bonds
edges_list = []
edge_features_list = []
for bond in mol.GetBonds():
i = bond.GetBeginAtomIdx()
j = bond.GetEndAtomIdx()
edge_feature = [allowable_features['possible_bonds'].index(
bond.GetBondType())] + [allowable_features[
'possible_bond_dirs'].index(
bond.GetBondDir())]
edges_list.append((i, j))
edge_features_list.append(edge_feature)
edges_list.append((j, i))
edge_features_list.append(edge_feature)
# data.edge_index: Graph connectivity in COO format with shape [2, num_edges]
edge_index = torch.tensor(np.array(edges_list).T, dtype=torch.long)
# data.edge_attr: Edge feature matrix with shape [num_edges, num_edge_features]
edge_attr = torch.tensor(np.array(edge_features_list),
dtype=torch.long)
else: # mol has no bonds
edge_index = torch.empty((2, 0), dtype=torch.long)
edge_attr = torch.empty((0, num_bond_features), dtype=torch.long)
data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr)
return data
def graph_data_obj_to_mol_simple(data_x, data_edge_index, data_edge_attr):
"""
Convert pytorch geometric data obj to rdkit mol object. NB: Uses simplified
atom and bond features, and represent as indices.
:param: data_x:
:param: data_edge_index:
:param: data_edge_attr
:return:
"""
mol = Chem.RWMol()
# atoms
atom_features = data_x.cpu().numpy()
num_atoms = atom_features.shape[0]
for i in range(num_atoms):
atomic_num_idx, chirality_tag_idx = atom_features[i]
atomic_num = allowable_features['possible_atomic_num_list'][atomic_num_idx]
chirality_tag = allowable_features['possible_chirality_list'][chirality_tag_idx]
atom = Chem.Atom(atomic_num)
atom.SetChiralTag(chirality_tag)
mol.AddAtom(atom)
# bonds
edge_index = data_edge_index.cpu().numpy()
edge_attr = data_edge_attr.cpu().numpy()
num_bonds = edge_index.shape[1]
for j in range(0, num_bonds, 2):
begin_idx = int(edge_index[0, j])
end_idx = int(edge_index[1, j])
bond_type_idx, bond_dir_idx = edge_attr[j]
bond_type = allowable_features['possible_bonds'][bond_type_idx]
bond_dir = allowable_features['possible_bond_dirs'][bond_dir_idx]
mol.AddBond(begin_idx, end_idx, bond_type)
# set bond direction
new_bond = mol.GetBondBetweenAtoms(begin_idx, end_idx)
new_bond.SetBondDir(bond_dir)
# Chem.SanitizeMol(mol) # fails for COC1=CC2=C(NC(=N2)[S@@](=O)CC2=NC=C(
# C)C(OC)=C2C)C=C1, when aromatic bond is possible
# when we do not have aromatic bonds
# Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_KEKULIZE)
return mol
def graph_data_obj_to_nx_simple(data):
"""
Converts graph Data object required by the pytorch geometric package to
network x data object. NB: Uses simplified atom and bond features,
and represent as indices. NB: possible issues with recapitulating relative
stereochemistry since the edges in the nx object are unordered.
:param data: pytorch geometric Data object
:return: network x object
"""
G = nx.Graph()
# atoms
atom_features = data.x.cpu().numpy()
num_atoms = atom_features.shape[0]
for i in range(num_atoms):
atomic_num_idx, chirality_tag_idx = atom_features[i]
G.add_node(i, atom_num_idx=atomic_num_idx, chirality_tag_idx=chirality_tag_idx)
pass
# bonds
edge_index = data.edge_index.cpu().numpy()
edge_attr = data.edge_attr.cpu().numpy()
num_bonds = edge_index.shape[1]
for j in range(0, num_bonds, 2):
begin_idx = int(edge_index[0, j])
end_idx = int(edge_index[1, j])
bond_type_idx, bond_dir_idx = edge_attr[j]
if not G.has_edge(begin_idx, end_idx):
G.add_edge(begin_idx, end_idx, bond_type_idx=bond_type_idx,
bond_dir_idx=bond_dir_idx)
return G
def nx_to_graph_data_obj_simple(G):
"""
Converts nx graph to pytorch geometric Data object. Assume node indices
are numbered from 0 to num_nodes - 1. NB: Uses simplified atom and bond
features, and represent as indices. NB: possible issues with
recapitulating relative stereochemistry since the edges in the nx
object are unordered.
:param G: nx graph obj
:return: pytorch geometric Data object
"""
# atoms
num_atom_features = 2 # atom type, chirality tag
atom_features_list = []
for _, node in G.nodes(data=True):
atom_feature = [node['atom_num_idx'], node['chirality_tag_idx']]
atom_features_list.append(atom_feature)
x = torch.tensor(np.array(atom_features_list), dtype=torch.long)
# bonds
num_bond_features = 2 # bond type, bond direction
if len(G.edges()) > 0: # mol has bonds
edges_list = []
edge_features_list = []
for i, j, edge in G.edges(data=True):
edge_feature = [edge['bond_type_idx'], edge['bond_dir_idx']]
edges_list.append((i, j))
edge_features_list.append(edge_feature)
edges_list.append((j, i))
edge_features_list.append(edge_feature)
# data.edge_index: Graph connectivity in COO format with shape [2, num_edges]
edge_index = torch.tensor(np.array(edges_list).T, dtype=torch.long)
# data.edge_attr: Edge feature matrix with shape [num_edges, num_edge_features]
edge_attr = torch.tensor(np.array(edge_features_list),
dtype=torch.long)
else: # mol has no bonds
edge_index = torch.empty((2, 0), dtype=torch.long)
edge_attr = torch.empty((0, num_bond_features), dtype=torch.long)
data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr)
return data
def get_gasteiger_partial_charges(mol, n_iter=12):
"""
Calculates list of gasteiger partial charges for each atom in mol object.
:param mol: rdkit mol object
:param n_iter: number of iterations. Default 12
:return: list of computed partial charges for each atom.
"""
Chem.rdPartialCharges.ComputeGasteigerCharges(mol, nIter=n_iter,
throwOnParamFailure=True)
partial_charges = [float(a.GetProp('_GasteigerCharge')) for a in
mol.GetAtoms()]
return partial_charges
def create_standardized_mol_id(smiles):
"""
:param smiles:
:return: inchi
"""
if check_smiles_validity(smiles):
# remove stereochemistry
smiles = AllChem.MolToSmiles(AllChem.MolFromSmiles(smiles),
isomericSmiles=False)
mol = AllChem.MolFromSmiles(smiles)
if mol != None: # to catch weird issue with O=C1O[al]2oc(=O)c3ccc(cn3)c3ccccc3c3cccc(c3)c3ccccc3c3cc(C(F)(F)F)c(cc3o2)-c2ccccc2-c2cccc(c2)-c2ccccc2-c2cccnc21
if '.' in smiles: # if multiple species, pick largest molecule
mol_species_list = split_rdkit_mol_obj(mol)
largest_mol = get_largest_mol(mol_species_list)
inchi = AllChem.MolToInchi(largest_mol)
else:
inchi = AllChem.MolToInchi(mol)
return inchi
else:
return
else:
return
def drop_nodes(data, aug_ratio):
node_num, _ = data.x.size()
_, edge_num = data.edge_index.size()
drop_num = int(node_num * aug_ratio)
idx_drop = np.random.choice(node_num, drop_num, replace=False)
idx_nondrop = [n for n in range(node_num) if not n in idx_drop]
#print('idx_drop: ', idx_drop)
#print('idx_nondrop sorted: ', idx_nondrop)
idx_dict = {idx_nondrop[n]:n for n in list(range(len(idx_nondrop)))}
#print(idx_dict)
edge_index = data.edge_index.numpy()
idx_drop = set(idx_drop)
idx_nondrop_edge = []
for i in range(edge_index.shape[1]):
tmp = set(edge_index[:, i])
if not idx_drop.intersection(tmp):
idx_nondrop_edge.append(i)
edge_index[0, i] = idx_dict[edge_index[0, i]]
edge_index[1, i] = idx_dict[edge_index[1, i]]
edge_index = torch.from_numpy(edge_index[:, idx_nondrop_edge])
edge_attr = data.edge_attr[idx_nondrop_edge, :]
try:
data.x = data.x[idx_nondrop]
data.edge_index = edge_index
data.edge_attr = edge_attr
except:
data = data
# print('data.x new', data.x)
# print('data.x try index')
# for i in range(data.x.size(0)):
# print(i, data.x[i])
# print('edge_index new', data.edge_index)
# print('edge_attr new', data.edge_attr)
return data
def drop_nodes_random(data, aug_ratio):
# print('data.x:', data.x)
# print('data.edge_index:', data.edge_index)
# print('data.edge_attr:', data.edge_attr)
node_num, _ = data.x.size()
_, edge_num = data.edge_index.size()
drop_num = int(node_num * aug_ratio)
idx_drop = np.random.choice(node_num, drop_num, replace=False)
idx_nondrop = [n for n in range(node_num) if not n in idx_drop]
# print('idx_drop,', idx_drop)
# print('idx_nondrop', idx_nondrop)
# drop node features
## data.x = data.x[idx_nondrop]
# modify edge index and feature
edge_index = data.edge_index.numpy()
idx_drop = set(idx_drop)
idx_nondrop_edge = []
for i in range(edge_index.shape[1]):
tmp = set(edge_index[:, i])
if not idx_drop.intersection(tmp):
idx_nondrop_edge.append(i)
edge_index = torch.from_numpy(edge_index[:, idx_nondrop_edge])
edge_attr = data.edge_attr[idx_nondrop_edge, :]
data.edge_index = edge_index
data.edge_attr = edge_attr
if data.edge_index.shape[1] != data.edge_attr.shape[0]:
print('data dropping failed!')
return
# print(data.x)
# print(data.edge_index)
# print(data.edge_attr)
return data
def drop_nodes_nonC(data, aug_ratio):
# print('data.x:', data.x)
# print('data.edge_index:', data.edge_index)
# print('data.edge_attr:', data.edge_attr)
node_num, _ = data.x.size()
_, edge_num = data.edge_index.size()
drop_num = int(node_num * aug_ratio)
atom_number = data.x[:, 0].numpy()
c_idx = np.where(atom_number == 5)[0]
nonc_idx = np.where(atom_number != 5)[0]
# get drop_idx
if drop_num <= len(nonc_idx):
idx_drop = np.random.choice(nonc_idx, drop_num, replace=False)
else:
tmp = np.random.choice(c_idx, drop_num-len(nonc_idx), replace=False)
idx_drop = np.concatenate([nonc_idx, tmp], axis=0)
idx_nondrop = [n for n in range(node_num) if not n in idx_drop]
# print('idx_drop,', idx_drop)
# print('idx_nondrop', idx_nondrop)
# drop node features
## data.x = data.x[idx_nondrop]
# modify edge index and feature
edge_index = data.edge_index.numpy()
idx_drop = set(idx_drop)
idx_nondrop_edge = []
for i in range(edge_index.shape[1]):
tmp = set(edge_index[:, i])
if not idx_drop.intersection(tmp):
idx_nondrop_edge.append(i)
edge_index = torch.from_numpy(edge_index[:, idx_nondrop_edge])
edge_attr = data.edge_attr[idx_nondrop_edge, :]
data.edge_index = edge_index
data.edge_attr = edge_attr
if data.edge_index.shape[1] != data.edge_attr.shape[0]:
print('data dropping failed!')
return
# print(data.x)
# print(data.edge_index)
# print(data.edge_attr)
return data
def drop_nodes_C(data, aug_ratio):
# print('data.x:', data.x)
# print('data.edge_index:', data.edge_index)
# print('data.edge_attr:', data.edge_attr)
node_num, _ = data.x.size()
_, edge_num = data.edge_index.size()
drop_num = int(node_num * aug_ratio)
atom_number = data.x[:, 0].numpy()
c_idx = np.where(atom_number == 5)[0]
# get drop_idx
idx_drop = np.random.choice(c_idx, drop_num, replace=False)
idx_nondrop = [n for n in range(node_num) if not n in idx_drop]
# print('idx_drop,', idx_drop)
# print('idx_nondrop', idx_nondrop)
# drop node features
## data.x = data.x[idx_nondrop]
# modify edge index and feature
edge_index = data.edge_index.numpy()
idx_drop = set(idx_drop)
idx_nondrop_edge = []
for i in range(edge_index.shape[1]):
tmp = set(edge_index[:, i])
if not idx_drop.intersection(tmp):
idx_nondrop_edge.append(i)
edge_index = torch.from_numpy(edge_index[:, idx_nondrop_edge])
edge_attr = data.edge_attr[idx_nondrop_edge, :]
data.edge_index = edge_index
data.edge_attr = edge_attr
if data.edge_index.shape[1] != data.edge_attr.shape[0]:
print('data dropping failed!')
return
# print(data.x)
# print(data.edge_index)
# print(data.edge_attr)
return data
def add_edges(data, aug_ratio):
node_num, _ = data.x.size()
_, edge_num = data.edge_index.size()
permute_num = int(edge_num * aug_ratio)
edge_index = data.edge_index.transpose(0, 1).numpy()
edge_index_add = np.random.choice(node_num, (permute_num, 2))
idx_drop = np.random.choice(edge_num, permute_num, replace=False)
edge_index[idx_drop] = edge_index_add
data.edge_index = torch.tensor(edge_index).transpose_(0, 1)
return data
def permute_edges(data, aug_ratio):
node_num, _ = data.x.size()
_, edge_num = data.edge_index.size()
permute_num = int(edge_num * aug_ratio)
edge_index = data.edge_index.transpose(0, 1).numpy()
edge_index_add = np.random.choice(node_num, (permute_num, 2))
idx_drop = np.random.choice(edge_num, permute_num, replace=False)
edge_index[idx_drop] = edge_index_add
data.edge_index = torch.tensor(edge_index).transpose_(0, 1)
return data
def drop_edges(data, aug_ratio):
node_num, _ = data.x.size()
_, edge_num = data.edge_index.size()
permute_num = int(edge_num * aug_ratio)
edge_index = data.edge_index.transpose(0, 1).numpy()
idx_nondrop = np.random.choice(edge_num, edge_num-permute_num, replace=False)
edge_index = edge_index[idx_nondrop, :]
data.edge_index = torch.tensor(edge_index).transpose_(0, 1)
data.edge_attr = data.edge_attr[idx_nondrop, :]
return data
def subgraph(data, aug_ratio):
node_num, _ = data.x.size()
_, edge_num = data.edge_index.size()
sub_num = int(node_num * aug_ratio)
edge_index = data.edge_index.numpy()
idx_sub = [np.random.randint(node_num, size=1)[0]]
#print('idx_sub: ', idx_sub)
idx_neigh = set([n for n in edge_index[1][edge_index[0]==idx_sub[0]]])
#print('idx_neigh: ', idx_neigh)
count = 0
while len(idx_sub) <= sub_num:
count = count + 1
if count > node_num:
break
if len(idx_neigh) == 0:
break
sample_node = np.random.choice(list(idx_neigh))
if sample_node in idx_sub:
continue
idx_sub.append(sample_node)
idx_neigh.union(set([n for n in edge_index[1][edge_index[0]==idx_sub[-1]]]))
# print('idx_sub_final: ', idx_sub)
# print('idx_neigh_final: ', idx_neigh)
idx_drop = [n for n in range(node_num) if not n in idx_sub]
#print('idx_drop: ', idx_drop)
idx_nondrop = sorted(idx_sub)
#print('idx_nondrop sorted: ', idx_nondrop)
idx_dict = {idx_nondrop[n]:n for n in list(range(len(idx_nondrop)))}
#print(idx_dict)
edge_index = data.edge_index.numpy()
idx_drop = set(idx_drop)
idx_nondrop_edge = []
for i in range(edge_index.shape[1]):
tmp = set(edge_index[:, i])
if not idx_drop.intersection(tmp):
idx_nondrop_edge.append(i)
edge_index[0, i] = idx_dict[edge_index[0, i]]
edge_index[1, i] = idx_dict[edge_index[1, i]]
edge_index = torch.from_numpy(edge_index[:, idx_nondrop_edge])
edge_attr = data.edge_attr[idx_nondrop_edge, :]
try:
data.x = data.x[idx_nondrop]
data.edge_index = edge_index
data.edge_attr = edge_attr
except:
data = data
# print('data.x new', data.x)
# print('data.x try index')
# for i in range(data.x.size(0)):
# print(i, data.x[i])
# print('edge_index new', data.edge_index)
# print('edge_attr new', data.edge_attr)
return data
def mask_attributes(data, aug_ratio, mask_edge = False):
node_num, feat_dim = data.x.size()
mask_num = int(node_num * aug_ratio)
idx_mask = np.random.choice(node_num, mask_num, replace=False)
data.x[idx_mask] = torch.tensor([num_atom_type-1, 0])
if mask_edge:
edge_index = data.edge_index.numpy()
idx_mask = set(idx_mask)
idx_mask_edge = []
for i in range(edge_index.shape[1]):
tmp = set(edge_index[:, i])
if idx_mask.intersection(tmp):
idx_mask_edge.append(i)
data.edge_attr[idx_mask_edge] = torch.tensor([num_bond_type-1, 0])
return data
def domain_aug(data, smiles_list, rule_indicator, rules, aug_times=1):
row_idx = data.id.cpu().numpy()[0]
#print(row_idx)
s = smiles_list[row_idx]
mol_obj = Chem.MolFromSmiles(s)
mol_prev = mol_obj
mol_next = None
for time in range(aug_times):
#print('aug time: ', time)
non_zero_idx = list(np.where(rule_indicator[row_idx, :]!=0)[0])
cnt = -1
while len(non_zero_idx)!=0:
col_idx = random.choice(non_zero_idx)
# calculate counts
rule = rules[col_idx]
rxn = AllChem.ReactionFromSmarts(rule['smarts'])
products = rxn.RunReactants((mol_prev,))
cnt = len(products)
if cnt != 0:
break
else:
non_zero_idx.remove(col_idx)
if cnt >= 1:
aug_idx = random.choice(range(cnt))
mol = products[aug_idx][0]
try:
Chem.SanitizeMol(mol)
except: # TODO: add detailed exception
pass
mol_next = mol
mol_prev = mol
#rule_indicator[row_idx, col_idx] -= 1
else:
mol_next = mol_prev
assert mol_next
data = mol_to_graph_data_obj_simple(mol_next)
return data
# def domain_aug_new(data, smiles_list, rule_indicator, rules, aug_times=1):
# row_idx = data.id.cpu().numpy()[0]
# s = smiles_list[row_idx]
# mol_obj = Chem.MolFromSmiles(s)
# mol_prev = mol_obj
# mol_next = None
# for time in range(aug_times):
# ri = np.random.randint(2)
# if ri==0:
# non_zero_idx = list(np.where(rule_indicator[row_idx, :]!=0)[0])
# cnt = -1
# while len(non_zero_idx)!=0:
# col_idx = random.choice(non_zero_idx)
# # calculate counts
# rule = rules[col_idx]
# rxn = AllChem.ReactionFromSmarts(rule['smarts'])
# products = rxn.RunReactants((mol_prev,))
# cnt = len(products)
# if cnt != 0:
# break
# else:
# non_zero_idx.remove(col_idx)
# if cnt >= 1:
# aug_idx = random.choice(range(cnt))
# mol = products[aug_idx][0]
# try:
# Chem.SanitizeMol(mol)
# except: # TODO: add detailed exception
# pass
# mol_next = mol
# mol_prev = mol
# else:
# mol_next = mol_prev
# assert mol_next
# data = mol_to_graph_data_obj_simple(mol_next)
# return data
import json
import pickle as pkl
class MoleculeDataset(InMemoryDataset):
def __init__(self,
root,
#data = None,
#slices = None,
transform=None,
pre_transform=None,
pre_filter=None,
dataset='esol',
aug='none', aug_ratio=None,
empty=False):
"""
Adapted from qm9.py. Disabled the download functionality
:param root: directory of the dataset, containing a raw and processed
dir. The raw dir should contain the file containing the smiles, and the
processed dir can either empty or a previously processed file
:param dataset: name of the dataset. Currently only implemented for
zinc250k, chembl_with_labels, tox21, hiv, bace, bbbp, clintox, esol,
freesolv, lipophilicity, muv, pcba, sider, toxcast
:param empty: if True, then will not load any data obj. For
initializing empty dataset
"""
self.dataset = dataset
self.root = root
self.aug = aug
self.aug_ratio = aug_ratio
self.get_count = 0
super(MoleculeDataset, self).__init__(root, transform, pre_transform,
pre_filter)
self.transform, self.pre_transform, self.pre_filter = transform, pre_transform, pre_filter
if not empty:
self.data, self.slices = torch.load(self.processed_paths[0])
self.processed_smiles = pd.read_csv(os.path.join(self.processed_dir, 'smiles.csv'), header=None)
assert len(self.processed_smiles) == len(self)
if self.dataset == 'bbbp':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset.upper() +'.csv', sep=',')
self.original_smiles = raw_file['smiles'].tolist()
elif self.dataset == 'bace':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset +'.csv', sep=',')
self.original_smiles = raw_file['mol'].tolist()
elif self.dataset == 'clintox':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset +'.csv', sep=',')
self.original_smiles = raw_file['smiles'].tolist()
elif self.dataset == 'sider':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset +'.csv', sep=',')
self.original_smiles = raw_file['smiles'].tolist()
elif self.dataset == 'tox21':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset +'.csv', sep=',')
self.original_smiles = raw_file['smiles'].tolist()
elif self.dataset == 'toxcast':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset +'_data.csv', sep=',')
self.original_smiles = raw_file['smiles'].tolist()
elif self.dataset == 'muv':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset +'.csv', sep=',')
self.original_smiles = raw_file['smiles'].tolist()
elif self.dataset == 'hiv':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset.upper() +'.csv', sep=',')
self.original_smiles = raw_file['smiles'].tolist()
elif self.dataset == 'mutag':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset +'_188_data.can', sep=' ', header=None)
self.original_smiles = raw_file[0].tolist()
elif self.dataset == 'dti':
raw_file = pd.read_csv(self.root + '/raw/' + self.dataset +'.csv', sep=',')
self.original_smiles = raw_file['smiles'].tolist()
else:
print('original smiles list not found!')
print('dataset smiles {:d} raw smiles {:d}'.format(len(self.processed_smiles), len(self.original_smiles)))
self.rules = json.load(open('isostere_transformations_new.json'))
with open('results/'+ self.dataset + '/rule_indicator_new.pkl', 'rb') as f:
d = pkl.load(f)
rule_indicator = d[0]
print('rule indicator shape: ', rule_indicator.shape)
self.rule_indicator = rule_indicator
def get(self, idx):
every = 4000000
self.get_count += 1
if self.get_count % every == 0:
print('my aug: {0}'.format(self.aug))
data = Data()
for key in self.data.keys:
item, slices = self.data[key], self.slices[key]
s = list(repeat(slice(None), item.dim()))
# print(key, item)
s[data.cat_dim(key, item)] = slice(slices[idx],
slices[idx + 1])
data[key] = item[s]
if self.aug == 'dropN_random':
data = drop_nodes_random(data, self.aug_ratio)
elif self.aug == 'dropN_nonC':
data = drop_nodes_nonC(data, self.aug_ratio)
elif self.aug == 'none':
data = data
elif self.aug == 'dropN_C':
data = drop_nodes_C(data, self.aug_ratio)
elif self.aug == 'drop_edge':
data = drop_edges(data, self.aug_ratio)
elif self.aug == 'permute_edge':
data = permute_edges(data, self.aug_ratio)
elif self.aug == 'mask_node':
data = mask_attributes(data, self.aug_ratio)
elif self.aug == 'mask_edge':
data = mask_attributes(data, self.aug_ratio, mask_edge=True)
elif self.aug == 'subgraph':
data = subgraph(data, self.aug_ratio)
elif self.aug == 'drop_node':
if self.get_count % every == 0:
print('[INFO] aug: drop_node')
data = drop_nodes(data, self.aug_ratio)
elif self.aug == 'random4':
ri = np.random.randint(4)
if ri == 0:
data = drop_nodes(data, self.aug_ratio)
elif ri == 1:
data = subgraph(data, self.aug_ratio)
elif ri == 2:
data = permute_edges(data, self.aug_ratio)
elif ri == 3:
data = mask_attributes(data, self.aug_ratio)
else:
print('sample augmentation error')
assert False
elif self.aug == 'DK1':
if self.get_count % every == 0:
print('[INFO] aug: DK1')
data = domain_aug(data, self.original_smiles, self.rule_indicator, self.rules, aug_times=1)
elif self.aug == 'DK2':
data = domain_aug(data, self.original_smiles, self.rule_indicator, self.rules, aug_times=2)
elif self.aug == 'DK3':
data = domain_aug(data, self.original_smiles, self.rule_indicator, self.rules, aug_times=3)
elif self.aug == 'DK5':
data = domain_aug(data, self.original_smiles, self.rule_indicator, self.rules, aug_times=5)
else:
print('augmnentation error')
return data
@property
def raw_file_names(self):
file_name_list = os.listdir(self.raw_dir)
# assert len(file_name_list) == 1 # currently assume we have a
# # single raw file
return file_name_list
@property
def processed_file_names(self):
return 'geometric_data_processed.pt'
def download(self):
raise NotImplementedError('Must indicate valid location of raw data. '
'No download allowed')
def process(self):
data_smiles_list = []
data_list = []
if self.dataset == 'zinc_standard_agent':
input_path = self.raw_paths[0]
input_df = pd.read_csv(input_path, sep=',', compression='gzip',
dtype='str')
smiles_list = list(input_df['smiles'])
zinc_id_list = list(input_df['zinc_id'])
for i in range(len(smiles_list)):
print(i)
s = smiles_list[i]
# each example contains a single species
try:
rdkit_mol = AllChem.MolFromSmiles(s)
if rdkit_mol != None: # ignore invalid mol objects
# # convert aromatic bonds to double bonds
# Chem.SanitizeMol(rdkit_mol,
# sanitizeOps=Chem.SanitizeFlags.SANITIZE_KEKULIZE)
data = mol_to_graph_data_obj_simple(rdkit_mol)
# manually add mol id
id = int(zinc_id_list[i].split('ZINC')[1].lstrip('0'))
data.id = torch.tensor(
[id]) # id here is zinc id value, stripped of
# leading zeros
data_list.append(data)
data_smiles_list.append(smiles_list[i])
except:
continue
elif self.dataset == 'dti':
input_path = self.raw_paths[0]
input_df = pd.read_csv(input_path, sep=',')
smiles_list = list(input_df['smiles'])
for i in range(len(smiles_list)):
print(i)
s = smiles_list[i]
rdkit_mol = AllChem.MolFromSmiles(s)
data = mol_to_graph_data_obj_simple(rdkit_mol)
data.id = torch.tensor([i])
data_list.append(data)
data_smiles_list.append(smiles_list[i])
elif self.dataset == 'chembl_filtered':
### get downstream test molecules.
from splitters import scaffold_split
###
downstream_dir = [
'dataset/bace',
'dataset/bbbp',
'dataset/clintox',
'dataset/esol',
'dataset/freesolv',
'dataset/hiv',
'dataset/lipophilicity',
'dataset/muv',
# 'dataset/pcba/processed/smiles.csv',
'dataset/sider',
'dataset/tox21',
'dataset/toxcast'
]
downstream_inchi_set = set()
for d_path in downstream_dir:
print(d_path)
dataset_name = d_path.split('/')[1]
downstream_dataset = MoleculeDataset(d_path, dataset=dataset_name)
downstream_smiles = pd.read_csv(os.path.join(d_path,
'processed', 'smiles.csv'),
header=None)[0].tolist()
assert len(downstream_dataset) == len(downstream_smiles)
_, _, _, (train_smiles, valid_smiles, test_smiles) = scaffold_split(downstream_dataset, downstream_smiles, task_idx=None, null_value=0,
frac_train=0.8,frac_valid=0.1, frac_test=0.1,
return_smiles=True)
### remove both test and validation molecules
remove_smiles = test_smiles + valid_smiles
downstream_inchis = []
for smiles in remove_smiles:
species_list = smiles.split('.')
for s in species_list: # record inchi for all species, not just
# largest (by default in create_standardized_mol_id if input has
# multiple species)
inchi = create_standardized_mol_id(s)
downstream_inchis.append(inchi)
downstream_inchi_set.update(downstream_inchis)
smiles_list, rdkit_mol_objs, folds, labels = \
_load_chembl_with_labels_dataset(os.path.join(self.root, 'raw'))
print('processing')
for i in range(len(rdkit_mol_objs)):
print(i)
rdkit_mol = rdkit_mol_objs[i]
if rdkit_mol != None:
# # convert aromatic bonds to double bonds
# Chem.SanitizeMol(rdkit_mol,
# sanitizeOps=Chem.SanitizeFlags.SANITIZE_KEKULIZE)
mw = Descriptors.MolWt(rdkit_mol)
if 50 <= mw <= 900:
inchi = create_standardized_mol_id(smiles_list[i])
if inchi != None and inchi not in downstream_inchi_set:
data = mol_to_graph_data_obj_simple(rdkit_mol)
# manually add mol id
data.id = torch.tensor(
[i]) # id here is the index of the mol in
# the dataset
data.y = torch.tensor(labels[i, :])
# fold information
if i in folds[0]:
data.fold = torch.tensor([0])
elif i in folds[1]:
data.fold = torch.tensor([1])
else:
data.fold = torch.tensor([2])
data_list.append(data)
data_smiles_list.append(smiles_list[i])
elif self.dataset == 'tox21':
smiles_list, rdkit_mol_objs, labels = \
_load_tox21_dataset(self.raw_paths[0])
for i in range(len(smiles_list)):
print(i)
rdkit_mol = rdkit_mol_objs[i]
## convert aromatic bonds to double bonds
#Chem.SanitizeMol(rdkit_mol,
#sanitizeOps=Chem.SanitizeFlags.SANITIZE_KEKULIZE)
data = mol_to_graph_data_obj_simple(rdkit_mol)
# manually add mol id
data.id = torch.tensor(
[i]) # id here is the index of the mol in
# the dataset
data.y = torch.tensor(labels[i, :])
data_list.append(data)
data_smiles_list.append(smiles_list[i])
elif self.dataset == 'hiv':
smiles_list, rdkit_mol_objs, labels = \
_load_hiv_dataset(self.raw_paths[0])
for i in range(len(smiles_list)):
print(i)
rdkit_mol = rdkit_mol_objs[i]
# # convert aromatic bonds to double bonds
# Chem.SanitizeMol(rdkit_mol,
# sanitizeOps=Chem.SanitizeFlags.SANITIZE_KEKULIZE)
data = mol_to_graph_data_obj_simple(rdkit_mol)
# manually add mol id
data.id = torch.tensor(
[i]) # id here is the index of the mol in
# the dataset
data.y = torch.tensor([labels[i]])
data_list.append(data)
data_smiles_list.append(smiles_list[i])
elif self.dataset == 'bace':
smiles_list, rdkit_mol_objs, folds, labels = \
_load_bace_dataset(self.raw_paths[0])
for i in range(len(smiles_list)):
print(i)
rdkit_mol = rdkit_mol_objs[i]
# # convert aromatic bonds to double bonds
# Chem.SanitizeMol(rdkit_mol,
# sanitizeOps=Chem.SanitizeFlags.SANITIZE_KEKULIZE)
data = mol_to_graph_data_obj_simple(rdkit_mol)
# manually add mol id
data.id = torch.tensor(
[i]) # id here is the index of the mol in
# the dataset
data.y = torch.tensor([labels[i]])
data.fold = torch.tensor([folds[i]])
data_list.append(data)