-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutil.py
More file actions
760 lines (642 loc) · 21.9 KB
/
util.py
File metadata and controls
760 lines (642 loc) · 21.9 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
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
import networkx as nx
import numpy as np
from sklearn.preprocessing import normalize
from sklearn.cluster import KMeans
from itertools import chain
import copy, torch, dgl
from rdkit import Chem
from rdkit.Chem import AllChem
import torch
from torch_geometric.data import InMemoryDataset
from torch_geometric.data.data import Data
from torch_geometric.utils import to_networkx
from torch_geometric.utils import to_undirected
import numpy as np
import networkx as nx
import pickle
import os
import scipy.io as sio
from math import comb
import time
import torch
from torch.utils.data import Dataset
# from mol_tree import MolTree
import numpy as np
from rdkit import Chem
from rdkit.Chem import BRICS
from rdkit.Chem import Descriptors
from rdkit.Chem import AllChem
dem, dem1, dem2 = 0, 0, 0
class Grapg8cDataset(InMemoryDataset):
def __init__(self, root, name, transform=None, pre_transform=None):
self.name = name
super(Grapg8cDataset, self).__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
self.name = name
@property
def raw_file_names(self):
name = self.name + ".g6"
return [name]
@property
def processed_file_names(self):
return 'data.pt'
def download(self):
# Download to `self.raw_dir`.
pass
def process(self):
# Read data into huge `Data` list.
global dem, dem1, dem2
b=self.processed_paths[0]
dataset = nx.read_graph6(self.raw_paths[0])
data_list = []
for i,datum in enumerate(dataset):
dem +=1
if dem%500 == 0:
time.sleep(0.5)
x = torch.ones(datum.number_of_nodes(),1)
edge_index = to_undirected(torch.tensor(list(datum.edges())).transpose(1,0))
data_list.append(Data(edge_index=edge_index, x=x, y=0))
if self.pre_filter is not None:
relsults = []
for data in data_list:
if self.pre_filter(data):
relsults.append(data)
dem2 +=1
if dem2 %50 == 0:
time.sleep(0.5)
#data_list = [data for data in data_list if self.pre_filter(data)]
data_list = relsults
if self.pre_transform is not None:
relsults = []
for data in data_list:
relsults.append(self.pre_transform(data) )
dem1 +=1
if dem1 %200 == 0:
time.sleep(0.5)
data_list =relsults
#data_list = [self.pre_transform(data) for data in data_list]
data, slices = self.collate(data_list)
torch.save((data, slices), self.processed_paths[0])
class SRDataset(InMemoryDataset):
def __init__(self, root, name, transform=None, pre_transform=None):
self.name = name
super(SRDataset, self).__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
self.name = name
@property
def raw_file_names(self):
name = self.name + ".g6"
return [name]
# sr16622 sr251256 sr261034 sr281264 sr291467 sr351668 sr351899 sr361446 sr401224
@property
def processed_file_names(self):
return 'data.pt'
def download(self):
# Download to `self.raw_dir`.
pass
def process(self):
# Read data into huge `Data` list.
b=self.processed_paths[0]
dataset = nx.read_graph6(self.raw_paths[0])
data_list = []
for i,datum in enumerate(dataset):
x = torch.ones(datum.number_of_nodes(),1)
edge_index = to_undirected(torch.tensor(list(datum.edges())).transpose(1,0))
data_list.append(Data(edge_index=edge_index, x=x, y=0))
if self.pre_filter is not None:
data_list = [data for data in data_list if self.pre_filter(data)]
if self.pre_transform is not None:
data_list = [self.pre_transform(data) for data in data_list]
data, slices = self.collate(data_list)
torch.save((data, slices), self.processed_paths[0])
def sanitize(mol):
try:
smiles = get_smiles(mol)
mol = get_mol(smiles)
except Exception as e:
return None
return mol
def copy_atom(atom):
new_atom = Chem.Atom(atom.GetSymbol())
new_atom.SetFormalCharge(atom.GetFormalCharge())
new_atom.SetAtomMapNum(atom.GetAtomMapNum())
return new_atom
def copy_edit_mol(mol):
new_mol = Chem.RWMol(Chem.MolFromSmiles(''))
for atom in mol.GetAtoms():
new_atom = copy_atom(atom)
new_mol.AddAtom(new_atom)
for bond in mol.GetBonds():
a1 = bond.GetBeginAtom().GetIdx()
a2 = bond.GetEndAtom().GetIdx()
bt = bond.GetBondType()
new_mol.AddBond(a1, a2, bt)
return new_mol
def get_clique_mol(mol, atoms):
# get the fragment of clique
smiles = Chem.MolFragmentToSmiles(mol, atoms, kekuleSmiles=True)
new_mol = Chem.MolFromSmiles(smiles, sanitize=False)
new_mol = copy_edit_mol(new_mol).GetMol()
new_mol = sanitize(new_mol) # We assume this is not None
return new_mol
# def get_clique_mol(mol, atoms):
# # get the fragment of clique
# Chem.Kekulize(mol)
# smiles = Chem.MolFragmentToSmiles(mol, atoms, kekuleSmiles=True)
# new_mol = Chem.MolFromSmiles(smiles, sanitize=False)
# new_mol = copy_edit_mol(new_mol).GetMol()
# new_mol = sanitize(new_mol) # We assume this is not None
# Chem.SanitizeMol(mol)
# return new_mol
def get_mol(smiles):
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
# Chem.Kekulize(mol)
return mol
def motif_decomp(mol):
n_atoms = mol.GetNumAtoms()
#print(f"n_atoms: {n_atoms}");
if n_atoms == 1:
return [[0]]
cliques = []
breaks = []
for bond in mol.GetBonds():
a1 = bond.GetBeginAtom().GetIdx()
a2 = bond.GetEndAtom().GetIdx()
cliques.append([a1, a2])
res = list(BRICS.FindBRICSBonds(mol))
if len(res) != 0:
for bond in res:
if [bond[0][0], bond[0][1]] in cliques:
cliques.remove([bond[0][0], bond[0][1]])
else:
cliques.remove([bond[0][1], bond[0][0]])
cliques.append([bond[0][0]])
cliques.append([bond[0][1]])
pre_cliques = cliques
# merge cliques
for c in range(len(cliques) - 1):
if c >= len(cliques):
break
for k in range(c + 1, len(cliques)):
if k >= len(cliques):
break
if len(set(cliques[c]) & set(cliques[k])) > 0:
cliques[c] = list(set(cliques[c]) | set(cliques[k]))
cliques[k] = []
cliques = [c for c in cliques if len(c) > 0]
cliques = [c for c in cliques if n_atoms> len(c) > 0]
#num_cli = len(cliques)
if len(cliques) ==0:
cliques = pre_cliques
return cliques
print(f"mol: {mol}"); print(f"cliques: {cliques}")
ssr_mol = Chem.GetSymmSSSR(mol)
for i in range(num_cli):
c = cliques[i]
cmol = get_clique_mol(mol, c)
print(f"cmol: {c}")
raise SystemExit()
ssr = Chem.GetSymmSSSR(cmol)
if len(ssr)>1:
for ring in ssr_mol:
if len(set(list(ring)) & set(c)) == len(list(ring)):
cliques.append(list(ring))
cliques[i] = list(set(cliques[i]) - set(list(ring)))
cliques = [c for c in cliques if n_atoms> len(c) > 0]
return cliques
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)
x = x.type(torch.int)
# print(x)
# raise SystemExit()
return x
# 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 getDist(dgl_g, coords_tensor):
Adj = dgl_g.adj(); Adj = Adj.to_dense()
num_nodes = dgl_g.num_nodes()
D = torch.zeros((num_nodes, 100))
for src in range(num_nodes):
for dst in range(num_nodes):
if Adj[src, dst] > 0:
D[src][dst] = torch.norm(coords_tensor[src] - coords_tensor[dst] )
return D
def load_dgl_benzene_wl(nx_g):
# print('loading dgl...')
# count = 0
edge_idx1 = [] ; edge_idx2 = []
for e in nx_g.edges:
edge_idx1.append(e[0])
edge_idx2.append(e[1])
g = dgl.graph((edge_idx1, edge_idx2))
g = dgl.to_bidirected(g)
num = g.number_of_nodes()
x = torch.ones(num, 2 )
corrds = torch.ones(num, 3)
# rdkit_mol = AllChem.MolFromSmiles(smile)
g.ndata['x'] = x #mol_to_graph_data_obj_simple(rdkit_mol)
g.ndata['c'] = corrds # get_3D(rdkit_mol)
d = getDist(g, g.ndata['c'])
g.ndata['d'] = d
noise = torch.randn(g.ndata['c'].size())
g.ndata['n'] = noise
# x_row = g.ndata['x'].size(0)
# d_row = g.ndata['d'].size(0)
# if x_row != d_row:
# print(f"g.ndata['x']: {g.ndata['x'].shape} | g.ndata['c']: {g.ndata['c'].shape} | g.ndata['d'] {g.ndata['d'].shape}")
# raise SystemExit()
return g, corrds, d
def load_x_from_smile(smile ):
rdkit_mol = AllChem.MolFromSmiles(smile)
return mol_to_graph_data_obj_simple(rdkit_mol)
def load_dgl_benzene(nx_g, smile ):
# print('loading dgl...')
# count = 0
edge_idx1 = [] ; edge_idx2 = []
for e in nx_g.edges:
edge_idx1.append(e[0])
edge_idx2.append(e[1])
g = dgl.graph((edge_idx1, edge_idx2))
g = dgl.to_bidirected(g)
#num = g.number_of_nodes()
#x = torch.ones(num, 1)
rdkit_mol = AllChem.MolFromSmiles(smile)
g.ndata['x'] = mol_to_graph_data_obj_simple(rdkit_mol)
#g.ndata['c'] = get_3D(rdkit_mol)
#d = getDist(g, g.ndata['c'])
#g.ndata['d'] = d
#noise = torch.randn(g.ndata['c'].size())
#g.ndata['n'] = noise
# x_row = g.ndata['x'].size(0)
# d_row = g.ndata['d'].size(0)
# if x_row != d_row:
# print(f"g.ndata['x']: {g.ndata['x'].shape} | g.ndata['c']: {g.ndata['c'].shape} | g.ndata['d'] {g.ndata['d'].shape}")
# raise SystemExit()
return g
def get_3D(mol):
#mol = Chem.AddHs(mol) # Ensures explicit Hs are added
if AllChem.EmbedMolecule(mol) != 0:
print("3D embedding failed for the molecule")
raise SystemExit()
AllChem.UFFOptimizeMolecule(mol)
conformer = mol.GetConformer()
coords = [conformer.GetAtomPosition(i) for i in range(mol.GetNumAtoms())]
coords_tensor = torch.tensor(coords, dtype=torch.float32) # Node feature tensor
#print(coords_tensor)
return coords_tensor
# sim S_ij ^1,...,k
# def get_sim(tran_M, src, dst, k_step = 5):
# # print(f'shape: tran_M: {np.shape(tran_M)}')
# sim_src_dst = []
# for i in range(k_step):
# trans_k = tran_M[i]
# neighbours_src = np.array(trans_k[src, :])
# neighbours_src = list (neighbours_src.flatten())
# neighbours_dst = np.array(trans_k[dst, :])
# neighbours_dst = list(neighbours_dst.flatten())
# scorse = get_scorse_k(neighbours_src,neighbours_dst)
# sim_src_dst.append(scorse)
# return sim_src_dst
# def get_sim_score(a, b):
# len_a = sum(a)
# len_b = sum(b)
# common_nodes = [i for i in a if i in b]
# num_common_nodes = sum(common_nodes)
# score = np.round(num_common_nodes/ (len_a + len_b - num_common_nodes),3)
# return score
# def get_scorse_k(a, b):
# common_nodes = 0
# pos_a = 0
# pos_b = 0
# for i in range(len(a)):
# if a[i]> 0:
# pos_a+= 1
# if b[i]> 0:
# common_nodes+=1
# if b[i]> 0:
# pos_b += 1
# sum = pos_a + pos_b - common_nodes
# if sum == 0:
# print("sum=0, error")
# raise SystemExit()
# return 0.000001
# return np.round(common_nodes/sum, 3)
# </sim S_ij>
def GetProbTranMat(Ak, num_node):
num_node, num_node2 = Ak.shape
if (num_node != num_node2):
print('M must be a square matrix!')
Ak_sum = np.sum(Ak, axis=0).reshape(1, -1)
Ak_sum = np.repeat(Ak_sum, num_node, axis=0)
log = np.log(1. / num_node)
probTranMat = np.log(np.divide(Ak, Ak_sum)) - log
probTranMat[probTranMat < 0] = 0; # set zero for negative and -inf elements
probTranMat[np.isnan(probTranMat)] = 0; # set zero for nan elements (the isolated nodes)
return probTranMat
def getM_logM(dgl_g, kstep=3):
tran_M = []
tran_logM = []
# Adj = np.zeros((num_nodes, num_nodes))
# for src in nx_g.nodes():
# src_degree = nx_g.degree(src)
# for dst in nx_g.nodes():
# if nx_g.has_edge(src, dst):
# Adj[src][dst] = round(1 / src_degree, 3)
Adj = dgl_g.adj()
Adj = Adj.to_dense()
num_nodes = dgl_g.num_nodes()
Ak = np.matrix(np.identity(num_nodes))
for i in range(kstep):
Ak = np.dot(Ak, Adj)
tran_M.append(Ak)
probTranMat = GetProbTranMat(Ak, num_nodes)
tran_logM.append(probTranMat)
return tran_M, tran_logM
def get_distance(deg_A, deg_B):
damp = 1 / (deg_A * deg_B) # -1
return damp # np.round ( np.exp(damp), 3)
def get_B_sim_phi(nx_g, tran_M, num_nodes, n_class, X, kstep=5):
#print(f'processing get_B_sim_phi')
count = 0
B = np.zeros((num_nodes, num_nodes)) #= np.zeros((num_nodes, num_nodes))
colour = np.zeros((num_nodes, num_nodes))
phi = np.zeros((num_nodes, num_nodes, 1))
sim = np.zeros((num_nodes, num_nodes, kstep))
trans_check = tran_M[kstep - 1]
not_adj = tran_M[0]
kmeans = KMeans(n_clusters= 2 , init='k-means++', max_iter=10, n_init=10, random_state=0)
y_kmeans = kmeans.fit_predict(X)
count = 0
count_1 = 0
for src in nx_g.nodes():
# if count % 50 == 0:
# print(f' processing node_th {src}/{num_nodes}')
for dst in nx_g.nodes():
if src == dst:
continue
if not_adj[src, dst] > 0:
continue
if colour[src, dst] == 1 or colour[src, dst] == 1:
continue
if trans_check[src, dst] > 0.001:
# sim
# sim_src_dst_list = get_sim(tran_M, src, dst)
# sim[src,dst] = sim_src_dst_list
# sim[dst, src] = sim_src_dst_list
src_d = nx_g.degree(src)
dst_d = nx_g.degree(dst)
if np.abs(src_d - dst_d) > 1:
continue
if y_kmeans[src] != y_kmeans[dst]:
continue
else:
count_1 += 1
d = get_distance(src_d, dst_d)
# B i, j
B[src, dst] = d
B[dst, src] = d
# phi i,j
if phi[src, dst] == 0:
phi[src, dst] = d
phi[dst, src] = d
colour[src, dst] = 1
colour[dst, src] = 1
B[src, src] = 0
count += 1
#(f'good neighbour: {count_1}')
# print(f'number not zero: {num}')
# raise SystemExit()
sim = compute_sim(tran_M, num_nodes, k_step=kstep)
return B, sim, phi
def compute_sim(tran_M, num_nodes, k_step=5):
sim = np.zeros((num_nodes, num_nodes, k_step))
trans_check = tran_M[k_step - 1]
for step in range(k_step):
#print(f'compute_sim transition step {step + 1}/{k_step}')
colour = np.zeros((num_nodes, num_nodes))
trans_k = copy.deepcopy(tran_M[step])
trans_k[trans_k >= 0.001] = 1
trans_k[trans_k < 0.001] = 0;
trans_k = np.array(trans_k)
row_sums = trans_k.sum(axis=1)
trans_mul = trans_k @ trans_k.T
for i in range(num_nodes):
for j in range(i + 1, num_nodes):
if trans_check[i, j] < 0.0001:
continue
if colour[i, j] == 1 or colour[j, i] == 1:
continue
# neighbours_src_list = (trans_k[i, :]) #neighbours_src = list (neighbours_src.flatten())
# neighbours_dst_list = (trans_k[j, :]) #neighbours_dst = list(neighbours_dst.flatten())
# sum1 = sum(neighbours_src_list)
# sum2 = sum(neighbours_dst_list)
# score = get_sim_score(neighbours_src_list,neighbours_dst_list)
score = np.round(trans_mul[i, j] / (row_sums[i] + row_sums[j] - trans_mul[i, j]), 4)
if score < 0.001:
score = 0
sim[i, j, step] = score
sim[j, i, step] = score
colour[i, j] = 1
colour[j, i] = 1
return sim
def get_A_D(nx_g, num_nodes):
num_edges = nx_g.number_of_edges()
# d= np.zeros((num_nodes, num_nodes))
d = np.zeros((num_nodes))
Adj = np.zeros((num_nodes, num_nodes))
for src in nx_g.nodes():
src_degree = nx_g.degree(src)
d[src] = src_degree
for dst in nx_g.nodes():
# dst_degree = nx_g.degree(dst)
# d[src][dst] = src_degree*dst_degree
if nx_g.has_edge(src, dst):
Adj[src][dst] = 1
# print(f'd matrix: {np.shape(d)}')
# Adj = normalizeRows(Adj)
# print(Adj)
# d = normalizeRows(d)
return Adj, d, num_edges
def load_dgl(nx_g, x ):
#print('loading dgl...')
edge_idx1 = []
edge_idx2 = []
for e in nx_g.edges:
edge_idx1.append(e[0])
edge_idx2.append(e[1])
# edge_idx1.append(e[1])
# edge_idx2.append(e[0])
# s_vals = []
# phi_vals = []
# for i in range(len(edge_idx1)):
# count += 1
# n1 = edge_idx1[i]
# n2 = edge_idx2[i]
# s = np.asarray(sim[n1][n2], dtype=float)
# s_vals.append(s)
# p = np.asarray(phi[n1][n2], dtype=float)
# phi_vals.append(p)
#print(f'networkx: number edges: {count}')
# s_vals = np.array(s_vals)
# phi_vals = np.array(phi_vals)
# test = np.any(np.isnan(s_vals))
# s_vals[np.isnan(s_vals)] = 0
# s_vals = normalize(s_vals, axis=0, norm='max')
# phi_vals = normalize(phi_vals, axis=0, norm='max')
# s_vals = torch.tensor(s_vals)
# phi_vals = torch.tensor(phi_vals)
g = dgl.graph((edge_idx1, edge_idx2))
g = dgl.to_bidirected(g)
# s_vals[torch.isnan(s_vals)] = 0
# phi_vals[torch.isnan(phi_vals)] = 0
g.ndata['x'] = x
# g.edata['sim'] = s_vals
# g.edata['phi'] = phi_vals
#print(f'loading dgl, done, DGL graph edges: {g.number_of_edges()}')
return g
def get_3D(mol):
if AllChem.EmbedMolecule(mol) != 0:
print("3D embedding failed for the molecule")
AllChem.UFFOptimizeMolecule(mol)
conformer = mol.GetConformer()
coords = [conformer.GetAtomPosition(i) for i in range(mol.GetNumAtoms())]
coords_tensor = torch.tensor(coords, dtype=torch.float32)
return coords_tensor
def load_dgl_fromPyG(data):
#print('loading dgl...')
#count = 0
edge_idx1 = []
edge_idx2 = []
edge_index = data.edge_index
edge_idx1 =edge_index[0]
edge_idx2 =edge_index[1]
# for e in nx_g.edges:
# edge_idx1.append(e[0])
# edge_idx2.append(e[1])
# edge_idx1.append(e[1])
# edge_idx2.append(e[0])
# s_vals = []
# phi_vals = []
# for i in range(len(edge_idx1)):
# count += 1
# n1 = edge_idx1[i]
# n2 = edge_idx2[i]
# s = np.asarray(sim[n1][n2], dtype=float)
# s_vals.append(s)
# p = np.asarray(phi[n1][n2], dtype=float)
# phi_vals.append(p)
#print(f'networkx: number edges: {count}')
# s_vals = np.array(s_vals)
# phi_vals = np.array(phi_vals)
# test = np.any(np.isnan(s_vals))
# s_vals[np.isnan(s_vals)] = 0
# s_vals = normalize(s_vals, axis=0, norm='max')
# phi_vals = normalize(phi_vals, axis=0, norm='max')
# s_vals = torch.tensor(s_vals)
# phi_vals = torch.tensor(phi_vals)
g = dgl.graph((edge_idx1, edge_idx2))
g = dgl.to_bidirected(g)
# s_vals[torch.isnan(s_vals)] = 0
# phi_vals[torch.isnan(phi_vals)] = 0
g.ndata['x'] = data.x
# g.edata['sim'] = s_vals
# g.edata['phi'] = phi_vals
#print(f'loading dgl, done, DGL graph edges: {g.number_of_edges()}')
return g
def load_dgl_fromPyG_pcqm4mv2(data):
# print('loading dgl...')
# print(f"dataset0: label: {data[1]}")
arr = np.asarray(data)
# print(f"data: {len(arr[0]['node_feat'][1])} ")
# num_nodes edge_index edge_feat
label = data[1]
x = arr[0]['node_feat']
x = torch.tensor(x)
edge_index = arr[0]['edge_index']
# print(f"label: {label}")
# print(f"x: {x}")
# print(f"edge_index: {edge_index}")
edge_idx1 = []
edge_idx2 = []
edge_index = edge_index
edge_idx1 = edge_index[0]
edge_idx2 = edge_index[1]
# for e in nx_g.edges:
# edge_idx1.append(e[0])
# edge_idx2.append(e[1])
# edge_idx1.append(e[1])
# edge_idx2.append(e[0])
# s_vals = []
# phi_vals = []
# for i in range(len(edge_idx1)):
# count += 1
# n1 = edge_idx1[i]
# n2 = edge_idx2[i]
# s = np.asarray(sim[n1][n2], dtype=float)
# s_vals.append(s)
# p = np.asarray(phi[n1][n2], dtype=float)
# phi_vals.append(p)
# print(f'networkx: number edges: {count}')
# s_vals = np.array(s_vals)
# phi_vals = np.array(phi_vals)
# test = np.any(np.isnan(s_vals))
# s_vals[np.isnan(s_vals)] = 0
# s_vals = normalize(s_vals, axis=0, norm='max')
# phi_vals = normalize(phi_vals, axis=0, norm='max')
# s_vals = torch.tensor(s_vals)
# phi_vals = torch.tensor(phi_vals)
g = dgl.graph((edge_idx1, edge_idx2))
g = dgl.to_bidirected(g)
# s_vals[torch.isnan(s_vals)] = 0
# phi_vals[torch.isnan(phi_vals)] = 0
g.ndata['x'] = x
# g.edata['sim'] = s_vals
# g.edata['phi'] = phi_vals
# print(f'loading dgl, done, DGL graph edges: {g.number_of_edges()}')
return g