monaaaaaa commited on
Commit
eeabcff
·
verified ·
1 Parent(s): 9084b3e

Upload 26 files

Browse files
GNN/__init__.py ADDED
File without changes
GNN/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (141 Bytes). View file
 
GNN/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (128 Bytes). View file
 
GNN/__pycache__/featurizer.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
GNN/__pycache__/featurizer.cpython-312.pyc ADDED
Binary file (8.76 kB). View file
 
GNN/__pycache__/layers.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
GNN/__pycache__/layers.cpython-312.pyc ADDED
Binary file (27.2 kB). View file
 
GNN/__pycache__/subgraphfp.cpython-310.pyc ADDED
Binary file (4.39 kB). View file
 
GNN/__pycache__/subgraphfp.cpython-312.pyc ADDED
Binary file (7.44 kB). View file
 
GNN/featurizer.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from rdkit import Chem
3
+ from rdkit.Chem import AllChem, MACCSkeys, rdMolDescriptors as rdDesc
4
+ from utils import *
5
+ import torch
6
+ import copy
7
+ from . import subgraphfp as subfp
8
+
9
+ PERIODIC_TABLE = Chem.GetPeriodicTable()
10
+ POSSIBLE_ATOMS = ['H', 'C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'I', 'B']
11
+
12
+ HYBRIDS = [Chem.rdchem.HybridizationType.SP,
13
+ Chem.rdchem.HybridizationType.SP2,
14
+ Chem.rdchem.HybridizationType.SP3,
15
+ Chem.rdchem.HybridizationType.SP3D,
16
+ Chem.rdchem.HybridizationType.SP3D2]
17
+
18
+ CHIRALS = [Chem.rdchem.ChiralType.CHI_UNSPECIFIED,
19
+ Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CW,
20
+ Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CCW,
21
+ Chem.rdchem.ChiralType.CHI_OTHER]
22
+
23
+ BOND_TYPES = [Chem.rdchem.BondType.SINGLE,
24
+ Chem.rdchem.BondType.DOUBLE,
25
+ Chem.rdchem.BondType.TRIPLE,
26
+ Chem.rdchem.BondType.AROMATIC]
27
+
28
+
29
+ def one_of_k_encoding(x, allowable_set):
30
+ if x not in allowable_set:
31
+ raise Exception("input {0} not in allowable set{1}:".format(x, allowable_set))
32
+ return list(map(lambda s: x == s, allowable_set))
33
+
34
+
35
+ def one_of_k_encoding_unk(x, allowable_set):
36
+ """Maps inputs not in the allowable set to the last element."""
37
+ if x not in allowable_set:
38
+ x = allowable_set[-1]
39
+
40
+ return list(map(lambda s: x == s, allowable_set))
41
+
42
+
43
+ def calc_atom_features_onehot(atom, feature):
44
+ '''
45
+ Method that computes atom level features from rdkit atom object
46
+ '''
47
+ atom_features = one_of_k_encoding_unk(atom.GetSymbol(), POSSIBLE_ATOMS)
48
+ atom_features += one_of_k_encoding_unk(atom.GetExplicitValence(), list(range(7)))
49
+ atom_features += one_of_k_encoding_unk(atom.GetImplicitValence(), list(range(7)))
50
+ atom_features += one_of_k_encoding_unk(atom.GetTotalNumHs(), list(range(5)))
51
+ atom_features += one_of_k_encoding_unk(atom.GetNumRadicalElectrons(), list(range(5)))
52
+ atom_features += one_of_k_encoding_unk(atom.GetTotalDegree(), list(range(7)))
53
+ atom_features += one_of_k_encoding_unk(atom.GetFormalCharge(), list(range(-2, 3)))
54
+ atom_features += one_of_k_encoding_unk(atom.GetHybridization(), HYBRIDS)
55
+ atom_features += one_of_k_encoding_unk(atom.GetIsAromatic(), [False, True])
56
+ atom_features += one_of_k_encoding_unk(atom.IsInRing(), [False, True])
57
+ atom_features += one_of_k_encoding_unk(atom.GetChiralTag(), CHIRALS)
58
+ atom_features += one_of_k_encoding_unk(atom.HasProp('_CIPCode'), ['R', 'S'])
59
+ atom_features += [PERIODIC_TABLE.GetRvdw(atom.GetSymbol())]
60
+ atom_features += [atom.HasProp('_ChiralityPossible')]
61
+ atom_features += [atom.GetAtomicNum()]
62
+ atom_features += [atom.GetMass() * 0.01]
63
+ atom_features += [atom.GetDegree()]
64
+ atom_features += [int(i) for i in list('{0:06b}'.format(feature))]
65
+
66
+ return atom_features
67
+
68
+
69
+ def calc_adjacent_tensor(bonds, atom_num, with_ring_conj=False):
70
+ '''
71
+ Method that constructs a AdjecentTensor with many AdjecentMatrics
72
+ :param bonds: bonds of a rdkit mol
73
+ :param atom_num: the atom number of the rdkit mol
74
+ :param with_ring_conj: should the AdjecentTensor contains bond in ring and
75
+ is conjugated info
76
+ :return: AdjecentTensor A shaped [N, F, N], where N is atom number and F is bond types
77
+ '''
78
+ bond_types = len(BOND_TYPES)
79
+ if with_ring_conj:
80
+ bond_types += 2
81
+
82
+ A = np.zeros([atom_num, bond_types, atom_num])
83
+
84
+ for bond in bonds:
85
+ b, e = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()
86
+ try:
87
+ bond_type = BOND_TYPES.index(bond.GetBondType())
88
+ A[b, bond_type, e] = 1
89
+ A[e, bond_type, b] = 1
90
+ if with_ring_conj:
91
+ if bond.IsInRing():
92
+ A[b, bond_types-2, e] = 1
93
+ A[e, bond_types-2, b] = 1
94
+ if bond.GetIsConjugated():
95
+ A[b, bond_types-1, e] = 1
96
+ A[e, bond_types-1, b] = 1
97
+ except:
98
+ pass
99
+ return A
100
+
101
+
102
+ def calc_data_from_smile(smiles, addh=False, with_ring_conj=False, with_atom_feats=True, with_submol_fp=True, radius=2):
103
+ '''
104
+ Method that constructs the data of a molecular.
105
+ :param smiles: SMILES representation of a molecule
106
+ :param addh: should we add all the Hs of the mol
107
+ :param with_ring_conj: should the AdjecentTensor contains bond in ring and
108
+ is conjugated info
109
+ :return: V, A, global_state, mol_size, subgraph_size
110
+ '''
111
+ mol = Chem.MolFromSmiles(smiles, sanitize=True)
112
+ # mol.UpdatePropertyCache(strict=False)
113
+
114
+ if addh:
115
+ mol = Chem.AddHs(mol)
116
+ # else:
117
+ # mol = Chem.RemoveHs(mol, sanitize=False)
118
+
119
+ mol_size = torch.IntTensor([mol.GetNumAtoms()])
120
+
121
+ V = []
122
+
123
+ if with_atom_feats:
124
+ features = rdDesc.GetFeatureInvariants(mol)
125
+
126
+ submoldict = {}
127
+ if with_submol_fp:
128
+ atoms, submols = subfp.get_atom_submol_radn(mol, radius, sanitize=True)
129
+ submoldict = dict(zip([a.GetIdx() for a in atoms], submols))
130
+
131
+ for i in range(mol.GetNumAtoms()):
132
+ atom_i = mol.GetAtomWithIdx(i)
133
+ if with_atom_feats:
134
+ atom_i_features = calc_atom_features_onehot(atom_i, features[i])
135
+ else:
136
+ atom_i_features = []
137
+
138
+ if with_submol_fp:
139
+ submol = submoldict[i]
140
+ # print(Chem.MolToSmiles(submol))
141
+ submolfp = subfp.gen_fps_from_mol(submol)
142
+ atom_i_features.extend(submolfp)
143
+
144
+ V.append(atom_i_features)
145
+
146
+ V = torch.FloatTensor(V)
147
+
148
+ if len(V.shape) != 2:
149
+ return None
150
+
151
+ A = calc_adjacent_tensor(mol.GetBonds(), mol.GetNumAtoms(), with_ring_conj)
152
+ A = torch.FloatTensor(A)
153
+
154
+ return {'V': V, 'A': A, 'mol_size': mol_size}
GNN/layers.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import numpy as np
6
+ import utils
7
+ import pickle
8
+
9
+ DEVICE = torch.cuda.is_available() and torch.device('cuda') or torch.device('cpu')
10
+
11
+
12
+ class GraphCNNLayer(nn.Module):
13
+ def __init__(self, n_feats, adj_chans=4, n_filters=64, bias=True):
14
+ super(GraphCNNLayer, self).__init__()
15
+ self.n_feats = n_feats
16
+ self.adj_chans = adj_chans
17
+ self.n_filters = n_filters
18
+ self.has_bias = bias
19
+
20
+ # [C*L, F], C = n_feats, L = adj_chans, F = n_filters; this is for the edge feats
21
+ self.weight_e = nn.Parameter(torch.FloatTensor(adj_chans*n_feats, n_filters))
22
+ # [C, F], this is for 𝐈𝐕in𝐖0
23
+ self.weight_i = nn.Parameter(torch.FloatTensor(n_feats, self.n_filters))
24
+
25
+ if bias:
26
+ self.bias = nn.Parameter(torch.FloatTensor(n_filters))
27
+ else:
28
+ self.register_parameter('bias', None)
29
+
30
+ self.reset_parameters()
31
+
32
+ def reset_parameters(self):
33
+ nn.init.xavier_uniform_(self.weight_e)
34
+ nn.init.xavier_uniform_(self.weight_i)
35
+
36
+ if self.bias is not None:
37
+ self.bias.data.fill_(0.01)
38
+
39
+ def forward(self, V, A):
40
+ '''V node features: [b, N, C], A adjs: [b, N, L, N], L = adj_chans'''
41
+ b, N, C = V.shape
42
+ b, N, L, _ = A.shape
43
+
44
+ # formula: 𝐕out = 𝐈𝐕in𝐖0 + GConv(𝐕in, 𝐹) + 𝐛; 𝐈𝐕in = 𝐕in, so 𝐈𝐕in𝐖0 = 𝐕in𝐖0
45
+
46
+ # A [b, N, L, N] -> [b, N*L, N]
47
+ A_reshape = A.view(-1, N*L, N)
48
+ # [b, N*L, N] * [b, N, C] -> [b, N*L, C]
49
+ n = torch.bmm(A_reshape, V)
50
+ # [b, N*L, C] -> [b, N, L*C]
51
+ n = n.view(-1, N, L*self.n_feats)
52
+
53
+ # n [b, N, L*C], W [C*L, F], V [b, N, C], W_I [C, F]
54
+ # -> [b, N, F] + [b, N, F] + b
55
+ output = torch.matmul(n, self.weight_e) + torch.matmul(V, self.weight_i)
56
+
57
+ if self.has_bias:
58
+ output += self.bias
59
+
60
+ # output: [b, N, F]
61
+ return output
62
+
63
+ def __repr__(self):
64
+ return f'{self.__class__.__name__}(n_feats={self.n_feats},adj_chans={self.adj_chans},n_filters={self.n_filters},bias={self.has_bias}) -> [b, N, {self.n_filters}]'
65
+
66
+
67
+ class GraphResidualCNNLayer(nn.Module):
68
+ def __init__(self, n_feats, adj_chans=4, bias=True):
69
+ super(GraphResidualCNNLayer, self).__init__()
70
+ self.n_feats = n_feats
71
+ self.adj_chans = adj_chans
72
+ self.has_bias = bias
73
+
74
+ # [C*L, F], C = n_feats, L = adj_chans
75
+ self.weight_layers = nn.ModuleList([nn.Linear(n_feats, n_feats) for _ in range(adj_chans)])
76
+
77
+ if bias:
78
+ self.bias = nn.Parameter(torch.FloatTensor(n_feats))
79
+ else:
80
+ self.register_parameter('bias', None)
81
+
82
+ self.reset_parameters()
83
+
84
+ def reset_parameters(self):
85
+ if self.bias is not None:
86
+ self.bias.data.fill_(0.01)
87
+
88
+ def forward(self, V, A):
89
+ '''V node features: [b, N, C], A adjs: [b, N, L, N], L = adj_chans'''
90
+ b, N, C = V.shape
91
+ b, N, L, _ = A.shape
92
+
93
+ for i in range(self.adj_chans):
94
+ # [b, N, C] -> [b, N, C]
95
+ hs = F.relu(self.weight_layers[i](V))
96
+ # [b, N, N]
97
+ a = A[:, :, i, :]
98
+ a = a.view(-1, N, N)
99
+ # [b, N, N] * [b, N, C] -> [b, N, C]
100
+ V = V + torch.bmm(a, hs)
101
+
102
+ if self.has_bias:
103
+ V += self.bias
104
+
105
+ # output: [b, N, C]
106
+ return V
107
+
108
+ def __repr__(self):
109
+ return f'{self.__class__.__name__}(n_feats={self.n_feats},adj_chans={self.adj_chans},bias={self.has_bias}) -> [b, N, {self.n_feats}]'
110
+
111
+
112
+ class GraphAttentionLayer(nn.Module):
113
+ def __init__(self, n_feats, adj_chans=4, n_filters=64, bias=True, dropout=0., alpha=0.2):
114
+ super(GraphAttentionLayer, self).__init__()
115
+ self.n_feats = n_feats
116
+ self.adj_chans = adj_chans
117
+ self.n_filters = n_filters
118
+ self.has_bias = bias
119
+ self.dropout = dropout
120
+ self.alpha = alpha
121
+
122
+ # [C*L, F], C = n_feats, L = adj_chans, F = n_filters; this is for the edge feats
123
+ self.weight_list = nn.ParameterList([nn.Parameter(torch.FloatTensor(n_feats, n_filters)) for _ in range(adj_chans)])
124
+ self.a1_list = nn.ParameterList([nn.Parameter(torch.FloatTensor(n_filters, 1)) for _ in range(adj_chans)])
125
+ self.a2_list = nn.ParameterList([nn.Parameter(torch.FloatTensor(n_filters, 1)) for _ in range(adj_chans)])
126
+
127
+ if bias:
128
+ self.bias = nn.Parameter(torch.FloatTensor(n_filters))
129
+ else:
130
+ self.register_parameter('bias', None)
131
+
132
+ self.reset_parameters()
133
+
134
+ def reset_parameters(self):
135
+ for w in self.weight_list:
136
+ nn.init.xavier_uniform_(w)
137
+ for w in self.a1_list:
138
+ nn.init.xavier_uniform_(w)
139
+ for w in self.a2_list:
140
+ nn.init.xavier_uniform_(w)
141
+ if self.bias is not None:
142
+ self.bias.data.fill_(0.01)
143
+
144
+ def forward(self, V, A):
145
+ '''V node features: [b, N, C], A adjs: [b, N, L, N], L = adj_chans'''
146
+ b, N, C = V.shape
147
+ b, N, L, _ = A.shape
148
+
149
+ output = None
150
+
151
+ # formula: 𝐕out = 𝐈𝐕in𝐖0 + GConv(𝐕in, 𝐹) + 𝐛; 𝐈𝐕in = 𝐕in, so 𝐈𝐕in𝐖0 = 𝐕in𝐖0
152
+ for i in range(self.adj_chans):
153
+ # [b, N, 1, N] -> [b, N, N]
154
+ adj = A[:, :, i, :].view(-1, N, N)
155
+
156
+ # [b, N, C] * [C, F] -> [b, N, F]
157
+ h = torch.matmul(V, self.weight_list[i])
158
+ # [b, N, F] * [F, 1] -> [b, N, 1]
159
+ f_1 = torch.matmul(h, self.a1_list[i])
160
+ # [b, N, F] * [F, 1] -> [b, N, 1]
161
+ f_2 = torch.matmul(h, self.a2_list[i])
162
+
163
+ # leaky_relu([b, N, 1] + [b, 1, N]) -> [b, N, N]
164
+ e = F.leaky_relu(f_1 + f_2.transpose(1, 2), self.alpha)
165
+
166
+ zero_vec = -9e15 * torch.ones_like(e)
167
+ # [b, N, N]
168
+ att = torch.where(adj > 0, e, zero_vec)
169
+ att = F.softmax(att, dim=1)
170
+ att = F.dropout(att, self.dropout, training=self.training)
171
+ # [b, N, N] * [b, N, F] -> [b, N, F]
172
+ if output is None:
173
+ output = torch.matmul(att, h)
174
+ else:
175
+ output += torch.matmul(att, h)
176
+
177
+ if self.has_bias:
178
+ output += self.bias
179
+
180
+ # output: [b, N, F]
181
+ return output
182
+
183
+ def __repr__(self):
184
+ return f'{self.__class__.__name__}(n_feats={self.n_feats},adj_chans={self.adj_chans},n_filters={self.n_filters},bias={self.has_bias},dropout={self.dropout},alpha={self.alpha}) -> [b, N, {self.n_filters}]'
185
+
186
+
187
+ class GraphNodeCatGlobalFeatures(nn.Module):
188
+ def __init__(self, global_feats, out_feats, mols=1, bias=True):
189
+ super(GraphNodeCatGlobalFeatures, self).__init__()
190
+ self.global_feats = global_feats
191
+ self.out_feats = out_feats
192
+ self.mols = mols
193
+ self.has_bias = bias
194
+
195
+ self.weights = nn.ParameterList([nn.Parameter(torch.FloatTensor(int(global_feats/mols), out_feats)) for _ in range(mols)])
196
+
197
+ self.biass = []
198
+ if bias:
199
+ self.biass = nn.ParameterList([nn.Parameter(torch.FloatTensor(out_feats)) for _ in range(mols)])
200
+ else:
201
+ self.register_parameter('bias', None)
202
+
203
+ self.reset_parameters()
204
+
205
+ def reset_parameters(self):
206
+ for weight in self.weights:
207
+ nn.init.xavier_uniform_(weight)
208
+ for bias in self.biass:
209
+ bias.data.fill_(0.01)
210
+
211
+ def forward(self, V, global_state, graph_size, subgraph_size=None):
212
+ # V: [b, N, Ov], global_state: [b, F], subgraph_size: [b, mols]
213
+ b, N, Ov = V.shape
214
+ O = self.out_feats
215
+ if self.mols == 1:
216
+ subgraph_size = graph_size.view(-1, 1)
217
+ global_state = torch.mm(global_state, self.weights[0])
218
+ else:
219
+ # global_state: [b, F] view -> [b*mols, F/mols]
220
+ global_state_view = global_state.view(b*self.mols, -1)
221
+
222
+ # split global_state into that of individual mols
223
+ idxmols = []
224
+ for i in range(self.mols):
225
+ idxmols.append(torch.IntTensor(list(range(i, b*self.mols, self.mols))).to(self.weights[0].device))
226
+
227
+ global_states = []
228
+ for i, idx in enumerate(idxmols):
229
+ # selected global_state of mols from global_state_view [b*mols, F/mols]. Out shape is [b, F/mols]
230
+ gs = global_state_view.index_select(dim=0, index=idx)
231
+ # gs: [b, F/mols] * weight: [F/mols, O] -> [b, O]; F = global_feats, O = out_feats
232
+ gs = torch.mm(gs, self.weights[i])
233
+
234
+ if self.has_bias:
235
+ gs += self.biass[i]
236
+
237
+ global_states.append(F.relu(gs))
238
+
239
+ # convert global_states back to global_state
240
+ # [[b, O] ... ] -> [b, mols*O]
241
+ global_state = torch.cat(global_states, dim=1)
242
+
243
+ # [b, mols*O] || [b, O] -> [b, (mols+1)*O]
244
+ global_state_new = torch.cat([global_state, torch.zeros(b, O).to(self.weights[0].device)], dim=-1)
245
+ # [b*(mols+1), O]
246
+ global_state_new = global_state_new.view(-1, O)
247
+
248
+ repeats = []
249
+ for sz in subgraph_size:
250
+ repeats.extend(sz.tolist() + [N-sz.sum()])
251
+ repeats = torch.tensor(repeats).to(self.weights[0].device)
252
+
253
+ # repeat form [b*(mols+1), O] -> [b*N, O], the content like [m1_feats, m2_feats, ... mn_feats, pads, ...]
254
+ global_state_new = global_state_new.repeat_interleave(repeats, dim=0)
255
+
256
+ # V view: [b*N, Ov], global_state_new: [b*N, O]
257
+ output = torch.cat([V.contiguous().view(-1, Ov), global_state_new], dim=1)
258
+
259
+ # output: [b, N, Ov+O]
260
+ return output.view(-1, N, Ov+O), global_state
261
+
262
+ def __repr__(self):
263
+ return f'{self.__class__.__name__}(global_feats={self.global_feats},out_feats={self.out_feats},bias={self.has_bias}) -> [b, N, {self.global_feats+self.out_feats}], [b, out_feats]'
264
+
265
+
266
+ class MultiHeadGlobalAttention(nn.Module):
267
+ '''Input [b, N, C] -> output [b, n_head*C] if concat or else [b, n_head]'''
268
+ def __init__(self, n_feats, n_head=5, alpha=0.2, concat=True, bias=True):
269
+ super(MultiHeadGlobalAttention, self).__init__()
270
+
271
+ self.n_feats = n_feats
272
+ self.n_head = n_head
273
+ self.alpha = alpha
274
+ self.concat = concat
275
+ self.has_bias = bias
276
+
277
+ self.weight = nn.Parameter(torch.FloatTensor(n_feats, n_head*n_feats))
278
+ self.tune_weight = nn.Parameter(torch.FloatTensor(1, n_head, n_feats))
279
+
280
+ if bias:
281
+ self.bias = nn.Parameter(torch.FloatTensor(n_head*n_feats))
282
+ else:
283
+ self.register_parameter('bias', None)
284
+
285
+ self.reset_parameters()
286
+
287
+ def reset_parameters(self):
288
+ nn.init.xavier_uniform_(self.weight)
289
+ nn.init.xavier_uniform_(self.tune_weight)
290
+ if self.bias is not None:
291
+ self.bias.data.fill_(0.01)
292
+
293
+ def forward(self, V, graph_size):
294
+ # Gather V of mols in a batch, after this, the pad was removed.
295
+ # print(248, V.shape, graph_size)
296
+ if V.shape[0] == 1:
297
+ Vg = torch.squeeze(V)
298
+ graph_size = [graph_size]
299
+ else:
300
+ Vg = torch.cat([torch.split(v.view(-1, v.shape[-1]), graph_size[i])[0] for i,v in enumerate(torch.split(V, 1))], dim=0)
301
+
302
+ Vg = torch.matmul(Vg, self.weight)
303
+ if self.has_bias:
304
+ Vg += self.bias
305
+ Vg = Vg.view(-1, self.n_head, self.n_feats)
306
+
307
+ alpha = torch.mul(self.tune_weight, Vg)
308
+ alpha = torch.sum(alpha, dim=-1)
309
+ alpha = F.leaky_relu(alpha, self.alpha) # original code is "alpha = tf.nn.leaky_relu(alpha, alpha=0.2)"
310
+ alpha = utils.segment_softmax(alpha, graph_size)
311
+
312
+ # alpha_collect = torch.mean(alpha, dim=-1) # origin code like this. alpha_collect not used?
313
+ alpha = alpha.view(-1, self.n_head, 1)
314
+ V = torch.mul(Vg, alpha)
315
+
316
+ if self.concat:
317
+ V = utils.segment_sum(V, graph_size)
318
+ V = V.view(-1, self.n_head*self.n_feats)
319
+ else:
320
+ V = torch.mean(V, dim=1)
321
+ V = utils.segment_sum(V, graph_size)
322
+
323
+ return V
324
+
325
+ def __repr__(self):
326
+ if self.concat:
327
+ outc = self.n_head*self.n_feats
328
+ else:
329
+ outc = self.n_head
330
+ return f'{self.__class__.__name__}(n_feats={self.n_feats},n_head={self.n_head},alpha={self.alpha},concat={self.concat},bias={self.has_bias}) -> [b, {outc}]'
331
+
332
+
333
+ class GraphEmbedPoolingLayer(nn.Module):
334
+ def __init__(self, n_feats, n_filters=1, mask=None, bias=True):
335
+ super(GraphEmbedPoolingLayer, self).__init__()
336
+ self.n_feats = n_feats
337
+ self.n_filters = n_filters
338
+ self.mask = mask
339
+ self.has_bias = bias
340
+
341
+ self.emb = nn.Linear(n_feats, n_filters, bias=bias)
342
+
343
+ def forward(self, V, A):
344
+ # [b, N, F]
345
+ factors = self.emb(V)
346
+
347
+ if self.mask is not None:
348
+ factors = torch.mul(factors, self.mask)
349
+
350
+ factors = F.softmax(factors, dim=1)
351
+ # [b, N, F] trans -> [b, F, N] * [b, N, C] -> [b, F, C]
352
+ result = torch.matmul(factors.transpose(1, 2).contiguous(), V)
353
+
354
+ if self.n_filters == 1:
355
+ return result.view(-1, self.n_feats), A
356
+
357
+ result_A = A.view(A.shape[0], -1, A.shape[-1])
358
+ result_A = torch.matmul(result_A, factors)
359
+ result_A = result_A.view(A.shape[0], A.shape[-1], -1)
360
+ result_A = torch.matmul(factors.transpose(1, 2).contiguous(), result_A)
361
+ result_A = result_A.view(A.shape[0], self.n_filters, A.shape[2], self.n_filters)
362
+
363
+ return result, result_A
364
+
365
+ def __repr__(self):
366
+ return f'{self.__class__.__name__}(n_feats={self.n_feats},n_filters={self.n_filters},mask={self.mask},bias={self.has_bias}) -> [b, {self.n_filters}, {self.n_feats}], [b, {self.n_filters}, L, {self.n_filters}]'
367
+
368
+
369
+ class GConvBlockWithGF(nn.Module):
370
+ def __init__(self, n_feats, n_filters, global_feats, global_out_feats, mols=1, adj_chans=4, bias=True, usegat=False):
371
+
372
+ super(GConvBlockWithGF, self).__init__()
373
+
374
+ self.n_feats = n_feats
375
+ self.n_filters = n_filters
376
+ self.global_out_feats = global_out_feats
377
+ self.global_feats = global_feats
378
+ self.mols = mols
379
+ self.adj_chans = adj_chans
380
+ self.has_bias = bias
381
+ self.usegat = usegat
382
+
383
+ self.broadcast_global_state = GraphNodeCatGlobalFeatures(global_feats, global_out_feats, mols, bias)
384
+ if usegat:
385
+ self.graph_conv = GraphAttentionLayer(n_feats+global_out_feats, adj_chans, n_filters)
386
+ else:
387
+ self.graph_conv = GraphCNNLayer(n_feats+global_out_feats, adj_chans, n_filters, bias)
388
+
389
+ self.bn_global = nn.BatchNorm1d(global_out_feats*mols)
390
+ self.bn_graph = nn.BatchNorm1d(n_filters)
391
+
392
+ def forward(self, V, A, global_state, graph_size, subgraph_size):
393
+ ######## transfer global_state #########
394
+ # V shape from [b, N, C] to [b, N, C+F], F is n_filters
395
+ V, global_state = self.broadcast_global_state(V, global_state, graph_size, subgraph_size)
396
+
397
+ ######## Graph Convolution #########
398
+ # V shape from [b, N, C+F] to [b, N, F1], F1 is n_filters
399
+ V = self.graph_conv(V, A)
400
+ V = self.bn_graph(V.transpose(1, 2).contiguous())
401
+ V = F.relu(V.transpose(1, 2))
402
+
403
+ global_state = F.relu(self.bn_global(global_state))
404
+
405
+ return V, global_state
406
+
407
+ def __repr__(self):
408
+ return f'{self.__class__.__name__}(n_feats={self.n_feats},n_filters={self.n_filters},global_feats={self.global_feats},global_out_feats={self.global_out_feats},mols={self.mols},adj_chans={self.adj_chans},bias={self.has_bias},usegat={self.usegat}) -> [b, N, {self.n_filters}], [b, {self.global_out_feats*self.mols}]'
409
+
410
+
411
+ class GConvBlockNoGF(nn.Module):
412
+ def __init__(self, n_feats, n_filters, mols=1, adj_chans=4, bias=True):
413
+
414
+ super(GConvBlockNoGF, self).__init__()
415
+
416
+ self.n_feats = n_feats
417
+ self.n_filters = n_filters
418
+ self.mols = mols
419
+ self.adj_chans = adj_chans
420
+ self.has_bias = bias
421
+
422
+ # self.graph_conv = GraphCNNLayer(n_feats+n_filters, adj_chans, n_filters, bias)
423
+ self.graph_conv = GraphCNNLayer(n_feats, adj_chans, n_filters, bias)
424
+
425
+ # self.bn_global = nn.BatchNorm1d(n_filters*mols)
426
+ self.bn_graph = nn.BatchNorm1d(n_filters)
427
+
428
+ def forward(self, V, A):
429
+ ######## Graph Convolution #########
430
+ # V shape from [b, N, C+F] to [b, N, F1], F1 is n_filters
431
+ V = self.graph_conv(V, A)
432
+ V = self.bn_graph(V.transpose(1, 2).contiguous())
433
+ V = F.relu(V.transpose(1, 2))
434
+
435
+ return V
436
+
437
+ def __repr__(self):
438
+ return f'{self.__class__.__name__}(n_feats={self.n_feats},n_filters={self.n_filters},mols={self.mols},adj_chans={self.adj_chans},bias={self.has_bias}) -> [b, N, {self.n_filters}]'
GNN/subgraphfp.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rdkit import Chem
2
+ from rdkit.Chem import Draw
3
+ from rdkit.Chem import AllChem, MACCSkeys, rdMolDescriptors as rdDesc
4
+ from collections import defaultdict
5
+ import numpy as np
6
+ import os, pickle, hashlib
7
+
8
+ AllChem.SetPreferCoordGen(True)
9
+
10
+ FINGERPRINT_DICT = defaultdict(lambda : len(FINGERPRINT_DICT))
11
+
12
+ ELEMENTS = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al',
13
+ 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn',
14
+ 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb',
15
+ 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In',
16
+ 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm',
17
+ 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta',
18
+ 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At',
19
+ 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk',
20
+ 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt',
21
+ 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og']
22
+
23
+ for e in ELEMENTS:
24
+ FINGERPRINT_DICT[e]
25
+
26
+ if os.path.exists('rdkit_fingerprint_list_r1.pkl'):
27
+ l = pickle.load(open('rdkit_fingerprint_list_r1.pkl', 'rb'))
28
+
29
+ for smi in l:
30
+ FINGERPRINT_DICT[smi]
31
+
32
+ print('Len fingerprint_list: %s' %len(FINGERPRINT_DICT)) + len(ELEMENTS)
33
+
34
+
35
+ def mol_with_atom_index(mol):
36
+ atoms = mol.GetNumAtoms()
37
+ for idx in range(atoms):
38
+ mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(mol.GetAtomWithIdx(idx).GetIdx()))
39
+ return mol
40
+
41
+
42
+ def prepare_mol_for_drawing(mol):
43
+ try:
44
+ mol_draw = Draw.rdMolDraw2D.PrepareMolForDrawing(mol)
45
+ except Chem.KekulizeException:
46
+ mol_draw = Draw.rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False)
47
+ Chem.SanitizeMol(mol_draw, Chem.SANITIZE_ALL ^ Chem.SANITIZE_KEKULIZE)
48
+ return mol_draw
49
+
50
+
51
+ def get_atom_submol_radn(mol, radius, sanitize=True):
52
+ atoms = []
53
+ submols = []
54
+ # smis = []
55
+ for atom in mol.GetAtoms():
56
+ atoms.append(atom)
57
+ r = radius
58
+ while r > 0:
59
+ try:
60
+ env = Chem.FindAtomEnvironmentOfRadiusN(mol, r, atom.GetIdx())
61
+ amap={}
62
+ submol = Chem.PathToSubmol(mol, env, atomMap=amap)
63
+ if sanitize:
64
+ Chem.SanitizeMol(submol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_ALL^Chem.SanitizeFlags.SANITIZE_KEKULIZE)
65
+ # smis.append(Chem.MolToSmiles(submol))
66
+ submols.append(submol)
67
+ break
68
+ except Exception as e:
69
+ print(64, e)
70
+ r -= 1
71
+
72
+ return atoms, submols #, smis
73
+
74
+
75
+ def gen_fps_from_mol(mol, nbits=256, use_morgan=True, use_macc=False, use_rdkit=False):
76
+ # morgan
77
+ fp = []
78
+ if use_morgan:
79
+ fp_vec = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=nbits)
80
+ fp1 = np.frombuffer(fp_vec.ToBitString().encode(), 'u1') - ord('0')
81
+ fp = fp1.tolist()
82
+ if use_macc:
83
+ # MACCSkeys
84
+ fp_vec = MACCSkeys.GenMACCSKeys(mol)
85
+ fp1 = np.frombuffer(fp_vec.ToBitString().encode(), 'u1') - ord('0')
86
+ fp.extend(fp1.tolist())
87
+ if use_rdkit:
88
+ fp_vec = Chem.RDKFingerprint(mol)
89
+ fp1 = np.frombuffer(fp_vec.ToBitString().encode(), 'u1') - ord('0')
90
+ fp.extend(fp1.tolist())
91
+
92
+ return fp
93
+
94
+
95
+ def gen_subgraph_fps_from_str(s, wordsdict={}):
96
+ if s in wordsdict:
97
+ return [wordsdict[s]]
98
+ else:
99
+ return [len(wordsdict)]
100
+
101
+
102
+ def gen_subgraph_fps_from_mol(mol, wordsdict={}):
103
+ try:
104
+ k = Chem.MolToSmiles(mol)
105
+ return gen_subgraph_fps_from_str(k, wordsdict)
106
+ except Exception as e:
107
+ print(e)
108
+ return [len(wordsdict)]
109
+
110
+
111
+ def calc_subgraph_fps_from_mol(mol, radius=2, nbits=128, use_macc=True, fptype=1, wordsdict={}):
112
+ # atoms, submols, smis = get_atom_submol_radn(mol, radius, True)
113
+ atoms, submols = get_atom_submol_radn(mol, radius, True)
114
+ feats = []
115
+ for idx, submol in enumerate(submols):
116
+ if fptype == 1:
117
+ feat = gen_fps_from_mol(submol, nbits, use_macc)
118
+ feats.append(feat)
119
+ elif fptype == 2:
120
+ feat = gen_subgraph_fps_from_mol(submol, wordsdict)
121
+ feats.append(feat)
122
+
123
+ return np.array(feats)
124
+
125
+
126
+ if __name__ == '__main__':
127
+ smi = 'C=C(S)C(N)(O)C'
128
+ smi = 'CC1CCN(CC1N(C)C2=NC=NC3=C2C=CN3)C(=O)CC#N'
129
+
130
+ mol = Chem.MolFromSmiles(smi, sanitize=False)
131
+
132
+ print(calc_subgraph_fps_from_mol(mol, 3))
133
+
134
+ mol = mol_with_atom_index(mol)
135
+ submols = get_atom_submol_radn(mol, 3)
136
+ submols = [prepare_mol_for_drawing(m) for m in submols]
137
+ hl = []
138
+ for idx, m in enumerate(submols):
139
+ for a in m.GetAtoms():
140
+ if int(a.GetProp('molAtomMapNumber')) == idx:
141
+ hl.append([a.GetIdx()])
142
+ break
143
+
144
+ draw = Draw.MolsToGridImage([mol] + submols, highlightAtomLists=[[]] + hl, molsPerRow=5)
145
+ draw.show()
146
+
GNN/utils.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def gather(x, indices):
5
+ indices = indices.view(-1, indices.shape[-1]).tolist()
6
+ out = torch.cat([x[i] for i in indices])
7
+
8
+ return out
9
+
10
+
11
+ def gather_nd(x, indices):
12
+ newshape = indices.shape[:-1] + x.shape[indices.shape[-1]:]
13
+ indices = indices.view(-1, indices.shape[-1]).tolist()
14
+ out = torch.cat([x[tuple(i)] for i in indices])
15
+
16
+ return out.reshape(newshape)
17
+
18
+
19
+ def gen_node_indices(size_list):
20
+ '''generate node index for extraction of nodes of each graph from batched data'''
21
+ node_num = []
22
+ node_range = []
23
+ size_list = [int(i) for i in size_list]
24
+ for i, n in enumerate(size_list):
25
+ node_num.extend([i]*n)
26
+ node_range.extend(list(range(n)))
27
+
28
+ node_num = torch.tensor(node_num)
29
+ node_range = torch.tensor(node_range)
30
+ indices = torch.stack([node_num, node_range], axis=1)
31
+ return indices, node_num, node_range
32
+
33
+
34
+ def segment_max(x, size_list):
35
+ size_list = [int(i) for i in size_list]
36
+ return torch.stack([torch.max(v, 0).values for v in torch.split(x, size_list)])
37
+
38
+
39
+ def segment_sum(x, size_list):
40
+ size_list = [int(i) for i in size_list]
41
+ return torch.stack([torch.sum(v, 0) for v in torch.split(x, size_list)])
42
+
43
+
44
+ def segment_softmax(gate, size_list):
45
+ segmax = segment_max(gate, size_list)
46
+ # expand segmax shape to alpha shape
47
+ segmax_expand = torch.cat([segmax[i].repeat(n,1) for i,n in enumerate(size_list)], dim=0)
48
+ subtract = gate - segmax_expand
49
+ exp = torch.exp(subtract)
50
+ segsum = segment_sum(exp, size_list)
51
+ # expand segmax shape to alpha shape
52
+ segsum_expand = torch.cat([segsum[i].repeat(n,1) for i,n in enumerate(size_list)], dim=0)
53
+ attention = exp / (segsum_expand + 1e-16)
54
+
55
+ return attention
56
+
57
+
58
+ def pad_V(V, max_n):
59
+ N, C = V.shape
60
+ if max_n > N:
61
+ zeros = torch.zeros(max_n-N, C)
62
+ V = torch.cat([V, zeros], dim=0)
63
+ return V
64
+
65
+
66
+ def pad_A(A, max_n):
67
+ N, L, _ = A.shape
68
+ if max_n > N:
69
+ zeros = torch.zeros(N, L, max_n-N)
70
+ A = torch.cat([A, zeros], dim=-1)
71
+ zeros = torch.zeros(max_n-N, L, max_n)
72
+ A = torch.cat([A, zeros], dim=0)
73
+
74
+ return A
75
+
76
+
77
+ def pad_prot(P, max_n):
78
+ N, = P.shape
79
+ if max_n > N:
80
+ zeros = torch.zeros(max_n-N)
81
+ P = torch.cat([P, zeros], dim=0)
82
+
83
+ return P.type(torch.IntTensor)
84
+
85
+
86
+ def create_batch(input, pad=False, device=torch.device('cpu')):
87
+ vl = []
88
+ al = []
89
+ gsl = []
90
+ msl = []
91
+ ssl = []
92
+ lbl = []
93
+ idxs = []
94
+ smis = []
95
+
96
+ for d in input:
97
+ vl.append(d['V'])
98
+ al.append(d['A'])
99
+ gsl.append(d['G'])
100
+ msl.append(d['mol_size'])
101
+ ssl.append(d['subgraph_size'])
102
+ lbl.append(d['label'])
103
+ idxs.append(d['index'])
104
+ smis.append(d['smiles'])
105
+
106
+ if gsl[0] is not None:
107
+ gsl = torch.stack(gsl, dim=0).to(device)
108
+
109
+ if pad:
110
+ max_n = max(map(lambda x:x.shape[0], vl))
111
+ vl1 = []
112
+ for v in vl:
113
+ vl1.append(pad_V(v, max_n))
114
+ al1 = []
115
+ for a in al:
116
+ al1.append(pad_A(a, max_n))
117
+
118
+ return {'V': torch.stack(vl1, dim=0).to(device),
119
+ 'A': torch.stack(al1, dim=0).to(device),
120
+ 'G': gsl,
121
+ 'mol_size': torch.cat(msl, dim=0).to(device),
122
+ 'subgraph_size': torch.stack(ssl, dim=0).to(device),
123
+ 'label': torch.stack(lbl, dim=0).to(device),
124
+ 'index': idxs,
125
+ 'smiles': smis}
126
+
127
+ return {'V': torch.stack(vl, dim=0).to(device),
128
+ 'A': torch.stack(al, dim=0).to(device),
129
+ 'G': gsl,
130
+ 'mol_size': torch.cat(msl, dim=0).to(device),
131
+ 'subgraph_size': torch.stack(ssl, dim=0).to(device),
132
+ 'label': torch.stack(lbl, dim=0).to(device),
133
+ 'index': idxs,
134
+ 'smiles': smis}
135
+
136
+
137
+ def create_mol_protein_batch(input, pad=False, device=torch.device('cpu'), pr=True):
138
+ vl = []
139
+ al = []
140
+ gsl = []
141
+ msl = []
142
+ ssl = []
143
+ prot = []
144
+ seq = []
145
+ lbl = []
146
+ idxs = []
147
+ smis = []
148
+ fpl = []
149
+
150
+ for d in input:
151
+ vl.append(d['V'])
152
+ al.append(d['A'])
153
+ gsl.append(d['G'])
154
+ msl.append(d['mol_size'])
155
+ ssl.append(d['subgraph_size'])
156
+ prot.append(d['protein_seq'])
157
+ seq.append(d['protein'])
158
+ lbl.append(d['label'])
159
+ idxs.append(d['index'])
160
+ smis.append(d['smiles'])
161
+ if 'fp' in d:
162
+ fpl.append(d['fp'])
163
+
164
+ if gsl[0] is not None:
165
+ if pad:
166
+ gsl = torch.stack(gsl, dim=0).to(device)
167
+ else:
168
+ gsl = [torch.unsqueeze(g, 0) for g in gsl]
169
+
170
+ fpt = None
171
+ if pad:
172
+ max_n = max(map(lambda x:x.shape[0], vl))
173
+ vl1 = []
174
+ if pr:
175
+ print('\tPadding V to max_n:', max_n)
176
+ for v in vl:
177
+ vl1.append(pad_V(v, max_n))
178
+
179
+ al1 = []
180
+ if pr:
181
+ print('\tPadding A to max_n:', max_n)
182
+ for a in al:
183
+ al1.append(pad_A(a, max_n))
184
+
185
+ max_prot = max(map(lambda x:x.shape[0], prot))
186
+ prot1 = []
187
+ if pr:
188
+ print('\tPadding protein_seq to max_n:', max_prot)
189
+ for p in prot:
190
+ prot1.append(pad_prot(p, max_prot))
191
+
192
+ fpt = None
193
+ if fpl:
194
+ fpt = torch.stack(fpl, dim=0).to(device)
195
+
196
+ return {'V': torch.stack(vl1, dim=0).to(device),
197
+ 'A': torch.stack(al1, dim=0).to(device),
198
+ 'G': gsl,
199
+ 'fp': fpt,
200
+ 'mol_size': torch.cat(msl, dim=0).to(device),
201
+ 'subgraph_size': torch.stack(ssl, dim=0).to(device),
202
+ 'protein_seq': torch.stack(prot1, dim=0).to(device),
203
+ 'label': torch.stack(lbl, dim=0).view(-1).to(device),
204
+ 'index': idxs,
205
+ 'smiles': smis,
206
+ 'protein': seq}
207
+
208
+ return {'V': [torch.unsqueeze(v, 0) for v in vl],
209
+ 'A': [torch.unsqueeze(a, 0) for a in al],
210
+ 'G': gsl,
211
+ 'fp': fpt,
212
+ 'mol_size': torch.cat(msl, dim=0).to(device),
213
+ 'subgraph_size': [torch.unsqueeze(s, 0) for s in ssl],
214
+ 'protein_seq': [torch.unsqueeze(p, 0) for p in prot],
215
+ 'label': torch.stack(lbl, dim=0).view(-1).to(device),
216
+ 'index': idxs,
217
+ 'smiles': smis,
218
+ 'protein': seq}
219
+
220
+
221
+ def create_mol_protein_fp_batch(input, pad=False, device=torch.device('cpu'), pr=True):
222
+ fp = []
223
+ prot = []
224
+ lbl = []
225
+ idxs = []
226
+ smis = []
227
+
228
+ for d in input:
229
+ fp.append(d['fp'])
230
+ prot.append(d['protein_seq'])
231
+ lbl.append(d['label'])
232
+ idxs.append(d['index'])
233
+ smis.append(d['smiles'])
234
+
235
+ if pad:
236
+ max_prot = max(map(lambda x: x.shape[0], prot))
237
+ prot1 = []
238
+ if pr:
239
+ print('\tPadding protein_seq to max_n:', max_prot)
240
+ for p in prot:
241
+ prot1.append(pad_prot(p, max_prot))
242
+
243
+ return {'fp': torch.stack(fp, dim=0).to(device),
244
+ 'protein_seq': torch.stack(prot1, dim=0).to(device),
245
+ 'label': torch.stack(lbl, dim=0).view(-1).to(device),
246
+ 'index': idxs,
247
+ 'smiles': smis}
248
+
249
+ return {'fp': [torch.unsqueeze(f, 0) for f in fp],
250
+ 'protein_seq': [torch.unsqueeze(p, 0) for p in prot],
251
+ 'label': torch.stack(lbl, dim=0).view(-1).to(device),
252
+ 'index': idxs,
253
+ 'smiles': smis}
a_predict222.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- conding: utf-8 -*-
2
+ # @Time : 2025/12/14 10:58
3
+ # @Author : psi
4
+
5
+ from utils import *
6
+ from modules import *
7
+ import os, sys
8
+ import numpy as np
9
+ from tqdm import tqdm
10
+ import random
11
+ import torch
12
+ from torch import nn
13
+ from config import CFG
14
+ from dataset import *
15
+ import torch.utils.data
16
+ import copy, json, pickle
17
+ import itertools as it
18
+ import glob
19
+ import torch.nn.functional as F
20
+
21
+
22
+ def my_collate(batch):
23
+ batch = list(filter(lambda x: (x is not None), batch))
24
+ msbinl, molfpl, molfml, vl, al, msl = [], [], [], [], [], []
25
+ bat = {}
26
+ msbinl1, msbinl2 = [], []
27
+
28
+ for b in batch:
29
+ if 'ms_bins' in b:
30
+ msbinl.append(b['ms_bins'])
31
+ if 'ms_bins1' in b:
32
+ msbinl1.append(b['ms_bins1'])
33
+ if 'ms_bins2' in b:
34
+ msbinl2.append(b['ms_bins2'])
35
+ if 'mol_fps' in b:
36
+ molfpl.append(b['mol_fps'])
37
+ if 'mol_fmvec' in b:
38
+ molfml.append(b['mol_fmvec'])
39
+ if 'V' in b:
40
+ vl.append(b['V'])
41
+ if 'A' in b:
42
+ al.append(b['A'])
43
+ if 'mol_size' in b:
44
+ msl.append(b['mol_size'])
45
+
46
+ if msbinl:
47
+ bat['ms_bins'] = torch.stack(msbinl)
48
+ if msbinl1:
49
+ bat['ms_bins1'] = torch.stack(msbinl1)
50
+ if msbinl2:
51
+ bat['ms_bins2'] = torch.stack(msbinl2)
52
+ if molfpl:
53
+ bat['mol_fps'] = torch.stack(molfpl)
54
+ if molfml:
55
+ bat['mol_fmvec'] = torch.stack(molfml)
56
+ if vl and al and msl:
57
+ max_n = max(map(lambda x:x.shape[0], vl))
58
+ vl1, al1 = [], []
59
+ for v in vl:
60
+ vl1.append(pad_V(v, max_n))
61
+ for a in al:
62
+ al1.append(pad_A(a, max_n))
63
+
64
+ bat['V'] = torch.stack(vl1)
65
+ bat['A'] = torch.stack(al1)
66
+ bat['mol_size'] = torch.cat(msl, dim=0)
67
+
68
+ # return torch.utils.data.dataloader.default_collate(batch)
69
+ return bat
70
+
71
+
72
+ def build_loaders(inp, mode, cfg, num_workers):
73
+ if type(inp[0]) is dict:
74
+ dataset = Dataset(inp, cfg)
75
+ else:
76
+ dataset = PathDataset(inp, cfg)
77
+ dataloader = torch.utils.data.DataLoader(
78
+ dataset,
79
+ batch_size=len(dataset),
80
+ num_workers=num_workers,
81
+ shuffle=True if mode == "train" else False,
82
+ collate_fn=my_collate
83
+ )
84
+ return dataloader
85
+
86
+
87
+ class Predictor():
88
+
89
+ def __init__(self, file, model_file):
90
+ CFG.load(file)
91
+ cfg = CFG
92
+ self.cfg = cfg
93
+ model = FragSimiModelNew(cfg).to(cfg.device)
94
+ encmodel = torch.load(model_file)
95
+ # model.mol_gnn_encoder.load_state_dict(encmodel.mol_gnn_encoder.state_dict())
96
+ model.load_state_dict(encmodel['state_dict'])
97
+
98
+ self.model = model
99
+ self.model.eval()
100
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
101
+
102
+ def process_file(self, ms, smi):
103
+ # d = json.load(open(file, 'r', encoding='utf-8'))
104
+ # ms = d['ms']
105
+ # smi = d['smiles']
106
+ # out = {'ms': ms, 'smiles': smi}
107
+ # ms = self.data[idx]['ms']
108
+ # smi = self.data[idx]['smiles']
109
+ nls = []
110
+ item = calc_feats(smi, ms, nls, self.cfg)
111
+ return item
112
+
113
+ def process(self, data):
114
+
115
+ res = []
116
+
117
+ for d in data:
118
+ try:
119
+ res.append([d['smiles'], self.process_file(d['ms'], d['smiles'])])
120
+ except Exception as e:
121
+ print(e)
122
+
123
+ if len(res) == 0:
124
+ return None
125
+
126
+ res1 = [x[1] for x in res]
127
+ res2 = [x[0] for x in res]
128
+
129
+ batch = my_collate(res1)
130
+
131
+ return batch, res2
132
+
133
+ def get_eval_info(self, ms_embeddings, mol_embeddings, top_ks=(1, 3, 5, 10)):
134
+ N = ms_embeddings.shape[0]
135
+
136
+ # 1. L2 归一化(非常关键)
137
+ # ms_norm = F.normalize(ms_embeddings, dim=1)
138
+ # mol_norm = F.normalize(mol_embeddings, dim=1)
139
+ ms_norm = ms_embeddings
140
+ mol_norm = mol_embeddings
141
+
142
+ recalls = {k: 0 for k in top_ks}
143
+
144
+ # 2. 对每个样本做检索
145
+ for i in range(N):
146
+ query = ms_norm[i] # (256,)
147
+ sims = torch.matmul(mol_norm, query) # (N,)
148
+
149
+ ranked_indices = torch.argsort(sims, descending=True)
150
+
151
+ for k in top_ks:
152
+ if i in ranked_indices[:k]:
153
+ recalls[k] += 1
154
+
155
+ # 3. 取平均
156
+ for k in recalls:
157
+ recalls[k] /= N
158
+
159
+ return recalls
160
+
161
+ def topk_similarity(self, ms_embedding, res_embeddings, batch_size=128, top_k=10):
162
+
163
+ ms_embedding = ms_embedding.to(self.device)
164
+ res_embeddings = res_embeddings.to(self.device)
165
+
166
+ # 保证是 float tensor
167
+ ms_embedding = ms_embedding.float()
168
+ res_embeddings = res_embeddings.float()
169
+
170
+ # 归一化(用于余弦相似度)
171
+ # ms_embedding = F.normalize(ms_embedding, dim=1)
172
+ # res_embeddings = F.normalize(res_embeddings, dim=1)
173
+
174
+ similarities = []
175
+
176
+ # 分 batch 计算
177
+ for i in range(0, res_embeddings.size(0), batch_size):
178
+ batch = res_embeddings[i:i + batch_size] # (B, 256)
179
+
180
+ # (1, 256) @ (256, B) -> (1, B)
181
+ sim = torch.matmul(ms_embedding, batch.T) # 余弦相似度
182
+ similarities.append(sim.squeeze(0)) # (B,)
183
+
184
+ # 拼接成 (15511,)
185
+ similarities = torch.cat(similarities, dim=0)
186
+
187
+ top_k = min(top_k, res_embeddings.size(0))
188
+ # 取 top_k
189
+ topk_sim, topk_idx = torch.topk(similarities, k=top_k)
190
+
191
+ return topk_sim, topk_idx
192
+
193
+ def predict(self, data):
194
+ # data_files = []
195
+ # for root, _, files in os.walk(file_path):
196
+ # for f in files:
197
+ # if f.endswith(('.json', '.pkl', '.mgf')):
198
+ # data_files.append(os.path.join(root, f))
199
+ # data = sorted(
200
+ # data_files,
201
+ # key=lambda x: int(os.path.splitext(os.path.basename(x))[0])
202
+ # )
203
+ batch, res_smiles = self.process(data)
204
+
205
+ if batch is None:
206
+ return None
207
+
208
+ for k, v in batch.items():
209
+ batch[k] = v.to(self.cfg.device)
210
+
211
+ loss, loss_infonce, loss_mse, ms_embeddings, mol_embeddings = self.model(batch, is_predict=True)
212
+
213
+ # recalls_info = self.get_eval_info(ms_embeddings, mol_embeddings)
214
+ # print(recalls_info)
215
+ #
216
+ # return loss, loss_infonce, loss_mse, recalls_info
217
+
218
+ ms_embedding = ms_embeddings[0:1, :]
219
+
220
+ topk_sim, topk_idx = self.topk_similarity(ms_embedding, mol_embeddings)
221
+ topk_idx = topk_idx.to("cpu").numpy().tolist()
222
+
223
+ res_pred_name = []
224
+ for x, i in enumerate(topk_idx):
225
+ res_pred_name.append([res_smiles[i], topk_sim[x].item()])
226
+
227
+ return res_pred_name
228
+
229
+
230
+ model_file = ["/root/代码/out_data/train-020/model-tloss3.239-vloss2.752-epoch0.pth",
231
+ "/root/代码/out_data/train-020/model-tloss2.487-vloss2.279-epoch1.pth",
232
+ "/root/代码/out_data/train-020/model-tloss2.086-vloss1.924-epoch2.pth",
233
+ "/root/代码/out_data/train-020/model-tloss1.716-vloss1.609-epoch3.pth",
234
+ "/root/代码/out_data/train-020/model-tloss1.414-vloss1.361-epoch4.pth",
235
+ '/root/代码/out_data/train-020/model-tloss1.177-vloss1.173-epoch5.pth',
236
+ "/root/代码/out_data/train-020/model-tloss0.99-vloss1.036-epoch6.pth",
237
+ '/root/代码/out_data/train-020/model-tloss0.849-vloss0.929-epoch7.pth',
238
+ '/root/代码/out_data/train-020/model-tloss0.736-vloss0.851-epoch8.pth',
239
+ '/root/代码/out_data/train-020/model-tloss0.647-vloss0.779-epoch9.pth',
240
+ '/root/代码/out_data/train-020/model-tloss0.575-vloss0.728-epoch10.pth'][-1]
241
+
242
+ pred = Predictor('config.json', model_file)
243
+
244
+
245
+ if __name__ == '__main__':
246
+
247
+
248
+ # file_path = ["../../data/CASMI2016/data/neg", "../../data/CASMI2017/data/neg"][0]
249
+ ms = [
250
+ [
251
+ 107.049103,
252
+ 11496.099609
253
+ ],
254
+ [
255
+ 131.050201,
256
+ 12601.5
257
+ ],
258
+ [
259
+ 157.053299,
260
+ 11285.700195
261
+ ],
262
+ [
263
+ 158.061096,
264
+ 2146837.0
265
+ ],
266
+ [
267
+ 222.022995,
268
+ 10585360.0
269
+ ]
270
+ ]
271
+ data = [{'ms': ms, 'smiles': "NC1=C2C=CC(=CC2=CC=C1)S(O)(=O)=O"},
272
+ {'ms': ms, 'smiles': "OS(=O)(=O)c1ccc2ccc(cc2c1)S(O)(=O)=O"},
273
+ {'ms': ms, 'smiles': "OC1=CC=CC2=C(C=CC=C12)S(O)(=O)=O"},
274
+ {'ms': ms, 'smiles': "OC(=O)c1nc(Cl)ccc1Cl"},
275
+ {'ms': ms, 'smiles': "CN1C=NC(=C1SC1=C2NC=NC2=NC=N1)[N+]([O-])=O"},
276
+ {'ms': ms, 'smiles': "CC(=O)NC1=CC=C(O)C(=C1)C(O)=O"}]
277
+ res_pred_name = pred.predict(data)
278
+
279
+ print(res_pred_name)
280
+
281
+
282
+
app.py ADDED
@@ -0,0 +1,996 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- conding: utf-8 -*-
2
+ # @Time : 2025/12/22 18:48
3
+ # @Author : psi
4
+ # -*- coding: utf-8 -*-
5
+ # @Time : 2025/12/22
6
+ # @Author : psi
7
+ import json
8
+ import time
9
+ import gradio as gr
10
+ import pandas as pd
11
+ from rdkit import Chem
12
+ from rdkit.Chem import Draw
13
+ import os
14
+ from PIL import Image
15
+ import base64
16
+ from smiles_to_pubchem_2d_image import smiles_to_pubchem_2d_image
17
+
18
+ flag_t = True
19
+
20
+ if flag_t:
21
+ from infer_predict111 import infer_online as pos_infer_online
22
+ # from infer_predict222 import infer_online as neg_infer_online
23
+
24
+ # from a_predict111 import pred as pos_pred
25
+ # from a_predict222 import pred as neg_pred
26
+
27
+
28
+ base_image_path = "/Users/xiaojie/Documents/lunwen/代码/data/"
29
+ logo_image_local_path = "logo_1.png"
30
+
31
+ # =========================
32
+ # 系统 SMILES 库(示例)
33
+ # =========================
34
+ SYSTEM_SMILES_DB = [
35
+ 'Br.C=CC1CN2CCC1CC2C(O)c1ccnc2ccc(OC)cc12',
36
+ "CCOC(=O)c1ccc(CCN)cc1",
37
+ "CN1CCN(CC1)C2=CC=CC=C2",
38
+ "COC1=CC=CC=C1C(=O)O",
39
+ "CCN(CC)C(=O)C1=CC=CC=C1",
40
+ "CCC1=CC=CC=C1O",
41
+ 'Br.C=CC1CN2CCC1CC2C(O)c1ccnc2ccc(OC)cc12',
42
+ ]
43
+
44
+
45
+ def infer_ms(msp_file, ion_mode, parent_mass, parent_mass_bn=50):
46
+ if ion_mode == "pos":
47
+ return pos_infer_online.infer(msp_file, parent_mass, parent_mass_bn)
48
+ else:
49
+ return neg_infer_online.infer(msp_file, parent_mass, parent_mass_bn)
50
+
51
+
52
+ # =========================
53
+ # Mock Cross-modal Retrieval
54
+ # =========================
55
+ def cross_modal_retrieval(parent_mass, ion_mode, msp_file, user_smiles, parent_mass_bn=50):
56
+ """
57
+ 真实版本中替换为:
58
+ - MS2 embedding
59
+ - SMILES embedding
60
+ - cosine similarity top-k
61
+ """
62
+
63
+ if not flag_t:
64
+ candidates = SYSTEM_SMILES_DB + user_smiles
65
+ return candidates[:8] # 故意 <10,用于测试留空逻辑
66
+
67
+ res_pred_name1 = infer_ms(msp_file, ion_mode, parent_mass, parent_mass_bn)
68
+
69
+ if len(user_smiles) == 0:
70
+ return res_pred_name1
71
+
72
+ data = []
73
+ for x in user_smiles:
74
+ data.append({'ms': msp_file, "smiles": x})
75
+
76
+ if ion_mode == "pos":
77
+ # results = pos_pred.predict(data)
78
+ results = pos_infer_online.pred_model.predict_1(data)
79
+ else:
80
+ # results = neg_pred.predict(data)
81
+ results = neg_infer_online.pred_model.predict_1(data)
82
+
83
+ if results is None:
84
+ return res_pred_name1
85
+
86
+ res_pred_name1 = res_pred_name1 + results
87
+
88
+ res_pred_name1 = sorted(res_pred_name1, key=lambda x: x[1], reverse=True)
89
+
90
+ return res_pred_name1[:10]
91
+
92
+
93
+ # =========================
94
+ # SMILES → Image
95
+ # =========================
96
+ def smiles_to_image1(smiles, size=(300, 300)):
97
+ mol = Chem.MolFromSmiles(smiles)
98
+ if mol is None:
99
+ return None
100
+ return Draw.MolToImage(mol, size=size)
101
+
102
+
103
+ def smiles_to_image(smiles, size=(300, 300)):
104
+ """
105
+ 通过读取本地文件并 Resize 后返回 PIL 对象,避免 Gradio 路径权限报错
106
+ """
107
+ # 你的图片基础路径
108
+ # base_image_path = "/Users/xiaojie/Documents/lunwen/代码/data/"
109
+
110
+ # 构造图片完整路径(这里假设文件名就是 smiles + .png)
111
+ # 如果你的文件名逻辑不同,请根据实际情况修改
112
+ img_path = os.path.join(base_image_path, f"{smiles}.png")
113
+ # img_path = '/Users/xiaojie/Documents/lunwen/代码/data/Br.C=CC1CN2CCC1CC2C(O)c1ccnc2ccc(OC)cc12.png'
114
+
115
+ try:
116
+ if os.path.exists(img_path):
117
+ # 打开图片文件
118
+ img = Image.open(img_path)
119
+ # 强制调整为 300x300 大小
120
+ img = img.resize(size, Image.Resampling.LANCZOS)
121
+ return img
122
+ else:
123
+ print(f"警告: 文件未找到 {img_path}")
124
+ # time.sleep(1)
125
+ img = smiles_to_image1(smiles)
126
+ return img
127
+ except Exception as e:
128
+ print(f"处理图片时出错: {e}")
129
+ return None
130
+
131
+
132
+ # =========================
133
+ # 加载用户 SMILES
134
+ # =========================
135
+ def load_user_smiles(file):
136
+ if file is None:
137
+ return []
138
+
139
+ if file.name.endswith(".txt"):
140
+ with open(file.name, "r") as f:
141
+ smiles = [l.strip() for l in f if l.strip()]
142
+
143
+ elif file.name.endswith(".csv"):
144
+ df = pd.read_csv(file.name)
145
+ if "smiles" not in df.columns:
146
+ raise ValueError("CSV 中必须包含 smiles 列")
147
+ smiles = df["smiles"].dropna().tolist()
148
+ else:
149
+ smiles = []
150
+
151
+ return [s for s in smiles if Chem.MolFromSmiles(s)]
152
+
153
+
154
+ def parse_msp(file):
155
+ if file.name.endswith(".msp"):
156
+ with open(file.name, "r", encoding='utf-8') as f:
157
+ lines = f.readlines()
158
+
159
+ start_index = 0
160
+ for i, line in enumerate(lines):
161
+ if line.startswith("Num Peaks:"):
162
+ start_index = i + 1
163
+ break
164
+
165
+ # 3. 提取数据行并转换为二维数组
166
+ peaks_array = []
167
+ for line in lines[start_index:]:
168
+ # split() 会自动处理空格和制表符 (\t)
169
+ parts = line.replace("\n", "").split()
170
+ if len(parts) == 2:
171
+ peaks_array.append([float(parts[0]), float(parts[1])])
172
+
173
+ return peaks_array
174
+
175
+ elif file.name.endswith(".mgf"):
176
+
177
+ with open(file.name, "r", encoding='utf-8') as f:
178
+ lines = f.readlines()
179
+ peaks_array = []
180
+ # 2. 遍历每一行进行判断
181
+ for line in lines:
182
+ # 排除掉不包含数值的标签行
183
+ if not line or any(tag in line for tag in ["BEGIN", "END", "=", "NAME"]):
184
+ continue
185
+
186
+ # 尝试将行内容切分为两部分
187
+ parts = line.replace("\n", "").split()
188
+
189
+ # 如果分割后有两个元素,且第一个元素是数字,则加入数组
190
+ if len(parts) == 2:
191
+ try:
192
+ mz = float(parts[0])
193
+ intensity = float(parts[1])
194
+ peaks_array.append([mz, intensity])
195
+ except ValueError:
196
+ # 如果转换数字失败(比如标题行),则跳过
197
+ continue
198
+ return peaks_array
199
+
200
+ elif file.name.endswith(".json"):
201
+
202
+ with open(file.name, "r", encoding='utf-8') as f:
203
+ line = json.load(f)
204
+
205
+ peaks_array = None
206
+ if 'ms' in line:
207
+ peaks_array = line['ms']
208
+ elif 'Ms' in line:
209
+ peaks_array = line['Ms']
210
+ elif 'MS' in line:
211
+ peaks_array = line['MS']
212
+ elif 'mS' in line:
213
+ peaks_array = line['mS']
214
+
215
+ return peaks_array
216
+
217
+ elif file.name.endswith(".mzXML"):
218
+
219
+ with open(file.name, "r", encoding='utf-8') as f:
220
+ lines = f.readlines()
221
+
222
+ return None
223
+
224
+ elif file.name.endswith(".mzML"):
225
+
226
+ with open(file.name, "r", encoding='utf-8') as f:
227
+ lines = f.readlines()
228
+
229
+ return None
230
+
231
+ else:
232
+ return None
233
+
234
+ # =========================
235
+ # 第一类:业务逻辑(只算结果)
236
+ # =========================
237
+ def run_retrieval(msp_file, ion_mode, parent_mass, user_smiles_file, parent_mass_bn=50):
238
+
239
+ if msp_file is None:
240
+ return [], None
241
+
242
+ print("msp_file ...", msp_file)
243
+ print("ion_mode ...", ion_mode)
244
+ print("parent_mass ...", parent_mass)
245
+ print("user_smiles_file ...", user_smiles_file)
246
+
247
+ user_smiles = load_user_smiles(user_smiles_file)
248
+
249
+ msp_file = parse_msp(msp_file)
250
+
251
+ print("msp_file ...", msp_file)
252
+
253
+ if msp_file is None:
254
+ return [], None
255
+
256
+ print("user_smiles ...", user_smiles)
257
+ smiles_list = cross_modal_retrieval(parent_mass, ion_mode, msp_file, user_smiles, parent_mass_bn)
258
+
259
+ print("smiles_list ...", smiles_list)
260
+
261
+ # scores_list = []
262
+ if isinstance(smiles_list[0], list):
263
+ scores_list = [x[1] for x in smiles_list]
264
+ smiles_list = [x[0] for x in smiles_list]
265
+
266
+ else:
267
+ scores_list = [1.0] * len(smiles_list)
268
+
269
+ results = []
270
+ rows = []
271
+
272
+ for i, smi in enumerate(smiles_list):
273
+ if i >= 10:
274
+ break
275
+
276
+ img = smiles_to_image(smi)
277
+
278
+ results.append({
279
+ "rank": i + 1,
280
+ "img": img,
281
+ "smiles": smi,
282
+ "score": scores_list[i]
283
+ })
284
+
285
+ rows.append({
286
+ "rank": i + 1,
287
+ "parent_ion_mass": parent_mass,
288
+ "ion_mode": ion_mode,
289
+ "smiles": smi,
290
+ "score": scores_list[i]
291
+ })
292
+
293
+ print("len results ...")
294
+ print(len(results))
295
+ csv_path = "cross_modal_results.csv"
296
+ pd.DataFrame(rows).to_csv(csv_path, index=False)
297
+
298
+ return results, csv_path
299
+
300
+
301
+ # =========================
302
+ # 第一类:业务逻辑(只算结果)
303
+ # =========================
304
+ def run_retrieval_2(msp_file, ion_mode, parent_mass, user_smiles_file, compound_num_min, compound_name_max, pr=10, parent_mass_bn=50):
305
+
306
+ if msp_file is None:
307
+ return [], None
308
+
309
+ print("msp_file ...", msp_file)
310
+ print("ion_mode ...", ion_mode)
311
+ print("parent_mass ...", parent_mass)
312
+ print("user_smiles_file ...", user_smiles_file)
313
+
314
+ user_smiles = load_user_smiles(user_smiles_file)
315
+
316
+ msp_file_s1, msp_file_s2 = saixuan_example(msp_file, compound_num_min, compound_name_max, pr)
317
+
318
+ if msp_file_s1 is None or len(msp_file_s1) == 0:
319
+ return [], None
320
+
321
+ print("msp_file_s ...", len(msp_file_s1))
322
+
323
+ print("user_smiles ...", user_smiles)
324
+
325
+ results = []
326
+ rows = []
327
+
328
+ for i11, msp_mass_file in enumerate(msp_file_s1):
329
+ msp_file = msp_mass_file['ms']
330
+ parent_mass = msp_mass_file['mass'][0]
331
+
332
+ smiles_list = cross_modal_retrieval(parent_mass, ion_mode, msp_file, user_smiles, parent_mass_bn)
333
+
334
+ print("smiles_list ...", smiles_list)
335
+
336
+ # scores_list = []
337
+ if isinstance(smiles_list[0], list):
338
+ scores_list = [x[1] for x in smiles_list]
339
+ smiles_list = [x[0] for x in smiles_list]
340
+
341
+ else:
342
+ scores_list = [1.0] * len(smiles_list)
343
+
344
+ for i, smi in enumerate(smiles_list):
345
+ if i >= 10:
346
+ break
347
+
348
+ if i11 == 0:
349
+ img = smiles_to_image(smi)
350
+
351
+ results.append({
352
+ "rank": i + 1,
353
+ "img": img,
354
+ "smiles": smi,
355
+ "score": scores_list[i]
356
+ })
357
+
358
+ rows.append({
359
+ "id": i11,
360
+ "rank": i + 1,
361
+ "parent_ion_mass": parent_mass,
362
+ "ion_mode": ion_mode,
363
+ "smiles": smi,
364
+ "score": scores_list[i]
365
+ })
366
+
367
+ print("len results ...")
368
+ print(len(results))
369
+ import datetime
370
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
371
+ csv_path = f"cross_modal_results_{timestamp}.csv"
372
+ pd.DataFrame(rows).to_csv(csv_path, index=False)
373
+
374
+ return results[:10], csv_path
375
+
376
+
377
+ # =========================
378
+ # 第二类:UI 适配(固定铺 10 个)
379
+ # =========================
380
+ def fill_top10(results, csv_path):
381
+ images = []
382
+ smiles_texts = []
383
+ score_texts = []
384
+ print("results ...")
385
+ print(results)
386
+
387
+ for i in range(10):
388
+ if i < len(results):
389
+ images.append(results[i]["img"])
390
+ smiles_texts.append(results[i]["smiles"])
391
+ score_texts.append(str(results[i]['score']))
392
+ else:
393
+ images.append(None)
394
+ smiles_texts.append("")
395
+ score_texts.append("")
396
+
397
+ return images + smiles_texts + score_texts + [csv_path]
398
+
399
+
400
+ def unified_run_retrieval(msp_file, ion_mode, parent_mass, user_smiles_file, compound_mode, compound_num_min, compound_name_max, pr=10, parent_mass_bn=50):
401
+ # 1. 执行原有的 retrieval 逻辑
402
+ if compound_mode == "单化合物":
403
+ results, csv_path = run_retrieval(msp_file, ion_mode, parent_mass, user_smiles_file, parent_mass_bn)
404
+ else:
405
+ results, csv_path = run_retrieval_2(msp_file, ion_mode, parent_mass, user_smiles_file, compound_num_min, compound_name_max, pr, parent_mass_bn)
406
+
407
+ # 2. 调用原有的 fill_top10 逻辑获取 UI 输出列表
408
+ # 假设 fill_top10 返回的是 image_outputs + smiles_outputs + [csv_file] 对应的值
409
+ ui_outputs = fill_top10(results, csv_path)
410
+
411
+ return ui_outputs
412
+
413
+
414
+ # ========================= # 示例填充 # =========================
415
+ def load_example():
416
+ time.sleep(1)
417
+ return "/Users/xiaojie/Documents/lunwen/代码/data/29579-06-0.mgf", "pos", 336.1735
418
+
419
+
420
+ def parse_ms_data_simple(lines):
421
+ results = []
422
+ current_entry = None
423
+
424
+ # 按行分割文本
425
+ # lines = raw_text.strip().split('\n')
426
+
427
+ for line in lines:
428
+ line = line.strip()
429
+ if not line:
430
+ continue
431
+
432
+ # 识别样本开始
433
+ if line == "BEGIN IONS":
434
+ current_entry = {"ms": [], "mass": []}
435
+ continue
436
+
437
+ # 识别样本结束
438
+ if line == "END IONS":
439
+ if current_entry is not None:
440
+ results.append(current_entry)
441
+ current_entry = None
442
+ continue
443
+
444
+ # 处于样本块内部时
445
+ if current_entry is not None:
446
+ if line.startswith("PEPMASS="):
447
+ # 提取 PEPMASS= 之后的部分并按空格切分
448
+ mass_values = line.split('=')[1].split()
449
+ current_entry["mass"] = [float(v) for v in mass_values]
450
+
451
+ elif "=" in line:
452
+ # 跳过其他元数据行,如 TITLE, CHARGE, RTINSECONDS 等
453
+ continue
454
+
455
+ else:
456
+ # 处理碎片数据行 (m/z intensity)
457
+ parts = line.split()
458
+ if len(parts) >= 2:
459
+ try:
460
+ mz = float(parts[0])
461
+ intensity = float(parts[1])
462
+ current_entry["ms"].append([mz, intensity])
463
+ except ValueError:
464
+ # 容错处理:如果行首不是数字则跳过
465
+ continue
466
+
467
+ return results
468
+
469
+
470
+ def parse_ms_data_msp(lines):
471
+ results = []
472
+ # lines = text.splitlines()
473
+
474
+ current_entry = None
475
+ capture_ms = False
476
+ peaks_to_collect = 0
477
+
478
+ for line in lines:
479
+ line = line.strip()
480
+ if not line:
481
+ continue
482
+
483
+ # 遇到新条目开始
484
+ if line.startswith("NAME:"):
485
+ if current_entry and current_entry["ms"]:
486
+ results.append(current_entry)
487
+ current_entry = {"mass": None, "ms": []}
488
+ capture_ms = False
489
+ continue
490
+
491
+ # 解析 PRECURSORMZ
492
+ if line.startswith("PRECURSORMZ:"):
493
+ mass_values = line.split(":", 1)[1].strip().split()
494
+ current_entry["mass"] = [float(v) for v in mass_values]
495
+
496
+ # 检测 Num Peaks,开始捕获 MS 数据
497
+ elif line.startswith("Num Peaks:"):
498
+ val = line.split(":", 1)[1].strip()
499
+ peaks_to_collect = int(val)
500
+ capture_ms = True
501
+
502
+ # 捕获峰数据
503
+ elif capture_ms and peaks_to_collect > 0:
504
+ parts = line.split()
505
+ if len(parts) >= 2:
506
+ mz = float(parts[0])
507
+ intensity = float(parts[1])
508
+ current_entry["ms"].append([mz, intensity])
509
+ peaks_to_collect -= 1
510
+ if peaks_to_collect == 0:
511
+ capture_ms = False
512
+
513
+ # 添加最后一个条目
514
+ if current_entry and current_entry["ms"]:
515
+ results.append(current_entry)
516
+
517
+ return results
518
+
519
+
520
+ def saixuan_example(file, min_val, max_val, pr=10):
521
+
522
+ if file.name.endswith(".msp"):
523
+
524
+ try:
525
+ with open(file.name, "r", encoding='utf-8') as f:
526
+ lines = f.readlines()
527
+
528
+ res2 = parse_ms_data_msp(lines)
529
+
530
+ res = []
531
+ for x in res2:
532
+ ms = []
533
+ for c in x['ms']:
534
+ if float(c[1]) <= pr:
535
+ continue
536
+
537
+ ms.append(c)
538
+
539
+ if len(ms) > 0:
540
+ res.append({
541
+ "ms": ms,
542
+ "mass": x["mass"]
543
+ })
544
+
545
+ res1 = []
546
+ for x in res:
547
+ pep_mass = x["mass"]
548
+ if len(pep_mass) == 2:
549
+ if float(pep_mass[1]) >= float(min_val) and float(pep_mass[1]) <= float(max_val):
550
+ res1.append(x)
551
+ else:
552
+ res1.append(x)
553
+
554
+ return res1, res
555
+
556
+ except Exception as e:
557
+ print(e)
558
+ return None, None
559
+
560
+ elif file.name.endswith(".mgf"):
561
+ try:
562
+ with open(file.name, "r", encoding='utf-8') as f:
563
+ lines = f.readlines()
564
+ res2 = parse_ms_data_simple(lines)
565
+ res = []
566
+ for x in res2:
567
+ ms = []
568
+ for c in x['ms']:
569
+ if float(c[1]) <= pr:
570
+ continue
571
+ ms.append(c)
572
+
573
+ if len(ms) > 0:
574
+ res.append({
575
+ "ms": ms,
576
+ "mass": x["mass"]
577
+ })
578
+
579
+ res1 = []
580
+ for x in res:
581
+ pep_mass = x["mass"]
582
+ if float(pep_mass[1]) >= float(min_val) and float(pep_mass[1]) <= float(max_val):
583
+ res1.append(x)
584
+
585
+ return res1, res
586
+
587
+ except Exception as e:
588
+ print(e)
589
+ return None, None
590
+
591
+ elif file.name.endswith(".json"):
592
+ try:
593
+ with open(file.name, "r", encoding='utf-8') as f:
594
+ lines = json.load(f)
595
+
596
+ res2 = []
597
+ for line in lines:
598
+ d = {"ms": None, "mass": None}
599
+ if 'ms' in line:
600
+ d['ms'] = line['ms']
601
+ elif 'Ms' in line:
602
+ d['ms'] = line['Ms']
603
+ elif 'MS' in line:
604
+ d['ms'] = line['MS']
605
+ elif 'mS' in line:
606
+ d['ms'] = line['mS']
607
+
608
+ if 'parent_mz' in line:
609
+ d['mass'] = [line['parent_mz']]
610
+
611
+ else:
612
+ d['mass'] = [0]
613
+
614
+ res2.append(d)
615
+
616
+ res = []
617
+ for x in res2:
618
+ ms = []
619
+ for c in x['ms']:
620
+ if float(c[1]) <= pr:
621
+ continue
622
+ ms.append(c)
623
+
624
+ if len(ms) > 0:
625
+ res.append({
626
+ "ms": ms,
627
+ "mass": x["mass"]
628
+ })
629
+
630
+ res1 = []
631
+ for x in res:
632
+ pep_mass = x["mass"]
633
+ if len(pep_mass) == 2:
634
+ if float(pep_mass[1]) >= float(min_val) and float(pep_mass[1]) <= float(max_val):
635
+ res1.append(x)
636
+ else:
637
+ res1.append(x)
638
+
639
+ return res1, res
640
+
641
+ except Exception as e:
642
+ print(e)
643
+ return None, None
644
+
645
+ else:
646
+ return None, None
647
+
648
+
649
+ # ---- 模拟文件解析逻辑 ----
650
+ def process_compounds(file, mode, min_val, max_val, pr=10):
651
+ if not file:
652
+ return "未上传文件", "未上传文件"
653
+
654
+ if mode == "单化合物":
655
+ return "1", "1"
656
+
657
+ # 这里放置你的解析逻辑,例如读取 msp 文件内容
658
+ # 假设我们通过某种逻辑得到了总数和筛选后的数量
659
+ # 以下为示例数值:
660
+ try:
661
+ # demo 逻辑:模拟从文件中读到了 50 个,经过响应值筛选剩下 10 个
662
+ res1, res2 = saixuan_example(file, min_val, max_val, pr=pr)
663
+ if res1 is not None and res2 is not None:
664
+ parsed_selected = len(res1)
665
+ parsed_total = len(res2)
666
+ return str(parsed_selected), str(parsed_total)
667
+ else:
668
+ return '0', '0'
669
+ except Exception as e:
670
+ return "解析错误", str(e)
671
+
672
+
673
+ # 1. 图片转 Base64 函数(解决���径显示不出的问题)
674
+ def get_base64_image(image_path):
675
+ try:
676
+ with open(image_path, "rb") as img_file:
677
+ return base64.b64encode(img_file.read()).decode('utf-8')
678
+ except Exception as e:
679
+ print(f"图片读取失败: {e}")
680
+ return ""
681
+
682
+
683
+ # CSS 样式:定义背景颜色、文字颜色和悬停效果
684
+ custom_css = """
685
+ #yellow_btn {
686
+ background-color: #FEBA02 !important; /* 黄色背景 */
687
+ color: black !important; /* 黑色文字,确保对比度 */
688
+ border: none;
689
+ }
690
+ #yellow_btn:hover {
691
+ background-color: #e6b800 !important; /* 鼠标悬停时稍微深一点的黄色 */
692
+ }
693
+
694
+ /* 新增:图片中的四种颜色按钮样式 */
695
+
696
+ /* 1. 深绿色 (#3D9F3C) */
697
+ #btn_green_dark {
698
+ background-color: #3D9F3C !important;
699
+ color: white !important;
700
+ border: none;
701
+ }
702
+ #btn_green_dark:hover {
703
+ background-color: #328532 !important; /* 悬停颜色稍深 */
704
+ }
705
+
706
+ /* 2. 浅绿色 (#9ED17B) */
707
+ #btn_green_light {
708
+ background-color: #9ED17B !important;
709
+ color: black !important;
710
+ border: none;
711
+ }
712
+ #btn_green_light:hover {
713
+ background-color: #89c065 !important;
714
+ }
715
+
716
+ /* 3. 中蓝色 (#367DB0) */
717
+ #btn_blue_medium {
718
+ background-color: #367DB0 !important;
719
+ color: white !important;
720
+ border: none;
721
+ }
722
+ #btn_blue_medium:hover {
723
+ background-color: #2b658f !important;
724
+ }
725
+
726
+ /* 4. 天蓝色 (#9DC7DD) */
727
+ #btn_blue_light {
728
+ background-color: #9DC7DD !important;
729
+ color: black !important;
730
+ border: none;
731
+ }
732
+ #btn_blue_light:hover {
733
+ background-color: #85b5cc !important;
734
+ }
735
+
736
+ """
737
+
738
+ # =========================
739
+ # Gradio UI
740
+ # =========================
741
+ with gr.Blocks(title="MS² → SMILES Cross-Modal Retrieval", css=custom_css) as demo:
742
+
743
+ # gr.Markdown("## 🔬 MS² → SMILES Cross-Modal Retrieval")
744
+
745
+ # gr.Markdown(
746
+ # """
747
+ # <div style="text-align: center;">
748
+ # <h2 style="
749
+ # background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
750
+ # -webkit-background-clip: text;
751
+ # -webkit-text-fill-color: transparent;
752
+ # font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
753
+ # font-size: 2.2em;
754
+ # font-weight: 800;
755
+ # margin-bottom: 10px;
756
+ # ">
757
+ # 🔬 MS² → SMILES Cross-Modal Retrieval
758
+ # </h2>
759
+ # </div>
760
+ # """
761
+ # )
762
+
763
+ # gr.Markdown(
764
+ # """
765
+ # <div style="text-align: center;">
766
+ # <h2 style="
767
+ # color: #FF007A;
768
+ # text-shadow: 2px 2px 10px rgba(255, 0, 122, 0.3);
769
+ # font-family: 'Arial Black', sans-serif;
770
+ # letter-spacing: 1px;
771
+ # ">
772
+ # 🔬 MS² → SMILES Cross-Modal Retrieval
773
+ # </h2>
774
+ # <hr style="border: 1px solid #FF007A; width: 50%; margin: auto;">
775
+ # </div>
776
+ # """
777
+ # )
778
+
779
+ # gr.Markdown(
780
+ # """
781
+ # <div style="
782
+ # text-align: center;
783
+ # background-color: #f0f7ff;
784
+ # padding: 20px;
785
+ # border-radius: 15px;
786
+ # border-left: 10px solid #3b82f6;
787
+ # ">
788
+ # <h2 style="color: #1e40af; margin: 0; font-family: system-ui;">
789
+ # 🔬 MS² → SMILES Cross-Modal Retrieval
790
+ # </h2>
791
+ # <p style="color: #60a5fa; font-weight: bold; margin-top: 5px;">
792
+ # Mass Spectrometry to Chemical Structure
793
+ # </p>
794
+ # </div>
795
+ # """
796
+ # )
797
+
798
+ img_local_path = logo_image_local_path
799
+ img_base64 = get_base64_image(img_local_path)
800
+
801
+ # 2. 构造 HTML:图标左对齐,文字绝对居中
802
+ header_html = f"""
803
+ <div style="
804
+ display: flex;
805
+ align-items: center;
806
+ position: relative;
807
+ background: linear-gradient(100deg, #3D9F3C 0%, #9ED17B 30%, #367DB0 70%, #9DC7DD 100%);
808
+ padding: 0;
809
+ border-radius: 12px;
810
+ box-shadow: 0 4px 15px rgba(0,0,0,0.15);
811
+ height: 100px;
812
+ overflow: hidden;
813
+ margin: 10px auto;
814
+ ">
815
+ <div style="
816
+ height: 100%;
817
+ display: flex;
818
+ align-items: center;
819
+ z-index: 2;
820
+ /* 核心:通过遮罩实现右侧自然渐变消失 */
821
+ -webkit-mask-image: linear-gradient(to right, black 70%, transparent 100%);
822
+ mask-image: linear-gradient(to right, black 70%, transparent 100%);
823
+ ">
824
+ <img src="data:image/png;base64,{img_base64}"
825
+ style="
826
+ height: 100%;
827
+ width: auto;
828
+ object-fit: contain;
829
+ mix-blend-mode: multiply; /* 过滤掉图片自身的白底 */
830
+ ">
831
+ </div>
832
+
833
+ <div style="
834
+ position: absolute;
835
+ left: 0;
836
+ right: 0;
837
+ text-align: center;
838
+ pointer-events: none;
839
+ ">
840
+ <h2 style="
841
+ color: white;
842
+ margin: 0;
843
+ font-family: 'Segoe UI', system-ui, sans-serif;
844
+ font-size: 26px;
845
+ font-weight: 700;
846
+ text-shadow: 0px 2px 4px rgba(0,0,0,0.2);
847
+ ">
848
+ 🔬 MS<sup style="font-size: 0.6em;">2</sup> → SMILES Cross-Modal Retrieval
849
+ </h2>
850
+ <p style="
851
+ color: rgba(255, 255, 255, 0.9);
852
+ margin: 4px 0 0 0;
853
+ font-size: 15px;
854
+ font-weight: 400;
855
+ letter-spacing: 0.5px;
856
+ ">
857
+ Mass Spectrometry to Chemical Structure Discovery
858
+ </p>
859
+ </div>
860
+ </div>
861
+ """
862
+
863
+ gr.HTML(header_html) # 注意:这里改用 gr.HTML 效果更稳定
864
+
865
+ # ---- 输入区 ----
866
+ msp_file = gr.File(label="上传 MS/MS 谱图 (.msp)", file_types=[".msp", ".mgf", ".json"])
867
+
868
+ with gr.Row():
869
+ ion_mode = gr.Radio(["pos", "neg"], label="离子模式", value="pos")
870
+ compound_mode = gr.Radio(["单化合物", "多化合物"], label="化合物情况", value="单化合物")
871
+ compound_num_min = gr.Number(label="响应值最小值", value=10000)
872
+ compound_name_max = gr.Number(label="响应值最大值", value=20000)
873
+ pr_min = gr.Number(label="二级碎片响应值过滤", value=10)
874
+ parent_mass = gr.Number(label="母离子质量", value=336.1735)
875
+ parent_mass_bn = gr.Number(label="母离子质量阈值", value=1000000)
876
+
877
+ with gr.Row():
878
+ # 新增一个“解析统计”按钮,或者直接用你的检索按钮
879
+ analyze_btn = gr.Button("统计化合物数量", variant="secondary", elem_id="btn_green_dark")
880
+
881
+ # ---- 结果显示区:设为不可手动编辑的 Textbox (interactive=False) ----
882
+ with gr.Row():
883
+ select_count = gr.Textbox(label="选择多少个", interactive=False, visible=False)
884
+ total_count = gr.Textbox(label="总共多少个", interactive=False, visible=False)
885
+
886
+ user_smiles_file = gr.File(
887
+ label="用户新增 SMILES 库 (txt / csv)",
888
+ file_types=[".txt", ".csv"]
889
+ )
890
+
891
+ # ===== 操作按钮 =====
892
+ with gr.Row():
893
+ example_btn = gr.Button("加载样例", elem_id="btn_blue_medium")
894
+ run_btn = gr.Button("Cross-modal Retrieval", variant="primary", elem_id="yellow_btn")
895
+
896
+ # ---- 结果区 ----
897
+ gr.Markdown("## 📊 Top-10 Retrieval Results")
898
+
899
+ image_outputs = []
900
+ smiles_outputs = []
901
+ scores_outputs = []
902
+
903
+ with gr.Row():
904
+ for i in range(5):
905
+ with gr.Column():
906
+ gr.Markdown(f"**Top-{i+1}**")
907
+ image_outputs.append(gr.Image(height=300, width=300))
908
+ smiles_outputs.append(
909
+ gr.Textbox(label="SMILES", interactive=False)
910
+ )
911
+ scores_outputs.append(
912
+ gr.Textbox(label="score", interactive=False)
913
+ )
914
+
915
+ with gr.Row():
916
+ for i in range(5, 10):
917
+ with gr.Column():
918
+ gr.Markdown(f"**Top-{i+1}**")
919
+ image_outputs.append(gr.Image(height=300, width=300))
920
+ smiles_outputs.append(
921
+ gr.Textbox(label="SMILES", interactive=False)
922
+ )
923
+ scores_outputs.append(
924
+ gr.Textbox(label="score", interactive=False)
925
+ )
926
+
927
+ # ===== 导出区 =====
928
+ with gr.Row():
929
+ csv_file = gr.File(label="结果 CSV")
930
+ # download_btn = gr.Button("下载 / 导出数据")
931
+
932
+ # 1. 控制文本框的显示/隐藏(可选,若想一直显示可去掉此段)
933
+ def toggle_boxes(mode):
934
+ return gr.update(visible=True), gr.update(visible=True)
935
+
936
+ compound_mode.change(toggle_boxes, inputs=compound_mode, outputs=[select_count, total_count])
937
+
938
+ # 2. 点击“统计”按钮时,解析文件并回填数据
939
+ analyze_btn.click(
940
+ fn=process_compounds,
941
+ inputs=[msp_file, compound_mode, compound_num_min, compound_name_max, pr_min],
942
+ outputs=[select_count, total_count]
943
+ )
944
+
945
+ # ===== 交互绑定 =====
946
+ example_btn.click(
947
+ fn=load_example,
948
+ outputs=[msp_file, ion_mode, parent_mass]
949
+ )
950
+
951
+ # ---- State ----
952
+ results_state = gr.State()
953
+ csv_state = gr.State()
954
+
955
+ # ---- 绑定 ----
956
+ # run_btn.click(
957
+ # fn=run_retrieval,
958
+ # inputs=[msp_file, ion_mode, parent_mass, user_smiles_file],
959
+ # outputs=[results_state, csv_state]
960
+ # )
961
+ #
962
+ # run_btn.click(
963
+ # fn=fill_top10,
964
+ # inputs=[results_state, csv_state],
965
+ # outputs=image_outputs + smiles_outputs + scores_outputs + [csv_file]
966
+ # )
967
+
968
+ # run_btn.click(
969
+ # fn=run_retrieval,
970
+ # inputs=[msp_file, ion_mode, parent_mass, user_smiles_file],
971
+ # outputs=[results_state, csv_state]
972
+ # ).then(
973
+ # fn=fill_top10,
974
+ # inputs=[results_state, csv_state],
975
+ # outputs=image_outputs + smiles_outputs + scores_outputs + [csv_file]
976
+ # )
977
+
978
+ run_btn.click(
979
+ fn=unified_run_retrieval,
980
+ inputs=[msp_file, ion_mode, parent_mass, user_smiles_file, compound_mode, compound_num_min, compound_name_max, pr_min, parent_mass_bn],
981
+ outputs=image_outputs + smiles_outputs + scores_outputs + [csv_file]
982
+ )
983
+
984
+ # download_btn.click(
985
+ # fn=lambda x: x,
986
+ # inputs=csv_file,
987
+ # outputs=csv_file
988
+ # )
989
+
990
+
991
+ if __name__ == "__main__":
992
+ demo.launch(server_name="0.0.0.0", server_port=7868, share=True)
993
+
994
+ # nohup python3 -u app.py > app_1.log 2>&1 &
995
+ # lsof -i :7865
996
+
cliplayers.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+ self.relu1 = nn.ReLU(inplace=True)
20
+
21
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(planes)
23
+ self.relu2 = nn.ReLU(inplace=True)
24
+
25
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
26
+
27
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
28
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
29
+ self.relu3 = nn.ReLU(inplace=True)
30
+
31
+ self.downsample = None
32
+ self.stride = stride
33
+
34
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
35
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
36
+ self.downsample = nn.Sequential(OrderedDict([
37
+ ("-1", nn.AvgPool2d(stride)),
38
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
39
+ ("1", nn.BatchNorm2d(planes * self.expansion))
40
+ ]))
41
+
42
+ def forward(self, x: torch.Tensor):
43
+ identity = x
44
+
45
+ out = self.relu1(self.bn1(self.conv1(x)))
46
+ out = self.relu2(self.bn2(self.conv2(out)))
47
+ out = self.avgpool(out)
48
+ out = self.bn3(self.conv3(out))
49
+
50
+ if self.downsample is not None:
51
+ identity = self.downsample(x)
52
+
53
+ out += identity
54
+ out = self.relu3(out)
55
+ return out
56
+
57
+
58
+ class AttentionPool2d(nn.Module):
59
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
60
+ super().__init__()
61
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
62
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
63
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
64
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
65
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
66
+ self.num_heads = num_heads
67
+
68
+ def forward(self, x):
69
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
70
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
71
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
72
+ x, _ = F.multi_head_attention_forward(
73
+ query=x[:1], key=x, value=x,
74
+ embed_dim_to_check=x.shape[-1],
75
+ num_heads=self.num_heads,
76
+ q_proj_weight=self.q_proj.weight,
77
+ k_proj_weight=self.k_proj.weight,
78
+ v_proj_weight=self.v_proj.weight,
79
+ in_proj_weight=None,
80
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
81
+ bias_k=None,
82
+ bias_v=None,
83
+ add_zero_attn=False,
84
+ dropout_p=0,
85
+ out_proj_weight=self.c_proj.weight,
86
+ out_proj_bias=self.c_proj.bias,
87
+ use_separate_proj_weight=True,
88
+ training=self.training,
89
+ need_weights=False
90
+ )
91
+ return x.squeeze(0)
92
+
93
+
94
+ class ModifiedResNet(nn.Module):
95
+ """
96
+ A ResNet class that is similar to torchvision's but contains the following changes:
97
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
98
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
99
+ - The final pooling layer is a QKV attention instead of an average pool
100
+ """
101
+
102
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
103
+ super().__init__()
104
+ self.output_dim = output_dim
105
+ self.input_resolution = input_resolution
106
+
107
+ # the 3-layer stem
108
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
109
+ self.bn1 = nn.BatchNorm2d(width // 2)
110
+ self.relu1 = nn.ReLU(inplace=True)
111
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
112
+ self.bn2 = nn.BatchNorm2d(width // 2)
113
+ self.relu2 = nn.ReLU(inplace=True)
114
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
115
+ self.bn3 = nn.BatchNorm2d(width)
116
+ self.relu3 = nn.ReLU(inplace=True)
117
+ self.avgpool = nn.AvgPool2d(2)
118
+
119
+ # residual layers
120
+ self._inplanes = width # this is a *mutable* variable used during construction
121
+ self.layer1 = self._make_layer(width, layers[0])
122
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
123
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
124
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
125
+
126
+ embed_dim = width * 32 # the ResNet feature dimension
127
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
128
+
129
+ def _make_layer(self, planes, blocks, stride=1):
130
+ layers = [Bottleneck(self._inplanes, planes, stride)]
131
+
132
+ self._inplanes = planes * Bottleneck.expansion
133
+ for _ in range(1, blocks):
134
+ layers.append(Bottleneck(self._inplanes, planes))
135
+
136
+ return nn.Sequential(*layers)
137
+
138
+ def forward(self, x):
139
+ def stem(x):
140
+ x = self.relu1(self.bn1(self.conv1(x)))
141
+ x = self.relu2(self.bn2(self.conv2(x)))
142
+ x = self.relu3(self.bn3(self.conv3(x)))
143
+ x = self.avgpool(x)
144
+ return x
145
+
146
+ x = x.type(self.conv1.weight.dtype)
147
+ x = stem(x)
148
+ x = self.layer1(x)
149
+ x = self.layer2(x)
150
+ x = self.layer3(x)
151
+ x = self.layer4(x)
152
+ x = self.attnpool(x)
153
+
154
+ return x
155
+
156
+
157
+ class LayerNorm(nn.LayerNorm):
158
+ """Subclass torch's LayerNorm to handle fp16."""
159
+
160
+ def forward(self, x: torch.Tensor):
161
+ orig_type = x.dtype
162
+ ret = super().forward(x.type(torch.float32))
163
+ return ret.type(orig_type)
164
+
165
+
166
+ class QuickGELU(nn.Module):
167
+ def forward(self, x: torch.Tensor):
168
+ return x * torch.sigmoid(1.702 * x)
169
+
170
+
171
+ class ResidualAttentionBlock(nn.Module):
172
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
173
+ super().__init__()
174
+
175
+ self.attn = nn.MultiheadAttention(d_model, n_head)
176
+ self.ln_1 = LayerNorm(d_model)
177
+ self.mlp = nn.Sequential(OrderedDict([
178
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
179
+ ("gelu", QuickGELU()),
180
+ ("c_proj", nn.Linear(d_model * 4, d_model))
181
+ ]))
182
+ self.ln_2 = LayerNorm(d_model)
183
+ self.attn_mask = attn_mask
184
+
185
+ def attention(self, x: torch.Tensor):
186
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
187
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
188
+
189
+ def forward(self, x: torch.Tensor):
190
+ x = x + self.attention(self.ln_1(x))
191
+ x = x + self.mlp(self.ln_2(x))
192
+ return x
193
+
194
+
195
+ class Transformer(nn.Module):
196
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
197
+ super().__init__()
198
+ self.width = width
199
+ self.layers = layers
200
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
201
+
202
+ def forward(self, x: torch.Tensor):
203
+ return self.resblocks(x)
204
+
205
+
206
+ class VisionTransformer(nn.Module):
207
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
208
+ super().__init__()
209
+ self.input_resolution = input_resolution
210
+ self.output_dim = output_dim
211
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
212
+
213
+ scale = width ** -0.5
214
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
215
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
216
+ self.ln_pre = LayerNorm(width)
217
+
218
+ self.transformer = Transformer(width, layers, heads)
219
+
220
+ self.ln_post = LayerNorm(width)
221
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
222
+
223
+ def forward(self, x: torch.Tensor):
224
+ x = self.conv1(x) # shape = [*, width, grid, grid]
225
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
226
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
227
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
228
+ x = x + self.positional_embedding.to(x.dtype)
229
+ x = self.ln_pre(x)
230
+
231
+ x = x.permute(1, 0, 2) # NLD -> LND
232
+ x = self.transformer(x)
233
+ x = x.permute(1, 0, 2) # LND -> NLD
234
+
235
+ x = self.ln_post(x[:, 0, :])
236
+
237
+ if self.proj is not None:
238
+ x = x @ self.proj
239
+
240
+ return x
241
+
242
+
243
+ class CLIP(nn.Module):
244
+ def __init__(self,
245
+ embed_dim: int,
246
+ # vision
247
+ image_resolution: int,
248
+ vision_layers: Union[Tuple[int, int, int, int], int],
249
+ vision_width: int,
250
+ vision_patch_size: int,
251
+ # text
252
+ context_length: int,
253
+ vocab_size: int,
254
+ transformer_width: int,
255
+ transformer_heads: int,
256
+ transformer_layers: int
257
+ ):
258
+ super().__init__()
259
+
260
+ self.context_length = context_length
261
+
262
+ if isinstance(vision_layers, (tuple, list)):
263
+ vision_heads = vision_width * 32 // 64
264
+ self.visual = ModifiedResNet(
265
+ layers=vision_layers,
266
+ output_dim=embed_dim,
267
+ heads=vision_heads,
268
+ input_resolution=image_resolution,
269
+ width=vision_width
270
+ )
271
+ else:
272
+ vision_heads = vision_width // 64
273
+ self.visual = VisionTransformer(
274
+ input_resolution=image_resolution,
275
+ patch_size=vision_patch_size,
276
+ width=vision_width,
277
+ layers=vision_layers,
278
+ heads=vision_heads,
279
+ output_dim=embed_dim
280
+ )
281
+
282
+ self.transformer = Transformer(
283
+ width=transformer_width,
284
+ layers=transformer_layers,
285
+ heads=transformer_heads,
286
+ attn_mask=self.build_attention_mask()
287
+ )
288
+
289
+ self.vocab_size = vocab_size
290
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
291
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
292
+ self.ln_final = LayerNorm(transformer_width)
293
+
294
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
295
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
296
+
297
+ self.initialize_parameters()
298
+
299
+ def initialize_parameters(self):
300
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
301
+ nn.init.normal_(self.positional_embedding, std=0.01)
302
+
303
+ if isinstance(self.visual, ModifiedResNet):
304
+ if self.visual.attnpool is not None:
305
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
306
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
307
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
308
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
309
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
310
+
311
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
312
+ for name, param in resnet_block.named_parameters():
313
+ if name.endswith("bn3.weight"):
314
+ nn.init.zeros_(param)
315
+
316
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
317
+ attn_std = self.transformer.width ** -0.5
318
+ fc_std = (2 * self.transformer.width) ** -0.5
319
+ for block in self.transformer.resblocks:
320
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
321
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
322
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
323
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
324
+
325
+ if self.text_projection is not None:
326
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
327
+
328
+ def build_attention_mask(self):
329
+ # lazily create causal attention mask, with full attention between the vision tokens
330
+ # pytorch uses additive attention mask; fill with -inf
331
+ mask = torch.empty(self.context_length, self.context_length)
332
+ mask.fill_(float("-inf"))
333
+ mask.triu_(1) # zero out the lower diagonal
334
+ return mask
335
+
336
+ @property
337
+ def dtype(self):
338
+ return self.visual.conv1.weight.dtype
339
+
340
+ def encode_image(self, image):
341
+ return self.visual(image.type(self.dtype))
342
+
343
+ def encode_text(self, text):
344
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
345
+
346
+ x = x + self.positional_embedding.type(self.dtype)
347
+ x = x.permute(1, 0, 2) # NLD -> LND
348
+ x = self.transformer(x)
349
+ x = x.permute(1, 0, 2) # LND -> NLD
350
+ x = self.ln_final(x).type(self.dtype)
351
+
352
+ # x.shape = [batch_size, n_ctx, transformer.width]
353
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
354
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
355
+
356
+ return x
357
+
358
+ def forward(self, image, text):
359
+ image_features = self.encode_image(image)
360
+ text_features = self.encode_text(text)
361
+
362
+ # normalized features
363
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
364
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
365
+
366
+ # cosine similarity as logits
367
+ logit_scale = self.logit_scale.exp()
368
+ logits_per_image = logit_scale * image_features @ text_features.t()
369
+ logits_per_text = logits_per_image.t()
370
+
371
+ # shape = [global_batch_size, global_batch_size]
372
+ return logits_per_image, logits_per_text
373
+
374
+
375
+ def convert_weights(model: nn.Module):
376
+ """Convert applicable model parameters to fp16"""
377
+
378
+ def _convert_weights_to_fp16(l):
379
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
380
+ l.weight.data = l.weight.data.half()
381
+ if l.bias is not None:
382
+ l.bias.data = l.bias.data.half()
383
+
384
+ if isinstance(l, nn.MultiheadAttention):
385
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
386
+ tensor = getattr(l, attr)
387
+ if tensor is not None:
388
+ tensor.data = tensor.data.half()
389
+
390
+ for name in ["text_projection", "proj"]:
391
+ if hasattr(l, name):
392
+ attr = getattr(l, name)
393
+ if attr is not None:
394
+ attr.data = attr.data.half()
395
+
396
+ model.apply(_convert_weights_to_fp16)
397
+
398
+
399
+ def build_model(state_dict: dict):
400
+ vit = "visual.proj" in state_dict
401
+
402
+ if vit:
403
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
404
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
405
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
406
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
407
+ image_resolution = vision_patch_size * grid_size
408
+ else:
409
+ counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
410
+ vision_layers = tuple(counts)
411
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
412
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
413
+ vision_patch_size = None
414
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
415
+ image_resolution = output_width * 32
416
+
417
+ embed_dim = state_dict["text_projection"].shape[1]
418
+ context_length = state_dict["positional_embedding"].shape[0]
419
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
420
+ transformer_width = state_dict["ln_final.weight"].shape[0]
421
+ transformer_heads = transformer_width // 64
422
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
423
+
424
+ model = CLIP(
425
+ embed_dim,
426
+ image_resolution, vision_layers, vision_width, vision_patch_size,
427
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
428
+ )
429
+
430
+ for key in ["input_resolution", "context_length", "vocab_size"]:
431
+ if key in state_dict:
432
+ del state_dict[key]
433
+
434
+ convert_weights(model)
435
+ model.load_state_dict(state_dict)
436
+ return model.eval()
config.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, json, math, os
2
+
3
+
4
+ d = {
5
+ 'debug': True,
6
+ 'dataset_path': '../data/tongji_data/pos.json',
7
+ 'train_data_file': '../data/tongji_data/tmp_input_ids_27/',
8
+ 'train_number_data': 1632069,
9
+ 'valid_data_file': '../data/tongji_data/test_2016_new_input_id_new.pt',
10
+ 'fptype': 'morgan',
11
+ 'valid_ratio': 0.1,
12
+ 'batch_size': 64,
13
+ 'lr': 1e-3,
14
+ 'min_lr': 2e-5,
15
+ 'weight_decay': 1e-3,
16
+ 'scheduler_type': 'warmup_cosine',
17
+ 'warmup_epochs': 1,
18
+ 'warmup_start_factor': 1.0,
19
+ 'patience': 2,
20
+ 'factor': 0.5,
21
+ 'add_nl': True,
22
+ 'binary_intn': False,
23
+ 'max_mz': 2000,
24
+ 'min_mz': 20,
25
+ 'energy': 'Energy1',
26
+ 'epochs': 50,
27
+ 'bin_size': 0.05,
28
+ 'ms_embedding_dim': 300,
29
+ 'ms_feature3_embedding_dim': 135,
30
+ 'ms3_meta_dim': 50,
31
+ 'projection_dim': 256,
32
+ 'ms_projection_layers': 1,
33
+ 'mol_embedding_dim': 2048,
34
+ 'mol_projection_layers': 1,
35
+ 'tsfm_in_ms': True,
36
+ 'tsfm_in_mol': False,
37
+ 'tsfm_layers': 6,
38
+ 'tsfm_heads': 8,
39
+ 'lstm_layers': 2,
40
+ 'lstm_in_ms': False,
41
+ 'lstm_in_mol': False,
42
+ 'dropout': 0.1,
43
+ 'nmodels': 1,
44
+ 'mol_encoder': 'gnn+fp', # fp, gnn or gnn+fp
45
+ 'molgnn_n_filters_list': [256, 256, 256],
46
+ 'molgnn_nhead': 4,
47
+ 'molgnn_readout_layers': 2,
48
+ 'seed': 1234,
49
+ 'dev_name': 'cuda:0',
50
+ 'keep_best_models_num': 3,
51
+ 'alpha': 0.5,
52
+ 'beta': 0.5,
53
+ 'structure_diag_weight': 0.25,
54
+ 'fp_dim': 2048,
55
+ "experiment_name_type": ['mol_gcn_base', 'mol_gat_base', 'mol_gcn_ms1', 'mol_gat_ms1', 'mol_gcn_ms3', 'mol_gat_ms3',
56
+ 'mol_gcn_ms1_ms3', 'mol_gat_ms1_ms3',
57
+ # loss 8 - 15
58
+ 'mol_gcn_base_loss', 'mol_gat_base_loss', 'mol_gcn_ms1_loss', 'mol_gat_ms1_loss',
59
+ 'mol_gcn_ms3_loss', 'mol_gat_ms3_loss', 'mol_gcn_ms1_ms3_loss', 'mol_gat_ms1_ms3_loss'][14]
60
+ }
61
+
62
+
63
+ class ConfigDict(dict):
64
+ '''
65
+ Makes a dictionary behave like an object,with attribute-style access.
66
+ '''
67
+ def __getattr__(self, name):
68
+ try:
69
+ return self[name]
70
+ except:
71
+ raise AttributeError(name)
72
+
73
+ def __setattr__(self, name, value):
74
+ self[name] = value
75
+
76
+ def save(self, fn, onlyprint=False):
77
+ if onlyprint:
78
+ print(self)
79
+ else:
80
+ json.dump(self, open(fn, 'w'), indent=2)
81
+
82
+ def load_dict(self, dic):
83
+ for k, v in dic.items():
84
+ self[k] = v
85
+ self.calc_ms_embedding_dim()
86
+
87
+ def load(self, fn):
88
+ try:
89
+ if type(fn) is dict:
90
+ d = fn
91
+ elif type(fn) is str:
92
+ if os.path.exists(fn):
93
+ d = json.load(open(fn, 'r'))
94
+ else:
95
+ d = json.loads(fn)
96
+ self.load_dict(d)
97
+ except Exception as e:
98
+ print(e)
99
+
100
+ def calc_ms_embedding_dim(self):
101
+ if 'bin_size' in self:
102
+ self['ms_embedding_dim'] = math.ceil((self['max_mz'] - self['min_mz']) / self['bin_size'])
103
+ if 'ms_embedding_dim' in self and 'add_nl' in self and self['add_nl']:
104
+ self['ms_embedding_dim'] += math.ceil((200) / self['bin_size'])
105
+
106
+ @property
107
+ def device(self):
108
+ try:
109
+ if torch.cuda.is_available():
110
+ return torch.device(self['dev_name'])
111
+ else:
112
+ return torch.device('cpu')
113
+ except Exception as e:
114
+ return torch.device('cpu')
115
+
116
+
117
+ CFG = ConfigDict()
118
+ CFG.load_dict(d)
dataset.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json
2
+ import torch
3
+ import utils
4
+ import numpy as np
5
+
6
+
7
+ def calc_feats(smi, ms, nls, cfg, ms_bins3=None, precursor_mz=490.28+18.01, diagnostic_ions=[102.05, 135.08],
8
+ neutral_losses=[18.01]):
9
+ item = {}
10
+ item['ms_bins'] = utils.ms_binner(ms, nls,
11
+ min_mz=cfg.min_mz,
12
+ max_mz=cfg.max_mz,
13
+ bin_size=cfg.bin_size,
14
+ add_nl=cfg.add_nl,
15
+ binary_intn=cfg.binary_intn)
16
+
17
+ # precursor = 490.28 + 18.01 # 模拟丢失水
18
+ precursor = precursor_mz
19
+ meta = np.zeros(25)
20
+ meta[0] = 1 # 假设第一位是 Orbitrap
21
+ item['ms_bins1'], item['ms_bins2'] = utils.ms_feature_processor(ms,
22
+ precursor,
23
+ meta,
24
+ diagnostic_ions=diagnostic_ions,
25
+ neutral_losses=neutral_losses)
26
+ item['ms_bins3'] = torch.tensor(ms_bins3) if ms_bins3 is not None else None
27
+
28
+ fmcalced = False
29
+ if 'fp' in cfg.mol_encoder:
30
+ if not 'fm' in cfg.mol_encoder:
31
+ item['mol_fps'] = utils.mol_fp_encoder(smi,
32
+ tp=cfg.fptype,
33
+ nbits=cfg.mol_embedding_dim)
34
+ else:
35
+ item['mol_fps'], item['mol_fmvec'] = utils.mol_fp_fm_encoder(smi,
36
+ tp=cfg.fptype,
37
+ nbits=cfg.mol_embedding_dim)
38
+ fmcalced = True
39
+
40
+ if 'gnn' in cfg.mol_encoder:
41
+ f = utils.mol_graph_featurizer(smi)
42
+ if not f:
43
+ return None
44
+ item.update(f)
45
+ if 'fm' in cfg.mol_encoder and not fmcalced:
46
+ item['mol_fmvec'] = utils.smi2fmvec(smi)
47
+
48
+ return item
49
+
50
+
51
+ class Dataset(torch.utils.data.Dataset):
52
+ def __init__(self, inp, cfg):
53
+ if type(inp) is str:
54
+ self.data = json.load(open(inp))
55
+ else:
56
+ self.data = inp
57
+
58
+ self.cfg = cfg
59
+
60
+ def __getitem__(self, idx):
61
+ d = self.data[idx]
62
+ if "ms_bins" in d:
63
+
64
+ return d
65
+ else:
66
+ item = {}
67
+ try:
68
+ if 'nls' in self.data[idx]:
69
+ nls = self.data[idx]['nls']
70
+ else:
71
+ nls = []
72
+
73
+ ms = self.data[idx]['ms']
74
+ smi = self.data[idx]['smiles']
75
+
76
+ item = calc_feats(smi, ms, nls, self.cfg)
77
+
78
+ except Exception as e:
79
+ print('='*50, idx, str(e))
80
+ return None
81
+
82
+ return item
83
+
84
+ def __len__(self):
85
+ return len(self.data)
86
+
87
+
88
+ class DatasetGNNFP(torch.utils.data.Dataset):
89
+ def __init__(self, inp, cfg):
90
+ if type(inp) is str:
91
+ self.data = json.load(open(inp))
92
+ else:
93
+ self.data = inp
94
+
95
+ self.cfg = cfg
96
+
97
+ def __getitem__(self, idx):
98
+ try:
99
+ smi = self.data[idx]['smiles']
100
+ item = {}
101
+ item['mol_fps'] = utils.mol_fp_encoder(smi,
102
+ tp=self.cfg.fptype,
103
+ nbits=self.cfg.mol_embedding_dim)
104
+ item.update(utils.mol_graph_featurizer(smi))
105
+ except Exception as e:
106
+ print('='*50, idx, str(e))
107
+ return None
108
+
109
+ return item
110
+
111
+ def __len__(self):
112
+ return len(self.data)
113
+
114
+
115
+ class PathDataset(torch.utils.data.Dataset):
116
+ def __init__(self, pathlist, cfg):
117
+ self.fns = pathlist
118
+ self.cfg = cfg
119
+ self.data = {}
120
+
121
+ def __getitem__(self, idx):
122
+ fn = self.fns[idx]
123
+ if fn.endswith(".pt"):
124
+ item = torch.load(fn)
125
+ return item
126
+
127
+ else:
128
+ try:
129
+ item = {}
130
+ nls = []
131
+ if not idx in self.data:
132
+ out = self.proc_data(self.fns[idx], self.cfg.energy)
133
+ if out is None:
134
+ return None
135
+ self.data[idx] = out
136
+
137
+ ms = self.data[idx]['ms']
138
+ smi = self.data[idx]['smiles']
139
+
140
+ item = calc_feats(smi, ms, nls, self.cfg)
141
+
142
+ except Exception as e:
143
+ print('='*50, idx, str(e))
144
+ return None
145
+
146
+ return item
147
+
148
+ def proc_data(self, fn, energy='Energy1'):
149
+ if fn.endswith('.json'):
150
+ d = json.load(open(fn, 'r', encoding='utf-8'))
151
+ l = d['ms']
152
+ smi = d['smiles']
153
+ out = {'ms': l, 'smiles': smi}
154
+ return out
155
+ else:
156
+ tl = open(fn).readlines()
157
+ l = []
158
+ try:
159
+ flag = False
160
+ for i in tl:
161
+ if energy in i:
162
+ smi = i.split(';')[-2]
163
+ flag = True
164
+ continue
165
+ if 'END IONS' in i:
166
+ if flag:
167
+ break
168
+ if flag:
169
+ mz, intn = i.split(' ')
170
+ l.append((float(mz), float(intn)))
171
+ except:
172
+ return None
173
+
174
+ out = {'ms': l, 'smiles': smi}
175
+ return out
176
+
177
+ def __len__(self):
178
+ return len(self.fns)
embedding_predict111.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- conding: utf-8 -*-
2
+ # @Time : 2025/12/14 10:58
3
+ # @Author : psi
4
+
5
+ from utils import *
6
+ from modules import *
7
+ import os, sys
8
+ import numpy as np
9
+ from tqdm import tqdm
10
+ import random
11
+ import torch
12
+ from torch import nn
13
+ from config import CFG
14
+ from dataset import *
15
+ import torch.utils.data
16
+ import copy, json, pickle
17
+ import itertools as it
18
+ import glob
19
+ import torch.nn.functional as F
20
+
21
+
22
+ def my_collate(batch):
23
+ batch = list(filter(lambda x: (x is not None), batch))
24
+ msbinl, molfpl, molfml, vl, al, msl = [], [], [], [], [], []
25
+ bat = {}
26
+ msbinl1, msbinl2 = [], []
27
+
28
+ for b in batch:
29
+ if 'ms_bins' in b:
30
+ msbinl.append(b['ms_bins'])
31
+ if 'ms_bins1' in b:
32
+ msbinl1.append(b['ms_bins1'])
33
+ if 'ms_bins2' in b:
34
+ msbinl2.append(b['ms_bins2'])
35
+ if 'mol_fps' in b:
36
+ molfpl.append(b['mol_fps'])
37
+ if 'mol_fmvec' in b:
38
+ molfml.append(b['mol_fmvec'])
39
+ if 'V' in b:
40
+ vl.append(b['V'])
41
+ if 'A' in b:
42
+ al.append(b['A'])
43
+ if 'mol_size' in b:
44
+ msl.append(b['mol_size'])
45
+
46
+ if msbinl:
47
+ bat['ms_bins'] = torch.stack(msbinl)
48
+ if msbinl1:
49
+ bat['ms_bins1'] = torch.stack(msbinl1)
50
+ if msbinl2:
51
+ bat['ms_bins2'] = torch.stack(msbinl2)
52
+ if molfpl:
53
+ bat['mol_fps'] = torch.stack(molfpl)
54
+ if molfml:
55
+ bat['mol_fmvec'] = torch.stack(molfml)
56
+ if vl and al and msl:
57
+ max_n = max(map(lambda x:x.shape[0], vl))
58
+ vl1, al1 = [], []
59
+ for v in vl:
60
+ vl1.append(pad_V(v, max_n))
61
+ for a in al:
62
+ al1.append(pad_A(a, max_n))
63
+
64
+ bat['V'] = torch.stack(vl1)
65
+ bat['A'] = torch.stack(al1)
66
+ bat['mol_size'] = torch.cat(msl, dim=0)
67
+
68
+ # return torch.utils.data.dataloader.default_collate(batch)
69
+ return bat
70
+
71
+
72
+ def build_loaders(inp, mode, cfg, num_workers):
73
+ if type(inp[0]) is dict:
74
+ dataset = Dataset(inp, cfg)
75
+ else:
76
+ dataset = PathDataset(inp, cfg)
77
+ dataloader = torch.utils.data.DataLoader(
78
+ dataset,
79
+ batch_size=len(dataset),
80
+ num_workers=num_workers,
81
+ shuffle=True if mode == "train" else False,
82
+ collate_fn=my_collate
83
+ )
84
+ return dataloader
85
+
86
+
87
+ class Predictor():
88
+
89
+ def __init__(self, file, model_file):
90
+ CFG.load(file)
91
+ cfg = CFG
92
+ self.cfg = cfg
93
+ model = FragSimiModelNew(cfg).to(cfg.device)
94
+ encmodel = torch.load(model_file)
95
+ # model.mol_gnn_encoder.load_state_dict(encmodel.mol_gnn_encoder.state_dict())
96
+ model.load_state_dict(encmodel['state_dict'])
97
+
98
+ self.model = model
99
+ self.model.eval()
100
+
101
+ def process_file(self, smi):
102
+ # d = json.load(open(file, 'r', encoding='utf-8'))
103
+ # ms = d['ms']
104
+ # smi = d['smiles']
105
+ ms = [[41.038587, 880600.0], [42.033833, 1973400.0], [43.041651, 2117400.0], [44.049388, 925150.0], [44.979347, 4397200.0], [51.022884, 593400.0], [53.038537, 9694400.0], [54.033783, 415000.0], [55.054152, 1911200.0], [56.049325, 4400500.0], [56.979301, 487200.0], [65.038474, 449400.0], [67.041567, 1667200.0], [67.054107, 786000.0], [68.049268, 6593250.0], [68.979253, 836000.0], [69.056975, 17628050.0], [69.069744, 290600.0], [70.06482, 1716900.0], [70.994926, 276400.0], [73.010627, 215600.0], [77.038437, 417800.0], [79.054112, 1319600.0], [80.049378, 3584000.0], [81.057194, 2957200.0], [82.064812, 25688800.0], [82.070396, 669000.0], [82.073249, 528650.0], [82.994909, 3564600.0], [83.072653, 7343000.0], [84.080502, 821400.0], [94.065026, 1006000.0], [95.049053, 230800.0], [96.080647, 13938800.0], [97.010531, 20776600.0], [97.013298, 339600.0], [98.989853, 367600.0], [110.096244, 1418800.0], [110.989833, 48727600.0], [110.991981, 1024000.0], [110.994248, 515600.0], [111.001067, 985400.0], [111.103933, 13806250.0], [112.111972, 17873400.0], [112.114998, 263400.0], [115.054168, 518400.0], [117.069717, 320200.0], [134.018401, 474400.0], [194.099834, 1533000.0], [194.993274, 21076400.0], [306.09803, 51809350.0], [306.181335, 516550.0]]
106
+
107
+ # out = {'ms': ms, 'smiles': smi}
108
+ # ms = self.data[idx]['ms']
109
+ # smi = self.data[idx]['smiles']
110
+ nls = []
111
+ item = calc_feats(smi, ms, nls, self.cfg)
112
+ return item
113
+
114
+ def process(self, file):
115
+ if isinstance(file, str):
116
+ res = json.load(open(file, 'r', encoding='utf-8'))
117
+ data = res['smiles']
118
+ res = []
119
+ for d in tqdm(data, desc='process ...'):
120
+ try:
121
+ res.append([d, self.process_file(d)])
122
+ except:
123
+ res.append([d, None])
124
+
125
+ o_file = '/dev/shm/data/tongji_data/all_pos_pred.pt'
126
+ torch.save(res, o_file)
127
+
128
+ os._exit(0)
129
+
130
+ else:
131
+ res = file
132
+ batch = my_collate(res)
133
+ return batch
134
+
135
+ def get_eval_info(self, ms_embeddings, mol_embeddings, top_ks=(1, 3, 5, 10)):
136
+ N = ms_embeddings.shape[0]
137
+
138
+ # 1. L2 归一化(非常关键)
139
+ # ms_norm = F.normalize(ms_embeddings, dim=1)
140
+ # mol_norm = F.normalize(mol_embeddings, dim=1)
141
+ ms_norm = ms_embeddings
142
+ mol_norm = mol_embeddings
143
+
144
+ recalls = {k: 0 for k in top_ks}
145
+
146
+ # 2. 对每个样本做检索
147
+ for i in range(N):
148
+ query = ms_norm[i] # (256,)
149
+ sims = torch.matmul(mol_norm, query) # (N,)
150
+
151
+ ranked_indices = torch.argsort(sims, descending=True)
152
+
153
+ for k in top_ks:
154
+ if i in ranked_indices[:k]:
155
+ recalls[k] += 1
156
+
157
+ # 3. 取平均
158
+ for k in recalls:
159
+ recalls[k] /= N
160
+
161
+ return recalls
162
+
163
+ def predict(self, file_path):
164
+ # data_files = []
165
+ # for root, _, files in os.walk(file_path):
166
+ # for f in files:
167
+ # if f.endswith(('.json', '.pkl', '.mgf')):
168
+ # data_files.append(os.path.join(root, f))
169
+ # data = sorted(
170
+ # data_files,
171
+ # key=lambda x: int(os.path.splitext(os.path.basename(x))[0])
172
+ # )
173
+ batch = self.process(file_path)
174
+ for k, v in batch.items():
175
+ batch[k] = v.to(self.cfg.device)
176
+
177
+ with torch.no_grad():
178
+ loss, loss_infonce, loss_mse, ms_embeddings, mol_embeddings = self.model(batch, is_predict=True)
179
+
180
+ # recalls_info = self.get_eval_info(ms_embeddings, mol_embeddings)
181
+ # print(recalls_info)
182
+ #
183
+ # return loss, loss_infonce, loss_mse, recalls_info
184
+
185
+ return mol_embeddings
186
+
187
+
188
+ if __name__ == '__main__':
189
+ model_file = ["model-tloss3.437-vloss2.907-epoch0.pth", "model-tloss2.495-vloss2.253-epoch1.pth",
190
+ "model-tloss1.987-vloss1.866-epoch2.pth", "model-tloss1.597-vloss1.573-epoch3.pth",
191
+ "model-tloss1.332-vloss1.384-epoch4.pth", "model-tloss1.088-vloss1.255-epoch5.pth",
192
+ "model-tloss0.899-vloss1.068-epoch6.pth",
193
+ "/root/代码/out_data/train-018/model-tloss0.76-vloss0.986-epoch0.pth",
194
+ "/root/代码/out_data/train-019/model-tloss0.608-vloss0.943-epoch0.pth",
195
+ "/root/代码/out_data/train-019/model-tloss0.577-vloss0.852-epoch1.pth",
196
+ "/root/代码/out_data/train-019/model-tloss0.503-vloss0.811-epoch2.pth",
197
+ '/root/代码/out_data/train-019/model-tloss0.448-vloss0.763-epoch3.pth',
198
+ '/root/代码/out_data/train-019/model-tloss0.405-vloss0.74-epoch4.pth',
199
+ '/root/代码/out_data/train-019/model-tloss0.367-vloss0.722-epoch5.pth',
200
+ '/root/代码/out_data/train-019/model-tloss0.337-vloss0.705-epoch6.pth',
201
+ '/root/代码/out_data/train-019/model-tloss0.317-vloss0.671-epoch7.pth'][-1]
202
+ model_name = model_file.split('/')[-1][:-4]
203
+ pred = Predictor('config.json', model_file)
204
+
205
+ # file_path = '/dev/shm/data/tongji_data/all_pos.json'
206
+ # loss, loss_infonce, loss_mse, recalls_info = pred.predict(file_path)
207
+
208
+ o_file = '/dev/shm/data/tongji_data/all_pos_pred.pt'
209
+ data = torch.load(o_file)
210
+ batch_size = 128
211
+ res = []
212
+ for i in tqdm(range(0, len(data), batch_size), desc='predict ...'):
213
+ batch = data[i:i+batch_size]
214
+ p = [x[1] for x in batch]
215
+ mol_embeddings = pred.predict(p)
216
+ mol_embeddings = mol_embeddings.to("cpu")
217
+ res.append(mol_embeddings)
218
+
219
+ result = torch.cat(res, dim=0)
220
+
221
+ print(f"len is : {len(data)} ...")
222
+ print(f"result shape is : {result.shape} ...")
223
+
224
+ out_file = f'/dev/shm/data/tongji_data/all_pos_pred_emb_{model_name}.pt'
225
+ torch.save(result, out_file)
embedding_predict222.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- conding: utf-8 -*-
2
+ # @Time : 2025/12/14 10:58
3
+ # @Author : psi
4
+
5
+ from utils import *
6
+ from modules import *
7
+ import os, sys
8
+ import numpy as np
9
+ from tqdm import tqdm
10
+ import random
11
+ import torch
12
+ from torch import nn
13
+ from config import CFG
14
+ from dataset import *
15
+ import torch.utils.data
16
+ import copy, json, pickle
17
+ import itertools as it
18
+ import glob
19
+ import torch.nn.functional as F
20
+
21
+
22
+ def my_collate(batch):
23
+ batch = list(filter(lambda x: (x is not None), batch))
24
+ msbinl, molfpl, molfml, vl, al, msl = [], [], [], [], [], []
25
+ bat = {}
26
+ msbinl1, msbinl2 = [], []
27
+
28
+ for b in batch:
29
+ if 'ms_bins' in b:
30
+ msbinl.append(b['ms_bins'])
31
+ if 'ms_bins1' in b:
32
+ msbinl1.append(b['ms_bins1'])
33
+ if 'ms_bins2' in b:
34
+ msbinl2.append(b['ms_bins2'])
35
+ if 'mol_fps' in b:
36
+ molfpl.append(b['mol_fps'])
37
+ if 'mol_fmvec' in b:
38
+ molfml.append(b['mol_fmvec'])
39
+ if 'V' in b:
40
+ vl.append(b['V'])
41
+ if 'A' in b:
42
+ al.append(b['A'])
43
+ if 'mol_size' in b:
44
+ msl.append(b['mol_size'])
45
+
46
+ if msbinl:
47
+ bat['ms_bins'] = torch.stack(msbinl)
48
+ if msbinl1:
49
+ bat['ms_bins1'] = torch.stack(msbinl1)
50
+ if msbinl2:
51
+ bat['ms_bins2'] = torch.stack(msbinl2)
52
+ if molfpl:
53
+ bat['mol_fps'] = torch.stack(molfpl)
54
+ if molfml:
55
+ bat['mol_fmvec'] = torch.stack(molfml)
56
+ if vl and al and msl:
57
+ max_n = max(map(lambda x:x.shape[0], vl))
58
+ vl1, al1 = [], []
59
+ for v in vl:
60
+ vl1.append(pad_V(v, max_n))
61
+ for a in al:
62
+ al1.append(pad_A(a, max_n))
63
+
64
+ bat['V'] = torch.stack(vl1)
65
+ bat['A'] = torch.stack(al1)
66
+ bat['mol_size'] = torch.cat(msl, dim=0)
67
+
68
+ # return torch.utils.data.dataloader.default_collate(batch)
69
+ return bat
70
+
71
+
72
+ def build_loaders(inp, mode, cfg, num_workers):
73
+ if type(inp[0]) is dict:
74
+ dataset = Dataset(inp, cfg)
75
+ else:
76
+ dataset = PathDataset(inp, cfg)
77
+ dataloader = torch.utils.data.DataLoader(
78
+ dataset,
79
+ batch_size=len(dataset),
80
+ num_workers=num_workers,
81
+ shuffle=True if mode == "train" else False,
82
+ collate_fn=my_collate
83
+ )
84
+ return dataloader
85
+
86
+
87
+ class Predictor():
88
+
89
+ def __init__(self, file, model_file):
90
+ CFG.load(file)
91
+ cfg = CFG
92
+ self.cfg = cfg
93
+ model = FragSimiModelNew(cfg).to(cfg.device)
94
+ encmodel = torch.load(model_file)
95
+ # model.mol_gnn_encoder.load_state_dict(encmodel.mol_gnn_encoder.state_dict())
96
+ model.load_state_dict(encmodel['state_dict'])
97
+
98
+ self.model = model
99
+ self.model.eval()
100
+
101
+ def process_file(self, smi):
102
+ # d = json.load(open(file, 'r', encoding='utf-8'))
103
+ # ms = d['ms']
104
+ # smi = d['smiles']
105
+
106
+ ms = [[41.998214, 491000.0], [107.049799, 633000.0], [131.049708, 1969500.0], [134.040609, 827000.0], [145.052688, 300000.0], [161.051274, 270500.0], [309.102783, 2374000.0]]
107
+ # out = {'ms': ms, 'smiles': smi}
108
+ # ms = self.data[idx]['ms']
109
+ # smi = self.data[idx]['smiles']
110
+ nls = []
111
+ item = calc_feats(smi, ms, nls, self.cfg)
112
+ return item
113
+
114
+ def process(self, file):
115
+
116
+ if isinstance(file, str):
117
+ res = json.load(open(file, 'r', encoding='utf-8'))
118
+ data = res['smiles']
119
+ res = []
120
+ for d in tqdm(data, desc='process ...'):
121
+ try:
122
+ res.append([d, self.process_file(d)])
123
+ except:
124
+ res.append([d, None])
125
+
126
+ o_file = '/dev/shm/data/tongji_data/all_neg_pred.pt'
127
+ torch.save(res, o_file)
128
+
129
+ os._exit(0)
130
+
131
+ else:
132
+ res = file
133
+ batch = my_collate(res)
134
+ return batch
135
+
136
+ def get_eval_info(self, ms_embeddings, mol_embeddings, top_ks=(1, 3, 5, 10)):
137
+ N = ms_embeddings.shape[0]
138
+
139
+ # 1. L2 归一化(非常关键)
140
+ # ms_norm = F.normalize(ms_embeddings, dim=1)
141
+ # mol_norm = F.normalize(mol_embeddings, dim=1)
142
+ ms_norm = ms_embeddings
143
+ mol_norm = mol_embeddings
144
+
145
+ recalls = {k: 0 for k in top_ks}
146
+
147
+ # 2. 对每个样本做检索
148
+ for i in range(N):
149
+ query = ms_norm[i] # (256,)
150
+ sims = torch.matmul(mol_norm, query) # (N,)
151
+
152
+ ranked_indices = torch.argsort(sims, descending=True)
153
+
154
+ for k in top_ks:
155
+ if i in ranked_indices[:k]:
156
+ recalls[k] += 1
157
+
158
+ # 3. 取平均
159
+ for k in recalls:
160
+ recalls[k] /= N
161
+
162
+ return recalls
163
+
164
+ def predict(self, file_path):
165
+ # data_files = []
166
+ # for root, _, files in os.walk(file_path):
167
+ # for f in files:
168
+ # if f.endswith(('.json', '.pkl', '.mgf')):
169
+ # data_files.append(os.path.join(root, f))
170
+ # data = sorted(
171
+ # data_files,
172
+ # key=lambda x: int(os.path.splitext(os.path.basename(x))[0])
173
+ # )
174
+ batch = self.process(file_path)
175
+ for k, v in batch.items():
176
+ batch[k] = v.to(self.cfg.device)
177
+
178
+ with torch.no_grad():
179
+ loss, loss_infonce, loss_mse, ms_embeddings, mol_embeddings = self.model(batch, is_predict=True)
180
+
181
+ # recalls_info = self.get_eval_info(ms_embeddings, mol_embeddings)
182
+ # print(recalls_info)
183
+
184
+ # return loss, loss_infonce, loss_mse, recalls_info
185
+
186
+ return mol_embeddings
187
+
188
+
189
+ if __name__ == '__main__':
190
+ model_file = ["/root/代码/out_data/train-020/model-tloss3.239-vloss2.752-epoch0.pth",
191
+ "/root/代码/out_data/train-020/model-tloss2.487-vloss2.279-epoch1.pth",
192
+ "/root/代码/out_data/train-020/model-tloss2.086-vloss1.924-epoch2.pth",
193
+ "/root/代码/out_data/train-020/model-tloss1.716-vloss1.609-epoch3.pth",
194
+ "/root/代码/out_data/train-020/model-tloss1.414-vloss1.361-epoch4.pth",
195
+ '/root/代码/out_data/train-020/model-tloss1.177-vloss1.173-epoch5.pth',
196
+ "/root/代码/out_data/train-020/model-tloss0.99-vloss1.036-epoch6.pth",
197
+ '/root/代码/out_data/train-020/model-tloss0.849-vloss0.929-epoch7.pth',
198
+ '/root/代码/out_data/train-020/model-tloss0.736-vloss0.851-epoch8.pth',
199
+ '/root/代码/out_data/train-020/model-tloss0.647-vloss0.779-epoch9.pth',
200
+ '/root/代码/out_data/train-020/model-tloss0.575-vloss0.728-epoch10.pth'][-1]
201
+
202
+ model_name = model_file.split('/')[-1][:-4]
203
+ pred = Predictor('config.json', model_file)
204
+
205
+ # file_path = '/dev/shm/data/tongji_data/all_neg.json'
206
+ # loss, loss_infonce, loss_mse, recalls_info = pred.predict(file_path)
207
+
208
+ o_file = '/dev/shm/data/tongji_data/all_neg_pred.pt'
209
+ data = torch.load(o_file)
210
+ batch_size = 128
211
+ res = []
212
+ for i in tqdm(range(0, len(data), batch_size), desc='predict ...'):
213
+ batch = data[i:i + batch_size]
214
+ p = [x[1] for x in batch]
215
+ mol_embeddings = pred.predict(p)
216
+ mol_embeddings = mol_embeddings.to("cpu")
217
+ res.append(mol_embeddings)
218
+
219
+ result = torch.cat(res, dim=0)
220
+
221
+ print(f"len is : {len(data)} ...")
222
+ print(f"result shape is : {result.shape} ...")
223
+
224
+ out_file = f'/dev/shm/data/tongji_data/all_neg_pred_emb_{model_name}.pt'
225
+ torch.save(result, out_file)
infer_predict111.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- conding: utf-8 -*-
2
+ # @Time : 2025/12/14 10:58
3
+ # @Author : psi
4
+
5
+ from utils import *
6
+ from modules import *
7
+ import os, sys
8
+ import numpy as np
9
+ from tqdm import tqdm
10
+ import random
11
+ import torch
12
+ from torch import nn
13
+ from config import CFG
14
+ from dataset import *
15
+ import torch.utils.data
16
+ import copy, json, pickle
17
+ import itertools as it
18
+ import glob
19
+ import torch.nn.functional as F
20
+
21
+
22
+ def my_collate(batch):
23
+ batch = list(filter(lambda x: (x is not None), batch))
24
+ msbinl, molfpl, molfml, vl, al, msl = [], [], [], [], [], []
25
+ bat = {}
26
+ msbinl1, msbinl2 = [], []
27
+
28
+ for b in batch:
29
+ if 'ms_bins' in b:
30
+ msbinl.append(b['ms_bins'])
31
+ if 'ms_bins1' in b:
32
+ msbinl1.append(b['ms_bins1'])
33
+ if 'ms_bins2' in b:
34
+ msbinl2.append(b['ms_bins2'])
35
+ if 'mol_fps' in b:
36
+ molfpl.append(b['mol_fps'])
37
+ if 'mol_fmvec' in b:
38
+ molfml.append(b['mol_fmvec'])
39
+ if 'V' in b:
40
+ vl.append(b['V'])
41
+ if 'A' in b:
42
+ al.append(b['A'])
43
+ if 'mol_size' in b:
44
+ msl.append(b['mol_size'])
45
+
46
+ if msbinl:
47
+ bat['ms_bins'] = torch.stack(msbinl)
48
+ if msbinl1:
49
+ bat['ms_bins1'] = torch.stack(msbinl1)
50
+ if msbinl2:
51
+ bat['ms_bins2'] = torch.stack(msbinl2)
52
+ if molfpl:
53
+ bat['mol_fps'] = torch.stack(molfpl)
54
+ if molfml:
55
+ bat['mol_fmvec'] = torch.stack(molfml)
56
+ if vl and al and msl:
57
+ max_n = max(map(lambda x:x.shape[0], vl))
58
+ vl1, al1 = [], []
59
+ for v in vl:
60
+ vl1.append(pad_V(v, max_n))
61
+ for a in al:
62
+ al1.append(pad_A(a, max_n))
63
+
64
+ bat['V'] = torch.stack(vl1)
65
+ bat['A'] = torch.stack(al1)
66
+ bat['mol_size'] = torch.cat(msl, dim=0)
67
+
68
+ # return torch.utils.data.dataloader.default_collate(batch)
69
+ return bat
70
+
71
+
72
+ def build_loaders(inp, mode, cfg, num_workers):
73
+ if type(inp[0]) is dict:
74
+ dataset = Dataset(inp, cfg)
75
+ else:
76
+ dataset = PathDataset(inp, cfg)
77
+ dataloader = torch.utils.data.DataLoader(
78
+ dataset,
79
+ batch_size=len(dataset),
80
+ num_workers=num_workers,
81
+ shuffle=True if mode == "train" else False,
82
+ collate_fn=my_collate
83
+ )
84
+ return dataloader
85
+
86
+
87
+ class Predictor():
88
+
89
+ def __init__(self, file, model_file):
90
+ CFG.load(file)
91
+ cfg = CFG
92
+ self.cfg = cfg
93
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
94
+ model = FragSimiModelNew(cfg).to(cfg.device)
95
+ encmodel = torch.load(model_file)
96
+ # model.mol_gnn_encoder.load_state_dict(encmodel.mol_gnn_encoder.state_dict())
97
+ model.load_state_dict(encmodel['state_dict'])
98
+
99
+ self.model = model
100
+ self.model.eval()
101
+
102
+ def process_file(self, ms):
103
+ # d = json.load(open(file, 'r', encoding='utf-8'))
104
+ # ms = d['ms']
105
+ smi = 'Br.C=CC1CN2CCC1CC2C(O)c1ccnc2ccc(OC)cc12'
106
+ # out = {'ms': ms, 'smiles': smi}
107
+ # ms = self.data[idx]['ms']
108
+ # smi = self.data[idx]['smiles']
109
+ nls = []
110
+ item = calc_feats(smi, ms, nls, self.cfg)
111
+ return item
112
+
113
+ def process(self, data):
114
+ res = []
115
+ res.append(self.process_file(data))
116
+
117
+ batch = my_collate(res)
118
+
119
+ return batch
120
+
121
+ def get_eval_info(self, ms_embeddings, mol_embeddings, top_ks=(1, 3, 5, 10)):
122
+ N = ms_embeddings.shape[0]
123
+
124
+ # 1. L2 归一化(非常关键)
125
+ # ms_norm = F.normalize(ms_embeddings, dim=1)
126
+ # mol_norm = F.normalize(mol_embeddings, dim=1)
127
+ ms_norm = ms_embeddings
128
+ mol_norm = mol_embeddings
129
+
130
+ recalls = {k: 0 for k in top_ks}
131
+
132
+ # 2. 对每个样本做检索
133
+ for i in range(N):
134
+ query = ms_norm[i] # (256,)
135
+ sims = torch.matmul(mol_norm, query) # (N,)
136
+
137
+ ranked_indices = torch.argsort(sims, descending=True)
138
+
139
+ for k in top_ks:
140
+ if i in ranked_indices[:k]:
141
+ recalls[k] += 1
142
+
143
+ # 3. 取平均
144
+ for k in recalls:
145
+ recalls[k] /= N
146
+
147
+ return recalls
148
+
149
+ def predict(self, ms):
150
+ # data_files = []
151
+ # for root, _, files in os.walk(file_path):
152
+ # for f in files:
153
+ # if f.endswith(('.json', '.pkl', '.mgf')):
154
+ # data_files.append(os.path.join(root, f))
155
+ # data = sorted(
156
+ # data_files,
157
+ # key=lambda x: int(os.path.splitext(os.path.basename(x))[0])
158
+ # )
159
+ batch = self.process(ms)
160
+ for k, v in batch.items():
161
+ batch[k] = v.to(self.cfg.device)
162
+
163
+ with torch.no_grad():
164
+ loss, loss_infonce, loss_mse, ms_embeddings, mol_embeddings = self.model(batch, is_predict=True)
165
+
166
+ # recalls_info = self.get_eval_info(ms_embeddings, mol_embeddings)
167
+ # print(recalls_info)
168
+ #
169
+ # return loss, loss_infonce, loss_mse, recalls_info
170
+
171
+ return ms_embeddings
172
+
173
+ def process_file_1(self, ms, smi):
174
+ # d = json.load(open(file, 'r', encoding='utf-8'))
175
+ # ms = d['ms']
176
+ # smi = d['smiles']
177
+ # out = {'ms': ms, 'smiles': smi}
178
+ # ms = self.data[idx]['ms']
179
+ # smi = self.data[idx]['smiles']
180
+ nls = []
181
+ item = calc_feats(smi, ms, nls, self.cfg)
182
+ return item
183
+
184
+ def process_1(self, data):
185
+
186
+ res = []
187
+
188
+ for d in data:
189
+ try:
190
+ res.append([d['smiles'], self.process_file_1(d['ms'], d['smiles'])])
191
+ except Exception as e:
192
+ print(e)
193
+
194
+ if len(res) == 0:
195
+ return None
196
+
197
+ res1 = [x[1] for x in res]
198
+ res2 = [x[0] for x in res]
199
+
200
+ batch = my_collate(res1)
201
+
202
+ return batch, res2
203
+
204
+ def get_eval_info_1(self, ms_embeddings, mol_embeddings, top_ks=(1, 3, 5, 10)):
205
+ N = ms_embeddings.shape[0]
206
+
207
+ # 1. L2 归一化(非常关键)
208
+ # ms_norm = F.normalize(ms_embeddings, dim=1)
209
+ # mol_norm = F.normalize(mol_embeddings, dim=1)
210
+ ms_norm = ms_embeddings
211
+ mol_norm = mol_embeddings
212
+
213
+ recalls = {k: 0 for k in top_ks}
214
+
215
+ # 2. 对每个样本做检索
216
+ for i in range(N):
217
+ query = ms_norm[i] # (256,)
218
+ sims = torch.matmul(mol_norm, query) # (N,)
219
+
220
+ ranked_indices = torch.argsort(sims, descending=True)
221
+
222
+ for k in top_ks:
223
+ if i in ranked_indices[:k]:
224
+ recalls[k] += 1
225
+
226
+ # 3. 取平均
227
+ for k in recalls:
228
+ recalls[k] /= N
229
+
230
+ return recalls
231
+
232
+ def topk_similarity_1(self, ms_embedding, res_embeddings, batch_size=128, top_k=10):
233
+
234
+ ms_embedding = ms_embedding.to(self.device)
235
+ res_embeddings = res_embeddings.to(self.device)
236
+
237
+ # 保证是 float tensor
238
+ ms_embedding = ms_embedding.float()
239
+ res_embeddings = res_embeddings.float()
240
+
241
+ # 归一化(用于余弦相似度)
242
+ # ms_embedding = F.normalize(ms_embedding, dim=1)
243
+ # res_embeddings = F.normalize(res_embeddings, dim=1)
244
+
245
+ similarities = []
246
+
247
+ # 分 batch 计算
248
+ for i in range(0, res_embeddings.size(0), batch_size):
249
+ batch = res_embeddings[i:i + batch_size] # (B, 256)
250
+
251
+ # (1, 256) @ (256, B) -> (1, B)
252
+ sim = torch.matmul(ms_embedding, batch.T) # 余弦相似度
253
+ similarities.append(sim.squeeze(0)) # (B,)
254
+
255
+ # 拼接成 (15511,)
256
+ similarities = torch.cat(similarities, dim=0)
257
+
258
+ top_k = min(top_k, res_embeddings.size(0))
259
+ # 取 top_k
260
+ topk_sim, topk_idx = torch.topk(similarities, k=top_k)
261
+
262
+ return topk_sim, topk_idx
263
+
264
+ def predict_1(self, data):
265
+ # data_files = []
266
+ # for root, _, files in os.walk(file_path):
267
+ # for f in files:
268
+ # if f.endswith(('.json', '.pkl', '.mgf')):
269
+ # data_files.append(os.path.join(root, f))
270
+ # data = sorted(
271
+ # data_files,
272
+ # key=lambda x: int(os.path.splitext(os.path.basename(x))[0])
273
+ # )
274
+ batch, res_smiles = self.process_1(data)
275
+
276
+ if batch is None:
277
+ return None
278
+
279
+ for k, v in batch.items():
280
+ batch[k] = v.to(self.cfg.device)
281
+
282
+ loss, loss_infonce, loss_mse, ms_embeddings, mol_embeddings = self.model(batch, is_predict=True)
283
+
284
+ # recalls_info = self.get_eval_info(ms_embeddings, mol_embeddings)
285
+ # print(recalls_info)
286
+ #
287
+ # return loss, loss_infonce, loss_mse, recalls_info
288
+ # ms_embedding = ms_embeddings.to(self.device)
289
+ # res_embeddings = mol_embeddings.to(self.device)
290
+ ms_embedding = ms_embeddings[0:1, :]
291
+
292
+ topk_sim, topk_idx = self.topk_similarity_1(ms_embedding, mol_embeddings)
293
+ topk_idx = topk_idx.to("cpu").numpy().tolist()
294
+
295
+ res_pred_name = []
296
+ for x, i in enumerate(topk_idx):
297
+ res_pred_name.append([res_smiles[i], topk_sim[x].item()])
298
+
299
+ return res_pred_name
300
+
301
+
302
+ class InferOnline():
303
+ def __init__(self, model_file):
304
+ pred = Predictor('config.json', model_file)
305
+ self.pred_model = pred
306
+
307
+ model_name = model_file.split('/')[-1][:-4]
308
+ emb_file = f'/dev/shm/data/tongji_data/all_pos_pred_emb_{model_name}.pt'
309
+ file_path = '/dev/shm/data/tongji_data/all_pos.json'
310
+
311
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
312
+ self.emb_data= torch.load(emb_file)
313
+ print("self.emb_data shape ,,,", self.emb_data.shape)
314
+ self.all_data = json.load(open(file_path, 'r', encoding='utf-8'))
315
+
316
+ print("self.all_data shape ...", len(self.all_data))
317
+
318
+ pred_file = "/dev/shm/data/tongji_data/all_pos_pred.pt"
319
+ self.pred_name_data = [x[0] for x in torch.load(pred_file)]
320
+ print("self.pred_name_data shape ,,,", len(self.pred_name_data))
321
+
322
+ self.pred_smiles_name_2_id = {x: i for i, x in enumerate(self.pred_name_data)}
323
+ print("self.pred_smiles_name_2_id shape ,,,", len(self.pred_smiles_name_2_id))
324
+
325
+ all_data_res3 = {}
326
+ for k, v in self.all_data['res3'].items():
327
+ v1 = [x for x in v if x in self.pred_name_data]
328
+ if len(v1) > 0:
329
+ all_data_res3[k] = v1
330
+ self.all_data['res3'] = all_data_res3
331
+
332
+ def select_smiles(self, parent_mz, bn=50):
333
+
334
+ res_smiles = []
335
+ for k, v in self.all_data['res3'].items():
336
+ k = float(k)
337
+ if k > parent_mz - bn and k < parent_mz + bn:
338
+ res_smiles += v
339
+
340
+ res_embeddings = []
341
+ for x in res_smiles:
342
+ i = self.pred_smiles_name_2_id[x]
343
+ res_embeddings.append(self.emb_data[i, :].unsqueeze(0))
344
+
345
+ res_embeddings = torch.cat(res_embeddings, dim=0)
346
+
347
+ return res_embeddings, res_smiles
348
+
349
+ def topk_similarity(self, ms_embedding, res_embeddings, batch_size=128, top_k=10):
350
+
351
+ ms_embedding = ms_embedding.to(self.device)
352
+ res_embeddings = res_embeddings.to(self.device)
353
+
354
+ # 保证是 float tensor
355
+ ms_embedding = ms_embedding.float()
356
+ res_embeddings = res_embeddings.float()
357
+
358
+ # 归一化(用于余弦相似度)
359
+ # ms_embedding = F.normalize(ms_embedding, dim=1)
360
+ # res_embeddings = F.normalize(res_embeddings, dim=1)
361
+
362
+ similarities = []
363
+
364
+ # 分 batch 计算
365
+ for i in range(0, res_embeddings.size(0), batch_size):
366
+ batch = res_embeddings[i:i + batch_size] # (B, 256)
367
+
368
+ # (1, 256) @ (256, B) -> (1, B)
369
+ sim = torch.matmul(ms_embedding, batch.T) # 余弦相似度
370
+ similarities.append(sim.squeeze(0)) # (B,)
371
+
372
+ # 拼接成 (15511,)
373
+ similarities = torch.cat(similarities, dim=0)
374
+
375
+ top_k = min(top_k, res_embeddings.size(0))
376
+ # 取 top_k
377
+ topk_sim, topk_idx = torch.topk(similarities, k=top_k)
378
+
379
+ return topk_sim, topk_idx
380
+
381
+ def infer(self, ms, parent_mz, bn=50):
382
+
383
+ ms_embeddings = self.pred_model.predict(ms) # (1, 256)
384
+
385
+ res_embeddings, res_smiles = self.select_smiles(parent_mz, bn=bn)
386
+ if len(res_smiles) == 0:
387
+ return []
388
+
389
+ topk_sim, topk_idx = self.topk_similarity(ms_embeddings, res_embeddings)
390
+ topk_idx = topk_idx.to("cpu").numpy().tolist()
391
+
392
+ res_pred_name = []
393
+ for x, i in enumerate(topk_idx):
394
+ res_pred_name.append([res_smiles[i], topk_sim[x].item()])
395
+
396
+ return res_pred_name
397
+
398
+
399
+ model_file = ["model-tloss3.437-vloss2.907-epoch0.pth", "model-tloss2.495-vloss2.253-epoch1.pth",
400
+ "model-tloss1.987-vloss1.866-epoch2.pth", "model-tloss1.597-vloss1.573-epoch3.pth",
401
+ "model-tloss1.332-vloss1.384-epoch4.pth", "model-tloss1.088-vloss1.255-epoch5.pth",
402
+ "model-tloss0.899-vloss1.068-epoch6.pth",
403
+ "/root/代码/out_data/train-018/model-tloss0.76-vloss0.986-epoch0.pth",
404
+ "/root/代码/out_data/train-019/model-tloss0.608-vloss0.943-epoch0.pth",
405
+ "/root/代码/out_data/train-019/model-tloss0.577-vloss0.852-epoch1.pth",
406
+ "/root/代码/out_data/train-019/model-tloss0.503-vloss0.811-epoch2.pth",
407
+ '/root/代码/out_data/train-019/model-tloss0.448-vloss0.763-epoch3.pth',
408
+ '/root/代码/out_data/train-019/model-tloss0.405-vloss0.74-epoch4.pth',
409
+ '/root/代码/out_data/train-019/model-tloss0.367-vloss0.722-epoch5.pth',
410
+ '/root/代码/out_data/train-019/model-tloss0.337-vloss0.705-epoch6.pth',
411
+ '/root/代码/out_data/train-019/model-tloss0.317-vloss0.671-epoch7.pth'][-1]
412
+
413
+ infer_online = InferOnline(model_file)
414
+
415
+
416
+ if __name__ == '__main__':
417
+
418
+
419
+ # pred = Predictor('config.json', model_file)
420
+ #
421
+ # file_path = ["../../data/CASMI2016/data/pos", "../../data/CASMI2017/data/pos"][1]
422
+ # loss, loss_infonce, loss_mse, recalls_info = pred.predict(file_path)
423
+ #
424
+ # print("loss ...", loss)
425
+ # print("loss_infonce ...", loss_infonce)
426
+ # print("loss_mse ...", loss_mse)
427
+ # print("recalls_info ...", recalls_info)
428
+
429
+ ms = [[41.038587, 880600.0], [42.033833, 1973400.0], [43.041651, 2117400.0], [44.049388, 925150.0], [44.979347, 4397200.0], [51.022884, 593400.0], [53.038537, 9694400.0], [54.033783, 415000.0], [55.054152, 1911200.0], [56.049325, 4400500.0], [56.979301, 487200.0], [65.038474, 449400.0], [67.041567, 1667200.0], [67.054107, 786000.0], [68.049268, 6593250.0], [68.979253, 836000.0], [69.056975, 17628050.0], [69.069744, 290600.0], [70.06482, 1716900.0], [70.994926, 276400.0], [73.010627, 215600.0], [77.038437, 417800.0], [79.054112, 1319600.0], [80.049378, 3584000.0], [81.057194, 2957200.0], [82.064812, 25688800.0], [82.070396, 669000.0], [82.073249, 528650.0], [82.994909, 3564600.0], [83.072653, 7343000.0], [84.080502, 821400.0], [94.065026, 1006000.0], [95.049053, 230800.0], [96.080647, 13938800.0], [97.010531, 20776600.0], [97.013298, 339600.0], [98.989853, 367600.0], [110.096244, 1418800.0], [110.989833, 48727600.0], [110.991981, 1024000.0], [110.994248, 515600.0], [111.001067, 985400.0], [111.103933, 13806250.0], [112.111972, 17873400.0], [112.114998, 263400.0], [115.054168, 518400.0], [117.069717, 320200.0], [134.018401, 474400.0], [194.099834, 1533000.0], [194.993274, 21076400.0], [306.09803, 51809350.0], [306.181335, 516550.0]]
430
+ parent_mz = 306.181335
431
+ res_pred_name = infer_online.infer(ms, parent_mz)
432
+ print(res_pred_name)
433
+ print(len(res_pred_name))
infer_predict222.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- conding: utf-8 -*-
2
+ # @Time : 2025/12/14 10:58
3
+ # @Author : psi
4
+
5
+ from utils import *
6
+ from modules import *
7
+ import os, sys
8
+ import numpy as np
9
+ from tqdm import tqdm
10
+ import random
11
+ import torch
12
+ from torch import nn
13
+ from config import CFG
14
+ from dataset import *
15
+ import torch.utils.data
16
+ import copy, json, pickle
17
+ import itertools as it
18
+ import glob
19
+ import torch.nn.functional as F
20
+
21
+
22
+ def my_collate(batch):
23
+ batch = list(filter(lambda x: (x is not None), batch))
24
+ msbinl, molfpl, molfml, vl, al, msl = [], [], [], [], [], []
25
+ bat = {}
26
+ msbinl1, msbinl2 = [], []
27
+
28
+ for b in batch:
29
+ if 'ms_bins' in b:
30
+ msbinl.append(b['ms_bins'])
31
+ if 'ms_bins1' in b:
32
+ msbinl1.append(b['ms_bins1'])
33
+ if 'ms_bins2' in b:
34
+ msbinl2.append(b['ms_bins2'])
35
+ if 'mol_fps' in b:
36
+ molfpl.append(b['mol_fps'])
37
+ if 'mol_fmvec' in b:
38
+ molfml.append(b['mol_fmvec'])
39
+ if 'V' in b:
40
+ vl.append(b['V'])
41
+ if 'A' in b:
42
+ al.append(b['A'])
43
+ if 'mol_size' in b:
44
+ msl.append(b['mol_size'])
45
+
46
+ if msbinl:
47
+ bat['ms_bins'] = torch.stack(msbinl)
48
+ if msbinl1:
49
+ bat['ms_bins1'] = torch.stack(msbinl1)
50
+ if msbinl2:
51
+ bat['ms_bins2'] = torch.stack(msbinl2)
52
+ if molfpl:
53
+ bat['mol_fps'] = torch.stack(molfpl)
54
+ if molfml:
55
+ bat['mol_fmvec'] = torch.stack(molfml)
56
+ if vl and al and msl:
57
+ max_n = max(map(lambda x:x.shape[0], vl))
58
+ vl1, al1 = [], []
59
+ for v in vl:
60
+ vl1.append(pad_V(v, max_n))
61
+ for a in al:
62
+ al1.append(pad_A(a, max_n))
63
+
64
+ bat['V'] = torch.stack(vl1)
65
+ bat['A'] = torch.stack(al1)
66
+ bat['mol_size'] = torch.cat(msl, dim=0)
67
+
68
+ # return torch.utils.data.dataloader.default_collate(batch)
69
+ return bat
70
+
71
+
72
+ def build_loaders(inp, mode, cfg, num_workers):
73
+ if type(inp[0]) is dict:
74
+ dataset = Dataset(inp, cfg)
75
+ else:
76
+ dataset = PathDataset(inp, cfg)
77
+ dataloader = torch.utils.data.DataLoader(
78
+ dataset,
79
+ batch_size=len(dataset),
80
+ num_workers=num_workers,
81
+ shuffle=True if mode == "train" else False,
82
+ collate_fn=my_collate
83
+ )
84
+ return dataloader
85
+
86
+
87
+ class Predictor():
88
+
89
+ def __init__(self, file, model_file):
90
+ CFG.load(file)
91
+ cfg = CFG
92
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
93
+ self.cfg = cfg
94
+ model = FragSimiModelNew(cfg).to(cfg.device)
95
+ encmodel = torch.load(model_file)
96
+ # model.mol_gnn_encoder.load_state_dict(encmodel.mol_gnn_encoder.state_dict())
97
+ model.load_state_dict(encmodel['state_dict'])
98
+
99
+ self.model = model
100
+ self.model.eval()
101
+
102
+ def process_file(self, ms):
103
+ # d = json.load(open(file, 'r', encoding='utf-8'))
104
+ # ms = d['ms']
105
+ smi = 'Cc1cc(OCc2nc(C#N)c(NCc3ccc(F)cc3)o2)ccc1'
106
+ # out = {'ms': ms, 'smiles': smi}
107
+ # ms = self.data[idx]['ms']
108
+ # smi = self.data[idx]['smiles']
109
+ nls = []
110
+ item = calc_feats(smi, ms, nls, self.cfg)
111
+ return item
112
+
113
+ def process(self, data):
114
+ res = []
115
+ res.append(self.process_file(data))
116
+
117
+ batch = my_collate(res)
118
+
119
+ return batch
120
+
121
+ def get_eval_info(self, ms_embeddings, mol_embeddings, top_ks=(1, 3, 5, 10)):
122
+ N = ms_embeddings.shape[0]
123
+
124
+ # 1. L2 归一化(非常关键)
125
+ # ms_norm = F.normalize(ms_embeddings, dim=1)
126
+ # mol_norm = F.normalize(mol_embeddings, dim=1)
127
+ ms_norm = ms_embeddings
128
+ mol_norm = mol_embeddings
129
+
130
+ recalls = {k: 0 for k in top_ks}
131
+
132
+ # 2. 对每个样本做检索
133
+ for i in range(N):
134
+ query = ms_norm[i] # (256,)
135
+ sims = torch.matmul(mol_norm, query) # (N,)
136
+
137
+ ranked_indices = torch.argsort(sims, descending=True)
138
+
139
+ for k in top_ks:
140
+ if i in ranked_indices[:k]:
141
+ recalls[k] += 1
142
+
143
+ # 3. 取平均
144
+ for k in recalls:
145
+ recalls[k] /= N
146
+
147
+ return recalls
148
+
149
+ def predict(self, ms):
150
+ # data_files = []
151
+ # for root, _, files in os.walk(file_path):
152
+ # for f in files:
153
+ # if f.endswith(('.json', '.pkl', '.mgf')):
154
+ # data_files.append(os.path.join(root, f))
155
+ # data = sorted(
156
+ # data_files,
157
+ # key=lambda x: int(os.path.splitext(os.path.basename(x))[0])
158
+ # )
159
+ batch = self.process(ms)
160
+ for k, v in batch.items():
161
+ batch[k] = v.to(self.cfg.device)
162
+
163
+ with torch.no_grad():
164
+ loss, loss_infonce, loss_mse, ms_embeddings, mol_embeddings = self.model(batch, is_predict=True)
165
+
166
+ # recalls_info = self.get_eval_info(ms_embeddings, mol_embeddings)
167
+ # print(recalls_info)
168
+ #
169
+ # return loss, loss_infonce, loss_mse, recalls_info
170
+
171
+ return ms_embeddings
172
+
173
+ def process_file_1(self, ms, smi):
174
+ # d = json.load(open(file, 'r', encoding='utf-8'))
175
+ # ms = d['ms']
176
+ # smi = d['smiles']
177
+ # out = {'ms': ms, 'smiles': smi}
178
+ # ms = self.data[idx]['ms']
179
+ # smi = self.data[idx]['smiles']
180
+ nls = []
181
+ item = calc_feats(smi, ms, nls, self.cfg)
182
+ return item
183
+
184
+ def process_1(self, data):
185
+
186
+ res = []
187
+
188
+ for d in data:
189
+ try:
190
+ res.append([d['smiles'], self.process_file_1(d['ms'], d['smiles'])])
191
+ except Exception as e:
192
+ print(e)
193
+
194
+ if len(res) == 0:
195
+ return None
196
+
197
+ res1 = [x[1] for x in res]
198
+ res2 = [x[0] for x in res]
199
+
200
+ batch = my_collate(res1)
201
+
202
+ return batch, res2
203
+
204
+ def get_eval_info_1(self, ms_embeddings, mol_embeddings, top_ks=(1, 3, 5, 10)):
205
+ N = ms_embeddings.shape[0]
206
+
207
+ # 1. L2 归一化(非常关键)
208
+ # ms_norm = F.normalize(ms_embeddings, dim=1)
209
+ # mol_norm = F.normalize(mol_embeddings, dim=1)
210
+ ms_norm = ms_embeddings
211
+ mol_norm = mol_embeddings
212
+
213
+ recalls = {k: 0 for k in top_ks}
214
+
215
+ # 2. 对每个样本做检索
216
+ for i in range(N):
217
+ query = ms_norm[i] # (256,)
218
+ sims = torch.matmul(mol_norm, query) # (N,)
219
+
220
+ ranked_indices = torch.argsort(sims, descending=True)
221
+
222
+ for k in top_ks:
223
+ if i in ranked_indices[:k]:
224
+ recalls[k] += 1
225
+
226
+ # 3. 取平均
227
+ for k in recalls:
228
+ recalls[k] /= N
229
+
230
+ return recalls
231
+
232
+ def topk_similarity_1(self, ms_embedding, res_embeddings, batch_size=128, top_k=10):
233
+
234
+ ms_embedding = ms_embedding.to(self.device)
235
+ res_embeddings = res_embeddings.to(self.device)
236
+
237
+ # 保证是 float tensor
238
+ ms_embedding = ms_embedding.float()
239
+ res_embeddings = res_embeddings.float()
240
+
241
+ # 归一化(用于余弦相似度)
242
+ # ms_embedding = F.normalize(ms_embedding, dim=1)
243
+ # res_embeddings = F.normalize(res_embeddings, dim=1)
244
+
245
+ similarities = []
246
+
247
+ # 分 batch 计算
248
+ for i in range(0, res_embeddings.size(0), batch_size):
249
+ batch = res_embeddings[i:i + batch_size] # (B, 256)
250
+
251
+ # (1, 256) @ (256, B) -> (1, B)
252
+ sim = torch.matmul(ms_embedding, batch.T) # 余弦相似度
253
+ similarities.append(sim.squeeze(0)) # (B,)
254
+
255
+ # 拼接成 (15511,)
256
+ similarities = torch.cat(similarities, dim=0)
257
+
258
+ top_k = min(top_k, res_embeddings.size(0))
259
+ # 取 top_k
260
+ topk_sim, topk_idx = torch.topk(similarities, k=top_k)
261
+
262
+ return topk_sim, topk_idx
263
+
264
+ def predict_1(self, data):
265
+ # data_files = []
266
+ # for root, _, files in os.walk(file_path):
267
+ # for f in files:
268
+ # if f.endswith(('.json', '.pkl', '.mgf')):
269
+ # data_files.append(os.path.join(root, f))
270
+ # data = sorted(
271
+ # data_files,
272
+ # key=lambda x: int(os.path.splitext(os.path.basename(x))[0])
273
+ # )
274
+ batch, res_smiles = self.process_1(data)
275
+
276
+ if batch is None:
277
+ return None
278
+
279
+ for k, v in batch.items():
280
+ batch[k] = v.to(self.cfg.device)
281
+
282
+ loss, loss_infonce, loss_mse, ms_embeddings, mol_embeddings = self.model(batch, is_predict=True)
283
+
284
+ # recalls_info = self.get_eval_info(ms_embeddings, mol_embeddings)
285
+ # print(recalls_info)
286
+ #
287
+ # return loss, loss_infonce, loss_mse, recalls_info
288
+
289
+ ms_embedding = ms_embeddings[0:1, :]
290
+
291
+ topk_sim, topk_idx = self.topk_similarity_1(ms_embedding, mol_embeddings)
292
+ topk_idx = topk_idx.to("cpu").numpy().tolist()
293
+
294
+ res_pred_name = []
295
+ for x, i in enumerate(topk_idx):
296
+ res_pred_name.append([res_smiles[i], topk_sim[x].item()])
297
+
298
+ return res_pred_name
299
+
300
+
301
+ class InferOnline():
302
+ def __init__(self, model_file):
303
+ pred = Predictor('config.json', model_file)
304
+ self.pred_model = pred
305
+
306
+ model_name = model_file.split('/')[-1][:-4]
307
+ emb_file = f'/dev/shm/data/tongji_data/all_neg_pred_emb_{model_name}.pt'
308
+ file_path = '/dev/shm/data/tongji_data/all_neg.json'
309
+
310
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
311
+ self.emb_data= torch.load(emb_file)
312
+ print("self.emb_data shape ,,,", self.emb_data.shape)
313
+ self.all_data = json.load(open(file_path, 'r', encoding='utf-8'))
314
+ print("self.all_data shape ...", len(self.all_data))
315
+
316
+ pred_file = "/dev/shm/data/tongji_data/all_neg_pred.pt"
317
+ self.pred_name_data = [x[0] for x in torch.load(pred_file)]
318
+ self.pred_smiles_name_2_id = {x: i for i, x in enumerate(self.pred_name_data)}
319
+ print("self.pred_smiles_name_2_id shape ,,,", len(self.pred_smiles_name_2_id))
320
+
321
+ all_data_res3 = {}
322
+ for k, v in self.all_data['res3'].items():
323
+ v1 = [x for x in v if x in self.pred_name_data]
324
+ if len(v1) > 0:
325
+ all_data_res3[k] = v1
326
+ self.all_data['res3'] = all_data_res3
327
+
328
+ def select_smiles(self, parent_mz, bn=50):
329
+
330
+ res_smiles = []
331
+ for k, v in self.all_data['res3'].items():
332
+ k = float(k)
333
+ if k > parent_mz - bn and k < parent_mz + bn:
334
+ res_smiles += v
335
+
336
+ res_embeddings = []
337
+ for x in res_smiles:
338
+ i = self.pred_smiles_name_2_id[x]
339
+ res_embeddings.append(self.emb_data[i, :].unsqueeze(0))
340
+
341
+ res_embeddings = torch.cat(res_embeddings, dim=0)
342
+
343
+ return res_embeddings, res_smiles
344
+
345
+ def topk_similarity(self, ms_embedding, res_embeddings, batch_size=128, top_k=10):
346
+
347
+ ms_embedding = ms_embedding.to(self.device)
348
+ res_embeddings = res_embeddings.to(self.device)
349
+
350
+ # 保证是 float tensor
351
+ ms_embedding = ms_embedding.float()
352
+ res_embeddings = res_embeddings.float()
353
+
354
+ # 归一化(用于余弦相似度)
355
+ # ms_embedding = F.normalize(ms_embedding, dim=1)
356
+ # res_embeddings = F.normalize(res_embeddings, dim=1)
357
+
358
+ similarities = []
359
+
360
+ # 分 batch 计算
361
+ for i in range(0, res_embeddings.size(0), batch_size):
362
+ batch = res_embeddings[i:i + batch_size] # (B, 256)
363
+
364
+ # (1, 256) @ (256, B) -> (1, B)
365
+ sim = torch.matmul(ms_embedding, batch.T) # 余弦相似度
366
+ similarities.append(sim.squeeze(0)) # (B,)
367
+
368
+ # 拼接成 (15511,)
369
+ similarities = torch.cat(similarities, dim=0)
370
+
371
+ top_k = min(top_k, res_embeddings.size(0))
372
+ # 取 top_k
373
+ topk_sim, topk_idx = torch.topk(similarities, k=top_k)
374
+
375
+ return topk_sim, topk_idx
376
+
377
+ def infer(self, ms, parent_mz, bn=50):
378
+
379
+ ms_embeddings = self.pred_model.predict(ms) # (1, 256)
380
+
381
+ res_embeddings, res_smiles = self.select_smiles(parent_mz, bn=bn)
382
+
383
+ if len(res_smiles) == 0:
384
+ return []
385
+
386
+ topk_sim, topk_idx = self.topk_similarity(ms_embeddings, res_embeddings)
387
+ topk_idx = topk_idx.to("cpu").numpy().tolist()
388
+
389
+ res_pred_name = []
390
+ for x, i in enumerate(topk_idx):
391
+ res_pred_name.append([res_smiles[i], topk_sim[x].item()])
392
+
393
+ return res_pred_name
394
+
395
+
396
+ model_file = ["/root/代码/out_data/train-020/model-tloss3.239-vloss2.752-epoch0.pth",
397
+ "/root/代码/out_data/train-020/model-tloss2.487-vloss2.279-epoch1.pth",
398
+ "/root/代码/out_data/train-020/model-tloss2.086-vloss1.924-epoch2.pth",
399
+ "/root/代码/out_data/train-020/model-tloss1.716-vloss1.609-epoch3.pth",
400
+ "/root/代码/out_data/train-020/model-tloss1.414-vloss1.361-epoch4.pth",
401
+ '/root/代码/out_data/train-020/model-tloss1.177-vloss1.173-epoch5.pth',
402
+ "/root/代码/out_data/train-020/model-tloss0.99-vloss1.036-epoch6.pth",
403
+ '/root/代码/out_data/train-020/model-tloss0.849-vloss0.929-epoch7.pth',
404
+ '/root/代码/out_data/train-020/model-tloss0.736-vloss0.851-epoch8.pth',
405
+ '/root/代码/out_data/train-020/model-tloss0.647-vloss0.779-epoch9.pth',
406
+ '/root/代码/out_data/train-020/model-tloss0.575-vloss0.728-epoch10.pth'][-1]
407
+
408
+ infer_online = InferOnline(model_file)
409
+
410
+
411
+ if __name__ == '__main__':
412
+
413
+
414
+ # pred = Predictor('config.json', model_file)
415
+ #
416
+ # file_path = ["../../data/CASMI2016/data/pos", "../../data/CASMI2017/data/pos"][1]
417
+ # loss, loss_infonce, loss_mse, recalls_info = pred.predict(file_path)
418
+ #
419
+ # print("loss ...", loss)
420
+ # print("loss_infonce ...", loss_infonce)
421
+ # print("loss_mse ...", loss_mse)
422
+ # print("recalls_info ...", recalls_info)
423
+
424
+ ms = [[41.998214, 491000.0], [107.049799, 633000.0], [131.049708, 1969500.0], [134.040609, 827000.0], [145.052688, 300000.0], [161.051274, 270500.0], [309.102783, 2374000.0]]
425
+ parent_mz = 336.115379
426
+ res_pred_name = infer_online.infer(ms, parent_mz)
427
+ print(res_pred_name)
428
+ print(len(res_pred_name))
isospec.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from rdkit import Chem
3
+ # from IsoSpecPy import IsoSpec
4
+ import IsoSpecPy as iso
5
+
6
+
7
+ def generate_isotopic_pattern(mol_formula, charge=1):
8
+ """生成理论同位素模式"""
9
+ # 初始化IsoSpec计算器
10
+ # calculator = IsoSpec.IsoTotalProb(formula=mol_formula,
11
+ # charge=charge,
12
+ # absolute_accuracy=0.9)
13
+ calculator = iso.IsoTotalProb(formula=mol_formula,
14
+ charge=charge,
15
+ absolute_accuracy=0.9)
16
+
17
+ # 获取峰列表 (m/z, 强度)
18
+ peaks = calculator.get_peaks()
19
+
20
+ # 归一化强度
21
+ intensities = np.array([p[1] for p in peaks])
22
+ intensities /= np.max(intensities)
23
+
24
+ return [(p[0], intensities[i]) for i, p in enumerate(peaks)]
25
+
26
+
27
+ def compare_isotopic_patterns(exp_pattern, theory_pattern, tolerance=0.01):
28
+ """比较实验与理论同位素模式"""
29
+ score = 0.0
30
+ matched_peaks = 0
31
+
32
+ for exp_mz, exp_int in exp_pattern:
33
+ for theo_mz, theo_int in theory_pattern:
34
+ if abs(exp_mz - theo_mz) <= tolerance:
35
+ # 余弦相似度计算
36
+ score += exp_int * theo_int
37
+ matched_peaks += 1
38
+ break
39
+
40
+ # 归一化得分
41
+ if matched_peaks > 0:
42
+ score /= matched_peaks
43
+ return score
44
+
45
+
46
+ # 示例用法
47
+ if __name__ == "__main__":
48
+ # 实验数据 (示例值)
49
+ experimental_data = [
50
+ (151.063, 1.00), # 基峰
51
+ (152.066, 0.32),
52
+ (153.069, 0.05)
53
+ ]
54
+
55
+ # 候选分子式
56
+ candidate_formulas = ["C8H10N2O2", "C7H10N4O", "C9H10O3"]
57
+
58
+ best_formula = None
59
+ best_score = -1
60
+
61
+ for formula in candidate_formulas:
62
+ # 生成理论同位素模式
63
+ theoretical_pattern = generate_isotopic_pattern(formula, charge=1)
64
+
65
+ # 比较相似度
66
+ score = compare_isotopic_patterns(experimental_data, theoretical_pattern)
67
+
68
+ print(f"Formula: {formula} | Score: {score:.4f}")
69
+
70
+ if score > best_score:
71
+ best_score = score
72
+ best_formula = formula
73
+
74
+ print(f"\nBest match: {best_formula} (Score: {best_score:.4f})")
modules.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.nn.functional as F
4
+ from config import CFG
5
+ import utils
6
+ import math
7
+ import numpy as np
8
+ from cliplayers import QuickGELU, Transformer as MSTsfmEncoder
9
+ from GNN import layers as gly
10
+
11
+ loss_func_ms = nn.CrossEntropyLoss()
12
+ loss_func = nn.CrossEntropyLoss()
13
+
14
+
15
+ class MolGNNEncoder(nn.Module):
16
+ def __init__(self,
17
+ outdim,
18
+ n_feats=74, # 330, # 74+256 morgan 256
19
+ n_filters_list=[256, 256, 256],
20
+ n_head=4,
21
+ mols=1,
22
+ adj_chans=6,
23
+ readout_layers=2,
24
+ bias=True):
25
+
26
+ super().__init__()
27
+
28
+ n_filters_list = [i for i in n_filters_list if i is not None]
29
+ lys = []
30
+
31
+ for i, nf in enumerate(n_filters_list):
32
+ if i == 0:
33
+ nf1 = n_feats
34
+ else:
35
+ nf1 = prevnf
36
+
37
+ prevnf = nf
38
+
39
+ ly = gly.GConvBlockNoGF(nf1, nf, mols, adj_chans, bias)
40
+ lys.append(ly)
41
+
42
+ self.block_layers = nn.ModuleList(lys)
43
+ self.attention_layer = gly.MultiHeadGlobalAttention(nf, n_head=n_head, concat=True, bias=bias)
44
+ self.readout_layers = nn.ModuleList(
45
+ [nn.Linear(nf * n_head, outdim, bias=bias)] + [nn.Linear(outdim, outdim) for _ in
46
+ range(readout_layers - 1)])
47
+ self.gelu = QuickGELU()
48
+
49
+ def forward(self, batch):
50
+ V = batch['V']
51
+ A = batch['A']
52
+ mol_size = batch['mol_size']
53
+
54
+ for ly in self.block_layers:
55
+ V = ly(V, A)
56
+
57
+ X = self.attention_layer(V, mol_size)
58
+
59
+ for ly in self.readout_layers:
60
+ X = self.gelu(ly(X))
61
+
62
+ return X
63
+
64
+
65
+ class GATBlock(nn.Module):
66
+ """GAT 卷积块: GraphAttentionLayer + BatchNorm + ELU + 残差连接"""
67
+
68
+ def __init__(self, n_feats, n_filters, adj_chans=6, bias=True, dropout=0.1, alpha=0.2):
69
+ super().__init__()
70
+ self.gat_conv = gly.GraphAttentionLayer(n_feats, adj_chans, n_filters, bias, dropout, alpha)
71
+ self.bn = nn.BatchNorm1d(n_filters)
72
+ # 残差分支: 当输入输出维度不同时, 用线性投影对齐
73
+ self.residual = nn.Linear(n_feats, n_filters, bias=False) if n_feats != n_filters else nn.Identity()
74
+
75
+ def forward(self, V, A):
76
+ V_res = self.residual(V) # [b, N, F]
77
+ V_out = self.gat_conv(V, A) # [b, N, F]
78
+ V_out = self.bn(V_out.transpose(1, 2).contiguous()).transpose(1, 2)
79
+ V_out = F.elu(V_out + V_res) # 残差 + ELU
80
+ return V_out
81
+
82
+
83
+ class MolGATEncoder(nn.Module):
84
+ """
85
+ 分子 GAT 编码器 — 与 MolGNNEncoder 同构, 将 GCN 替换为 GAT.
86
+ 结构: GAT Block × N → MultiHead Global Attention → MLP Readout
87
+ """
88
+
89
+ def __init__(self,
90
+ outdim,
91
+ n_feats=74,
92
+ n_filters_list=[256, 256, 256],
93
+ n_head=4,
94
+ mols=1,
95
+ adj_chans=6,
96
+ readout_layers=2,
97
+ dropout=0.1,
98
+ bias=True):
99
+
100
+ super().__init__()
101
+
102
+ n_filters_list = [i for i in n_filters_list if i is not None]
103
+ lys = []
104
+
105
+ for i, nf in enumerate(n_filters_list):
106
+ if i == 0:
107
+ nf1 = n_feats
108
+ else:
109
+ nf1 = prevnf
110
+
111
+ prevnf = nf
112
+
113
+ ly = GATBlock(nf1, nf, adj_chans, bias, dropout)
114
+ lys.append(ly)
115
+
116
+ self.block_layers = nn.ModuleList(lys)
117
+ self.attention_layer = gly.MultiHeadGlobalAttention(nf, n_head=n_head, concat=True, bias=bias)
118
+ self.readout_layers = nn.ModuleList(
119
+ [nn.Linear(nf * n_head, outdim, bias=bias)] +
120
+ [nn.Linear(outdim, outdim, bias=bias) for _ in range(readout_layers - 1)]
121
+ )
122
+ self.gelu = QuickGELU()
123
+ self.dropout = nn.Dropout(dropout)
124
+
125
+ def forward(self, batch):
126
+ V = batch['V']
127
+ A = batch['A']
128
+ mol_size = batch['mol_size']
129
+
130
+ for ly in self.block_layers:
131
+ V = ly(V, A)
132
+
133
+ X = self.attention_layer(V, mol_size)
134
+
135
+ for ly in self.readout_layers:
136
+ X = self.dropout(self.gelu(ly(X)))
137
+
138
+ return X
139
+
140
+
141
+ class ProjectionHead(nn.Module):
142
+ def __init__(self,
143
+ embedding_dim,
144
+ projection_dim,
145
+ cfg,
146
+ transformer=True,
147
+ lstm=False):
148
+
149
+ super().__init__()
150
+
151
+ self.projection = nn.Linear(embedding_dim, projection_dim)
152
+ self.gelu = nn.GELU() # QuickGELU()
153
+ self.transformer = None
154
+ if transformer:
155
+ self.transformer = MSTsfmEncoder(projection_dim, cfg.tsfm_layers, cfg.tsfm_heads)
156
+ self.lstm = None
157
+ if lstm:
158
+ self.lstm = nn.LSTM(input_size=projection_dim, hidden_size=projection_dim, num_layers=cfg.lstm_layers,
159
+ batch_first=True)
160
+ self.dropout = nn.Dropout(cfg.dropout)
161
+
162
+ def forward(self, x):
163
+ projected = self.projection(x)
164
+ if self.transformer is None:
165
+ x = self.gelu(projected)
166
+ else:
167
+ x = self.transformer(projected)
168
+ if not self.lstm is None:
169
+ x, (_, _) = self.lstm(x)
170
+ x = self.dropout(x)
171
+
172
+ return x
173
+
174
+
175
+ # New name in paper is CMSSPModel
176
+ class FragSimiModel(nn.Module):
177
+ def __init__(
178
+ self,
179
+ cfg
180
+ ):
181
+ super().__init__()
182
+
183
+ self.cfg = cfg
184
+ self.mol_gnn_encoder = None
185
+ mol_embedding_dim = cfg.mol_embedding_dim
186
+
187
+ if 'gnn' in self.cfg.mol_encoder:
188
+ self.mol_gnn_encoder = MolGNNEncoder(outdim=cfg.mol_embedding_dim,
189
+ n_filters_list=cfg.molgnn_n_filters_list,
190
+ n_head=cfg.molgnn_nhead,
191
+ readout_layers=cfg.molgnn_readout_layers)
192
+ if 'fp' in self.cfg.mol_encoder:
193
+ mol_embedding_dim = 2 * cfg.mol_embedding_dim
194
+
195
+ if 'fm' in self.cfg.mol_encoder:
196
+ mol_embedding_dim += 10
197
+
198
+ self.ms_projection = ProjectionHead(cfg.ms_embedding_dim,
199
+ cfg.projection_dim,
200
+ cfg,
201
+ cfg.tsfm_in_ms,
202
+ cfg.lstm_in_ms)
203
+
204
+ self.mol_projection = ProjectionHead(mol_embedding_dim,
205
+ cfg.projection_dim,
206
+ cfg,
207
+ cfg.tsfm_in_mol,
208
+ cfg.lstm_in_mol)
209
+
210
+ def forward(self, batch):
211
+ ms_features = batch["ms_bins"]
212
+ mol_feat_list = []
213
+ if 'gnn' in self.cfg.mol_encoder:
214
+ mol_feat_list.append(self.mol_gnn_encoder(batch))
215
+ if 'fp' in self.cfg.mol_encoder:
216
+ mol_feat_list.append(batch["mol_fps"])
217
+ if 'fm' in self.cfg.mol_encoder:
218
+ mol_feat_list.append(batch["mol_fmvec"])
219
+
220
+ if len(mol_feat_list) > 1:
221
+ mol_features = torch.cat(mol_feat_list, dim=1)
222
+ else:
223
+ mol_features = mol_feat_list[0]
224
+
225
+ # Getting ms and mol Embeddings (with same dimension)
226
+ ms_embeddings = self.ms_projection(ms_features)
227
+ mol_embeddings = self.mol_projection(mol_features)
228
+
229
+ # Calculating the Loss
230
+ # logits = (mol_embeddings @ ms_embeddings.t())
231
+ # logit_scale = self.logit_scale.exp()
232
+ logits = mol_embeddings @ ms_embeddings.t()
233
+
234
+ ground_truth = torch.arange(ms_features.shape[0], dtype=torch.long, device=self.cfg.device)
235
+
236
+ ms_loss = loss_func(logits, ground_truth)
237
+ mol_loss = loss_func(logits.t(), ground_truth)
238
+ loss = (ms_loss + mol_loss) / 2.0 # shape: (batch_size)
239
+
240
+ return loss.mean()
241
+
242
+
243
+ # --- 1. Sinusoidal Embedding (对应图中 MS分支的 "正弦m/z嵌入") ---
244
+ class SinusoidalPositionEmbeddings(nn.Module):
245
+ def __init__(self, dim):
246
+ super().__init__()
247
+ self.dim = dim
248
+
249
+ def forward(self, time):
250
+ device = time.device
251
+ half_dim = self.dim // 2
252
+ embeddings = math.log(10000) / (half_dim - 1)
253
+ embeddings = torch.exp(torch.arange(half_dim, device=device) * -embeddings)
254
+ embeddings = time[:, None] * embeddings[None, :]
255
+ embeddings = torch.cat((embeddings.sin(), embeddings.cos()), dim=-1)
256
+ return embeddings
257
+
258
+
259
+ # --- 2. Tanimoto Similarity Calculation (对应图中 "结构MSE损失") ---
260
+ def batch_tanimoto_sim(x1, x2):
261
+ '''
262
+ 计算两个batch指纹之间的Tanimoto相似度矩阵
263
+ x1, x2: shape (batch_size, fp_dim), assuming binary (0/1) floats
264
+ '''
265
+ # Tanimoto coefficient = (A . B) / (|A|^2 + |B|^2 - A . B)
266
+ dot_prod = torch.matmul(x1, x2.t())
267
+ x1_sum = torch.sum(x1 ** 2, dim=1).view(-1, 1)
268
+ x2_sum = torch.sum(x2 ** 2, dim=1).view(1, -1)
269
+
270
+ denominator = x1_sum + x2_sum - dot_prod
271
+ # Avoid division by zero
272
+ return dot_prod / (denominator + 1e-8)
273
+
274
+
275
+ # --- 3. Hybrid Loss Function (对应图中 "联合损失函数") ---
276
+ class HybridAlignLoss(nn.Module):
277
+ def __init__(self, alpha=0.5, beta=1.0, temperature=0.07):
278
+ super().__init__()
279
+ self.alpha = alpha # Tanimoto MSE 的权重
280
+ self.beta = beta # InfoNCE 的权重
281
+ self.temp = temperature
282
+ self.cross_entropy = nn.CrossEntropyLoss()
283
+ self.mse_loss = nn.MSELoss()
284
+
285
+ def forward(self, ms_emb, mol_emb, mol_fps):
286
+ """
287
+ ms_emb: (batch, dim) normalized
288
+ mol_emb: (batch, dim) normalized
289
+ mol_fps: (batch, fp_dim) 原始指纹,用于计算Ground Truth相似度
290
+ """
291
+ # 1. InfoNCE Loss (Contrastive)
292
+ logits = (ms_emb @ mol_emb.t()) / self.temp
293
+ labels = torch.arange(ms_emb.shape[0], device=ms_emb.device)
294
+ loss_i2t = self.cross_entropy(logits, labels)
295
+ loss_t2i = self.cross_entropy(logits.t(), labels)
296
+ loss_infonce = (loss_i2t + loss_t2i) / 2
297
+
298
+ # 2. Tanimoto MSE Loss (Structure Constraint)
299
+ # 预测的相似度矩阵 (Cosine Similarity of Embeddings)
300
+ # 因为 embedding 已经 normalize 过了,所以 dot product 就是 cosine sim
301
+ pred_sim_matrix = ms_emb @ mol_emb.t()
302
+
303
+ # 真实的结构相似度矩阵 (Ground Truth)
304
+ with torch.no_grad():
305
+ target_sim_matrix = batch_tanimoto_sim(mol_fps, mol_fps)
306
+
307
+ loss_mse = self.mse_loss(pred_sim_matrix, target_sim_matrix)
308
+
309
+ # 3. Total Loss
310
+ total_loss = self.beta * loss_infonce + self.alpha * loss_mse
311
+
312
+ return total_loss, loss_infonce, loss_mse
313
+
314
+
315
+ class MolFusionHead(nn.Module):
316
+ def __init__(self, gnn_out_dim, fp_dim=1024, projection_dim=256, dropout=0.1):
317
+ super().__init__()
318
+
319
+ # 对应图中的流程:
320
+ # Graph特征 -> 128维
321
+ self.gnn_proj = nn.Linear(gnn_out_dim, 128)
322
+
323
+ # Morgan指纹 -> 256维 (图示 Morgan编码)
324
+ self.fp_proj = nn.Sequential(
325
+ nn.Linear(fp_dim, 256),
326
+ nn.LayerNorm(256),
327
+ nn.GELU()
328
+ )
329
+
330
+ # 融合与压缩: 128 + 256 -> 256
331
+ self.fusion_layer = nn.Sequential(
332
+ nn.Linear(128 + 256, 256),
333
+ nn.LayerNorm(256),
334
+ nn.Dropout(dropout),
335
+ nn.GELU()
336
+ )
337
+
338
+ def forward(self, gnn_feat, fps):
339
+ # gnn_feat: 来自 GAT/GNN 的输出
340
+ # fps: Morgan fingerprints
341
+
342
+ x_graph = self.gnn_proj(gnn_feat) # -> 128
343
+ x_fp = self.fp_proj(fps) # -> 256
344
+
345
+ # 拼接 (Concatenation)
346
+ x_cat = torch.cat([x_graph, x_fp], dim=1)
347
+
348
+ # 融合压缩
349
+ out = self.fusion_layer(x_cat)
350
+ return out
351
+
352
+
353
+ class SinusoidalMzEmbedding(nn.Module):
354
+ def __init__(self, dim=256, max_mz=2000):
355
+ super().__init__()
356
+ self.dim = dim
357
+ self.max_mz = max_mz
358
+ # 预计算分母项,参考 Transformer Positional Encoding
359
+ div_term = torch.exp(torch.arange(0, dim, 2).float() * (-math.log(10000.0) / dim))
360
+ self.register_buffer('div_term', div_term)
361
+
362
+ def forward(self, mz_values):
363
+ """
364
+ mz_values: (Batch, Seq_Len) or (Seq_Len,)
365
+ Returns: (..., 256)
366
+ """
367
+ # 将 m/z 视为位置信息
368
+ pe = torch.zeros(*mz_values.shape, self.dim, device=mz_values.device)
369
+ position = mz_values.unsqueeze(-1) # (..., 1)
370
+
371
+ # sin/cos 编码
372
+ pe[..., 0::2] = torch.sin(position * self.div_term)
373
+ pe[..., 1::2] = torch.cos(position * self.div_term)
374
+ return pe
375
+
376
+
377
+ class FragSimiModelNew(nn.Module):
378
+ def __init__(self, cfg):
379
+ super().__init__()
380
+ self.cfg = cfg
381
+ self.experiment_name_type = cfg.experiment_name_type
382
+ # --- LEFT BRANCH: MOLECULE ---
383
+ # 1. GNN Encoder (对应图中 "分子图构建" -> "GAT")
384
+ # 假设 GNN 输出维度由 cfg.mol_embedding_dim 定义
385
+ if 'gnn' in self.cfg.mol_encoder:
386
+ self.mol_gnn_encoder = MolGNNEncoder(
387
+ outdim=cfg.mol_embedding_dim,
388
+ n_filters_list=cfg.molgnn_n_filters_list,
389
+ n_head=cfg.molgnn_nhead,
390
+ readout_layers=cfg.molgnn_readout_layers
391
+ )
392
+
393
+ self.mol_gat_encoder = MolGATEncoder(
394
+ outdim=cfg.mol_embedding_dim,
395
+ n_filters_list=cfg.molgnn_n_filters_list,
396
+ n_head=cfg.molgnn_nhead,
397
+ readout_layers=cfg.molgnn_readout_layers
398
+ )
399
+
400
+ # 2. Fusion Layer (对应图中 "图池化与特征融合")
401
+ # 假设 Morgan FP 输入是 2048 或 1024,需在 cfg 中定义
402
+ fp_input_dim = getattr(cfg, 'fp_dim', 2048)
403
+ self.mol_fusion = MolFusionHead(
404
+ gnn_out_dim=cfg.mol_embedding_dim,
405
+ fp_dim=fp_input_dim,
406
+ projection_dim=256 # 图片指定的最终对齐维度
407
+ )
408
+
409
+ # --- RIGHT BRANCH: MS SPECTRA ---
410
+ # 对应图中 "6层 Transformer 编码器" + "ESA"
411
+ # 这里的 Transformer 改为处理 embedding 后的序列
412
+ ms_dim = 256
413
+ self.ms_input_proj = nn.Linear(cfg.ms_embedding_dim, ms_dim)
414
+ self.ms_transformer = MSTsfmEncoder(
415
+ width=ms_dim, # 图片暗示中间维度
416
+ layers=6, # 图片明确提到 "6层Transformer"
417
+ heads=8
418
+ )
419
+
420
+ self.ms_input_proj3 = nn.Linear(cfg.ms_feature3_embedding_dim, ms_dim)
421
+ self.ms_transformer3 = MSTsfmEncoder(
422
+ width=ms_dim, # 图片暗示中间维度
423
+ layers=6, # 图片明确提到 "6层Transformer"
424
+ heads=8
425
+ )
426
+
427
+ # 正弦位置编码 (如果输入是 peaks 序列而非 bins,这里很有用)
428
+ # 假设 ms_bins 已经是处理好的特征,这里加一层 Embedding 增强
429
+ self.ms_pos_embed = SinusoidalPositionEmbeddings(256)
430
+
431
+ # 正弦编码层
432
+ self.mz_embedder = SinusoidalMzEmbedding(dim=256)
433
+
434
+ # 将其他 29 维特征映射到 256 维,以便与 m/z 嵌入相加
435
+ self.feature_proj = nn.Linear(29, 256)
436
+
437
+ # Transformer (图片中的 6层 Transformer)
438
+ # self.transformer = nn.TransformerEncoder(
439
+ # nn.TransformerEncoderLayer(d_model=256, nhead=8, dim_feedforward=1024),
440
+ # num_layers=6
441
+ # )
442
+ self.transformer = MSTsfmEncoder(
443
+ width=256, # 图片暗示中间维度
444
+ layers=6, # 图片明确提到 "6层Transformer"
445
+ heads=8
446
+ )
447
+
448
+ # 最后的均值池化与维度压缩 (256维)
449
+ self.final_proj = nn.Sequential(
450
+ nn.Linear(256, 256),
451
+ nn.LayerNorm(256),
452
+ nn.Dropout(cfg.dropout)
453
+ )
454
+
455
+ # MS 最终压缩层 (284 -> 256, 简化为 Linear)
456
+ self.ms_final_proj = nn.Sequential(
457
+ nn.Linear(256, 256),
458
+ nn.LayerNorm(256),
459
+ nn.Dropout(cfg.dropout)
460
+ )
461
+
462
+ self.ms_final_proj3 = nn.Sequential(
463
+ nn.Linear(256, 256),
464
+ nn.LayerNorm(256),
465
+ nn.Dropout(cfg.dropout)
466
+ )
467
+
468
+ # all 最后的均值池化与维度压缩 (256维)
469
+ self.all_final_proj1 = nn.Sequential(
470
+ nn.Linear(256, 256),
471
+ nn.LayerNorm(256),
472
+ nn.Dropout(cfg.dropout)
473
+ )
474
+
475
+ self.all_final_proj = nn.Sequential(
476
+ nn.Linear(512, 256),
477
+ nn.LayerNorm(256),
478
+ nn.Dropout(cfg.dropout)
479
+ )
480
+
481
+ self.all_final_proj3 = nn.Sequential(
482
+ nn.Linear(256 * 3, 256),
483
+ nn.LayerNorm(256),
484
+ nn.Dropout(cfg.dropout)
485
+ )
486
+
487
+ # --- LOSS ---
488
+ # 引入 Tanimoto MSE 联合损失
489
+ alpha = self.cfg.alpha
490
+ beta = self.cfg.beta
491
+ self.loss_fn = HybridAlignLoss(alpha=alpha, beta=beta)
492
+
493
+ # Logit scale (Temperature parameter for CLIP loss)
494
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
495
+
496
+ def forward(self, batch, is_predict=False):
497
+ # ---------------------------
498
+ # 1. Molecule Branch Forward
499
+ # ---------------------------
500
+ if "gcn" in self.experiment_name_type:
501
+ mol_gnn_feat = self.mol_gnn_encoder(batch) # GNN 特征
502
+ elif 'gat' in self.experiment_name_type:
503
+ mol_gnn_feat = self.mol_gat_encoder(batch)
504
+
505
+ mol_fps = batch["mol_fps"] # Morgan 指纹 (Ground Truth)
506
+
507
+ # 融合 GNN 和 FP 特征 -> 256 dim
508
+ mol_embeddings = self.mol_fusion(mol_gnn_feat, mol_fps)
509
+
510
+ # ---------------------------
511
+ # 2. MS Branch Forward
512
+ # ---------------------------
513
+ ms_features = batch["ms_bins"]
514
+
515
+ # 投影到 Transformer 维度
516
+ x_ms = self.ms_input_proj(ms_features) # (Batch, 256) or (Batch, Seq, 256)
517
+
518
+ # 如果是序列数据,添加位置编码
519
+ if len(x_ms.shape) == 3:
520
+ pos_emb = self.ms_pos_embed(torch.arange(x_ms.shape[1], device=x_ms.device))
521
+ x_ms = x_ms + pos_emb
522
+ else:
523
+ # 如果输入已经是 pooled vector,这就作为简单的特征变换
524
+ x_ms = x_ms.unsqueeze(1) # Fake sequence for transformer if needed
525
+
526
+ x_ms = self.ms_transformer(x_ms) # (16, 1, 256)
527
+
528
+ # 如果 Transformer 输出是序列,取 Mean Pooling 或 CLS token
529
+ if len(x_ms.shape) == 3:
530
+ x_ms = x_ms.mean(dim=1) # Average Pooling (对应图中 "均值池化")
531
+
532
+ ms_embeddings = self.ms_final_proj(x_ms)
533
+
534
+ if 'ms3' in self.experiment_name_type:
535
+ ##### ms_bins3
536
+ if 'ms_bins3' in batch:
537
+ ms_features3 = batch["ms_bins3"].to(self.ms_input_proj3.weight.dtype)
538
+ x_ms3 = self.ms_input_proj3(ms_features3)
539
+ x_ms3 = self.ms_transformer3(x_ms3) # (16, 1, 256)
540
+
541
+ # 如果 Transformer 输出是序列,取 Mean Pooling 或 CLS token
542
+ if len(x_ms3.shape) == 3:
543
+ x_ms3 = x_ms3.mean(dim=1) # Average Pooling (对应图中 "均值池化")
544
+
545
+ ms_embeddings3 = self.ms_final_proj3(x_ms3)
546
+
547
+ if 'ms1' in self.experiment_name_type:
548
+ ######
549
+ ms_features, ms_mz = batch["ms_bins1"], batch["ms_bins2"]
550
+ # 1. 计算 m/z 嵌入 (Batch, 100, 256)
551
+ mz_emb = self.mz_embedder(ms_mz)
552
+
553
+ # 2. 投影其他特征 (Batch, 100, 29) -> (Batch, 100, 256)
554
+ feat_emb = self.feature_proj(ms_features)
555
+
556
+ # 3. 融合 (相加) - 对应图中 "+额外输入" 和特征初始化
557
+ x = mz_emb + feat_emb
558
+
559
+ # 4. Transformer 编码
560
+ # Permute for Transformer (Seq, Batch, Dim)
561
+ # x = x.permute(1, 0, 2)
562
+ x = self.transformer(x)
563
+ # x = x.permute(1, 0, 2) # (Batch, Seq, Dim)
564
+
565
+ # 5. 均值池化 (Mean Pooling)
566
+ # 可以在 mask 掉 padding 的位置进行 mean,这里简化处理
567
+ x = x.mean(dim=1)
568
+
569
+ # 6. 最终输出
570
+ out = self.final_proj(x)
571
+
572
+ if 'ms3' in self.experiment_name_type and 'ms1' in self.experiment_name_type:
573
+ out1 = torch.cat([ms_embeddings, ms_embeddings3, out], dim=-1)
574
+ ms_embeddings = self.all_final_proj3(out1)
575
+
576
+ elif 'ms3' in self.experiment_name_type:
577
+ out1 = torch.cat([ms_embeddings, ms_embeddings3], dim=-1)
578
+ ms_embeddings = self.all_final_proj(out1)
579
+ elif 'ms1' in self.experiment_name_type:
580
+ out1 = torch.cat([ms_embeddings, out], dim=-1)
581
+ ms_embeddings = self.all_final_proj(out1)
582
+ else:
583
+ ms_embeddings = self.all_final_proj1(ms_embeddings)
584
+
585
+ # if 'ms_bins3' in batch:
586
+ # out1 = torch.cat([ms_embeddings, ms_embeddings3, out], dim=-1)
587
+ # ms_embeddings = self.all_final_proj3(out1)
588
+ #
589
+ # else:
590
+ # out1 = torch.cat([ms_embeddings, out], dim=-1)
591
+ # ms_embeddings = self.all_final_proj(out1)
592
+
593
+ # ---------------------------
594
+ # 3. Normalization & Loss
595
+ # ---------------------------
596
+ # Normalize embeddings for Cosine Similarity
597
+ ms_embeddings = F.normalize(ms_embeddings, dim=-1, p=2)
598
+ mol_embeddings = F.normalize(mol_embeddings, dim=-1, p=2)
599
+
600
+ # Return loss directly during training
601
+ loss, loss_infonce, loss_mse = self.loss_fn(ms_embeddings, mol_embeddings, mol_fps)
602
+
603
+ if 'loss' not in self.experiment_name_type:
604
+ loss = loss_infonce
605
+
606
+ if is_predict:
607
+ if 'loss' not in self.experiment_name_type:
608
+ loss = loss_infonce
609
+
610
+ return loss, loss_infonce, loss_mse, ms_embeddings, mol_embeddings
611
+
612
+ return loss
train.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utils import *
2
+ from modules import *
3
+ import os, sys
4
+ import numpy as np
5
+ from tqdm import tqdm
6
+ import random
7
+ import torch
8
+ from torch import nn
9
+ from config import CFG
10
+ from dataset import *
11
+ import torch.utils.data
12
+ import copy, json, pickle
13
+ import itertools as it
14
+
15
+
16
+ def make_next_record_dir(basedir, prefix=''):
17
+ path = '%s/%%s001/' % basedir
18
+ n = 2
19
+ while os.path.exists(path % prefix):
20
+ path = '%s/%%s%.3d/' % (basedir, n)
21
+ n += 1
22
+
23
+ pth = path % prefix
24
+ os.makedirs(pth)
25
+ return pth
26
+
27
+
28
+ def setup_seed(seed):
29
+ torch.manual_seed(seed)
30
+ torch.cuda.manual_seed(seed)
31
+ np.random.seed(seed)
32
+ random.seed(seed)
33
+ torch.backends.cudnn.deterministic = True
34
+
35
+
36
+ def my_collate(batch):
37
+ batch = list(filter(lambda x: (x is not None), batch))
38
+ msbinl, molfpl, molfml, vl, al, msl = [], [], [], [], [], []
39
+ bat = {}
40
+ msbinl1, msbinl2, msbinl3 = [], [], []
41
+
42
+ for b in batch:
43
+ if 'ms_bins' in b:
44
+ msbinl.append(b['ms_bins'])
45
+ if 'ms_bins1' in b:
46
+ msbinl1.append(b['ms_bins1'])
47
+ if 'ms_bins2' in b:
48
+ msbinl2.append(b['ms_bins2'])
49
+ if 'ms_bins3' in b and b['ms_bins3'] is not None:
50
+ msbinl3.append(b['ms_bins3'])
51
+ if 'mol_fps' in b:
52
+ molfpl.append(b['mol_fps'])
53
+ if 'mol_fmvec' in b:
54
+ molfml.append(b['mol_fmvec'])
55
+ if 'V' in b:
56
+ vl.append(b['V'])
57
+ if 'A' in b:
58
+ al.append(b['A'])
59
+ if 'mol_size' in b:
60
+ msl.append(b['mol_size'])
61
+
62
+ if msbinl:
63
+ bat['ms_bins'] = torch.stack(msbinl)
64
+ if msbinl1:
65
+ bat['ms_bins1'] = torch.stack(msbinl1)
66
+ if msbinl2:
67
+ bat['ms_bins2'] = torch.stack(msbinl2)
68
+ if msbinl3:
69
+ bat['ms_bins3'] = torch.stack(msbinl3)
70
+ if molfpl:
71
+ bat['mol_fps'] = torch.stack(molfpl)
72
+ if molfml:
73
+ bat['mol_fmvec'] = torch.stack(molfml)
74
+ if vl and al and msl:
75
+ max_n = max(map(lambda x: x.shape[0], vl))
76
+ vl1, al1 = [], []
77
+ for v in vl:
78
+ vl1.append(pad_V(v, max_n))
79
+ for a in al:
80
+ al1.append(pad_A(a, max_n))
81
+
82
+ bat['V'] = torch.stack(vl1)
83
+ bat['A'] = torch.stack(al1)
84
+ bat['mol_size'] = torch.cat(msl, dim=0)
85
+
86
+ # return torch.utils.data.dataloader.default_collate(batch)
87
+ return bat
88
+
89
+
90
+ def make_train_valid(data, valid_ratio, seed=1234):
91
+ idxs = np.arange(len(data))
92
+ np.random.seed(seed)
93
+ np.random.shuffle(idxs)
94
+
95
+ lenval = int(valid_ratio * len(data))
96
+
97
+ valid_set = [data[i] for i in idxs[:lenval]]
98
+ train_set = [data[i] for i in idxs[lenval:]]
99
+
100
+ return train_set, valid_set
101
+
102
+
103
+ def build_loaders(inp, mode, cfg, num_workers):
104
+ if type(inp[0]) is dict:
105
+ dataset = Dataset(inp, cfg)
106
+ else:
107
+ dataset = PathDataset(inp, cfg)
108
+ dataloader = torch.utils.data.DataLoader(
109
+ dataset,
110
+ batch_size=cfg.batch_size,
111
+ num_workers=num_workers,
112
+ shuffle=True if mode == "train" else False,
113
+ collate_fn=my_collate
114
+ )
115
+ return dataloader
116
+
117
+
118
+ def train_epoch(model, train_loader, optimizer, lr_scheduler, step):
119
+ loss_meter = AvgMeter()
120
+ tqdm_object = tqdm(train_loader, total=len(train_loader))
121
+
122
+ for batch in tqdm_object:
123
+ for k, v in batch.items():
124
+ batch[k] = v.to(CFG.device)
125
+
126
+ loss = model(batch)
127
+ optimizer.zero_grad()
128
+ loss.backward()
129
+ optimizer.step()
130
+ if step == "batch":
131
+ lr_scheduler.step()
132
+
133
+ count = batch["ms_bins"].size(0)
134
+ loss_meter.update(loss.item(), count)
135
+
136
+ tqdm_object.set_postfix(train_loss=loss_meter.avg, lr=get_lr(optimizer))
137
+ return loss_meter
138
+
139
+
140
+ def valid_epoch(model, valid_loader):
141
+ loss_meter = AvgMeter()
142
+
143
+ tqdm_object = tqdm(valid_loader, total=len(valid_loader))
144
+ for batch in tqdm_object:
145
+ for k, v in batch.items():
146
+ batch[k] = v.to(CFG.device)
147
+
148
+ loss = model(batch)
149
+
150
+ count = batch["ms_bins"].size(0)
151
+ loss_meter.update(loss.item(), count)
152
+
153
+ tqdm_object.set_postfix(valid_loss=loss_meter.avg)
154
+
155
+ return loss_meter
156
+
157
+
158
+ def main(data, cfg=CFG, savedir='data/train', encmodel=None, ratio=1):
159
+ setup_seed(cfg.seed)
160
+
161
+ train_data_file = cfg.train_data_file
162
+ valid_data_file = cfg.valid_data_file
163
+
164
+ if train_data_file.endswith('.pt'):
165
+ train_set = torch.load(train_data_file)
166
+ elif train_data_file.endswith('.json'):
167
+ train_set = json.load(open(train_data_file, 'r', encoding='utf-8'))
168
+
169
+ if valid_data_file.endswith('.pt'):
170
+ valid_set = torch.load(valid_data_file)
171
+ elif valid_data_file.endswith('.json'):
172
+ valid_set = json.load(open(valid_data_file, 'r', encoding='utf-8'))
173
+
174
+ if os.path.isdir(train_data_file):
175
+ train_set = []
176
+ for i in tqdm(range(cfg.train_number_data), desc='load train ...'):
177
+ tmp_file = train_data_file + str(i) + ".pt"
178
+ if os.path.exists(tmp_file):
179
+ # tmp_d = torch.load(tmp_file)
180
+ # train_set.append(tmp_d)
181
+ train_set.append(tmp_file)
182
+
183
+ print("len train data ...", len(train_set))
184
+ print("len valid_set data ...", len(valid_set))
185
+
186
+ # train_data_file = "data/train_data.json"
187
+ # valid_data_file = "data/valid_data.json"
188
+ #
189
+ # if os.path.exists(train_data_file):
190
+ # train_set = json.load(open(train_data_file, 'r', encoding='utf-8'))
191
+ # valid_set = json.load(open(valid_data_file, 'r', encoding='utf-8'))
192
+ # else:
193
+ # train_set, valid_set = make_train_valid(data, valid_ratio=cfg.valid_ratio, seed=cfg.seed)
194
+ #
195
+ # json.dump(train_set, open(train_data_file, 'w', encoding='utf-8'))
196
+ # json.dump(valid_set, open(valid_data_file, 'w', encoding='utf-8'))
197
+ #
198
+ # n = len(train_set)
199
+ # if ratio < 1:
200
+ # train_set = random.sample(train_set, int(n*ratio))
201
+ # print(f'Ratio {ratio}, lenall {n}, newtrainset {len(train_set)}')
202
+
203
+ train_loader = build_loaders(train_set, "train", cfg, 10)
204
+ valid_loader = build_loaders(valid_set, "valid", cfg, 10)
205
+
206
+ step = "epoch"
207
+
208
+ best_loss = float('inf')
209
+ best_model_fn = ''
210
+ best_model_fns = []
211
+
212
+ # model = FragSimiModel(cfg).to(cfg.device)
213
+ model = FragSimiModelNew(cfg).to(cfg.device)
214
+
215
+ if not encmodel is None:
216
+ model.mol_gnn_encoder.load_state_dict(encmodel.mol_gnn_encoder.state_dict())
217
+ # fraze mol_gnn_encoder weights
218
+ '''for name, param in model.named_parameters():
219
+ if 'mol_gnn_encoder' in name:
220
+ print(152, 'fraze mol_gnn_encoder weights')
221
+ param.requires_grad = False'''
222
+
223
+ print(model)
224
+ print(cfg.device)
225
+ print(model.feature_proj.bias.device)
226
+
227
+ optimizer = torch.optim.AdamW(
228
+ model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay
229
+ )
230
+
231
+ lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
232
+ optimizer, mode="min", patience=cfg.patience, factor=cfg.factor
233
+ )
234
+
235
+ for epoch in range(cfg.epochs):
236
+ print(f"Epoch: {epoch + 1}/{cfg.epochs}")
237
+ model.train()
238
+ train_loss = train_epoch(model, train_loader, optimizer, lr_scheduler, step)
239
+ model.eval()
240
+ with torch.no_grad():
241
+ valid_loss = valid_epoch(model, valid_loader)
242
+
243
+ if True: # valid_loss.avg < best_loss:
244
+ best_loss = valid_loss.avg
245
+ best_model_fn = f"{savedir}/model-tloss{round(train_loss.avg, 3)}-vloss{round(valid_loss.avg, 3)}-epoch{epoch}.pth"
246
+ best_model_fn_base = best_model_fn.replace('.pth', '')
247
+ n = 1
248
+ while os.path.exists(best_model_fn):
249
+ best_model_fn = best_model_fn_base + f'-{n}.pth'
250
+ n += 1
251
+
252
+ checkpoint = {'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), 'config': dict(CFG)}
253
+ best_model_fns.append(best_model_fn)
254
+ torch.save(checkpoint, best_model_fn)
255
+ print("Saved Best Model!")
256
+
257
+ best_model_fnl = []
258
+ for fn in best_model_fns:
259
+ if os.path.exists(fn):
260
+ best_model_fnl.append(fn)
261
+
262
+ for fn in best_model_fnl[:-cfg.keep_best_models_num]:
263
+ os.remove(fn)
264
+
265
+ best_model_fnl = best_model_fnl[-cfg.keep_best_models_num:]
266
+
267
+ print(best_model_fnl, best_loss)
268
+ return best_model_fnl, best_loss
269
+
270
+
271
+ if __name__ == "__main__":
272
+ # try:
273
+ # conffn = sys.argv[1]
274
+ # if conffn.endswith('.json'):
275
+ # CFG.load(sys.argv[1])
276
+ # elif conffn.endswith('.pth'):
277
+ # dpath = CFG.dataset_path
278
+ # d = torch.load(conffn)
279
+ # CFG.load(d['config'])
280
+ # CFG.dataset_path = dpath
281
+ # print('Use config from', conffn)
282
+ # except:
283
+ # pass
284
+ #
285
+ # try:
286
+ # savedir = sys.argv[2]
287
+ # except:
288
+ # savedir = 'out_data/'
289
+
290
+ # os.system('mkdir -p %s' % savedir)
291
+
292
+ savedir = 'out_data/'
293
+ mg = None
294
+
295
+ print(CFG)
296
+
297
+ if os.path.isdir(CFG.dataset_path):
298
+ # data = [os.path.join(CFG.dataset_path, i) for i in os.listdir(CFG.dataset_path) if i.endswith('mgf')]
299
+ # elif os.path.isfile(CFG.dataset_path):
300
+ # if CFG.dataset_path.endswith('.pkl'):
301
+ # data = pickle.load(open(CFG.dataset_path, 'rb'))
302
+ # else:
303
+ # data = json.load(open(CFG.dataset_path))
304
+ # pklfn = CFG.dataset_path.replace('.json', '.pkl')
305
+ # if not os.path.exists(pklfn):
306
+ # pickle.dump(data, open(pklfn, 'wb'))
307
+ # 支持多级目录通配符
308
+ data_files = []
309
+ for root, _, files in os.walk(CFG.dataset_path):
310
+ for f in files:
311
+ if f.endswith(('.json', '.pkl', '.mgf')):
312
+ data_files.append(os.path.join(root, f))
313
+ data = data_files
314
+ elif '*' in CFG.dataset_path: # 新增通配符支持
315
+ import glob
316
+
317
+ data = glob.glob(CFG.dataset_path)
318
+ elif os.path.isfile(CFG.dataset_path):
319
+ data = [CFG.dataset_path]
320
+
321
+ subdir = make_next_record_dir(savedir, f'train-')
322
+ os.system(f'cp -a *py {subdir}; cp -a GNN {subdir}')
323
+ CFG.save(f'{subdir}/config.json')
324
+
325
+ modelfnl, _ = main(data, CFG, subdir, mg)
326
+
327
+ # CUDA_VISIBLE_DEVICES=7 nohup python3 -u train.py > train_024_14.log 2>&1 &
utils.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rdkit import Chem
2
+ from rdkit.Chem import AllChem, MACCSkeys
3
+ from rdkit.Chem.rdmolops import FastFindRings
4
+ from rdkit.Chem.rdMolDescriptors import CalcMolFormula
5
+ import torch
6
+ import numpy as np
7
+ import scipy
8
+ import scipy.sparse as ss
9
+ import scipy.sparse.linalg
10
+ import math
11
+ import json
12
+ import itertools as it
13
+ import re
14
+ from GNN import featurizer as ft
15
+
16
+ import rdkit.RDLogger as rkl
17
+ logger = rkl.logger()
18
+ logger.setLevel(rkl.ERROR)
19
+
20
+ import rdkit.rdBase as rkrb
21
+ rkrb.DisableLog('rdApp.error')
22
+
23
+ # 50w metabolites fpbit relative aboundance > 5%
24
+ FPBitIdx = [1, 5, 13, 41, 69, 80, 84, 94, 114, 117, 118, 119, 125, 133, 145,
25
+ 147, 191, 192, 197, 202, 222, 227, 231, 249, 283, 294, 310, 314,
26
+ 322, 333, 352, 361, 378, 387, 389, 392, 401, 406, 441, 478, 486,
27
+ 489, 519, 521, 524, 555, 561, 591, 598, 599, 610, 622, 650, 656,
28
+ 667, 675, 677, 679, 680, 694, 695, 715, 718, 722, 729, 736, 739,
29
+ 745, 750, 760, 775, 781, 787, 794, 798, 802, 807, 811, 823, 835,
30
+ 841, 849, 869, 872, 874, 875, 881, 890, 896, 926, 935, 980, 991,
31
+ 1004, 1009, 1017, 1019, 1027, 1028, 1035, 1037, 1039, 1057, 1060,
32
+ 1066, 1070, 1077, 1088, 1097, 1114, 1126, 1136, 1142, 1143, 1145,
33
+ 1152, 1154, 1160, 1162, 1171, 1181, 1195, 1199, 1202, 1218, 1234,
34
+ 1236, 1243, 1257, 1267, 1274, 1279, 1283, 1292, 1294, 1309, 1313,
35
+ 1323, 1325, 1349, 1356, 1357, 1366, 1380, 1381, 1385, 1386, 1391,
36
+ 1399, 1436, 1440, 1441, 1444, 1452, 1454, 1457, 1475, 1476, 1477,
37
+ 1480, 1487, 1516, 1536, 1544, 1558, 1564, 1573, 1599, 1602, 1604,
38
+ 1607, 1619, 1648, 1670, 1683, 1693, 1716, 1722, 1737, 1738, 1745,
39
+ 1747, 1750, 1754, 1755, 1764, 1781, 1803, 1808, 1810, 1816, 1838,
40
+ 1844, 1847, 1855, 1860, 1866, 1873, 1905, 1911, 1917, 1921, 1923,
41
+ 1928, 1933, 1950, 1951, 1970, 1977, 1980, 1984, 1991, 2002, 2033, 2034, 2038]
42
+
43
+
44
+ class ConfigDict(dict):
45
+ '''
46
+ Makes a dictionary behave like an object,with attribute-style access.
47
+ '''
48
+ def __getattr__(self, name):
49
+ try:
50
+ return self[name]
51
+ except:
52
+ raise AttributeError(name)
53
+
54
+ def __setattr__(self, name, value):
55
+ self[name] = value
56
+
57
+ def save(self, fn):
58
+ json.dump(self, open(fn, 'w'), indent=2)
59
+
60
+ def load_dict(self, dic):
61
+ for k, v in dic.items():
62
+ self[k] = v
63
+
64
+ def load(self, fn):
65
+ try:
66
+ d = json.load(open(fn, 'r'))
67
+ self.load_dict(d)
68
+ except Exception as e:
69
+ print(e)
70
+
71
+
72
+ def conv_out_dim(length_in, kernel, stride, padding, dilation):
73
+ length_out = (length_in + 2 * padding - dilation * (kernel - 1) - 1) // stride + 1
74
+ return length_out
75
+
76
+
77
+ def filter_ms(ms, thr=0.05, max_mz=2000):
78
+ mz = []
79
+ intn = []
80
+ maxi = 0
81
+ for m, i in ms:
82
+ if m < max_mz and i > maxi:
83
+ maxi = i
84
+
85
+ for m, i in ms:
86
+ if m < max_mz and i/maxi > thr:
87
+ mz.append(m)
88
+ intn.append(round(i/maxi*100, 2))
89
+
90
+ return mz, intn
91
+
92
+
93
+ def calc_nls(ms, thr=0.05, max_mz=2000):
94
+ mz, intn = filter_ms(ms, thr=0.05, max_mz=2000)
95
+
96
+ nlmass = []
97
+ nlintn = []
98
+ for a, b in it.combinations(mz[::-1], 2):
99
+ nl = a - b
100
+ if 0 < nl < 200:
101
+ nlmass.append(round(nl, 5))
102
+ idxa = mz.index(a)
103
+ idxb = mz.index(b)
104
+ nlintn.append(round((intn[idxa]+intn[idxb])/2., 5))
105
+
106
+ nls = sorted(list(zip(nlmass, nlintn)))
107
+ return nls
108
+
109
+
110
+ # --- 2. 辅助函数:匹配诊断离子与中性丢失 ---
111
+ def check_match(val, targets, tolerance=0.02):
112
+ """判断 val 是否在 targets 列表中 (带容差)"""
113
+ if not targets:
114
+ return 0.0
115
+ val_arr = np.array([val])
116
+ target_arr = np.array(targets)
117
+ # 广播计算差值绝对值
118
+ diff = np.abs(val_arr.reshape(-1, 1) - target_arr.reshape(1, -1))
119
+ # 如果有任意一个差值小于容差,返回 1.0
120
+ match = np.any(diff <= tolerance)
121
+ return 1.0 if match else 0.0
122
+
123
+
124
+ # --- 3. 核心处理函数 (对应图中的整个流程) ---
125
+ def ms_feature_processor(ms,
126
+ precursor_mz,
127
+ metadata_vec=None,
128
+ max_peaks=100,
129
+ diagnostic_ions=[102.05, 135.08], # 图片示例:生物碱
130
+ neutral_losses=[18.01], # 图片示例:水、羟基
131
+ max_mz=2000):
132
+ """
133
+ 输入:
134
+ ms: list of [mz, intensity]
135
+ precursor_mz: 前体离子 m/z (用于计算中性丢失)
136
+ metadata_vec: (25,) 维度的元数据向量 (仪器/加合物/电荷)
137
+ 输出:
138
+ node_features: (max_peaks, feature_dim) - 这里的 feature_dim 不包含 m/z嵌入,m/z嵌入通常在模型 forward 中做
139
+ mz_values: (max_peaks,) - 用于输入给 SinusoidalMzEmbedding
140
+ """
141
+
142
+ # 1. [MS数据采集过滤] - 过滤无效数据
143
+ valid_ms = []
144
+ for m, i in ms:
145
+ if m <= max_mz and i > 0:
146
+ valid_ms.append([m, i])
147
+
148
+ if not valid_ms:
149
+ # 如果为空,返回零填充
150
+ return torch.zeros(max_peaks, 29), torch.zeros(max_peaks)
151
+
152
+ valid_ms = np.array(valid_ms)
153
+
154
+ # 2. [保留强度 T100 峰]
155
+ # 按强度降序排序
156
+ sort_idx = np.argsort(valid_ms[:, 1])[::-1]
157
+ top_k_idx = sort_idx[:max_peaks]
158
+
159
+ # 截取 Top K
160
+ top_ms = valid_ms[top_k_idx]
161
+
162
+ # 为了 Transformer 处理方便,通常按 m/z 重新升序排列 (虽然 Transformer 有位置编码,但有序输入有助于学习)
163
+ resort_idx = np.argsort(top_ms[:, 0])
164
+ top_ms = top_ms[resort_idx]
165
+
166
+ # 解包
167
+ mz_vals = top_ms[:, 0]
168
+ int_vals = top_ms[:, 1]
169
+
170
+ # 归一化强度 (0-1)
171
+ max_int = int_vals.max() if int_vals.max() > 0 else 1.0
172
+ norm_int = int_vals / max_int
173
+
174
+ # --- 特征构建 ---
175
+ feature_list = []
176
+
177
+ # 处理元数据 (图片要求:元数据编码25维)
178
+ if metadata_vec is None:
179
+ metadata_vec = np.zeros(25) # 默认零向量
180
+ else:
181
+ # 确保是 numpy 且长度正确,这里做简单的截断或填充
182
+ metadata_vec = np.array(metadata_vec)
183
+ if len(metadata_vec) > 25:
184
+ metadata_vec = metadata_vec[:25]
185
+ elif len(metadata_vec) < 25:
186
+ metadata_vec = np.pad(metadata_vec, (0, 25 - len(metadata_vec)))
187
+
188
+ for i in range(len(mz_vals)):
189
+ m = mz_vals[i]
190
+ inten = norm_int[i]
191
+
192
+ # 3. [诊断离子与中性丢失匹配]
193
+ # 诊断标记 (1维)
194
+ is_diagnostic = check_match(m, diagnostic_ions)
195
+
196
+ # 中性丢失标记 (1维) - 检查 (Precursor - Fragment) 是否在列表中
197
+ current_nl = precursor_mz - m
198
+ is_neutral_loss = check_match(current_nl, neutral_losses) if current_nl > 0 else 0.0
199
+
200
+ # 前体 m/z 加权 (图片提及 "前体m/z加权")
201
+ # 这里实现一个简单的注意力加权逻辑:如果 fragment 接近 precursor,权重高
202
+ # 或者根据图片意图,可能是指 Precursor m/z 作为一个单独的特征值拼进去
203
+ # 这里我们假设它是一个特征维度
204
+ precursor_weight = abs(m - precursor_mz) / (precursor_mz + 1e-5)
205
+
206
+ # 4. [特征拼接]
207
+ # 注意:256维的m/z嵌入通常在 GPU 上通过 nn.Module 计算,这里只准备 inputs
208
+ # 此时的特征: [强度(1), 诊断(1), 丢失(1), 前体权重(1), 元数据(25)] = 29 dims
209
+
210
+ feat = np.concatenate([
211
+ [inten],
212
+ [is_diagnostic],
213
+ [is_neutral_loss],
214
+ [precursor_weight],
215
+ metadata_vec
216
+ ])
217
+ feature_list.append(feat)
218
+
219
+ # Pad 到 max_peaks (如果不足 100 个峰)
220
+ num_actual = len(feature_list)
221
+ pad_len = max_peaks - num_actual
222
+
223
+ features_tensor = torch.FloatTensor(np.array(feature_list))
224
+ mz_tensor = torch.FloatTensor(mz_vals)
225
+
226
+ if pad_len > 0:
227
+ # Padding features with 0
228
+ feat_pad = torch.zeros(pad_len, 29) # 29 = 1+1+1+1+25
229
+ features_tensor = torch.cat([features_tensor, feat_pad], dim=0)
230
+
231
+ # Padding m/z with 0 (or padding value)
232
+ mz_pad = torch.zeros(pad_len)
233
+ mz_tensor = torch.cat([mz_tensor, mz_pad], dim=0)
234
+
235
+ return features_tensor, mz_tensor
236
+
237
+
238
+ def ms_binner(ms, nls=[], min_mz=20, max_mz=2000, bin_size=0.05, add_nl=False, binary_intn=False):
239
+ """
240
+ Convert the given spectrum to a binned sparse SciPy vector.
241
+
242
+ Parameters
243
+ ----------
244
+ spectrum_mz : np.ndarray
245
+ The peak m/z values of the spectrum to be converted to a vector.
246
+ spectrum_intensity : np.ndarray
247
+ The peak intensities of the spectrum to be converted to a vector.
248
+ min_mz : float
249
+ The minimum m/z to include in the vector.
250
+ bin_size : float
251
+ The bin size in m/z used to divide the m/z range.
252
+ num_bins : int
253
+ The number of elements of which the vector consists.
254
+
255
+ Returns
256
+ -------
257
+ ss.csr_matrix
258
+ The binned spectrum vector.
259
+ """
260
+ if add_nl and not nls:
261
+ nls = calc_nls(ms, max_mz=max_mz)
262
+
263
+ nltensor = None
264
+ mz, intn = filter_ms(ms)
265
+
266
+ if add_nl:
267
+ nlmass = []
268
+ nlintn = []
269
+
270
+ if not nls:
271
+ nls = calc_nls(ms, max_mz=max_mz)
272
+
273
+ for m, i in nls:
274
+ if m < 200:
275
+ if binary_intn:
276
+ i = 1
277
+ nlmass.append(m)
278
+ nlintn.append(i)
279
+
280
+ nlmass = np.array(nlmass)
281
+ nlintn = np.array(nlintn)
282
+ if len(nlintn) > 0:
283
+ nlintn = nlintn/nlintn.max()
284
+ num_nlbins = math.ceil((200) / bin_size)
285
+ # print('num_nlbins', num_nlbins)
286
+ nlbins = (nlmass / bin_size).astype(np.int32)
287
+
288
+ if len(nlmass) > 0:
289
+ vecnl = ss.csr_matrix(
290
+ (nlintn,
291
+ (np.repeat(0, len(nlintn)), nlbins)),
292
+ shape=(1, num_nlbins),
293
+ dtype=np.float32)
294
+
295
+ vecnl = (vecnl / scipy.sparse.linalg.norm(vecnl)*100)
296
+ nltensor = torch.FloatTensor(vecnl.todense()).view(-1)
297
+ else:
298
+ nltensor = torch.zeros(num_nlbins)
299
+
300
+ mz = np.array(mz)
301
+ keepidx = (mz <= max_mz)
302
+ mz = mz[keepidx]
303
+ intn = np.array(intn)
304
+ intn = intn[keepidx]
305
+
306
+ if binary_intn:
307
+ intn[intn > 0] = 1.0
308
+ elif len(intn) > 0:
309
+ intn = intn/intn.max()
310
+
311
+ num_bins = math.ceil((max_mz - min_mz) / bin_size)
312
+ # print('num_bins', num_bins)
313
+ bins = ((mz - min_mz) / bin_size).astype(np.int32)
314
+
315
+ # print(num_bins, intn, bins)
316
+
317
+ if len(mz) > 0:
318
+ vec = ss.csr_matrix(
319
+ (intn,
320
+ (np.repeat(0, len(intn)), bins)),
321
+ shape=(1, num_bins),
322
+ dtype=np.float32)
323
+
324
+ if not binary_intn:
325
+ vec = (vec / scipy.sparse.linalg.norm(vec)*100)
326
+
327
+ mstensor = torch.FloatTensor(vec.todense()).view(-1)
328
+ else:
329
+ mstensor = torch.zeros(num_bins)
330
+
331
+ if not nltensor is None:
332
+ return torch.cat([nltensor, mstensor], dim=0)
333
+
334
+ return mstensor
335
+
336
+
337
+ def formula2vec(formula, elements=['C', 'H', 'O', 'N', 'P', 'S', 'P', 'F', 'Cl', 'Br']):
338
+ formula_p = re.findall(r'([A-Z][a-z]*)(\d*)', formula)
339
+ vec = np.zeros(len(elements))
340
+ for i in range(len(formula_p)):
341
+ ele = formula_p[i][0]
342
+ num = formula_p[i][1]
343
+ if num == '':
344
+ num = 1
345
+ else:
346
+ num = int(num)
347
+ if ele in elements:
348
+ vec[elements.index(ele)] += num
349
+ return np.array(vec)
350
+
351
+
352
+ def mol_fp_encoder0(smiles, tp='rdkit', nbits=2048):
353
+ mol = Chem.MolFromSmiles(smiles)
354
+ if mol is None:
355
+ mol = Chem.MolFromSmiles(smiles, sanitize=False)
356
+ if not mol is None:
357
+ mol.UpdatePropertyCache()
358
+ FastFindRings(mol)
359
+
360
+ if mol is None:
361
+ return None, None
362
+
363
+ if tp == 'morgan':
364
+ fp_vec = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=nbits)
365
+ fp = np.frombuffer(fp_vec.ToBitString().encode(), 'u1') - ord('0')
366
+ fp = fp.tolist()
367
+ elif tp == 'morgan1':
368
+ fp_vec = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048)
369
+ fp = np.frombuffer(fp_vec.ToBitString().encode(), 'u1') - ord('0')
370
+ fp = fp[FPBitIdx].tolist()
371
+ elif tp == 'macc':
372
+ # MACCSkeys
373
+ fp_vec = MACCSkeys.GenMACCSKeys(mol)
374
+ fp = np.frombuffer(fp_vec.ToBitString().encode(), 'u1') - ord('0')
375
+ fp = fp.tolist()
376
+ elif tp == 'rdkit':
377
+ fp_vec = Chem.RDKFingerprint(mol, nBitsPerHash=1)
378
+ fp = np.frombuffer(fp_vec.ToBitString().encode(), 'u1') - ord('0')
379
+ fp = fp.tolist()
380
+
381
+ return torch.FloatTensor(fp), mol
382
+
383
+
384
+ def mol_fp_encoder(smiles, tp='rdkit', nbits=2048):
385
+ fpenc, _ = mol_fp_encoder0(smiles, tp, nbits)
386
+ return fpenc
387
+
388
+
389
+ def mol_fp_fm_encoder(smiles, tp='rdkit', nbits=2048):
390
+ fmenc = None
391
+ fpenc, mol = mol_fp_encoder0(smiles, tp, nbits)
392
+ if not mol is None:
393
+ fm = CalcMolFormula(mol)
394
+ fmenc = torch.FloatTensor(formula2vec(fm))
395
+ return fpenc, fmenc
396
+
397
+
398
+ def smi2fmvec(smiles):
399
+ mol = Chem.MolFromSmiles(smiles)
400
+ if mol is None:
401
+ return None
402
+ fm = CalcMolFormula(mol)
403
+ fmenc = torch.FloatTensor(formula2vec(fm))
404
+
405
+ return fmenc
406
+
407
+
408
+ def mol_graph_featurizer(smiles):
409
+ # mol_graph = {V, A, mol_size}
410
+ '''mol_graph = ft.calc_data_from_smile(smiles,
411
+ addh=True,
412
+ with_ring_conj=True,
413
+ with_atom_feats=True,
414
+ with_submol_fp=True,
415
+ radius=2)
416
+ '''
417
+ mol_graph = ft.calc_data_from_smile(smiles,
418
+ addh=False,
419
+ with_ring_conj=True,
420
+ with_atom_feats=True,
421
+ with_submol_fp=False,
422
+ radius=2)
423
+ return mol_graph
424
+
425
+
426
+ def pad_V(V, max_n):
427
+ N, C = V.shape
428
+ if max_n > N:
429
+ zeros = torch.zeros(max_n-N, C)
430
+ V = torch.cat([V, zeros], dim=0)
431
+ return V
432
+
433
+
434
+ def pad_A(A, max_n):
435
+ N, L, _ = A.shape
436
+ if max_n > N:
437
+ zeros = torch.zeros(N, L, max_n-N)
438
+ A = torch.cat([A, zeros], dim=-1)
439
+ zeros = torch.zeros(max_n-N, L, max_n)
440
+ A = torch.cat([A, zeros], dim=0)
441
+ return A
442
+
443
+
444
+ class AvgMeter:
445
+ def __init__(self, name="Metric"):
446
+ self.name = name
447
+ self.reset()
448
+
449
+ def reset(self):
450
+ self.avg, self.sum, self.count = [0] * 3
451
+
452
+ def update(self, val, count=1):
453
+ self.count += count
454
+ self.sum += val * count
455
+ self.avg = self.sum / self.count
456
+
457
+ def __repr__(self):
458
+ text = f"{self.name}: {self.avg:.4f}"
459
+ return text
460
+
461
+
462
+ def get_lr(optimizer):
463
+ for param_group in optimizer.param_groups:
464
+ return param_group["lr"]
465
+
466
+
467
+ def segment_max(x, size_list):
468
+ size_list = [int(i) for i in size_list]
469
+ return torch.stack([torch.max(v, 0).values for v in torch.split(x, size_list)])
470
+
471
+
472
+ def segment_sum(x, size_list):
473
+ size_list = [int(i) for i in size_list]
474
+ return torch.stack([torch.sum(v, 0) for v in torch.split(x, size_list)])
475
+
476
+
477
+ def segment_softmax(gate, size_list):
478
+ segmax = segment_max(gate, size_list)
479
+ # expand segmax shape to alpha shape
480
+ segmax_expand = torch.cat([segmax[i].repeat(n, 1) for i, n in enumerate(size_list)], dim=0)
481
+ subtract = gate - segmax_expand
482
+ exp = torch.exp(subtract)
483
+ segsum = segment_sum(exp, size_list)
484
+ # expand segmax shape to alpha shape
485
+ segsum_expand = torch.cat([segsum[i].repeat(n, 1) for i, n in enumerate(size_list)], dim=0)
486
+ attention = exp / (segsum_expand + 1e-16)
487
+
488
+ return attention
489
+
490
+
491
+ def pad_ms_list(ms_list, thr=0.05, min_mz=20, max_mz=2000):
492
+ thr = thr*100
493
+ mslst = []
494
+ for ms in ms_list:
495
+ ms = np.array(ms)
496
+ ms[:, 1] = ms[:, 1]/ms[:, 1].max()*100
497
+
498
+ if thr > 0:
499
+ ms = ms[(ms[:, 1] >= thr)]
500
+
501
+ ms = ms[(ms[:, 0] >= min_mz)]
502
+ ms = ms[(ms[:, 0] <= max_mz)]
503
+
504
+ mslst.append(ms)
505
+
506
+ size_list = [ms.shape[0] for ms in mslst]
507
+ maxlen = max(size_list)
508
+
509
+ l = []
510
+ for ms in mslst:
511
+ extn = maxlen-len(ms)
512
+ if extn > 0:
513
+ l.append(np.concatenate([ms, [[0, 0]]*extn], axis=0))
514
+ else:
515
+ l.append(ms)
516
+
517
+ return torch.FloatTensor(np.stack(l)), torch.IntTensor(size_list)