File size: 68,820 Bytes
de2c4f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# P2PXML - Deep Geometric Framework to Predict Antibody-Antigen Binding Affinity"
      ],
      "metadata": {
        "id": "N47Ue-53WqAG"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "List of resources:\n",
        "\n",
        "*   Paper: https://www.biorxiv.org/content/10.1101/2024.06.09.598103v1\n",
        "*   Project Page: https://drug-discovery-entc.github.io/p2pxml/\n",
        "*   Codes: https://github.com/Drug-Discovery-ENTC/p2pxml/\n",
        "*   Our dataset: https://zenodo.org/records/11531319\n",
        "\n",
        "The codes, including this notebook, are released under MIT license (https://github.com/Drug-Discovery-ENTC/p2pxml/blob/main/LICENSE) and the dataset is released under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en)."
      ],
      "metadata": {
        "id": "35qWIH9dWzu7"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Citation:\n",
        "\n",
        "```bibtex\n",
        "@article{bandara2024deep,\n",
        "  title={Deep Geometric Framework to Predict Antibody-Antigen Binding Affinity},\n",
        "  author={Bandara, Nuwan Sriyantha and Premathilaka, Dasun and Chandanayake, Sachini and Hettiarachchi, Sahan and Varenthirarajah, Vithurshan and Munasinghe, Aravinda and Madhawa, Kaushalya and Charles, Subodha},\n",
        "  journal={bioRxiv},\n",
        "  pages={2024--06},\n",
        "  year={2024},\n",
        "  publisher={Cold Spring Harbor Laboratory}\n",
        "}\n",
        "```"
      ],
      "metadata": {
        "id": "sA_FHFqAY25r"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "*Disclaimer: This is a minimal working demonstration and the results may be inaccurate. Even though our models are trained on our curated dataset, which is the largest and most generalized publicly-available dataset for antibody-antigen binding affinity prediction to-date in the literature (to the best of our knowledge), it is still biased towards certain antigen variants such as HIV and SARS-CoV-2 due to their abundance in terms of number of data points in the dataset.*"
      ],
      "metadata": {
        "id": "VnvPPD74XZBK"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Run all the cells"
      ],
      "metadata": {
        "id": "3Yam7nw1w2vB"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "!pip install torchmetrics\n",
        "!pip install torch_geometric\n",
        "!pip install Biopandas\n",
        "!pip install Bio\n",
        "!pip install periodictable"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "id": "0LGtmIUycmB_",
        "outputId": "2d00a0bd-9a18-4f2f-9b5d-5d4cd2dd481d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Collecting torchmetrics\n",
            "  Downloading torchmetrics-1.4.0.post0-py3-none-any.whl (868 kB)\n",
            "\u001b[?25l     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/868.8 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K     \u001b[91m━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m81.9/868.8 kB\u001b[0m \u001b[31m2.5 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K     \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━\u001b[0m \u001b[32m645.1/868.8 kB\u001b[0m \u001b[31m9.8 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m868.8/868.8 kB\u001b[0m \u001b[31m9.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: numpy>1.20.0 in /usr/local/lib/python3.10/dist-packages (from torchmetrics) (1.25.2)\n",
            "Requirement already satisfied: packaging>17.1 in /usr/local/lib/python3.10/dist-packages (from torchmetrics) (24.1)\n",
            "Requirement already satisfied: torch>=1.10.0 in /usr/local/lib/python3.10/dist-packages (from torchmetrics) (2.3.0+cu121)\n",
            "Collecting lightning-utilities>=0.8.0 (from torchmetrics)\n",
            "  Downloading lightning_utilities-0.11.2-py3-none-any.whl (26 kB)\n",
            "Requirement already satisfied: setuptools in /usr/local/lib/python3.10/dist-packages (from lightning-utilities>=0.8.0->torchmetrics) (67.7.2)\n",
            "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.10/dist-packages (from lightning-utilities>=0.8.0->torchmetrics) (4.12.2)\n",
            "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->torchmetrics) (3.14.0)\n",
            "Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->torchmetrics) (1.12.1)\n",
            "Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->torchmetrics) (3.3)\n",
            "Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->torchmetrics) (3.1.4)\n",
            "Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->torchmetrics) (2023.6.0)\n",
            "Collecting nvidia-cuda-nvrtc-cu12==12.1.105 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_cuda_nvrtc_cu12-12.1.105-py3-none-manylinux1_x86_64.whl (23.7 MB)\n",
            "Collecting nvidia-cuda-runtime-cu12==12.1.105 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_cuda_runtime_cu12-12.1.105-py3-none-manylinux1_x86_64.whl (823 kB)\n",
            "Collecting nvidia-cuda-cupti-cu12==12.1.105 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_cuda_cupti_cu12-12.1.105-py3-none-manylinux1_x86_64.whl (14.1 MB)\n",
            "Collecting nvidia-cudnn-cu12==8.9.2.26 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_cudnn_cu12-8.9.2.26-py3-none-manylinux1_x86_64.whl (731.7 MB)\n",
            "Collecting nvidia-cublas-cu12==12.1.3.1 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_cublas_cu12-12.1.3.1-py3-none-manylinux1_x86_64.whl (410.6 MB)\n",
            "Collecting nvidia-cufft-cu12==11.0.2.54 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_cufft_cu12-11.0.2.54-py3-none-manylinux1_x86_64.whl (121.6 MB)\n",
            "Collecting nvidia-curand-cu12==10.3.2.106 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_curand_cu12-10.3.2.106-py3-none-manylinux1_x86_64.whl (56.5 MB)\n",
            "Collecting nvidia-cusolver-cu12==11.4.5.107 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_cusolver_cu12-11.4.5.107-py3-none-manylinux1_x86_64.whl (124.2 MB)\n",
            "Collecting nvidia-cusparse-cu12==12.1.0.106 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_cusparse_cu12-12.1.0.106-py3-none-manylinux1_x86_64.whl (196.0 MB)\n",
            "Collecting nvidia-nccl-cu12==2.20.5 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_nccl_cu12-2.20.5-py3-none-manylinux2014_x86_64.whl (176.2 MB)\n",
            "Collecting nvidia-nvtx-cu12==12.1.105 (from torch>=1.10.0->torchmetrics)\n",
            "  Using cached nvidia_nvtx_cu12-12.1.105-py3-none-manylinux1_x86_64.whl (99 kB)\n",
            "Requirement already satisfied: triton==2.3.0 in /usr/local/lib/python3.10/dist-packages (from torch>=1.10.0->torchmetrics) (2.3.0)\n",
            "Collecting nvidia-nvjitlink-cu12 (from nvidia-cusolver-cu12==11.4.5.107->torch>=1.10.0->torchmetrics)\n",
            "  Downloading nvidia_nvjitlink_cu12-12.5.40-py3-none-manylinux2014_x86_64.whl (21.3 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m21.3/21.3 MB\u001b[0m \u001b[31m46.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch>=1.10.0->torchmetrics) (2.1.5)\n",
            "Requirement already satisfied: mpmath<1.4.0,>=1.1.0 in /usr/local/lib/python3.10/dist-packages (from sympy->torch>=1.10.0->torchmetrics) (1.3.0)\n",
            "Installing collected packages: nvidia-nvtx-cu12, nvidia-nvjitlink-cu12, nvidia-nccl-cu12, nvidia-curand-cu12, nvidia-cufft-cu12, nvidia-cuda-runtime-cu12, nvidia-cuda-nvrtc-cu12, nvidia-cuda-cupti-cu12, nvidia-cublas-cu12, lightning-utilities, nvidia-cusparse-cu12, nvidia-cudnn-cu12, nvidia-cusolver-cu12, torchmetrics\n",
            "Successfully installed lightning-utilities-0.11.2 nvidia-cublas-cu12-12.1.3.1 nvidia-cuda-cupti-cu12-12.1.105 nvidia-cuda-nvrtc-cu12-12.1.105 nvidia-cuda-runtime-cu12-12.1.105 nvidia-cudnn-cu12-8.9.2.26 nvidia-cufft-cu12-11.0.2.54 nvidia-curand-cu12-10.3.2.106 nvidia-cusolver-cu12-11.4.5.107 nvidia-cusparse-cu12-12.1.0.106 nvidia-nccl-cu12-2.20.5 nvidia-nvjitlink-cu12-12.5.40 nvidia-nvtx-cu12-12.1.105 torchmetrics-1.4.0.post0\n",
            "Collecting torch_geometric\n",
            "  Downloading torch_geometric-2.5.3-py3-none-any.whl (1.1 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.1/1.1 MB\u001b[0m \u001b[31m25.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (4.66.4)\n",
            "Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (1.25.2)\n",
            "Requirement already satisfied: scipy in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (1.11.4)\n",
            "Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (2023.6.0)\n",
            "Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (3.1.4)\n",
            "Requirement already satisfied: aiohttp in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (3.9.5)\n",
            "Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (2.31.0)\n",
            "Requirement already satisfied: pyparsing in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (3.1.2)\n",
            "Requirement already satisfied: scikit-learn in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (1.2.2)\n",
            "Requirement already satisfied: psutil>=5.8.0 in /usr/local/lib/python3.10/dist-packages (from torch_geometric) (5.9.5)\n",
            "Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.10/dist-packages (from aiohttp->torch_geometric) (1.3.1)\n",
            "Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->torch_geometric) (23.2.0)\n",
            "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from aiohttp->torch_geometric) (1.4.1)\n",
            "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.10/dist-packages (from aiohttp->torch_geometric) (6.0.5)\n",
            "Requirement already satisfied: yarl<2.0,>=1.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->torch_geometric) (1.9.4)\n",
            "Requirement already satisfied: async-timeout<5.0,>=4.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->torch_geometric) (4.0.3)\n",
            "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch_geometric) (2.1.5)\n",
            "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->torch_geometric) (3.3.2)\n",
            "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->torch_geometric) (3.7)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->torch_geometric) (2.0.7)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->torch_geometric) (2024.6.2)\n",
            "Requirement already satisfied: joblib>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from scikit-learn->torch_geometric) (1.4.2)\n",
            "Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.10/dist-packages (from scikit-learn->torch_geometric) (3.5.0)\n",
            "Installing collected packages: torch_geometric\n",
            "Successfully installed torch_geometric-2.5.3\n",
            "Collecting Biopandas\n",
            "  Downloading biopandas-0.4.1-py2.py3-none-any.whl (878 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m879.0/879.0 kB\u001b[0m \u001b[31m18.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: numpy>=1.16.2 in /usr/local/lib/python3.10/dist-packages (from Biopandas) (1.25.2)\n",
            "Requirement already satisfied: pandas>=0.24.2 in /usr/local/lib/python3.10/dist-packages (from Biopandas) (2.0.3)\n",
            "Requirement already satisfied: setuptools in /usr/local/lib/python3.10/dist-packages (from Biopandas) (67.7.2)\n",
            "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.10/dist-packages (from pandas>=0.24.2->Biopandas) (2.8.2)\n",
            "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.10/dist-packages (from pandas>=0.24.2->Biopandas) (2023.4)\n",
            "Requirement already satisfied: tzdata>=2022.1 in /usr/local/lib/python3.10/dist-packages (from pandas>=0.24.2->Biopandas) (2024.1)\n",
            "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.8.2->pandas>=0.24.2->Biopandas) (1.16.0)\n",
            "Installing collected packages: Biopandas\n",
            "Successfully installed Biopandas-0.4.1\n",
            "Collecting Bio\n",
            "  Downloading bio-1.7.1-py3-none-any.whl (280 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m281.0/281.0 kB\u001b[0m \u001b[31m8.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting biopython>=1.80 (from Bio)\n",
            "  Downloading biopython-1.83-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.1 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.1/3.1 MB\u001b[0m \u001b[31m84.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting gprofiler-official (from Bio)\n",
            "  Downloading gprofiler_official-1.0.0-py3-none-any.whl (9.3 kB)\n",
            "Collecting mygene (from Bio)\n",
            "  Downloading mygene-3.2.2-py2.py3-none-any.whl (5.4 kB)\n",
            "Requirement already satisfied: pandas in /usr/local/lib/python3.10/dist-packages (from Bio) (2.0.3)\n",
            "Requirement already satisfied: pooch in /usr/local/lib/python3.10/dist-packages (from Bio) (1.8.2)\n",
            "Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from Bio) (2.31.0)\n",
            "Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from Bio) (4.66.4)\n",
            "Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from biopython>=1.80->Bio) (1.25.2)\n",
            "Collecting biothings-client>=0.2.6 (from mygene->Bio)\n",
            "  Downloading biothings_client-0.3.1-py2.py3-none-any.whl (29 kB)\n",
            "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.10/dist-packages (from pandas->Bio) (2.8.2)\n",
            "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.10/dist-packages (from pandas->Bio) (2023.4)\n",
            "Requirement already satisfied: tzdata>=2022.1 in /usr/local/lib/python3.10/dist-packages (from pandas->Bio) (2024.1)\n",
            "Requirement already satisfied: platformdirs>=2.5.0 in /usr/local/lib/python3.10/dist-packages (from pooch->Bio) (4.2.2)\n",
            "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from pooch->Bio) (24.1)\n",
            "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->Bio) (3.3.2)\n",
            "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->Bio) (3.7)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->Bio) (2.0.7)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->Bio) (2024.6.2)\n",
            "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.8.2->pandas->Bio) (1.16.0)\n",
            "Installing collected packages: biopython, gprofiler-official, biothings-client, mygene, Bio\n",
            "Successfully installed Bio-1.7.1 biopython-1.83 biothings-client-0.3.1 gprofiler-official-1.0.0 mygene-3.2.2\n",
            "Collecting periodictable\n",
            "  Downloading periodictable-1.7.0.tar.gz (1.0 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.0/1.0 MB\u001b[0m \u001b[31m21.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "Requirement already satisfied: pyparsing in /usr/local/lib/python3.10/dist-packages (from periodictable) (3.1.2)\n",
            "Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from periodictable) (1.25.2)\n",
            "Building wheels for collected packages: periodictable\n",
            "  Building wheel for periodictable (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "  Created wheel for periodictable: filename=periodictable-1.7.0-py3-none-any.whl size=752513 sha256=1eb56758363adbb2061156246a94af1e3606f299807b00cce152f7027d875432\n",
            "  Stored in directory: /root/.cache/pip/wheels/7e/19/a2/fef5d0ca2b1ad2b199e863a6e796ad9d5efc86563d80c91a0c\n",
            "Successfully built periodictable\n",
            "Installing collected packages: periodictable\n",
            "Successfully installed periodictable-1.7.0\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "import pandas as pd\n",
        "import numpy as np\n",
        "from tqdm import tqdm\n",
        "import math\n",
        "\n",
        "import torch\n",
        "import torch.nn as nn\n",
        "from torch.optim import AdamW\n",
        "from torch import Tensor\n",
        "import torch.nn.functional as F\n",
        "from torch.nn import Parameter\n",
        "from torch.nn import Sequential, Linear, ReLU, MultiheadAttention, Dropout, LayerNorm, AvgPool1d\n",
        "from torchmetrics.functional import mean_absolute_error\n",
        "import torch.optim as optim\n",
        "from torch.utils.data import Dataset, DataLoader\n",
        "from torch.optim.lr_scheduler import LambdaLR\n",
        "from tqdm import tqdm\n",
        "\n",
        "from torch.nn.init import zeros_,xavier_normal_\n",
        "\n",
        "import os\n",
        "\n",
        "import networkx as nx\n",
        "import torch_geometric.data as Data\n",
        "from torch_geometric.loader import DataLoader\n",
        "from torch_geometric.nn import GCNConv, global_mean_pool, GATConv\n",
        "from torch_geometric.transforms import NormalizeScale\n",
        "from torch_geometric.data import Batch\n",
        "from torchmetrics.functional import mean_absolute_error\n",
        "from torch.utils.data import random_split\n",
        "\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "from biopandas.pdb import PandasPdb\n",
        "import periodictable\n",
        "from Bio import SeqIO\n",
        "from Bio.PDB import PDBParser\n",
        "from Bio.SeqUtils import seq1\n",
        "\n",
        "from sklearn.model_selection import train_test_split\n",
        "\n",
        "import warnings\n",
        "warnings.filterwarnings(\"ignore\")\n",
        "\n",
        "import logging, sys"
      ],
      "metadata": {
        "cellView": "form",
        "id": "z72fVm0ybIX5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Note**\n",
        "\n",
        "Here, input the **.pdb** files for both antibody and antigen. *Note that the current maximum FASTA sequence lengths for antibody and antigen are 669 and 3102 respectively.*\n",
        "\n",
        "Example PDB files for an antibody-antigen pair can be found at https://github.com/Drug-Discovery-ENTC/p2pxml/tree/main/data"
      ],
      "metadata": {
        "id": "Yyu_GMViwOen"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "from google.colab import files\n",
        "import os\n",
        "import shutil\n",
        "import pandas as pd\n",
        "\n",
        "os.makedirs(\"antibodies\", exist_ok=True)\n",
        "os.makedirs(\"antigens\", exist_ok=True)\n",
        "os.makedirs(\"graph_data\", exist_ok = True)\n",
        "\n",
        "print(\"Please upload the antibody .pdb file.\")\n",
        "uploaded_antibody = files.upload()\n",
        "\n",
        "print(\" \")\n",
        "print(\"Please upload the antigen .pdb file.\")\n",
        "uploaded_antigen = files.upload()\n",
        "\n",
        "uploaded = {**uploaded_antibody, **uploaded_antigen}\n",
        "\n",
        "if len(uploaded) != 2:\n",
        "    print(\"Error: Please upload exactly two .pdb files.\")\n",
        "else:\n",
        "    pdb_files = [filename for filename in uploaded.keys() if filename.endswith('.pdb')]\n",
        "\n",
        "    if len(pdb_files) != 2:\n",
        "        print(\"Error: Please upload exactly two .pdb files.\")\n",
        "    else:\n",
        "        antibody_name = os.path.splitext(pdb_files[0])[0]\n",
        "        antigen_name = os.path.splitext(pdb_files[1])[0]\n",
        "\n",
        "        test_df = pd.DataFrame({\n",
        "            \"Ab\": [antibody_name],\n",
        "            \"Ag\": [antigen_name],\n",
        "            \"log(IC50)\": 0.0\n",
        "        })\n",
        "\n",
        "        shutil.move(pdb_files[0], os.path.join(\"antibodies\", pdb_files[0]))\n",
        "        shutil.move(pdb_files[1], os.path.join(\"antigens\", pdb_files[1]))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 184
        },
        "cellView": "form",
        "id": "vJY-76IGngwE",
        "outputId": "6da824c5-99a0-462c-cc6f-0f54752321c8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Please upload the antibody .pdb file.\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ],
            "text/html": [
              "\n",
              "     <input type=\"file\" id=\"files-726cd675-eace-48d3-a066-db99c7b38db1\" name=\"files[]\" multiple disabled\n",
              "        style=\"border:none\" />\n",
              "     <output id=\"result-726cd675-eace-48d3-a066-db99c7b38db1\">\n",
              "      Upload widget is only available when the cell has been executed in the\n",
              "      current browser session. Please rerun this cell to enable.\n",
              "      </output>\n",
              "      <script>// Copyright 2017 Google LLC\n",
              "//\n",
              "// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
              "// you may not use this file except in compliance with the License.\n",
              "// You may obtain a copy of the License at\n",
              "//\n",
              "//      http://www.apache.org/licenses/LICENSE-2.0\n",
              "//\n",
              "// Unless required by applicable law or agreed to in writing, software\n",
              "// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
              "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
              "// See the License for the specific language governing permissions and\n",
              "// limitations under the License.\n",
              "\n",
              "/**\n",
              " * @fileoverview Helpers for google.colab Python module.\n",
              " */\n",
              "(function(scope) {\n",
              "function span(text, styleAttributes = {}) {\n",
              "  const element = document.createElement('span');\n",
              "  element.textContent = text;\n",
              "  for (const key of Object.keys(styleAttributes)) {\n",
              "    element.style[key] = styleAttributes[key];\n",
              "  }\n",
              "  return element;\n",
              "}\n",
              "\n",
              "// Max number of bytes which will be uploaded at a time.\n",
              "const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
              "\n",
              "function _uploadFiles(inputId, outputId) {\n",
              "  const steps = uploadFilesStep(inputId, outputId);\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  // Cache steps on the outputElement to make it available for the next call\n",
              "  // to uploadFilesContinue from Python.\n",
              "  outputElement.steps = steps;\n",
              "\n",
              "  return _uploadFilesContinue(outputId);\n",
              "}\n",
              "\n",
              "// This is roughly an async generator (not supported in the browser yet),\n",
              "// where there are multiple asynchronous steps and the Python side is going\n",
              "// to poll for completion of each step.\n",
              "// This uses a Promise to block the python side on completion of each step,\n",
              "// then passes the result of the previous step as the input to the next step.\n",
              "function _uploadFilesContinue(outputId) {\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  const steps = outputElement.steps;\n",
              "\n",
              "  const next = steps.next(outputElement.lastPromiseValue);\n",
              "  return Promise.resolve(next.value.promise).then((value) => {\n",
              "    // Cache the last promise value to make it available to the next\n",
              "    // step of the generator.\n",
              "    outputElement.lastPromiseValue = value;\n",
              "    return next.value.response;\n",
              "  });\n",
              "}\n",
              "\n",
              "/**\n",
              " * Generator function which is called between each async step of the upload\n",
              " * process.\n",
              " * @param {string} inputId Element ID of the input file picker element.\n",
              " * @param {string} outputId Element ID of the output display.\n",
              " * @return {!Iterable<!Object>} Iterable of next steps.\n",
              " */\n",
              "function* uploadFilesStep(inputId, outputId) {\n",
              "  const inputElement = document.getElementById(inputId);\n",
              "  inputElement.disabled = false;\n",
              "\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  outputElement.innerHTML = '';\n",
              "\n",
              "  const pickedPromise = new Promise((resolve) => {\n",
              "    inputElement.addEventListener('change', (e) => {\n",
              "      resolve(e.target.files);\n",
              "    });\n",
              "  });\n",
              "\n",
              "  const cancel = document.createElement('button');\n",
              "  inputElement.parentElement.appendChild(cancel);\n",
              "  cancel.textContent = 'Cancel upload';\n",
              "  const cancelPromise = new Promise((resolve) => {\n",
              "    cancel.onclick = () => {\n",
              "      resolve(null);\n",
              "    };\n",
              "  });\n",
              "\n",
              "  // Wait for the user to pick the files.\n",
              "  const files = yield {\n",
              "    promise: Promise.race([pickedPromise, cancelPromise]),\n",
              "    response: {\n",
              "      action: 'starting',\n",
              "    }\n",
              "  };\n",
              "\n",
              "  cancel.remove();\n",
              "\n",
              "  // Disable the input element since further picks are not allowed.\n",
              "  inputElement.disabled = true;\n",
              "\n",
              "  if (!files) {\n",
              "    return {\n",
              "      response: {\n",
              "        action: 'complete',\n",
              "      }\n",
              "    };\n",
              "  }\n",
              "\n",
              "  for (const file of files) {\n",
              "    const li = document.createElement('li');\n",
              "    li.append(span(file.name, {fontWeight: 'bold'}));\n",
              "    li.append(span(\n",
              "        `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
              "        `last modified: ${\n",
              "            file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
              "                                    'n/a'} - `));\n",
              "    const percent = span('0% done');\n",
              "    li.appendChild(percent);\n",
              "\n",
              "    outputElement.appendChild(li);\n",
              "\n",
              "    const fileDataPromise = new Promise((resolve) => {\n",
              "      const reader = new FileReader();\n",
              "      reader.onload = (e) => {\n",
              "        resolve(e.target.result);\n",
              "      };\n",
              "      reader.readAsArrayBuffer(file);\n",
              "    });\n",
              "    // Wait for the data to be ready.\n",
              "    let fileData = yield {\n",
              "      promise: fileDataPromise,\n",
              "      response: {\n",
              "        action: 'continue',\n",
              "      }\n",
              "    };\n",
              "\n",
              "    // Use a chunked sending to avoid message size limits. See b/62115660.\n",
              "    let position = 0;\n",
              "    do {\n",
              "      const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
              "      const chunk = new Uint8Array(fileData, position, length);\n",
              "      position += length;\n",
              "\n",
              "      const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
              "      yield {\n",
              "        response: {\n",
              "          action: 'append',\n",
              "          file: file.name,\n",
              "          data: base64,\n",
              "        },\n",
              "      };\n",
              "\n",
              "      let percentDone = fileData.byteLength === 0 ?\n",
              "          100 :\n",
              "          Math.round((position / fileData.byteLength) * 100);\n",
              "      percent.textContent = `${percentDone}% done`;\n",
              "\n",
              "    } while (position < fileData.byteLength);\n",
              "  }\n",
              "\n",
              "  // All done.\n",
              "  yield {\n",
              "    response: {\n",
              "      action: 'complete',\n",
              "    }\n",
              "  };\n",
              "}\n",
              "\n",
              "scope.google = scope.google || {};\n",
              "scope.google.colab = scope.google.colab || {};\n",
              "scope.google.colab._files = {\n",
              "  _uploadFiles,\n",
              "  _uploadFilesContinue,\n",
              "};\n",
              "})(self);\n",
              "</script> "
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Saving 0.5γ.pdb to 0.5γ.pdb\n",
            " \n",
            "Please upload the antigen .pdb file.\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ],
            "text/html": [
              "\n",
              "     <input type=\"file\" id=\"files-dbe4ccc2-7c30-42c9-9d5c-74425ea6f0f7\" name=\"files[]\" multiple disabled\n",
              "        style=\"border:none\" />\n",
              "     <output id=\"result-dbe4ccc2-7c30-42c9-9d5c-74425ea6f0f7\">\n",
              "      Upload widget is only available when the cell has been executed in the\n",
              "      current browser session. Please rerun this cell to enable.\n",
              "      </output>\n",
              "      <script>// Copyright 2017 Google LLC\n",
              "//\n",
              "// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
              "// you may not use this file except in compliance with the License.\n",
              "// You may obtain a copy of the License at\n",
              "//\n",
              "//      http://www.apache.org/licenses/LICENSE-2.0\n",
              "//\n",
              "// Unless required by applicable law or agreed to in writing, software\n",
              "// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
              "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
              "// See the License for the specific language governing permissions and\n",
              "// limitations under the License.\n",
              "\n",
              "/**\n",
              " * @fileoverview Helpers for google.colab Python module.\n",
              " */\n",
              "(function(scope) {\n",
              "function span(text, styleAttributes = {}) {\n",
              "  const element = document.createElement('span');\n",
              "  element.textContent = text;\n",
              "  for (const key of Object.keys(styleAttributes)) {\n",
              "    element.style[key] = styleAttributes[key];\n",
              "  }\n",
              "  return element;\n",
              "}\n",
              "\n",
              "// Max number of bytes which will be uploaded at a time.\n",
              "const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
              "\n",
              "function _uploadFiles(inputId, outputId) {\n",
              "  const steps = uploadFilesStep(inputId, outputId);\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  // Cache steps on the outputElement to make it available for the next call\n",
              "  // to uploadFilesContinue from Python.\n",
              "  outputElement.steps = steps;\n",
              "\n",
              "  return _uploadFilesContinue(outputId);\n",
              "}\n",
              "\n",
              "// This is roughly an async generator (not supported in the browser yet),\n",
              "// where there are multiple asynchronous steps and the Python side is going\n",
              "// to poll for completion of each step.\n",
              "// This uses a Promise to block the python side on completion of each step,\n",
              "// then passes the result of the previous step as the input to the next step.\n",
              "function _uploadFilesContinue(outputId) {\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  const steps = outputElement.steps;\n",
              "\n",
              "  const next = steps.next(outputElement.lastPromiseValue);\n",
              "  return Promise.resolve(next.value.promise).then((value) => {\n",
              "    // Cache the last promise value to make it available to the next\n",
              "    // step of the generator.\n",
              "    outputElement.lastPromiseValue = value;\n",
              "    return next.value.response;\n",
              "  });\n",
              "}\n",
              "\n",
              "/**\n",
              " * Generator function which is called between each async step of the upload\n",
              " * process.\n",
              " * @param {string} inputId Element ID of the input file picker element.\n",
              " * @param {string} outputId Element ID of the output display.\n",
              " * @return {!Iterable<!Object>} Iterable of next steps.\n",
              " */\n",
              "function* uploadFilesStep(inputId, outputId) {\n",
              "  const inputElement = document.getElementById(inputId);\n",
              "  inputElement.disabled = false;\n",
              "\n",
              "  const outputElement = document.getElementById(outputId);\n",
              "  outputElement.innerHTML = '';\n",
              "\n",
              "  const pickedPromise = new Promise((resolve) => {\n",
              "    inputElement.addEventListener('change', (e) => {\n",
              "      resolve(e.target.files);\n",
              "    });\n",
              "  });\n",
              "\n",
              "  const cancel = document.createElement('button');\n",
              "  inputElement.parentElement.appendChild(cancel);\n",
              "  cancel.textContent = 'Cancel upload';\n",
              "  const cancelPromise = new Promise((resolve) => {\n",
              "    cancel.onclick = () => {\n",
              "      resolve(null);\n",
              "    };\n",
              "  });\n",
              "\n",
              "  // Wait for the user to pick the files.\n",
              "  const files = yield {\n",
              "    promise: Promise.race([pickedPromise, cancelPromise]),\n",
              "    response: {\n",
              "      action: 'starting',\n",
              "    }\n",
              "  };\n",
              "\n",
              "  cancel.remove();\n",
              "\n",
              "  // Disable the input element since further picks are not allowed.\n",
              "  inputElement.disabled = true;\n",
              "\n",
              "  if (!files) {\n",
              "    return {\n",
              "      response: {\n",
              "        action: 'complete',\n",
              "      }\n",
              "    };\n",
              "  }\n",
              "\n",
              "  for (const file of files) {\n",
              "    const li = document.createElement('li');\n",
              "    li.append(span(file.name, {fontWeight: 'bold'}));\n",
              "    li.append(span(\n",
              "        `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
              "        `last modified: ${\n",
              "            file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
              "                                    'n/a'} - `));\n",
              "    const percent = span('0% done');\n",
              "    li.appendChild(percent);\n",
              "\n",
              "    outputElement.appendChild(li);\n",
              "\n",
              "    const fileDataPromise = new Promise((resolve) => {\n",
              "      const reader = new FileReader();\n",
              "      reader.onload = (e) => {\n",
              "        resolve(e.target.result);\n",
              "      };\n",
              "      reader.readAsArrayBuffer(file);\n",
              "    });\n",
              "    // Wait for the data to be ready.\n",
              "    let fileData = yield {\n",
              "      promise: fileDataPromise,\n",
              "      response: {\n",
              "        action: 'continue',\n",
              "      }\n",
              "    };\n",
              "\n",
              "    // Use a chunked sending to avoid message size limits. See b/62115660.\n",
              "    let position = 0;\n",
              "    do {\n",
              "      const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
              "      const chunk = new Uint8Array(fileData, position, length);\n",
              "      position += length;\n",
              "\n",
              "      const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
              "      yield {\n",
              "        response: {\n",
              "          action: 'append',\n",
              "          file: file.name,\n",
              "          data: base64,\n",
              "        },\n",
              "      };\n",
              "\n",
              "      let percentDone = fileData.byteLength === 0 ?\n",
              "          100 :\n",
              "          Math.round((position / fileData.byteLength) * 100);\n",
              "      percent.textContent = `${percentDone}% done`;\n",
              "\n",
              "    } while (position < fileData.byteLength);\n",
              "  }\n",
              "\n",
              "  // All done.\n",
              "  yield {\n",
              "    response: {\n",
              "      action: 'complete',\n",
              "    }\n",
              "  };\n",
              "}\n",
              "\n",
              "scope.google = scope.google || {};\n",
              "scope.google.colab = scope.google.colab || {};\n",
              "scope.google.colab._files = {\n",
              "  _uploadFiles,\n",
              "  _uploadFilesContinue,\n",
              "};\n",
              "})(self);\n",
              "</script> "
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Saving AC10_29.pdb to AC10_29.pdb\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "kigJrq_0XkxU"
      },
      "outputs": [],
      "source": [
        "# @title\n",
        "max_antibody_sequence_length = 669\n",
        "max_antigen_sequence_length = 3102\n",
        "\n",
        "class ProteinDataset(Dataset):\n",
        "    def __init__(self, df, max_antibody_sequence_length, max_antigen_sequence_length, save_dir='/content/graph_data'):\n",
        "        self.sequences = df['Ab'].values\n",
        "        self.viruses = df['Ag'].values\n",
        "        self.labels = df['log(IC50)'].values\n",
        "        self.max_antibody_sequence_length = max_antibody_sequence_length\n",
        "        self.max_antigen_sequence_length = max_antigen_sequence_length\n",
        "        self.save_dir = save_dir\n",
        "        os.makedirs(save_dir, exist_ok=True)\n",
        "\n",
        "    def __len__(self):\n",
        "        return len(self.sequences)\n",
        "\n",
        "    def __getitem__(self, idx):\n",
        "        sequence = self.sequences[idx]\n",
        "        virus = self.viruses[idx]\n",
        "        label = self.labels[idx]\n",
        "        label = torch.tensor(label, dtype=torch.float64)\n",
        "\n",
        "        antibody = self.load_or_generate_graph(sequence, self.max_antibody_sequence_length, 'antibodies')\n",
        "        antigen = self.load_or_generate_graph(virus, self.max_antigen_sequence_length, 'antigens')\n",
        "\n",
        "        if antibody is not None and antigen is not None:\n",
        "            return antibody, antigen, label\n",
        "        else:\n",
        "            return self.__getitem__((idx + 1) % len(self))  # Ensure idx is within bounds\n",
        "\n",
        "    def load_or_generate_graph(self, pdb_file, max_sequence_length, graph_type):\n",
        "        graph_path = os.path.join(self.save_dir, f'{graph_type}_{pdb_file}.pt')\n",
        "\n",
        "        if os.path.exists(graph_path):\n",
        "            return torch.load(graph_path)\n",
        "\n",
        "        if graph_type == 'antigens':\n",
        "            graph_constructed = self.pdb_to_graph_virus(pdb_file, max_sequence_length)\n",
        "        else:\n",
        "            graph_constructed = self.pdb_to_graph_antibody(pdb_file, max_sequence_length)\n",
        "\n",
        "        if graph_constructed is not None:\n",
        "            torch.save(graph_constructed, graph_path)\n",
        "        return graph_constructed\n",
        "\n",
        "    def pdb_to_graph_virus(self, pdb_file, max_antigen_sequence_length):\n",
        "        return self.pdb_to_graph(pdb_file, max_antigen_sequence_length, 'antigens')\n",
        "\n",
        "    def pdb_to_graph_antibody(self, pdb_file, max_antibody_sequence_length):\n",
        "        return self.pdb_to_graph(pdb_file, max_antibody_sequence_length, 'antibodies')\n",
        "\n",
        "    def pdb_to_graph(self, pdb_file, max_sequence_length, graph_type):\n",
        "        seq_length = max_sequence_length\n",
        "        amino_acids = list(\"ACDEFGHIKLMNPQRSTVWY\")\n",
        "        aa_to_index = {aa: i for i, aa in enumerate(amino_acids)}\n",
        "        pdbparser = PDBParser()\n",
        "\n",
        "        try:\n",
        "            structure = pdbparser.get_structure(pdb_file, os.path.join(f'/content/{graph_type}/'+pdb_file+'.pdb'))\n",
        "            chains = {chain.id: seq1(''.join(residue.resname for residue in chain)) for chain in structure.get_chains()}\n",
        "            full_sequence = ''\n",
        "            for value in chains.values():\n",
        "                full_sequence += value\n",
        "            full_sequence = full_sequence.replace(\"X\", \"\")\n",
        "\n",
        "            if len(full_sequence) > seq_length:\n",
        "                print(f\"Exceeds max length {graph_type}\")\n",
        "                return None\n",
        "\n",
        "            indices = [aa_to_index[aa] for aa in full_sequence]\n",
        "            encoded = F.one_hot(torch.tensor(indices), num_classes=len(amino_acids)).float()\n",
        "            padded_encoded = F.pad(encoded.flatten(), (0, max(seq_length * len(amino_acids) - encoded.flatten().shape[0], 0)))\n",
        "\n",
        "            ppdb = PandasPdb()\n",
        "            ppdb.read_pdb(os.path.join(f'/content/{graph_type}/'+pdb_file+'.pdb'))\n",
        "            coords = ppdb.df['ATOM'][['x_coord', 'y_coord', 'z_coord']].values\n",
        "            atomic_nums = ppdb.df['ATOM']['element_symbol'].apply(lambda symbol: periodictable.elements.symbol(symbol).number).values\n",
        "\n",
        "            graph = nx.Graph()\n",
        "            num_atoms = len(coords)\n",
        "            for i in range(num_atoms):\n",
        "                graph.add_node(i, x=coords[i][0], y=coords[i][1], z=coords[i][2], atomic_number=atomic_nums[i])\n",
        "            for i in range(num_atoms):\n",
        "                for j in range(i + 1, num_atoms):\n",
        "                    dist = ((coords[i] - coords[j]) ** 2).sum() ** 0.5\n",
        "                    if dist < 5:\n",
        "                        bond_strength = 1 / dist\n",
        "                        graph.add_edge(i, j, distance=dist, bond_strength=bond_strength)\n",
        "\n",
        "            edge_attrs = {}\n",
        "\n",
        "            for u, v, data in graph.edges(data=True):\n",
        "                edge_attrs[(u, v)] = [data['distance'], data['bond_strength']]\n",
        "                edge_attrs[(v, u)] = [data['distance'], data['bond_strength']]\n",
        "\n",
        "            data = Data.Data(\n",
        "                x=torch.tensor(list(nx.get_node_attributes(graph, 'x').values())).to(torch.float64),\n",
        "                y_coord=torch.tensor(list(nx.get_node_attributes(graph, 'y').values())).to(torch.float64),\n",
        "                z_coord=torch.tensor(list(nx.get_node_attributes(graph, 'z').values())).to(torch.float64),\n",
        "                pos=torch.tensor(coords).to(torch.float64),\n",
        "                edge_index=torch.tensor(list(graph.edges)).to(torch.float64).t().contiguous(),\n",
        "                edge_attr=torch.tensor([edge_attrs[e] for e in graph.edges()]).to(torch.float64),\n",
        "                z=torch.tensor(list(nx.get_node_attributes(graph, 'atomic_number').values())).to(torch.float64),\n",
        "                seq=padded_encoded.to(torch.float64),\n",
        "                y = torch.tensor([0.0]).to(torch.float64)\n",
        "            )\n",
        "            return data\n",
        "\n",
        "        except Exception as e:\n",
        "            print(e)\n",
        "            return None\n",
        "\n",
        "test_ds = ProteinDataset(test_df, max_antibody_sequence_length, max_antigen_sequence_length)\n",
        "test_loader = DataLoader(test_ds, batch_size=1, shuffle=False)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "class SelfAttention(nn.Module):\n",
        "    def __init__(self, embed_dim, num_heads=16):\n",
        "        super(SelfAttention, self).__init__()\n",
        "        self.embed_dim = embed_dim\n",
        "        self.num_heads = num_heads\n",
        "        if embed_dim % num_heads != 0:\n",
        "            raise ValueError(f\"embedding dimension = {embed_dim} should be divisible by number of heads = {num_heads}\")\n",
        "        self.head_dim = embed_dim // num_heads\n",
        "        self.query_dense = nn.Linear(embed_dim, embed_dim)\n",
        "        self.key_dense = nn.Linear(embed_dim, embed_dim)\n",
        "        self.value_dense = nn.Linear(embed_dim, embed_dim)\n",
        "        self.combine_heads = nn.Linear(embed_dim, embed_dim)\n",
        "\n",
        "    def forward(self, inputs):\n",
        "        query = self.query_dense(inputs)\n",
        "        key = self.key_dense(inputs)\n",
        "        value = self.value_dense(inputs)\n",
        "        query = query.view(-1, self.num_heads, self.head_dim)\n",
        "        key = key.view(-1, self.num_heads, self.head_dim)\n",
        "        value = value.view(-1, self.num_heads, self.head_dim)\n",
        "        query = query.permute(1, 0, 2)\n",
        "        key = key.permute(1, 0, 2)\n",
        "        value = value.permute(1, 0, 2)\n",
        "        dot_product = torch.matmul(query, key.permute(0, 2, 1))\n",
        "        scaled_dot_product = dot_product / torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32))\n",
        "        attention_weights = torch.softmax(scaled_dot_product, dim=-1)\n",
        "        output = torch.matmul(attention_weights, value)\n",
        "        output = output.permute(1, 0, 2)\n",
        "        output = output.view(-1, self.embed_dim)\n",
        "        output = self.combine_heads(output)\n",
        "        return output\n",
        "\n",
        "class TransformerBlock(nn.Module):\n",
        "    def __init__(self, embed_dim, num_heads, dense_dim=1024, dropout_rate=0.1):\n",
        "        super(TransformerBlock, self).__init__()\n",
        "        self.attention = SelfAttention(embed_dim, num_heads)\n",
        "        self.dropout1 = nn.Dropout(dropout_rate)\n",
        "        self.norm1 = nn.LayerNorm(embed_dim, eps=1e-6)\n",
        "        self.dense1 = nn.Linear(embed_dim, dense_dim)\n",
        "        self.dropout2 = nn.Dropout(dropout_rate)\n",
        "        self.norm2 = nn.LayerNorm(embed_dim, eps=1e-6)\n",
        "        self.dense2 = nn.Linear(dense_dim, embed_dim)\n",
        "\n",
        "    def forward(self, inputs):\n",
        "        attention_output = self.attention(inputs)\n",
        "        attention_output = self.dropout1(attention_output)\n",
        "        output1 = self.norm1(inputs + attention_output)\n",
        "        dense_output = self.dense1(output1)\n",
        "        dense_output = self.dropout2(dense_output)\n",
        "        output2 = self.norm2(output1 + dense_output)\n",
        "        output = self.dense2(output2)\n",
        "        return output\n",
        "\n",
        "class CrossAttention(nn.Module):\n",
        "    def __init__(self, dim, input_shape):\n",
        "        super(CrossAttention, self).__init__()\n",
        "        self.dim = dim\n",
        "        self.input_shape = input_shape\n",
        "\n",
        "        self.Wq = nn.Parameter(torch.Tensor(input_shape[0][-1], self.dim))\n",
        "        self.Wk = nn.Parameter(torch.Tensor(input_shape[1][-1], self.dim))\n",
        "        self.Wv = nn.Parameter(torch.Tensor(input_shape[1][-1], self.dim))\n",
        "\n",
        "        nn.init.xavier_uniform_(self.Wq)\n",
        "        nn.init.xavier_uniform_(self.Wk)\n",
        "        nn.init.xavier_uniform_(self.Wv)\n",
        "\n",
        "    def forward(self, inputs):\n",
        "        x, y = inputs\n",
        "\n",
        "        Q = torch.matmul(x, self.Wq)\n",
        "        K = torch.matmul(y, self.Wk)\n",
        "        V = torch.matmul(y, self.Wv)\n",
        "\n",
        "        attn_weights = torch.matmul(Q, K.t()) / torch.sqrt(torch.tensor(self.dim, dtype=torch.float64))\n",
        "        attn_weights = F.softmax(attn_weights, dim=-1)\n",
        "        attn_output = attn_weights * V\n",
        "        output = torch.cat([x, attn_output], dim=-1)\n",
        "\n",
        "        return output\n",
        "\n",
        "class CombinedModel(nn.Module):\n",
        "    def __init__(self, hidden_channels=128, num_layers=16):\n",
        "        super(CombinedModel, self).__init__()\n",
        "\n",
        "        self.cross_attn_1 = CrossAttention(128, [(1024,),(1024,)])\n",
        "        self.cross_attn_2 = CrossAttention(128,[(1024,),(1024,)])\n",
        "        self.cross_attn = CrossAttention(128,[(1152,),(1152,)])\n",
        "        self.self_atten_1 = nn.AdaptiveAvgPool1d(1)\n",
        "        self.self_atten_2 = nn.AdaptiveAvgPool1d(1)\n",
        "        self.cross_pooling = nn.AdaptiveAvgPool1d(1)\n",
        "        self.dense = nn.Linear(1280, 256)\n",
        "        self.output_layer1 = nn.Linear(2816, 128)\n",
        "        self.output_layer = nn.Linear(128, 1)\n",
        "\n",
        "        self.input_1 = nn.Linear(input_shape_1[0], 1024)\n",
        "        self.self_attn_1 = SelfAttention(1024)\n",
        "        self.transformer_1 = TransformerBlock(1024, 4)\n",
        "        self.pooling_1 = nn.AdaptiveAvgPool1d(1)\n",
        "        self.dense_1 = nn.Linear(1024, 1024)\n",
        "        self.dropout_1 = nn.Dropout(p=0.05)\n",
        "\n",
        "        self.input_2 = nn.Linear(input_shape_2[0], 1024)\n",
        "        self.self_attn_2 = SelfAttention(1024)\n",
        "        self.transformer_2 = TransformerBlock(1024, 4)\n",
        "        self.pooling_2 = nn.AdaptiveAvgPool1d(1)\n",
        "        self.dense_2 = nn.Linear(1024, 1024)\n",
        "        self.dropout_2 = nn.Dropout(p=0.05)\n",
        "\n",
        "        self.num_layers = num_layers\n",
        "\n",
        "        self.convs1 = nn.ModuleList()\n",
        "        self.convs1.append(GCNConv(4, hidden_channels))\n",
        "        for _ in range(num_layers - 1):\n",
        "            self.convs1.append(GCNConv(hidden_channels, hidden_channels))\n",
        "\n",
        "        self.convs2 = nn.ModuleList()\n",
        "        self.convs2.append(GCNConv(4, hidden_channels))\n",
        "        for _ in range(num_layers - 1):\n",
        "            self.convs2.append(GCNConv(hidden_channels, hidden_channels))\n",
        "\n",
        "        self.cross_att = GATConv(hidden_channels, hidden_channels, heads=2)\n",
        "\n",
        "        self.lin1 = nn.Linear(2816, hidden_channels)\n",
        "        self.lin2 = nn.Linear(hidden_channels, 1)\n",
        "\n",
        "        self.transform = NormalizeScale()\n",
        "\n",
        "    def forward(self, data_batch_1, data_batch_2):\n",
        "        x1 = data_batch_1.x.double()\n",
        "        edge_index_1 = data_batch_1.edge_index\n",
        "        z1 = data_batch_1.z\n",
        "        y1_coord = data_batch_1.y_coord\n",
        "        z1_coord = data_batch_1.z_coord\n",
        "\n",
        "        concatenated_x1 = torch.stack([x1, z1, y1_coord, z1_coord], dim=1)\n",
        "\n",
        "        # Apply graph normalization\n",
        "        data_batch_1 = self.transform(data_batch_1)\n",
        "        x1 = data_batch_1.x\n",
        "\n",
        "        for i in range(self.num_layers):\n",
        "            concatenated_x1 = self.convs1[i](concatenated_x1, edge_index_1.to(torch.int64))\n",
        "            concatenated_x1 = F.relu(concatenated_x1.double())\n",
        "\n",
        "        # Process second graph\n",
        "        x2 = data_batch_2.x\n",
        "        edge_index_2 = data_batch_2.edge_index\n",
        "        z2 = data_batch_2.z\n",
        "        y2_coord = data_batch_2.y_coord\n",
        "        z2_coord = data_batch_2.z_coord\n",
        "\n",
        "        concatenated_x2 = torch.stack([x2, z2, y2_coord, z2_coord], dim=1)\n",
        "\n",
        "        # Apply graph normalization\n",
        "        data_batch_2 = self.transform(data_batch_2)\n",
        "        x2 = data_batch_2.x\n",
        "\n",
        "        for i in range(self.num_layers):\n",
        "            concatenated_x2 = self.convs2[i](concatenated_x2, edge_index_2.to(torch.int64))\n",
        "            concatenated_x2 = F.relu(concatenated_x2)\n",
        "\n",
        "        # Cross-attention block\n",
        "        x1 = self.cross_att(concatenated_x1, edge_index_1.to(torch.int64))\n",
        "        x2 = self.cross_att(concatenated_x2, edge_index_2.to(torch.int64))\n",
        "\n",
        "        # Concatenate all tensors along the last dimension\n",
        "        x = torch.cat([\n",
        "            global_mean_pool(x1, data_batch_1.batch),\n",
        "            global_mean_pool(x2, data_batch_2.batch)], dim=1)\n",
        "\n",
        "        input_11 = self.input_1(data_batch_1.seq)\n",
        "        self_attn_1 = self.self_attn_1(input_11)\n",
        "        transformer_1 = self.transformer_1(self_attn_1)\n",
        "        pooling_1 = self.pooling_1(transformer_1.transpose(0, 1)).squeeze(dim=1)\n",
        "        dense_1 = self.dense_1(pooling_1)\n",
        "        dropout_1 = self.dropout_1(dense_1)\n",
        "\n",
        "        input_22 = self.input_2(data_batch_2.seq)\n",
        "        self_attn_2 = self.self_attn_2(input_22)\n",
        "        transformer_2 = self.transformer_2(self_attn_2)\n",
        "        pooling_2 = self.pooling_2(transformer_2.transpose(0, 1)).squeeze(dim=1)\n",
        "        dense_2 = self.dense_2(pooling_2)\n",
        "        dropout_2 = self.dropout_2(dense_2)\n",
        "\n",
        "        input_shape = [(dropout_1.shape[-1],), (dropout_2.shape[-1],)]\n",
        "        cross_attn_1 = self.cross_attn_1([dropout_1, dropout_2])\n",
        "        cross_attn_2 = self.cross_attn_2([self.self_attn_1(input_11), self.self_attn_2(input_22)])\n",
        "        cross_pooling = self.cross_pooling(cross_attn_2.transpose(0, 1)).squeeze(dim=1)\n",
        "        cross_attn = self.cross_attn([cross_attn_1, cross_pooling])\n",
        "        cross_atten = F.tanh(self.dense(cross_attn))\n",
        "\n",
        "        self_atten_1 = self.self_atten_1(self_attn_1.transpose(0, 1)).squeeze(dim=1)\n",
        "        self_atten_2 = self.self_atten_2(self_attn_2.transpose(0, 1)).squeeze(dim=1)\n",
        "        attention_scores = torch.cat([self_atten_1, self_atten_2, cross_atten], dim=-1)\n",
        "\n",
        "        x_2 = torch.cat([self.pooling_2(x.transpose(0, 1)).squeeze(dim=1), attention_scores], dim = -1)\n",
        "\n",
        "        attention_scores = torch.cat([attention_scores, self.pooling_2(x.transpose(0, 1)).squeeze(dim=1)], dim = -1)\n",
        "\n",
        "        output_layer1 = F.tanh(self.output_layer1(attention_scores)) #transformer\n",
        "        output_layer = self.output_layer(output_layer1)\n",
        "\n",
        "        x = F.relu(self.lin1(x_2))\n",
        "        x = self.lin2(x)\n",
        "\n",
        "        return x, output_layer"
      ],
      "metadata": {
        "cellView": "form",
        "id": "apGATVycfjcM"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "!wget \"https://uniofmora-my.sharepoint.com/:u:/g/personal/180066f_uom_lk/EY2Q0k-ghI1Hs6iZfCUwF6gBJZacOak9XEwzmPd6SK9uAQ?e=yHk23u&download=1\"\n",
        "old_name = r\"/content/EY2Q0k-ghI1Hs6iZfCUwF6gBJZacOak9XEwzmPd6SK9uAQ?e=yHk23u&download=1\"\n",
        "new_name = r\"/content/model_weights.pth\"\n",
        "os.rename(old_name, new_name)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "id": "wWCGMOsynHU8",
        "outputId": "dc83398f-ea31-4e0e-93ce-c0460ebd7fe5"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "--2024-06-20 14:59:31--  https://uniofmora-my.sharepoint.com/:u:/g/personal/180066f_uom_lk/EY2Q0k-ghI1Hs6iZfCUwF6gBJZacOak9XEwzmPd6SK9uAQ?e=yHk23u&download=1\n",
            "Resolving uniofmora-my.sharepoint.com (uniofmora-my.sharepoint.com)... 13.107.136.10, 13.107.138.10, 2620:1ec:8f8::10, ...\n",
            "Connecting to uniofmora-my.sharepoint.com (uniofmora-my.sharepoint.com)|13.107.136.10|:443... connected.\n",
            "HTTP request sent, awaiting response... 302 Found\n",
            "Location: /personal/180066f_uom_lk/Documents/FYP/model_weights/28_best_model.pth?ga=1 [following]\n",
            "--2024-06-20 14:59:31--  https://uniofmora-my.sharepoint.com/personal/180066f_uom_lk/Documents/FYP/model_weights/28_best_model.pth?ga=1\n",
            "Reusing existing connection to uniofmora-my.sharepoint.com:443.\n",
            "HTTP request sent, awaiting response... 200 OK\n",
            "Length: 2475531770 (2.3G) [application/octet-stream]\n",
            "Saving to: ‘EY2Q0k-ghI1Hs6iZfCUwF6gBJZacOak9XEwzmPd6SK9uAQ?e=yHk23u&download=1’\n",
            "\n",
            "EY2Q0k-ghI1Hs6iZfCU 100%[===================>]   2.30G   142MB/s    in 24s     \n",
            "\n",
            "2024-06-20 14:59:55 (98.5 MB/s) - ‘EY2Q0k-ghI1Hs6iZfCUwF6gBJZacOak9XEwzmPd6SK9uAQ?e=yHk23u&download=1’ saved [2475531770/2475531770]\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Running on GPU (\"cuda\") device is advised"
      ],
      "metadata": {
        "id": "FtQaxzI349rF"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "input_shape_1 = (int(max_antibody_sequence_length*20),)\n",
        "input_shape_2 = (int(max_antigen_sequence_length*20),)\n",
        "\n",
        "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
        "com_model = CombinedModel().to(device)\n",
        "com_model = com_model.to(torch.float64)\n",
        "\n",
        "alpha = 0.45\n",
        "beta = 0.55\n",
        "gamma = 0.05\n",
        "\n",
        "com_model_cp  = torch.load('/content/model_weights.pth')\n",
        "com_model_epoch = com_model_cp['epoch']\n",
        "com_model.load_state_dict(com_model_cp['model_state_dict'])\n",
        "\n",
        "# Evaluate the model\n",
        "com_model.eval()\n",
        "test_loss = 0.0\n",
        "test_mae = 0.0\n",
        "total_samples = 0\n",
        "\n",
        "with torch.no_grad():\n",
        "    for input in test_loader:\n",
        "        input_1 = input[0].to(device)\n",
        "        input_2 = input[1].to(device)\n",
        "        target = input[2].to(device)\n",
        "        batch_size = input_1.size(0)\n",
        "\n",
        "        if input_1.pos is not None:\n",
        "            input_1 = NormalizeScale()(input_1)\n",
        "        else:\n",
        "            print(\"Data does not have position information, skipping normalization.\")\n",
        "\n",
        "        if input_2.pos is not None:\n",
        "            input_2 = NormalizeScale()(input_2)\n",
        "        else:\n",
        "            print(\"Data does not have position information, skipping normalization.\")\n",
        "\n",
        "        output_gnn, output_tranf = com_model(input_1, input_2)\n",
        "        print(f\"Predicted binding affinity for the uploaded antibody-antigen pair (in IC50): {10**(alpha*output_gnn.item()+beta*output_tranf.item()+gamma*np.abs(output_gnn.item() - output_tranf.item()))}\") #"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "id": "Sdn3Mq5PbxRb",
        "outputId": "66b69bc7-fe5b-424c-ebae-4995c9cf2011"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Predicted binding affinity for the uploaded antibody-antigen pair (in IC50): 22.93421825850764\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Notes:**\n",
        "\n",
        "- Check that the runtime type is set to GPU at \"Runtime\" -> \"Change runtime type\".\n",
        "- Try to restart the session \"Runtime\" -> \"Restart session and run all\".\n",
        "- Check your input PDB files.\n",
        "- Our current model only supports proteins with amino-acid sequence lengths upto 669 (for antibodies) and 3102 (for antigens).\n",
        "- If you encounter any bugs, please report the issue to https://github.com/Drug-Discovery-ENTC/p2pxml/issues or email the corresponding author (Nuwan) at pmnsribandara@gmail.com"
      ],
      "metadata": {
        "id": "SUyJQvdLMI3j"
      }
    }
  ]
}