-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathqbmg.py
8828 lines (8827 loc) · 263 KB
/
qbmg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "QBMG.ipynb",
"provenance": [],
"collapsed_sections": [],
"mount_file_id": "1GnI2v4oO7M4w2FsSsfXmv44MMbSNtHYn",
"authorship_tag": "ABX9TyPoojveiJKTL+09Dj94SZE1",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/SK124/aa4b928c0349dc1e16879ef7b641e990/qbmg.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"metadata": {
"id": "ZowR9VejxtNz",
"outputId": "7ad65284-1140-40f5-d329-e43a7660df6f",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
}
},
"source": [
"\"\"\" Imports neccesary for installing RDkit \"\"\"\n",
"\n",
"#!wget -c https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\n",
"!cp '/content/drive/My Drive/Miniconda3-latest-Linux-x86_64.sh' /content/\n",
"!chmod +x Miniconda3-latest-Linux-x86_64.sh\n",
"!time bash ./Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local\n",
"!time conda install -q -y -c conda-forge rdkit\n",
"%matplotlib inline\n",
"import matplotlib.pyplot as plt\n",
"import sys\n",
"import os\n",
"sys.path.append('/usr/local/lib/python3.7/site-packages/rdkit')\n",
"%cd /usr/local/lib/python3.7/site-packages/"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"PREFIX=/usr/local\n",
"Unpacking payload ...\n",
"Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\bdone\n",
"Solving environment: - \b\b\\ \b\bdone\n",
"\n",
"## Package Plan ##\n",
"\n",
" environment location: /usr/local\n",
"\n",
" added / updated specs:\n",
" - _libgcc_mutex==0.1=main\n",
" - ca-certificates==2020.1.1=0\n",
" - certifi==2020.4.5.1=py37_0\n",
" - cffi==1.14.0=py37he30daa8_1\n",
" - chardet==3.0.4=py37_1003\n",
" - conda-package-handling==1.6.1=py37h7b6447c_0\n",
" - conda==4.8.3=py37_0\n",
" - cryptography==2.9.2=py37h1ba5d50_0\n",
" - idna==2.9=py_1\n",
" - ld_impl_linux-64==2.33.1=h53a641e_7\n",
" - libedit==3.1.20181209=hc058e9b_0\n",
" - libffi==3.3=he6710b0_1\n",
" - libgcc-ng==9.1.0=hdf63c60_0\n",
" - libstdcxx-ng==9.1.0=hdf63c60_0\n",
" - ncurses==6.2=he6710b0_1\n",
" - openssl==1.1.1g=h7b6447c_0\n",
" - pip==20.0.2=py37_3\n",
" - pycosat==0.6.3=py37h7b6447c_0\n",
" - pycparser==2.20=py_0\n",
" - pyopenssl==19.1.0=py37_0\n",
" - pysocks==1.7.1=py37_0\n",
" - python==3.7.7=hcff3b4d_5\n",
" - readline==8.0=h7b6447c_0\n",
" - requests==2.23.0=py37_0\n",
" - ruamel_yaml==0.15.87=py37h7b6447c_0\n",
" - setuptools==46.4.0=py37_0\n",
" - six==1.14.0=py37_0\n",
" - sqlite==3.31.1=h62c20be_1\n",
" - tk==8.6.8=hbc83047_0\n",
" - tqdm==4.46.0=py_0\n",
" - urllib3==1.25.8=py37_0\n",
" - wheel==0.34.2=py37_0\n",
" - xz==5.2.5=h7b6447c_0\n",
" - yaml==0.1.7=had09818_2\n",
" - zlib==1.2.11=h7b6447c_3\n",
"\n",
"\n",
"The following NEW packages will be INSTALLED:\n",
"\n",
" _libgcc_mutex pkgs/main/linux-64::_libgcc_mutex-0.1-main\n",
" ca-certificates pkgs/main/linux-64::ca-certificates-2020.1.1-0\n",
" certifi pkgs/main/linux-64::certifi-2020.4.5.1-py37_0\n",
" cffi pkgs/main/linux-64::cffi-1.14.0-py37he30daa8_1\n",
" chardet pkgs/main/linux-64::chardet-3.0.4-py37_1003\n",
" conda pkgs/main/linux-64::conda-4.8.3-py37_0\n",
" conda-package-han~ pkgs/main/linux-64::conda-package-handling-1.6.1-py37h7b6447c_0\n",
" cryptography pkgs/main/linux-64::cryptography-2.9.2-py37h1ba5d50_0\n",
" idna pkgs/main/noarch::idna-2.9-py_1\n",
" ld_impl_linux-64 pkgs/main/linux-64::ld_impl_linux-64-2.33.1-h53a641e_7\n",
" libedit pkgs/main/linux-64::libedit-3.1.20181209-hc058e9b_0\n",
" libffi pkgs/main/linux-64::libffi-3.3-he6710b0_1\n",
" libgcc-ng pkgs/main/linux-64::libgcc-ng-9.1.0-hdf63c60_0\n",
" libstdcxx-ng pkgs/main/linux-64::libstdcxx-ng-9.1.0-hdf63c60_0\n",
" ncurses pkgs/main/linux-64::ncurses-6.2-he6710b0_1\n",
" openssl pkgs/main/linux-64::openssl-1.1.1g-h7b6447c_0\n",
" pip pkgs/main/linux-64::pip-20.0.2-py37_3\n",
" pycosat pkgs/main/linux-64::pycosat-0.6.3-py37h7b6447c_0\n",
" pycparser pkgs/main/noarch::pycparser-2.20-py_0\n",
" pyopenssl pkgs/main/linux-64::pyopenssl-19.1.0-py37_0\n",
" pysocks pkgs/main/linux-64::pysocks-1.7.1-py37_0\n",
" python pkgs/main/linux-64::python-3.7.7-hcff3b4d_5\n",
" readline pkgs/main/linux-64::readline-8.0-h7b6447c_0\n",
" requests pkgs/main/linux-64::requests-2.23.0-py37_0\n",
" ruamel_yaml pkgs/main/linux-64::ruamel_yaml-0.15.87-py37h7b6447c_0\n",
" setuptools pkgs/main/linux-64::setuptools-46.4.0-py37_0\n",
" six pkgs/main/linux-64::six-1.14.0-py37_0\n",
" sqlite pkgs/main/linux-64::sqlite-3.31.1-h62c20be_1\n",
" tk pkgs/main/linux-64::tk-8.6.8-hbc83047_0\n",
" tqdm pkgs/main/noarch::tqdm-4.46.0-py_0\n",
" urllib3 pkgs/main/linux-64::urllib3-1.25.8-py37_0\n",
" wheel pkgs/main/linux-64::wheel-0.34.2-py37_0\n",
" xz pkgs/main/linux-64::xz-5.2.5-h7b6447c_0\n",
" yaml pkgs/main/linux-64::yaml-0.1.7-had09818_2\n",
" zlib pkgs/main/linux-64::zlib-1.2.11-h7b6447c_3\n",
"\n",
"\n",
"Preparing transaction: / \b\b- \b\b\\ \b\bdone\n",
"Executing transaction: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n",
"installation finished.\n",
"WARNING:\n",
" You currently have a PYTHONPATH environment variable set. This may cause\n",
" unexpected behavior when running the Python interpreter in Miniconda3.\n",
" For best results, please verify that your PYTHONPATH only points to\n",
" directories of packages that are compatible with the Python interpreter\n",
" in Miniconda3: /usr/local\n",
"\n",
"real\t0m29.081s\n",
"user\t0m11.913s\n",
"sys\t0m3.755s\n",
"Collecting package metadata (current_repodata.json): ...working... done\n",
"Solving environment: ...working... done\n",
"\n",
"## Package Plan ##\n",
"\n",
" environment location: /usr/local\n",
"\n",
" added / updated specs:\n",
" - rdkit\n",
"\n",
"\n",
"The following packages will be downloaded:\n",
"\n",
" package | build\n",
" ---------------------------|-----------------\n",
" boost-1.72.0 | py37h9de70de_0 316 KB conda-forge\n",
" boost-cpp-1.72.0 | h7b93d67_2 16.3 MB conda-forge\n",
" bzip2-1.0.8 | h516909a_2 396 KB conda-forge\n",
" ca-certificates-2020.6.20 | hecda079_0 145 KB conda-forge\n",
" cairo-1.16.0 | h3fc0475_1005 1.5 MB conda-forge\n",
" certifi-2020.6.20 | py37hc8dfbb8_0 151 KB conda-forge\n",
" conda-4.8.3 | py37hc8dfbb8_1 3.0 MB conda-forge\n",
" fontconfig-2.13.1 | h1056068_1002 365 KB conda-forge\n",
" freetype-2.10.2 | he06d7ca_0 905 KB conda-forge\n",
" glib-2.65.0 | h3eb4bd4_0 2.9 MB\n",
" icu-67.1 | he1b5a44_0 12.9 MB conda-forge\n",
" jpeg-9d | h516909a_0 266 KB conda-forge\n",
" lcms2-2.11 | hbd6801e_0 431 KB conda-forge\n",
" libblas-3.8.0 | 17_openblas 11 KB conda-forge\n",
" libcblas-3.8.0 | 17_openblas 11 KB conda-forge\n",
" libgfortran-ng-7.5.0 | hdf63c60_13 1.7 MB conda-forge\n",
" libiconv-1.15 | h516909a_1006 2.0 MB conda-forge\n",
" liblapack-3.8.0 | 17_openblas 11 KB conda-forge\n",
" libopenblas-0.3.10 |pthreads_hb3c22a3_4 7.8 MB conda-forge\n",
" libpng-1.6.37 | hed695b0_1 308 KB conda-forge\n",
" libtiff-4.1.0 | hc7e4089_6 668 KB conda-forge\n",
" libuuid-2.32.1 | h14c3975_1000 26 KB conda-forge\n",
" libwebp-base-1.1.0 | h516909a_3 845 KB conda-forge\n",
" libxcb-1.13 | h14c3975_1002 396 KB conda-forge\n",
" libxml2-2.9.10 | h72b56ed_2 1.3 MB conda-forge\n",
" lz4-c-1.9.2 | he1b5a44_1 226 KB conda-forge\n",
" numpy-1.19.1 | py37h8960a57_0 5.2 MB conda-forge\n",
" olefile-0.46 | py_0 31 KB conda-forge\n",
" openssl-1.1.1g | h516909a_1 2.1 MB conda-forge\n",
" pandas-1.1.0 | py37h3340039_0 10.5 MB conda-forge\n",
" pcre-8.44 | he1b5a44_0 261 KB conda-forge\n",
" pillow-7.2.0 | py37h718be6c_1 675 KB conda-forge\n",
" pixman-0.38.0 | h516909a_1003 594 KB conda-forge\n",
" pthread-stubs-0.4 | h14c3975_1001 5 KB conda-forge\n",
" pycairo-1.19.1 | py37h01af8b0_3 77 KB conda-forge\n",
" python-dateutil-2.8.1 | py_0 220 KB conda-forge\n",
" python_abi-3.7 | 1_cp37m 4 KB conda-forge\n",
" pytz-2020.1 | pyh9f0ad1d_0 227 KB conda-forge\n",
" rdkit-2020.03.4 | py37hdd87690_0 24.6 MB conda-forge\n",
" tk-8.6.10 | hed695b0_0 3.2 MB conda-forge\n",
" xorg-kbproto-1.0.7 | h14c3975_1002 26 KB conda-forge\n",
" xorg-libice-1.0.10 | h516909a_0 57 KB conda-forge\n",
" xorg-libsm-1.2.3 | h84519dc_1000 25 KB conda-forge\n",
" xorg-libx11-1.6.10 | h516909a_0 918 KB conda-forge\n",
" xorg-libxau-1.0.9 | h14c3975_0 13 KB conda-forge\n",
" xorg-libxdmcp-1.1.3 | h516909a_0 18 KB conda-forge\n",
" xorg-libxext-1.3.4 | h516909a_0 51 KB conda-forge\n",
" xorg-libxrender-0.9.10 | h516909a_1002 31 KB conda-forge\n",
" xorg-renderproto-0.11.1 | h14c3975_1002 8 KB conda-forge\n",
" xorg-xextproto-7.3.0 | h14c3975_1002 27 KB conda-forge\n",
" xorg-xproto-7.0.31 | h14c3975_1007 72 KB conda-forge\n",
" zstd-1.4.5 | h6597ccf_2 712 KB conda-forge\n",
" ------------------------------------------------------------\n",
" Total: 104.2 MB\n",
"\n",
"The following NEW packages will be INSTALLED:\n",
"\n",
" boost conda-forge/linux-64::boost-1.72.0-py37h9de70de_0\n",
" boost-cpp conda-forge/linux-64::boost-cpp-1.72.0-h7b93d67_2\n",
" bzip2 conda-forge/linux-64::bzip2-1.0.8-h516909a_2\n",
" cairo conda-forge/linux-64::cairo-1.16.0-h3fc0475_1005\n",
" fontconfig conda-forge/linux-64::fontconfig-2.13.1-h1056068_1002\n",
" freetype conda-forge/linux-64::freetype-2.10.2-he06d7ca_0\n",
" glib pkgs/main/linux-64::glib-2.65.0-h3eb4bd4_0\n",
" icu conda-forge/linux-64::icu-67.1-he1b5a44_0\n",
" jpeg conda-forge/linux-64::jpeg-9d-h516909a_0\n",
" lcms2 conda-forge/linux-64::lcms2-2.11-hbd6801e_0\n",
" libblas conda-forge/linux-64::libblas-3.8.0-17_openblas\n",
" libcblas conda-forge/linux-64::libcblas-3.8.0-17_openblas\n",
" libgfortran-ng conda-forge/linux-64::libgfortran-ng-7.5.0-hdf63c60_13\n",
" libiconv conda-forge/linux-64::libiconv-1.15-h516909a_1006\n",
" liblapack conda-forge/linux-64::liblapack-3.8.0-17_openblas\n",
" libopenblas conda-forge/linux-64::libopenblas-0.3.10-pthreads_hb3c22a3_4\n",
" libpng conda-forge/linux-64::libpng-1.6.37-hed695b0_1\n",
" libtiff conda-forge/linux-64::libtiff-4.1.0-hc7e4089_6\n",
" libuuid conda-forge/linux-64::libuuid-2.32.1-h14c3975_1000\n",
" libwebp-base conda-forge/linux-64::libwebp-base-1.1.0-h516909a_3\n",
" libxcb conda-forge/linux-64::libxcb-1.13-h14c3975_1002\n",
" libxml2 conda-forge/linux-64::libxml2-2.9.10-h72b56ed_2\n",
" lz4-c conda-forge/linux-64::lz4-c-1.9.2-he1b5a44_1\n",
" numpy conda-forge/linux-64::numpy-1.19.1-py37h8960a57_0\n",
" olefile conda-forge/noarch::olefile-0.46-py_0\n",
" pandas conda-forge/linux-64::pandas-1.1.0-py37h3340039_0\n",
" pcre conda-forge/linux-64::pcre-8.44-he1b5a44_0\n",
" pillow conda-forge/linux-64::pillow-7.2.0-py37h718be6c_1\n",
" pixman conda-forge/linux-64::pixman-0.38.0-h516909a_1003\n",
" pthread-stubs conda-forge/linux-64::pthread-stubs-0.4-h14c3975_1001\n",
" pycairo conda-forge/linux-64::pycairo-1.19.1-py37h01af8b0_3\n",
" python-dateutil conda-forge/noarch::python-dateutil-2.8.1-py_0\n",
" python_abi conda-forge/linux-64::python_abi-3.7-1_cp37m\n",
" pytz conda-forge/noarch::pytz-2020.1-pyh9f0ad1d_0\n",
" rdkit conda-forge/linux-64::rdkit-2020.03.4-py37hdd87690_0\n",
" xorg-kbproto conda-forge/linux-64::xorg-kbproto-1.0.7-h14c3975_1002\n",
" xorg-libice conda-forge/linux-64::xorg-libice-1.0.10-h516909a_0\n",
" xorg-libsm conda-forge/linux-64::xorg-libsm-1.2.3-h84519dc_1000\n",
" xorg-libx11 conda-forge/linux-64::xorg-libx11-1.6.10-h516909a_0\n",
" xorg-libxau conda-forge/linux-64::xorg-libxau-1.0.9-h14c3975_0\n",
" xorg-libxdmcp conda-forge/linux-64::xorg-libxdmcp-1.1.3-h516909a_0\n",
" xorg-libxext conda-forge/linux-64::xorg-libxext-1.3.4-h516909a_0\n",
" xorg-libxrender conda-forge/linux-64::xorg-libxrender-0.9.10-h516909a_1002\n",
" xorg-renderproto conda-forge/linux-64::xorg-renderproto-0.11.1-h14c3975_1002\n",
" xorg-xextproto conda-forge/linux-64::xorg-xextproto-7.3.0-h14c3975_1002\n",
" xorg-xproto conda-forge/linux-64::xorg-xproto-7.0.31-h14c3975_1007\n",
" zstd conda-forge/linux-64::zstd-1.4.5-h6597ccf_2\n",
"\n",
"The following packages will be UPDATED:\n",
"\n",
" ca-certificates pkgs/main::ca-certificates-2020.1.1-0 --> conda-forge::ca-certificates-2020.6.20-hecda079_0\n",
" certifi pkgs/main::certifi-2020.4.5.1-py37_0 --> conda-forge::certifi-2020.6.20-py37hc8dfbb8_0\n",
" conda pkgs/main::conda-4.8.3-py37_0 --> conda-forge::conda-4.8.3-py37hc8dfbb8_1\n",
" openssl pkgs/main::openssl-1.1.1g-h7b6447c_0 --> conda-forge::openssl-1.1.1g-h516909a_1\n",
" tk pkgs/main::tk-8.6.8-hbc83047_0 --> conda-forge::tk-8.6.10-hed695b0_0\n",
"\n",
"\n",
"Preparing transaction: ...working... done\n",
"Verifying transaction: ...working... done\n",
"Executing transaction: ...working... done\n",
"\n",
"real\t0m37.696s\n",
"user\t0m31.591s\n",
"sys\t0m3.763s\n",
"/usr/local/lib/python3.7/site-packages\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "PrfKBJmAezj-",
"outputId": "6c07f573-9d75-4fd3-c2fc-88ccb78f8758",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
}
},
"source": [
"%cd /usr/local/lib/python3.7/site-packages/\n",
"import re\n",
"import pandas as pd\n",
"import numpy as np\n",
"import random\n",
"import pickle\n",
"import sys\n",
"import time\n",
"import torch\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"from torch.utils.data import Dataset\n",
"from torch.utils.data import DataLoader\n",
"from rdkit import Chem\n",
"from rdkit.Chem import DataStructs\n",
"from rdkit.Chem import AllChem\n",
"from rdkit.Chem import RDConfig\n",
"from tqdm import tqdm"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"/usr/local/lib/python3.7/site-packages\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "k1vhytV4e1nx",
"outputId": "46b82bf7-d28e-499f-8d19-476d2b22e603",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 219
}
},
"source": [
"%cd /content/\n",
"path='/content/drive/My Drive/De NovoDrug/full_data_final.csv'\n",
"df=pd.read_csv(path)\n",
"df.head()"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"/content\n"
],
"name": "stdout"
},
{
"output_type": "execute_result",
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>col</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>CC(C)(C)c1ccc2occ(CC(=O)Nc3ccccc3F)c2c1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>C[C@@H]1CC(Nc2cncc(-c3nncn3C)c2)C[C@@H](C)C1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>N#Cc1ccc(-c2ccc(O[C@@H](C(=O)N3CCCC3)c3ccccc3)...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>CCOC(=O)[C@@H]1CCCN(C(=O)c2nc(-c3ccc(C)cc3)n3c...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>N#CC1=C(SCC(=O)Nc2cccc(Cl)c2)N=C([O-])[C@H](C#...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" col\n",
"0 CC(C)(C)c1ccc2occ(CC(=O)Nc3ccccc3F)c2c1\n",
"1 C[C@@H]1CC(Nc2cncc(-c3nncn3C)c2)C[C@@H](C)C1\n",
"2 N#Cc1ccc(-c2ccc(O[C@@H](C(=O)N3CCCC3)c3ccccc3)...\n",
"3 CCOC(=O)[C@@H]1CCCN(C(=O)c2nc(-c3ccc(C)cc3)n3c...\n",
"4 N#CC1=C(SCC(=O)Nc2cccc(Cl)c2)N=C([O-])[C@H](C#..."
]
},
"metadata": {
"tags": []
},
"execution_count": 41
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "0AwPndlDe4op"
},
"source": [
"def csv2txt(dataframe):\n",
" \" Writes the CSV File to text file \" \n",
" with open('drug.txt','w') as f:\n",
" for i in range(len(dataframe)):\n",
" text=dataframe['col'][i]\n",
" f.write(text+'\\n')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "9aKXrtGRk49c"
},
"source": [
"csv2txt(df)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "XR76a4aAlZHp"
},
"source": [
"\n",
"def txt2list(fname):\n",
" \" Takes the molecules in text file to and store it in list \"\n",
" smiles = []\n",
" with open(fname, 'r') as f:\n",
" for line in f:\n",
" smiles.append(line.split()[0])\n",
" return smiles"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "Gky6vDq9lbla"
},
"source": [
"smiles=txt2list('drug.txt')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "9Hqoxco-ln9t",
"outputId": "96516b92-efd5-4ac9-893b-cfa26fdefc5a",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
}
},
"source": [
"len(smiles)"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"100000"
]
},
"metadata": {
"tags": []
},
"execution_count": 46
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "XhZ4007lmBfH"
},
"source": [
"\n",
"def replace_halogen(string):\n",
" \"\"\"Regex to replace Br and Cl with single letters\"\"\"\n",
" br = re.compile('Br')\n",
" cl = re.compile('Cl')\n",
" string = br.sub('R', string)\n",
" string = cl.sub('L', string)\n",
"\n",
" return string\n"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "zeFfZcUIeol0"
},
"source": [
"def construct_vocabulary(smiles_list,fname):\n",
" \"\"\"Returns all the characters present in a text file.\n",
" Uses regex to find characters/tokens of the format '[x]'.\"\"\"\n",
" add_chars = set()\n",
" for i, smiles in enumerate(smiles_list):\n",
" regex = '(\\[[^\\[\\]]{1,10}])'\n",
"\n",
" \"\"\"\n",
" Regex Explaination : \\ signifies a special sequence inside a specific set [] of characters for eg.([...CC[NH+]COCN...]) so \\[...] , which can contain [NH+] like molecules inside it which is taken care by the ... as explained in the following \n",
" To capture such [NH+],[C@@H],[...] molecules, ^ (start with operator) is used, which is to say such a token is going to start, inside which we give the \\[\\] to denote a specific sequence which will start with a '[' and end with ']' ie.[NH+] or [C@@H], here \\ is used to say escape the inbetween enitities(C@@H,NH+) ie dont split them\n",
" There can be numbers 1,2....10 to denote begining of rings within the sequence like CCCcc1n.... to capture these numbers {1,10} ie all numbers between 1 to 10, is used\n",
" INPUT SMILE ----> 'CCC[C@@H][NH3+][O+][O-][OH+][P+]COCCCcc1nnn' \n",
" char_list = ['CCC','[C@@H]','[NH3+]','[O+]','[O-]','[OH+]','[P+]','COCCCcc1nnn']\n",
" \n",
" \"\"\"\n",
" smiles = replace_halogen(smiles)\n",
" char_list = re.split(regex, smiles)\n",
" for char in char_list:\n",
" \"There are characters like [NH+] which need to considered as single token rather than '[', 'N','H','+',']'\"\n",
" if char.startswith('['):\n",
" add_chars.add(char)\n",
"\n",
" else:\n",
" \"chars inside charlist need to be split as well i.e. COCCCcc1nnn need to split into tokens like 'C','O','1','c','n' \"\n",
" chars = [unit for unit in char]\n",
" [add_chars.add(unit) for unit in chars]\n",
"\n",
" print(\"Number of characters: {}\".format(len(add_chars)))\n",
" with open(fname, 'w') as f:\n",
" for char in add_chars:\n",
" f.write(char + \"\\n\")\n",
" return add_chars\n"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "f6hRPcn6fn_M",
"outputId": "ec9998a3-0146-4125-b704-1360c369f5a4",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
}
},
"source": [
"construct_vocabulary(smiles,'vocab.txt')"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"Number of characters: 58\n"
],
"name": "stdout"
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"{'#',\n",
" '(',\n",
" ')',\n",
" '-',\n",
" '/',\n",
" '1',\n",
" '2',\n",
" '3',\n",
" '4',\n",
" '5',\n",
" '6',\n",
" '7',\n",
" '=',\n",
" 'C',\n",
" 'F',\n",
" 'I',\n",
" 'L',\n",
" 'N',\n",
" 'O',\n",
" 'P',\n",
" 'R',\n",
" 'S',\n",
" '[C@@H]',\n",
" '[C@@]',\n",
" '[C@H]',\n",
" '[C@]',\n",
" '[CH-]',\n",
" '[CH2-]',\n",
" '[N+]',\n",
" '[N-]',\n",
" '[NH+]',\n",
" '[NH-]',\n",
" '[NH2+]',\n",
" '[NH3+]',\n",
" '[O+]',\n",
" '[O-]',\n",
" '[OH+]',\n",
" '[P+]',\n",
" '[P@@H]',\n",
" '[P@@]',\n",
" '[P@]',\n",
" '[PH2]',\n",
" '[S+]',\n",
" '[S-]',\n",
" '[S@@]',\n",
" '[S@]',\n",
" '[SH+]',\n",
" '[n+]',\n",
" '[n-]',\n",
" '[nH+]',\n",
" '[nH]',\n",
" '[o+]',\n",
" '[s+]',\n",
" '\\\\',\n",
" 'c',\n",
" 'n',\n",
" 'o',\n",
" 's'}"
]
},
"metadata": {
"tags": []
},
"execution_count": 49
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "BjdQRfjjZctN"
},
"source": [
"class Vocabulary(object):\n",
" \"\"\"A class for handling encoding/decoding from SMILES to an array of indices\"\"\"\n",
" def __init__(self, init_from_file=None, max_length=100):\n",
" \"E and G are used to signify ending and begining of seqeunce\"\n",
" self.special_tokens = ['E', 'G']\n",
" \"Other tokens frmo SMILES grammer need to be added\"\n",
" self.additional_chars = set()\n",
" self.chars = self.special_tokens\n",
" self.vocab_size = len(self.chars)\n",
" self.vocab = dict(zip(self.chars, range(len(self.chars)))) \n",
" # self.vocab = dict((c, i+1) for i, c in enumerate(self.chars))\n",
" self.reversed_vocab = {v: k for k, v in self.vocab.items()}\n",
" #self.reversed_vocab = {v+1: k for k, v in self.vocab.items()} \n",
" self.max_length = max_length\n",
" if init_from_file: \n",
" \" vocab.txt file which contains all the tokens is given as a input which initiates the vocabulary for the language model\" \n",
" self.init_from_file(init_from_file)\n",
"\n",
" def encode(self, char_list):\n",
" \"\"\"Takes a list of characters (eg '[C@@H]') and encodes to array of indices\"\"\"\n",
" smiles_matrix = np.zeros(len(char_list), dtype=np.float32)\n",
" for i, char in enumerate(char_list):\n",
" \"2D Matrix : All the tokens are converted from SMILES to integers\"\n",
" smiles_matrix[i] = self.vocab[char]\n",
" return smiles_matrix\n",
"\n",
" def decode(self, matrix):\n",
" \"\"\"Takes an array of indices and returns the corresponding SMILES\"\"\"\n",
" chars = []\n",
" for i in matrix:\n",
" \"If E token which is the End token is reached, the process terminates\"\n",
" if i == self.vocab['E']: break\n",
" chars.append(self.reversed_vocab[i])\n",
" smiles = \"\".join(chars)\n",
" smiles = smiles.replace(\"L\", \"Cl\").replace(\"R\", \"Br\")\n",
" return smiles\n",
"\n",
" def tokenize(self, smiles):\n",
" \"\"\"Takes a SMILES and return a list of characters/tokens\"\"\"\n",
" regex = '(\\[[^\\[\\]]{1,10}\\])'\n",
" smiles = replace_halogen(smiles)\n",
" char_list = re.split(regex, smiles)\n",
" tokenized = []\n",
" \"SMILES Sequence needs to be converted to tokens for preprocessing, this is the same code we had in Vocabulary class\"\n",
" for char in char_list:\n",
" if char.startswith('['):\n",
" tokenized.append(char)\n",
" else:\n",
" chars = [unit for unit in char]\n",
" [tokenized.append(unit) for unit in chars]\n",
" \"E token is added to signify the ending of a token\"\n",
" tokenized.append('E')\n",
" return tokenized\n",
"\n",
" def add_characters(self, chars):\n",
" \"\"\"Adds characters to the vocabulary\"\"\"\n",
" for char in chars:\n",
" self.additional_chars.add(char)\n",
" char_list = list(self.additional_chars)\n",
" char_list.sort()\n",
" self.chars = char_list + self.special_tokens\n",
" self.vocab_size = len(self.chars)\n",
" self.vocab = dict(zip(self.chars, range(len(self.chars))))\n",
" self.reversed_vocab = {v: k for k, v in self.vocab.items()}\n",
"\n",
"\n",
" def init_from_file(self, file):\n",
" \"\"\"Takes a file containing \\n separated characters to initialize the vocabulary\"\"\"\n",
" with open(file, 'r') as f:\n",
" \"All characters from vocab.txt file which has all the unique tokens is taken and added to the Vocabukary of the model\" \n",
" chars = f.read().split()\n",
" self.add_characters(chars)\n",
"\n",
" def __len__(self):\n",
" return len(self.chars)\n",
"\n",
" def __str__(self):\n",
" return \"Vocabulary containing {} tokens: {}\".format(len(self), self.chars)\n",
"\n",
"class MolData(Dataset):\n",
" \"\"\"Custom PyTorch Dataset that takes a file containing SMILES.\n",
" Args:\n",
" fname : path to a file containing \\n separated SMILES.\n",
" voc : a Vocabulary instance\n",
" Returns:\n",
" A custom PyTorch dataset for training the Prior.\n",
" \"\"\"\n",
" def __init__(self, fname, voc):\n",
" self.voc = voc\n",
" self.smiles = []\n",
" with open(fname, 'r') as f:\n",
" for line in f:\n",
" self.smiles.append(line.split()[0])\n",
"\n",
" def __getitem__(self, i): \n",
" mol = self.smiles[i]\n",
" tokenized = self.voc.tokenize(mol)\n",
" encoded = self.voc.encode(tokenized)\n",
" return Variable(encoded)\n",
"\n",
" def __len__(self):\n",
" return len(self.smiles)\n",
"\n",
" def __str__(self):\n",
" return \"Dataset containing {} structures.\".format(len(self))\n",
"\n",
" @classmethod\n",
" def collate_fn(cls, arr):\n",
" \"\"\"Function to take a list of encoded sequences and turn them into a batch\"\"\"\n",
" max_length = max([seq.size(0) for seq in arr])\n",
" \"\"\" For every batch lets say 64, 64 sequences will be taken an the maximum length of the sequence from that batch woul be max_length \n",
" and the shorter seqeunces will be padded till the max_length before passing it to the GRU \"\"\"\n",
" collated_arr = Variable(torch.zeros(len(arr), max_length))\n",
" for i, seq in enumerate(arr):\n",
" collated_arr[i, :seq.size(0)] = seq\n",
" return collated_arr\n",
"\n",
"\n",
"def Variable(tensor):\n",
" \"\"\"Wrapper for torch.autograd.Variable that also accepts\n",
" numpy arrays directly and automatically assigns it to\n",
" the GPU.\"\"\"\n",
" if isinstance(tensor, np.ndarray):\n",
" tensor = torch.from_numpy(tensor)\n",
" if torch.cuda.is_available():\n",
" return torch.autograd.Variable(tensor).cuda()\n",
" return torch.autograd.Variable(tensor)\n",
"\n",
"def decrease_learning_rate(optimizer, decrease_by=0.01):\n",
" \"\"\"Multiplies the learning rate of the optimizer by 1 - decrease_by\"\"\"\n",
" for param_group in optimizer.param_groups:\n",
" param_group['lr'] *= (1 - decrease_by)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "aNkqMdZZZtGX"
},
"source": [
"class GRU(nn.Module):\n",
" \"\"\" Implements a three layer GRU cell including an embedding layer\n",
" and an output linear layer back to the size of the vocabulary\"\"\"\n",
" def __init__(self, voc_size):\n",
" super(GRU, self).__init__()\n",
" self.embedding = nn.Embedding(voc_size, 128)\n",
" self.gru_1 = nn.GRUCell(128, 512)\n",
" self.gru_2 = nn.GRUCell(512, 512)\n",
" self.gru_3 = nn.GRUCell(512, 512)\n",
" self.linear = nn.Linear(512, voc_size)\n",
"\n",
" def forward(self, x, h):\n",
" x = self.embedding(x)\n",
" h_out = Variable(torch.zeros(h.size()))\n",
" x = h_out[0] = self.gru_1(x, h[0])\n",
" x = h_out[1] = self.gru_2(x, h[1])\n",
" x = h_out[2] = self.gru_3(x, h[2])\n",
" x = self.linear(x)\n",
" return x, h_out\n",
"\n",
" def init_h(self, batch_size):\n",
" # Initial cell state is zero\n",
" return Variable(torch.zeros(3, batch_size, 512))\n",
"\n",
"class RNN():\n",
" \"\"\"Implements the Prior and Agent RNN. Needs a Vocabulary instance in\n",
" order to determine size of the vocabulary and index of the END token\"\"\"\n",
" def __init__(self, voc):\n",
" self.rnn = GRU(voc.vocab_size)\n",
" if torch.cuda.is_available():\n",
" self.rnn.cuda()\n",
" self.voc = voc\n",
"\n",
" def likelihood(self, target):\n",
" \"\"\"\n",
" Retrieves the likelihood of a given sequence\n",
" Args:\n",
" target: (batch_size * sequence_lenght) A batch of sequences\n",
" Outputs:\n",
" log_probs : (batch_size) Log likelihood for each example*\n",
" \n",
" \"\"\"\n",
" batch_size, seq_length = target.size()\n",
" start_token = Variable(torch.zeros(batch_size, 1).long())\n",
" start_token[:] = self.voc.vocab['G'] \n",
" x = torch.cat((start_token, target[:, :-1]), 1) # G (beginning token) is added to each sequence in the batch.\n",
" h = self.rnn.init_h(batch_size) # hidden state is also initalized as per batch size\n",
" log_probs = Variable(torch.zeros(batch_size)) #Variable to store log_probabilities \n",
"\n",
" for step in range(seq_length):\n",
" \"\"\" for every step from 1 to sequnce length, we pass the GRU, Seqeunce based on the timestep and hidden state and get logits and \n",
" hidden state after taking that step\n",
" logits is a vector of 'D' dimension where D = voc_size with scores on what should be the next token, which is converted to \n",
" log_probs using log_softmax and sent to the NLL Loss function which compares the next predicted word by RNN and Ground Truth and calculates \n",
" the loss per sequence per timestep which is accumalted under log_probs and returns total loss after end time step \"\"\"\n",
" logits, h = self.rnn(x[:, step], h)\n",
" log_prob = F.log_softmax(logits)\n",
" log_probs += NLLLoss(log_prob, target[:, step])\n",
" return log_probs\n",
"\n",
" def sample(self, batch_size, max_length=150):\n",
" \"\"\"\n",
" Sample a batch of sequences\n",
" Args:\n",
" batch_size : Number of sequences to sample \n",
" max_length: Maximum length of the sequences\n",
" Outputs:\n",
" seqs: (batch_size, seq_length) The sampled sequences.\n",
" log_probs : (batch_size) Log likelihood for each sequence.\n",
" \n",
" \"\"\"\n",
" start_token = Variable(torch.zeros(batch_size).long())\n",
" start_token[:] = self.voc.vocab['G']\n",
" h = self.rnn.init_h(batch_size)\n",
" x = start_token\n",
"\n",
" sequences = []\n",
" log_probs = Variable(torch.zeros(batch_size))\n",
" finished = torch.zeros(batch_size).byte()\n",
" if torch.cuda.is_available():\n",
" finished = finished.cuda()\n",
"\n",
" for step in range(max_length):\n",
" \"\"\" After language model learns the semantic syntax, we need to check its perfomance which is why we sample from it.\n",
" The code here is exactly similar to the code in likeilhood function \"\"\" \n",
" logits, h = self.rnn(x, h)\n",
" prob = F.softmax(logits)\n",
" log_prob = F.log_softmax(logits)\n",
" \"\"\" torch.multinomial returns a tensor where each row contains 1 index sampled from the multinomial probability distribution \n",
" located in the corresponding row of tensor input.\n",
" \"\"\"\n",
" x = torch.multinomial(prob,1).view(-1)\n",
" sequences.append(x.view(-1, 1))\n",
" log_probs += NLLLoss(log_prob, x)\n",
"\n",
" x = Variable(x.data)\n",
" \"\"\" Sampling terminates when E token is spit out of GRU \"\"\"\n",
" EOS_sampled = (x == self.voc.vocab['E']).data\n",
" finished = torch.ge(finished + EOS_sampled, 1)\n",
" if torch.prod(finished) == 1: break\n",
"\n",
" sequences = torch.cat(sequences, 1)\n",
" return sequences.data, log_probs\n",
"\n",
"def NLLLoss(inputs, targets):\n",
" \"\"\"\n",
" Custom Negative Log Likelihood loss that returns loss per example,\n",
" rather than for the entire batch.\n",
" Args:\n",
" inputs : (batch_size, num_classes) *Log probabilities of each class*\n",
" targets: (batch_size) *Target class index*\n",
" Outputs:\n",
" loss : (batch_size) *Loss for each example*\n",
" \"\"\"\n",
"\n",
" if torch.cuda.is_available():\n",
" target_expanded = torch.zeros(inputs.size()).cuda()\n",
" else:\n",
" target_expanded = torch.zeros(inputs.size())\n",
"\n",
" target_expanded.scatter_(1, targets.contiguous().view(-1, 1).data, 1.0)\n",
" loss = Variable(target_expanded) * inputs\n",
" loss = torch.sum(loss, 1)\n",
" return loss"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "WwU9EPsproH2"
},
"source": [
"\" Using the log-softmax will punish bigger mistakes in likelihood space higher.\""
]
},
{
"cell_type": "code",
"metadata": {
"id": "oivqMAeefprT",
"outputId": "e2230255-e5ce-43e1-c168-1f905b449976",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
}
},
"source": [
"def pretrain(restore_from = None):\n",
" \"\"\"Trains the Prior RNN\"\"\"\n",
"\n",
" voc = Vocabulary(init_from_file=\"vocab.txt\")\n",
" moldata = MolData(\"drug.txt\", voc)\n",
" data = DataLoader(moldata, batch_size=128, shuffle=True, drop_last=True,\n",
" collate_fn=MolData.collate_fn)\n",
" \n",
" Prior = RNN(voc)\n",
" \n",
" # Can restore from a saved RNN\n",
" if restore_from:\n",
" Prior.rnn.load_state_dict(torch.load(restore_from))\n",
"\n",
" optimizer = torch.optim.Adam(Prior.rnn.parameters(), lr = 0.001)\n",
" for epoch in range(1, 51):\n",
" # When training on a few million compounds, this model converges\n",
" # in a few of epochs or even faster. If model sized is increased\n",
" # its probably a good idea to check loss against an external set of\n",
" # validation SMILES to make sure we dont overfit too much.\n",
" for step, batch in tqdm(enumerate(data), total=len(data)):\n",
"\n",
" # Sample from DataLoader\n",
" seqs = batch.long()\n",
"\n",
" # Calculate loss\n",
" log_p= Prior.likelihood(seqs)\n",
" loss = - log_p.mean()\n",
"\n",
" # Calculate gradients and take a step\n",
" optimizer.zero_grad()\n",
" loss.backward()\n",
" optimizer.step()\n",