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
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
"""

Module: model.py

Description:

    This module defines the neural network architecture for the REDDA framework used in drug repositioning.

    It includes several components such as a link prediction decoder, heterogeneous graph convolutional layers,

    semantic attention mechanisms, and graph attention modules. Adapted for the new knowledge graph dataset.

"""

import torch
import torch.nn as nn
import dgl.nn as dglnn
import dgl


class InnerProductDecoder(nn.Module):
    """

    Decoder layer that computes the inner product between drug and disease embeddings for link prediction.

    Optionally applies a linear transformation to the disease embeddings.

    """

    def __init__(self, input_dim=None, dropout=0.4):
        """

        Parameters:

            input_dim (int, optional): Dimension of input features. If provided, a linear layer is used.

            dropout (float): Dropout rate.

        """
        super(InnerProductDecoder, self).__init__()
        self.dropout = nn.Dropout(dropout)
        if input_dim:
            self.weights = nn.Linear(input_dim, input_dim, bias=False)
            nn.init.xavier_uniform_(self.weights.weight)

    def forward(self, feature):
        """

        Forward pass to compute the similarity score matrix.



        Parameters:

            feature (dict): Dictionary containing node features for 'drug' and 'disease'.



        Returns:

            torch.Tensor: The computed score matrix with shape [num_drugs, num_diseases].

        """
        # Apply dropout to drug and disease features
        feature["drug"] = self.dropout(feature["drug"])
        feature["disease"] = self.dropout(feature["disease"])
        R = feature["drug"]
        D = self.weights(feature["disease"]) if hasattr(self, "weights") else feature["disease"]
        outputs = R @ D.T
        return outputs


class Node_Embedding(nn.Module):
    """

    Basic heterogeneous graph convolution layer to generate node embeddings for each relation type.

    """

    def __init__(self, in_feats, out_feats, dropout, rel_names):
        """

        Parameters:

            in_feats (int): Input feature dimension.

            out_feats (int): Output feature dimension.

            dropout (float): Dropout rate.

            rel_names (list): List of relation names to construct individual GraphConv layers.

        """
        super().__init__()
        # Create a dictionary of GraphConv layers for each relation
        hetero_conv_dict = {}
        for rel in rel_names:
            graphconv = dglnn.GraphConv(in_feats, out_feats)
            nn.init.xavier_normal_(graphconv.weight)
            hetero_conv_dict[rel] = graphconv
        self.dropout = nn.Dropout(p=dropout)
        self.embedding = dglnn.HeteroGraphConv(hetero_conv_dict, aggregate="sum")
        self.bn_layer = nn.BatchNorm1d(out_feats)
        self.prelu = nn.PReLU()

    def forward(self, graph, inputs, bn=False, dp=False):
        """

        Forward pass for the node embedding.



        Parameters:

            graph (dgl.DGLHeteroGraph): Input heterogeneous graph.

            inputs (dict): Dictionary of input node features keyed by node type.

            bn (bool): Whether to apply batch normalization.

            dp (bool): Whether to apply dropout.



        Returns:

            dict: Updated node features keyed by node type.

        """
        h = self.embedding(graph, inputs)
        # Apply batch normalization and dropout if specified
        if bn and dp:
            h = {k: self.prelu(self.dropout(self.bn_layer(v))) for k, v in h.items()}
        elif dp:
            h = {k: self.prelu(self.dropout(v)) for k, v in h.items()}
        elif bn:
            h = {k: self.prelu(self.bn_layer(v)) for k, v in h.items()}
        else:
            h = {k: self.prelu(v) for k, v in h.items()}
        return h


class SemanticAttention(nn.Module):
    """

    Attention mechanism to aggregate multiple embeddings.

    """

    def __init__(self, in_feats, hidden_size=128):
        """

        Parameters:

            in_feats (int): Dimension of input features.

            hidden_size (int): Hidden layer size for attention projection.

        """
        super(SemanticAttention, self).__init__()
        self.project = nn.Sequential(
            nn.Linear(in_feats, hidden_size),
            nn.Tanh(),
            nn.Linear(hidden_size, 1, bias=False),
        )

    def forward(self, z, is_print=False):
        """

        Apply semantic attention to a stack of embeddings.



        Parameters:

            z (torch.Tensor): Tensor of shape [batch, num_layers, in_feats].

            is_print (bool): If True, prints the attention weights.



        Returns:

            torch.Tensor: Aggregated embedding of shape [batch, in_feats].

        """
        w = self.project(z).mean(0)  # Average over the batch dimension
        beta = torch.softmax(w, dim=0)
        beta = beta.expand((z.shape[0],) + beta.shape)
        if is_print:
            print(beta)
        return (beta * z).sum(1)


class SubnetworkEncoder(nn.Module):
    """

    Module to compute topological subnetwork embeddings using multiple heterogeneous graph convolution blocks.

    Adapted for the new knowledge graph with multiple node types.

    """

    def __init__(self, ntypes, in_feats, out_feats, dropout):
        """

        Parameters:

            ntypes (list): List of node types present in the graph.

            in_feats (int): Input feature dimension.

            out_feats (int): Output feature dimension.

            dropout (float): Dropout rate.

        """
        super(SubnetworkEncoder, self).__init__()
        self.ntypes = ntypes

        # Define subnetworks based on the new knowledge graph structure
        # Drug-centric subnetworks
        self.drug_disease = Node_Embedding(in_feats, out_feats, dropout,
                                           ['drug_drug', 'drug_disease_indication', 'disease_disease'])
        
        self.drug_protein = Node_Embedding(in_feats, out_feats, dropout,
                                           ['drug_drug', 'drug_protein', 'protein_protein'])
        
        self.drug_effect = Node_Embedding(in_feats, out_feats, dropout,
                                          ['drug_drug', 'drug_effect'])
        
        # Protein-centric subnetworks
        self.protein_bioprocess = Node_Embedding(in_feats, out_feats, dropout,
                                                 ['protein_protein', 'protein_bioprocess', 'bioprocess_bioprocess'])
        
        self.protein_cellcomp = Node_Embedding(in_feats, out_feats, dropout,
                                               ['protein_protein', 'protein_cellcomp', 'cellcomp_cellcomp'])
        
        self.protein_molfunc = Node_Embedding(in_feats, out_feats, dropout,
                                              ['protein_protein', 'protein_molfunc', 'molfunc_molfunc'])
        
        self.protein_pathway = Node_Embedding(in_feats, out_feats, dropout,
                                              ['protein_protein', 'protein_pathway', 'pathway_pathway'])
        
        self.protein_disease = Node_Embedding(in_feats, out_feats, dropout,
                                              ['protein_protein', 'protein_disease', 'disease_disease'])
        
        # Disease-centric subnetworks
        self.disease_phenotype = Node_Embedding(in_feats, out_feats, dropout,
                                                ['disease_disease', 'disease_phenotype_positive', 'phenotype_phenotype'])
        
        self.disease_exposure = Node_Embedding(in_feats, out_feats, dropout,
                                               ['disease_disease', 'disease_exposure'])
        
        # Biological process subnetworks
        self.bioprocess_network = Node_Embedding(in_feats, out_feats, dropout,
                                                 ['bioprocess_bioprocess'])
        
        self.cellcomp_network = Node_Embedding(in_feats, out_feats, dropout,
                                               ['cellcomp_cellcomp'])
        
        self.molfunc_network = Node_Embedding(in_feats, out_feats, dropout,
                                              ['molfunc_molfunc'])
        
        self.pathway_network = Node_Embedding(in_feats, out_feats, dropout,
                                              ['pathway_pathway'])
        
        self.phenotype_network = Node_Embedding(in_feats, out_feats, dropout,
                                                ['phenotype_phenotype'])
        
        self.semantic_attention = SemanticAttention(in_feats=out_feats)

    def forward(self, g, h, bn=False, dp=False):
        """

        Compute subnetwork embeddings and aggregate them using semantic attention.



        Parameters:

            g (dgl.DGLHeteroGraph): Input heterogeneous graph.

            h (dict): Dictionary of node features.

            bn (bool): Whether to apply batch normalization.

            dp (bool): Whether to apply dropout.



        Returns:

            dict: Updated node features for each node type.

        """
        new_h = {ntype: [] for ntype in self.ntypes}

        # Drug-Disease subnet
        if 'drug' in self.ntypes and 'disease' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['drug_drug', 'drug_disease_indication', 'disease_disease'])
                h_sub = self.drug_disease(subgraph, {'drug': h['drug'], 'disease': h['disease']}, bn, dp)
                new_h['drug'].append(h_sub['drug'])
                new_h['disease'].append(h_sub['disease'])
            except:
                pass

        # Drug-Protein subnet
        if 'drug' in self.ntypes and 'protein' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['drug_drug', 'drug_protein', 'protein_protein'])
                h_sub = self.drug_protein(subgraph, {'drug': h['drug'], 'protein': h['protein']}, bn, dp)
                new_h['drug'].append(h_sub['drug'])
                new_h['protein'].append(h_sub['protein'])
            except:
                pass

        # Drug-Effect subnet
        if 'drug' in self.ntypes and 'effect' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['drug_drug', 'drug_effect'])
                h_sub = self.drug_effect(subgraph, {'drug': h['drug'], 'effect': h['effect']}, bn, dp)
                new_h['drug'].append(h_sub['drug'])
                new_h['effect'].append(h_sub['effect'])
            except:
                pass

        # Protein-Bioprocess subnet
        if 'protein' in self.ntypes and 'bioprocess' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['protein_protein', 'protein_bioprocess', 'bioprocess_bioprocess'])
                h_sub = self.protein_bioprocess(subgraph, {'protein': h['protein'], 'bioprocess': h['bioprocess']}, bn, dp)
                new_h['protein'].append(h_sub['protein'])
                new_h['bioprocess'].append(h_sub['bioprocess'])
            except:
                pass

        # Protein-Cellcomp subnet
        if 'protein' in self.ntypes and 'cellcomp' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['protein_protein', 'protein_cellcomp', 'cellcomp_cellcomp'])
                h_sub = self.protein_cellcomp(subgraph, {'protein': h['protein'], 'cellcomp': h['cellcomp']}, bn, dp)
                new_h['protein'].append(h_sub['protein'])
                new_h['cellcomp'].append(h_sub['cellcomp'])
            except:
                pass

        # Protein-Molfunc subnet
        if 'protein' in self.ntypes and 'molfunc' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['protein_protein', 'protein_molfunc', 'molfunc_molfunc'])
                h_sub = self.protein_molfunc(subgraph, {'protein': h['protein'], 'molfunc': h['molfunc']}, bn, dp)
                new_h['protein'].append(h_sub['protein'])
                new_h['molfunc'].append(h_sub['molfunc'])
            except:
                pass

        # Protein-Pathway subnet
        if 'protein' in self.ntypes and 'pathway' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['protein_protein', 'protein_pathway', 'pathway_pathway'])
                h_sub = self.protein_pathway(subgraph, {'protein': h['protein'], 'pathway': h['pathway']}, bn, dp)
                new_h['protein'].append(h_sub['protein'])
                new_h['pathway'].append(h_sub['pathway'])
            except:
                pass

        # Protein-Disease subnet
        if 'protein' in self.ntypes and 'disease' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['protein_protein', 'protein_disease', 'disease_disease'])
                h_sub = self.protein_disease(subgraph, {'protein': h['protein'], 'disease': h['disease']}, bn, dp)
                new_h['protein'].append(h_sub['protein'])
                new_h['disease'].append(h_sub['disease'])
            except:
                pass

        # Disease-Phenotype subnet
        if 'disease' in self.ntypes and 'phenotype' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['disease_disease', 'disease_phenotype_positive', 'phenotype_phenotype'])
                h_sub = self.disease_phenotype(subgraph, {'disease': h['disease'], 'phenotype': h['phenotype']}, bn, dp)
                new_h['disease'].append(h_sub['disease'])
                new_h['phenotype'].append(h_sub['phenotype'])
            except:
                pass

        # Disease-Exposure subnet
        if 'disease' in self.ntypes and 'exposure' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['disease_disease', 'disease_exposure'])
                h_sub = self.disease_exposure(subgraph, {'disease': h['disease'], 'exposure': h['exposure']}, bn, dp)
                new_h['disease'].append(h_sub['disease'])
                new_h['exposure'].append(h_sub['exposure'])
            except:
                pass

        # Self-loop subnetworks for biological entities
        if 'bioprocess' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['bioprocess_bioprocess'])
                h_sub = self.bioprocess_network(subgraph, {'bioprocess': h['bioprocess']}, bn, dp)
                new_h['bioprocess'].append(h_sub['bioprocess'])
            except:
                pass

        if 'cellcomp' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['cellcomp_cellcomp'])
                h_sub = self.cellcomp_network(subgraph, {'cellcomp': h['cellcomp']}, bn, dp)
                new_h['cellcomp'].append(h_sub['cellcomp'])
            except:
                pass

        if 'molfunc' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['molfunc_molfunc'])
                h_sub = self.molfunc_network(subgraph, {'molfunc': h['molfunc']}, bn, dp)
                new_h['molfunc'].append(h_sub['molfunc'])
            except:
                pass

        if 'pathway' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['pathway_pathway'])
                h_sub = self.pathway_network(subgraph, {'pathway': h['pathway']}, bn, dp)
                new_h['pathway'].append(h_sub['pathway'])
            except:
                pass

        if 'phenotype' in self.ntypes:
            try:
                subgraph = g.edge_type_subgraph(['phenotype_phenotype'])
                h_sub = self.phenotype_network(subgraph, {'phenotype': h['phenotype']}, bn, dp)
                new_h['phenotype'].append(h_sub['phenotype'])
            except:
                pass

        # Aggregate multiple embeddings with semantic attention
        for ntype in self.ntypes:
            if new_h[ntype]:  # Only process if there are embeddings
                h[ntype] = torch.stack(new_h[ntype], dim=1)
                h[ntype] = self.semantic_attention(h[ntype])
        return h


class Graph_attention(nn.Module):
    """

    Multi-omics graph attention block that aggregates information from all node types.

    """

    def __init__(self, in_feats, out_feats, num_heads, dropout):
        """

        Parameters:

            in_feats (int): Input feature dimension.

            out_feats (int): Output feature dimension.

            num_heads (int): Number of attention heads.

            dropout (float): Dropout rate.

        """
        super().__init__()
        self.gat = dglnn.GATConv(in_feats, out_feats, num_heads,
                                 dropout, dropout,
                                 activation=nn.PReLU(),
                                 allow_zero_in_degree=True)
        self.gat.reset_parameters()
        self.linear = nn.Linear(in_feats * num_heads, out_feats)
        self.prelu = nn.PReLU()
        self.bn_layer = nn.BatchNorm1d(out_feats)

    def forward(self, graph, inputs, bn=False):
        """

        Forward pass for graph attention.



        Parameters:

            graph (dgl.DGLHeteroGraph): Input heterogeneous graph.

            inputs (dict): Dictionary of node features.

            bn (bool): Whether to apply batch normalization.



        Returns:

            tuple: Aggregated disease and drug embeddings.

        """
        # Convert heterogeneous graph to homogeneous
        num_dis = graph.num_nodes("disease")
        num_drug = graph.num_nodes("drug")
        new_g = dgl.to_homogeneous(graph)
        new_h = torch.cat([feat for feat in inputs.values()], dim=0)
        new_h = self.gat(new_g, new_h)
        new_h = self.prelu(torch.mean(new_h, dim=1))
        if bn:
            return self.bn_layer(new_h[:num_dis]), self.bn_layer(new_h[num_dis:num_drug + num_dis])
        return new_h[:num_dis], new_h[num_dis:num_drug + num_dis]


class Model(nn.Module):
    """

    Overall REDDA architecture for drug repositioning, adapted for the new knowledge graph.

    """

    def __init__(self, etypes, ntypes, in_feats, hidden_feats, num_heads, dropout):
        """

        Parameters:

            etypes (list): List of edge types.

            ntypes (list): List of node types.

            in_feats (int): Input feature dimension.

            hidden_feats (int): Hidden layer dimension.

            num_heads (int): Number of attention heads.

            dropout (float): Dropout rate.

        """
        super(Model, self).__init__()
        self.ntypes = ntypes

        # Linear projection layers for each node type
        self.node_projections = nn.ModuleDict()
        for ntype in ntypes:
            self.node_projections[ntype] = nn.Linear(in_feats, hidden_feats)
            nn.init.xavier_normal_(self.node_projections[ntype].weight)

        # Two layers of node embedding generation
        self.feat_generate_layer1 = Node_Embedding(hidden_feats, hidden_feats, dropout, etypes)
        self.feat_generate_layer2 = Node_Embedding(hidden_feats, hidden_feats, dropout, etypes)
        # Subnetwork encoder to capture local topological features
        self.subnet_layer = SubnetworkEncoder(ntypes, hidden_feats, hidden_feats, dropout)
        # Graph attention layer to capture global information
        self.totalnet_layer = Graph_attention(hidden_feats, hidden_feats, num_heads, dropout)
        # Layer-level semantic attention for drug and disease embeddings
        self.layer_attention_layer_drug = SemanticAttention(hidden_feats)
        self.layer_attention_layer_dis = SemanticAttention(hidden_feats)
        # Final prediction decoder using inner product
        self.predict = InnerProductDecoder(hidden_feats)

    def forward(self, g, x):
        """

        Forward pass of the REDDA model.



        Parameters:

            g (dgl.DGLHeteroGraph): Input heterogeneous graph.

            x (dict): Dictionary of initial node features for each node type.



        Returns:

            torch.Tensor: Predicted score matrix between drugs and diseases.

        """
        drug_emb_list, dis_emb_list = [], []
        h = {ntype: x[ntype] for ntype in self.ntypes}

        # Apply linear transformation to initial features
        for ntype in self.ntypes:
            h[ntype] = self.node_projections[ntype](h[ntype])

        drug_emb_list.append(h["drug"])
        dis_emb_list.append(h["disease"])

        # Generate updated embeddings via heterogeneous GCN layers
        h = self.feat_generate_layer1(g, h, bn=True, dp=True)
        h = self.feat_generate_layer2(g, h, bn=True, dp=True)
        drug_emb_list.append(h["drug"])
        dis_emb_list.append(h["disease"])

        # Obtain subnetwork embeddings
        h = self.subnet_layer(g, h, bn=False, dp=True)
        drug_emb_list.append(h["drug"])
        dis_emb_list.append(h["disease"])

        # Apply graph attention for global aggregation
        h["disease"], h["drug"] = self.totalnet_layer(g, h, bn=False)
        drug_emb_list.append(h["drug"])
        dis_emb_list.append(h["disease"])

        # Apply layer-level semantic attention to fuse embeddings from different layers
        h["drug"] = self.layer_attention_layer_drug(torch.stack(drug_emb_list, dim=1))
        h["disease"] = self.layer_attention_layer_dis(torch.stack(dis_emb_list, dim=1))

        return self.predict(h)