-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathjchem.py
1862 lines (1458 loc) · 56 KB
/
jchem.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
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Draw
from rdkit import DataStructs
from rdkit.Chem import MACCSkeys
from rdkit.Chem import FragmentCatalog
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from scipy import stats
# This is James Sungjin Kim's library
import jutil
def _show_mol_r0( smiles = 'C1=CC=CC=C1', name_tag = False):
"""
This function shows the molecule defined by smiles code.
The procedure follows:
-
First, benzene can be defined as follows.
Before defining molecule, the basic library of rdkit can be loaded using the import command.
Second, the 2D coordination of the molecule can be calculated.
For coordination calculation, AllChem sub-tool should be included.
Third, the molecular graph is drawn and save it
so as to see in the picture manipulation tool.
To use Draw, we must include Draw tool from rdkit.Chem.
Then, it is time to load png file and show the image on screen.
Input: smiles code
"""
if name_tag:
print(smiles)
m = Chem.MolFromSmiles( smiles)
tmp = AllChem.Compute2DCoords( m)
f_name = '{}.png'.format( 'smiles')
Draw.MolToFile(m, f_name)
img_m = plt.imread( f_name)
plt.imshow( img_m)
plt.show()
def show_mol( smiles = 'C1=CC=CC=C1', name_tag = False, idx = None, disp = False, graph = True, f_name = None):
"""
This function shows the molecule defined by smiles code.
The procedure follows:
-
First, benzene can be defined as follows.
Before defining molecule, the basic library of rdkit can be loaded using the import command.
Second, the 2D coordination of the molecule can be calculated.
For coordination calculation, AllChem sub-tool should be included.
Third, the molecular graph is drawn and save it
so as to see in the picture manipulation tool.
To use Draw, we must include Draw tool from rdkit.Chem.
Then, it is time to load png file and show the image on screen.
Input: smiles code
E.g.,
map( lambda xx: jchem.show_mol( xx[1], name_tag = True, idx = xx[0] + 1), enumerate(mol_smiles_list))
"""
if name_tag:
if idx:
print(idx, smiles)
else:
print(smiles)
m = Chem.MolFromSmiles( smiles)
cnonical_sm = Chem.MolToSmiles( m)
if disp:
print(cnonical_sm)
tmp = AllChem.Compute2DCoords( m)
if f_name is None:
f_name = '{}.png'.format( 'smiles')
Draw.MolToFile(m, f_name)
# For web service, plotting will be activated only if graph flag is true <2015-12-10>.
if graph:
img_m = plt.imread( f_name)
plt.imshow( img_m)
plt.show()
def _show_mol_r0( smiles = 'C1=CC=CC=C1', name_tag = False, idx = None):
"""
This function shows the molecule defined by smiles code.
The procedure follows:
-
First, benzene can be defined as follows.
Before defining molecule, the basic library of rdkit can be loaded using the import command.
Second, the 2D coordination of the molecule can be calculated.
For coordination calculation, AllChem sub-tool should be included.
Third, the molecular graph is drawn and save it
so as to see in the picture manipulation tool.
To use Draw, we must include Draw tool from rdkit.Chem.
Then, it is time to load png file and show the image on screen.
Input: smiles code
E.g.,
map( lambda xx: jchem.show_mol( xx[1], name_tag = True, idx = xx[0] + 1), enumerate(mol_smiles_list))
"""
if name_tag:
if idx:
print(idx, smiles)
else:
print(smiles)
m = Chem.MolFromSmiles( smiles)
tmp = AllChem.Compute2DCoords( m)
f_name = '{}.png'.format( 'smiles')
Draw.MolToFile(m, f_name)
img_m = plt.imread( f_name)
plt.imshow( img_m)
plt.show()
def showmol( smiles = 'C1=CC=CC=C1', name_tag = False, idx = None, sanitize = True):
"""
This function shows the molecule defined by smiles code.
The procedure follows:
-
First, benzene can be defined as follows.
Before defining molecule, the basic library of rdkit can be loaded using the import command.
Second, the 2D coordination of the molecule can be calculated.
For coordination calculation, AllChem sub-tool should be included.
Third, the molecular graph is drawn and save it
so as to see in the picture manipulation tool.
To use Draw, we must include Draw tool from rdkit.Chem.
Then, it is time to load png file and show the image on screen.
Input: smiles code
E.g.,
map( lambda xx: jchem.show_mol( xx[1], name_tag = True, idx = xx[0] + 1), enumerate(mol_smiles_list))
"""
if name_tag:
if idx:
print(idx, smiles)
else:
print(smiles)
m = Chem.MolFromSmiles( smiles, sanitize = sanitize)
print(m)
tmp = AllChem.Compute2DCoords( m)
f_name = '{}.png'.format( 'smiles')
Draw.MolToFile(m, f_name)
img_m = plt.imread( f_name)
plt.imshow( img_m)
plt.show()
def _calc_corr_r0( smilesArr, radius = 2, nBits = 1024):
ms_mid = [Chem.MolFromSmiles( m_sm) for m_sm in smilesArr]
f_m = [AllChem.GetMorganFingerprintAsBitVect(x, radius, nBits) for x in ms_mid]
Nm = len(f_m)
A = np.zeros( (Nm, Nm))
for (m1, f1) in enumerate(f_m):
for (m2, f2) in enumerate(f_m):
# print( "Base:{0}, Target:{1}".format( ms_smiles_base.keys()[bx], ms_smiles_mid.keys()[mx]))
A[m1, m2] = DataStructs.DiceSimilarity( f1, f2)
return A
def get_xM( s_l, radius = 4, nBits = 1024):
"""
Extract smiles codes and then convert them to fingerprint matrix.
"""
#s_l = pdr[ smiles_id].tolist()
m_l = list(map( Chem.MolFromSmiles, s_l))
fp_l = [AllChem.GetMorganFingerprintAsBitVect(m, radius = radius, nBits = nBits) for m in m_l]
xM = np.mat( fp_l)
return xM
def get_fpV( s_l, radius = 4, nBits = 1024):
"""
Extract smiles codes and then convert them to fingerprint matrix.
"""
#s_l = pdr[ smiles_id].tolist()
m_l = list(map( Chem.MolFromSmiles, s_l))
fp_l = [AllChem.GetMorganFingerprintAsBitVect(m, radius = radius, nBits = nBits).ToBitString() for m in m_l]
return fp_l
def get_fpD( s_l, radius = 4, nBits = 1024):
"""
Extract smiles codes and then convert them to fingerprint matrix.
"""
#s_l = pdr[ smiles_id].tolist()
m_l = list(map( Chem.MolFromSmiles, s_l))
fp_l = [AllChem.GetMorganFingerprintAsBitVect(m, radius = radius, nBits = nBits).ToBitString() for m in m_l]
fp_int_l = {}
fp_int_l['list'] = [ int(fp, base=2) for fp in fp_l]
fp_int_l['nBits'] = nBits
return fp_int_l
def calc_corr( smilesArr, radius = 2, nBits = 1024):
ms_mid = [Chem.MolFromSmiles( m_sm) for m_sm in smilesArr]
f_m = [AllChem.GetMorganFingerprintAsBitVect(x, radius, nBits) for x in ms_mid]
Nm = len(f_m)
A = np.zeros( (Nm, Nm))
for (m1, f1) in enumerate(f_m):
for (m2, f2) in enumerate(f_m):
# print( "Base:{0}, Target:{1}".format( ms_smiles_base.keys()[bx], ms_smiles_mid.keys()[mx]))
A[m1, m2] = DataStructs.TanimotoSimilarity( f1, f2)
return A
def calc_corr_r4( smilesArr, radius = 4, nBits = 1024):
ms_mid = [Chem.MolFromSmiles( m_sm) for m_sm in smilesArr]
f_m = [AllChem.GetMorganFingerprintAsBitVect(x, radius, nBits) for x in ms_mid]
Nm = len(f_m)
A = np.zeros( (Nm, Nm))
for (m1, f1) in enumerate(f_m):
for (m2, f2) in enumerate(f_m):
# print( "Base:{0}, Target:{1}".format( ms_smiles_base.keys()[bx], ms_smiles_mid.keys()[mx]))
A[m1, m2] = DataStructs.TanimotoSimilarity( f1, f2)
return A
def calc_corr_rad( smilesArr, radius = 2):
ms_mid = [Chem.MolFromSmiles( m_sm) for m_sm in smilesArr]
f_m = [AllChem.GetMorganFingerprint(x, radius) for x in ms_mid]
Nm = len(f_m)
A = np.zeros( (Nm, Nm))
for (m1, f1) in enumerate(f_m):
for (m2, f2) in enumerate(f_m):
# print( "Base:{0}, Target:{1}".format( ms_smiles_base.keys()[bx], ms_smiles_mid.keys()[mx]))
A[m1, m2] = DataStructs.DiceSimilarity( f1, f2)
return A
class jfingerprt_circular():
def __init__(self, radius = 2, nBits = 1024):
self.radius = radius
self.nBits = nBits
def smiles_to_ff( self, smilesArr):
"""
smiles array will be transformed to fingerprint array
"""
ms_mid = [Chem.MolFromSmiles( m_sm) for m_sm in smilesArr]
fps_mid = [AllChem.GetMorganFingerprintAsBitVect(x, self.radius, self.nBits) for x in ms_mid]
return fps_mid
def similarity( self, ms_smiles_mid, ms_smiles_base):
"""
Input: dictionary type required such as {nick name: smiles code, ...}
"""
"""
# Processing for mid
print( "Target: {}".format( ms_smiles_mid.keys()))
fps_mid = self.smiles_to_ff( ms_smiles_mid.values())
#processing for base
print( "Base: {}".format( ms_smiles_base.keys()))
fps_base = self.smiles_to_ff( ms_smiles_base.values())
"""
for idx in ["mid", "base"]:
ms_smiles = eval( 'ms_smiles_{}'.format( idx))
print(( '{0}: {1}'.format( idx.upper(), list(ms_smiles.keys()))))
exec( 'fps_{} = self.smiles_to_ff( ms_smiles.values())'.format( idx))
return fps_base, fps_mid
def return_similarity( self, ms_smiles_mid, ms_smiles_base, property_of_base = None):
fps_base, fps_mid = self.similarity( ms_smiles_mid, ms_smiles_base)
Nb, Nm = len(fps_base), len(fps_mid)
A = np.zeros( (Nm, Nb))
b = np.zeros( Nb)
for (bx, f_b) in enumerate(fps_base):
for (mx, f_m) in enumerate(fps_mid):
# print( "Base:{0}, Target:{1}".format( ms_smiles_base.keys()[bx], ms_smiles_mid.keys()[mx]))
A[mx, bx] = DataStructs.DiceSimilarity( f_b, f_m)
# print( A[mx, bx])
if property_of_base:
b[ bx] = property_of_base[ bx]
# print( b[ bx])
if property_of_base:
# print "b is obtained."
return A, b
else:
return A
def get_w( self, ms_smiles_mid, ms_smiles_base, property_of_base):
"""
property_of_base, which is b, must be entered
"""
[A, b] = self.return_similarity( ms_smiles_mid, ms_smiles_base, property_of_base)
w = np.dot( np.linalg.pinv(A), b)
return w
def get_w_full( self, ms_smiles_mid, ms_smiles_base, property_of_base):
"""
property_of_base, which is b, must be entered
"""
[A, b] = self.return_similarity( ms_smiles_mid, ms_smiles_base, property_of_base)
B = A.transpose()
w_full = np.dot( np.linalg.pinv(B), b)
return w_full
def clean_smiles_vec( sv):
"It removes bad smiles code elements in smiles code vector."
new_sv = []
for x in sv:
y = Chem.MolFromSmiles(x)
if y:
new_sv.append( x)
print("Vector size becomes: {0} --> {1}".format( len(sv), len(new_sv)))
return new_sv
def clean_smiles_vec_io( sv, out):
""""
It removes bad smiles code elements in smiles code vector
as well as the corresponding outut value vector.
"""
new_sv = []
new_out = []
for x, o in zip( sv, out):
y = Chem.MolFromSmiles(x)
if y:
new_sv.append( x)
new_out.append( o)
# print "Vector size becomes: {0} --> {1}".format( len(sv), len(new_sv))
return new_sv, new_out
def _clean_fp_M_r0( xM):
"""
1. Zero sum column vectors will be removed.
2. All one column vectors wiil be also removed.
"""
xM_clean = []
xM_sum = np.sum( xM, 0)
for iy in range( xM.shape[1]):
if xM_sum and xM_sum < xM.shape[0]:
xM_column = xM[:,iy].T.tolist()[0]
xM_clean.append( xM_column)
return xM_clean
def _clean_fp_M_r0( xM):
"""
1. Zero sum column vectors will be removed.
2. All one column vectors will be also removed.
3. The same patterns for different position will be merged to one.
"""
#xM_clean = np.copy( xM)
iy_list = []
xM_sum = np.sum( xM, 0)
for iy in range( xM.shape[1]):
if xM_sum[0,iy] == 0 or xM_sum[0,iy] == xM.shape[0]:
#print 'deleted: ', iy
iy_list.append( iy)
xM = np.delete(xM, iy_list, 1)
# if pattern is the same, the same pattern columns are removed except remaining only one column
iy_list = []
for iy in range( xM.shape[1]):
if iy not in iy_list:
pat = xM[:, iy]
# print pat
for iy2 in range( iy+1, xM.shape[1]):
if iy2 not in iy_list:
if not np.all( pat - xM[:, iy2]):
iy_list.append( iy2)
#print iy_list
xM = np.delete(xM, iy_list, 1)
return xM
def _clean_fp_M_r0( xM):
"""
1. Zero sum column vectors will be removed.
2. All one column vectors wiil be also removed.
3. The same patterns for different position will be merged to one.
* np.all() and np.any() should be understand clearly.
"""
#xM_clean = np.copy( xM)
iy_list = []
xM_sum = np.sum( xM, 0)
for iy in range( xM.shape[1]):
if xM_sum[0,iy] == 0 or xM_sum[0,iy] == xM.shape[0]:
#print 'deleted: ', iy
iy_list.append( iy)
xM = np.delete(xM, iy_list, 1)
# if pattern is the same, the same pattern columns are removed except remaining only one column
iy_list = []
for iy in range( xM.shape[1]):
if iy not in iy_list:
pat = xM[:, iy]
# print pat
for iy2 in range( iy+1, xM.shape[1]):
if iy2 not in iy_list:
if not np.any( pat - xM[:, iy2]):
iy_list.append( iy2)
#print iy_list
#xM = np.delete(xM, iy_list, 1)
return xM
def gff( smiles = 'c1ccccc1O', rad = 2, nBits = 1024):
"It generates fingerprint from smiles code"
x = Chem.MolFromSmiles( smiles)
return AllChem.GetMorganFingerprintAsBitVect( x, rad, nBits)
def gfb( smiles = 'c1ccccc1O', rad = 4, nBits = 1024):
"""
It generates fingerprint from smiles code
Fingerprint is fp not ff, so it is changed from ff to fp.
Morevoer, rad = 4 is default for property modeling.
"""
x = Chem.MolFromSmiles( smiles)
return AllChem.GetMorganFingerprintAsBitVect( x, rad, nBits)
def gff_vec( smiles_vec, rad = 2, nBits = 1024):
"It generates a fingerprint vector from a smiles code vector"
return [gff(x, rad, nBits) for x in smiles_vec]
def gfb_vec( smiles_vec, rad = 4, nBits = 1024):
"It generates a fingerprint vector from a smiles code vector"
return [gfb(x, rad, nBits) for x in smiles_vec]
def _gff_binlist_r0( smiles_vec, rad = 2, nBits = 1024):
"""
It generates a binary list of fingerprint vector from a smiles code vector.
Each string will be expanded to be the size of nBits such as 1024.
- It shows error message when nBits < 1024 and len(x) > nBits.
"""
ff_vec = gff_vec( smiles_vec, rad, nBits)
ff_bin = [ bin(int(x.ToBinary().encode("hex"), 16)) for x in ff_vec]
#Show error message when nBits < 1024 and len(x) > nBits
for x in ff_bin:
if len(x[2:]) > nBits:
print('The length of x is {0}, which is larger than {1}'.format(len(x[2:]), nBits))
print('So, the minimal value of nBits must be 1024 generally.')
return [ list(map( int, list( '0'*(nBits - len(x[2:])) + x[2:]))) for x in ff_bin]
def gff_binlist( smiles_vec, rad = 2, nBits = 1024):
"""
It generates a binary list of fingerprint vector from a smiles code vector.
Each string will be expanded to be the size of nBits such as 1024.
- It shows error message when nBits < 1024 and len(x) > nBits.
- Now bits reduced to match input value of nBit eventhough the real output is large
"""
ff_vec = gff_vec( smiles_vec, rad, nBits)
ff_bin = [ bin(int(x.ToBinary().encode("hex"), 16)) for x in ff_vec]
#Show error message when nBits < 1024 and len(x) > nBits
"""
for x in ff_bin:
if len(x[2:]) > nBits:
print 'The length of x is {0}, which is larger than {1}'.format(len(x[2:]), nBits)
print 'So, the minimal value of nBits must be 1024 generally.'
return [ map( int, list( '0'*(nBits - len(x[2:])) + x[2:])) for x in ff_bin]
"""
return [ list(map( int, list( jutil.sleast(x[2:], nBits)))) for x in ff_bin]
def gfb_binlist( smiles_vec, rad = 4, nBits = 1024):
"""
It generates a binary list of fingerprint vector from a smiles code vector.
Each string will be expanded to be the size of nBits such as 1024.
- It shows error message when nBits < 1024 and len(x) > nBits.
- Now bits reduced to match input value of nBit eventhough the real output is large
- fp clean will be adopted.
"""
ff_vec = gfb_vec( smiles_vec, rad, nBits)
ff_bin = [ bin(int(x.ToBinary().encode("hex"), 16)) for x in ff_vec]
#Show error message when nBits < 1024 and len(x) > nBits
"""
for x in ff_bin:
if len(x[2:]) > nBits:
print 'The length of x is {0}, which is larger than {1}'.format(len(x[2:]), nBits)
print 'So, the minimal value of nBits must be 1024 generally.'
return [ map( int, list( '0'*(nBits - len(x[2:])) + x[2:])) for x in ff_bin]
"""
return [ list(map( int, list( jutil.sleast(x[2:], nBits)))) for x in ff_bin]
def gfp_binlist( smiles_vec, rad = 4, nBits = 1024):
gff_binlist( smiles_vec, rad = rad, nBits = nBits)
def gff_binlist_bnbp( smiles_vec, rad = 2, nBits = 1024, bnbp = 'bn'):
"""
It generates a binary list of fingerprint vector from a smiles code vector.
Each string will be expanded to be the size of nBits such as 1024.
- It shows error message when nBits < 1024 and len(x) > nBits.
- Now bits reduced to match input value of nBit eventhough the real output is large
bnbp --> if binary input, bnbp = 'bn', else if bipolar input, bnbp = 'bp'
"""
ff_vec = gff_vec( smiles_vec, rad, nBits)
ff_bin = [ bin(int(x.ToBinary().encode("hex"), 16)) for x in ff_vec]
if bnbp == 'bp': #bipolar input generation
return [ list(map( jutil.int_bp, list( jutil.sleast(x[2:], nBits)))) for x in ff_bin]
else:
return [ list(map( int, list( jutil.sleast(x[2:], nBits)))) for x in ff_bin]
def gff_M( smiles_vec, rad = 2, nBits = 1024):
"It generated a binary matrix from a smiles code vecor."
return np.mat(gff_binlist( smiles_vec, rad = rad, nBits = nBits))
def gfp_M( smiles_vec, rad = 4, nBits = 1024):
"It generated a binary matrix from a smiles code vecor."
xM = np.mat(gfb_binlist( smiles_vec, rad = rad, nBits = nBits))
#Now fingerprint matrix is cleaned if column is all the same value such as all 1, all 0
return clean_fp_M( xM)
def gfp_M_simple( smiles_vec):
"It generated a binary matrix from a smiles code vecor."
xM = []
for xs in smiles_vec:
mol = Chem.MolFromSmiles( xs)
fp = Chem.RDKFingerprint( mol)
fp_b = fp.ToBitString()
fp_b_list = list(map( int, fp_b))
xM.append( fp_b_list)
xM = np.mat( xM)
return xM
def gff_M_bnbp( smiles_vec, rad = 2, nBits = 1024, bnbp = 'bn'):
"It generated a binary matrix from a smiles code vecor."
return np.mat(gff_binlist_bnbp( smiles_vec, rad, nBits, bnbp))
def ff_bin( smiles = 'c1ccccc1O'):
"""
It generates binary string fingerprint value
Output -> '0b0010101...'
"""
mol = Chem.MolFromSmiles( smiles)
fp = AllChem.GetMorganFingerprint(mol,2)
fp_hex = fp.ToBinary().encode("hex")
fp_bin = bin( int( fp_hex, 16))
# print fp_bin
return fp_bin
def ff_binstr( smiles = 'c1ccccc1O'):
"""
It generates binary string fingerprint value without head of 0b.
So, in order to translate back into int value, the head should be attached
at the starting point. output_bin = '0b' + output_binstr
Output -> '0010101...'
"""
mol = Chem.MolFromSmiles( smiles)
fp = AllChem.GetMorganFingerprint(mol,2)
fp_hex = fp.ToBinary().encode("hex")
fp_bin = bin( int( fp_hex, 16))
fp_binstr = fp_bin[2:]
# print fp_bin
return fp_binstr
def ff_int( smiles = 'c1ccccc1O'):
"""
It generates binary string fingerprint value
Output -> long integer value
which can be transformed to binary string using bin()
"""
mol = Chem.MolFromSmiles( smiles)
fp = AllChem.GetMorganFingerprint(mol,2)
fp_hex = fp.ToBinary().encode("hex")
fp_int = int( fp_hex, 16)
# fp_bin = bin( fp_int)
# print fp_bin
return fp_int
def calc_tm_dist_int( A_int, B_int):
"""
Calculate tanimoto distance of A_int and B_int
where X_int isinteger fingerprint vlaue of material A.
"""
C_int = A_int & B_int
A_str = bin(A_int)[2:]
B_str = bin(B_int)[2:]
C_str = bin(C_int)[2:]
lmax = max( [len( A_str), len( B_str), len( C_str)])
""" this shows calculation process
print "A:", A_str.ljust( lmax, '0')
print "B:", B_str.ljust( lmax, '0')
print "C:", C_str.ljust( lmax, '0')
"""
a = A_str.count('1')
b = B_str.count('1')
c = C_str.count('1')
# print a, b, c
if a == 0 and b == 0:
tm_dist = 1
else:
tm_dist = float(c) / float( a + b - c)
return tm_dist
def calc_tm_dist( A_smiles, B_smiles):
A_int = ff_int( A_smiles)
B_int = ff_int( B_smiles)
return calc_tm_dist_int( A_int, B_int)
def getw( Xs, Ys, N = 57, nBits = 400):
"It calculate weight vector for specific N and nNBits."
Xs50 = Xs[:N]
Ys50 = Ys[:N]
X = gff_M( Xs50, nBits=400)
y = np.mat( Ys50).T
print(X.shape)
# Xw = y is assumed for Mutiple linear regression
w = np.linalg.pinv( X) * y
#print w
plt.plot( w)
plt.show()
return w
def getw_clean( Xs, Ys, N = None, rad = 2, nBits = 1024):
"Take only 50, each of which has safe smile code."
nXs, nYs = clean_smiles_vec_io( Xs, Ys)
# print len(nXs), len(nYs)
if N is None:
N = len( nXs)
X = gff_M( nXs[:N], rad = rad, nBits = nBits)
y = np.mat( nYs[:N]).T
w = np.linalg.pinv( X) * y
plt.plot( w)
plt.title('Weight Vector')
plt.show()
y_calc = X*w
e = y - y_calc
se = (e.T * e)
mse = (e.T * e) / len(e)
print("SE =", se)
print("MSE =", mse)
print("RMSE =", np.sqrt( mse))
plt.plot(e)
plt.title("Error Vector: y - y_{calc}")
plt.show()
plt.plot(y, label='original')
plt.plot(y_calc, label='predicted')
plt.legend()
plt.title("Output values: org vs. pred")
plt.show()
return w
def getw_clean_bnbp( Xs, Ys, N = None, rad = 2, nBits = 1024, bnbp = 'bn'):
"""
Take only 50, each of which has safe smile code.
Translate the input into bipolar values.
"""
nXs, nYs = clean_smiles_vec_io( Xs, Ys)
# print len(nXs), len(nYs)
if N is None:
N = len( nXs)
X = gff_M_bnbp( nXs[:N], rad = rad, nBits = nBits, bnbp = bnbp)
y = np.mat( nYs[:N]).T
w = np.linalg.pinv( X) * y
plt.plot( w)
plt.title('Weight Vector')
plt.show()
y_calc = X*w
e = y - y_calc
se = (e.T * e)
mse = (e.T * e) / len(e)
print("SE =", se)
print("MSE =", mse)
print("RMSE =", np.sqrt( mse))
plt.plot(e)
plt.title("Error Vector: y - y_{calc}")
plt.show()
plt.plot(y, label='original')
plt.plot(y_calc, label='predicted')
plt.legend()
plt.title("Output values: org vs. pred")
plt.show()
return w
def fpM_pat( xM):
#%matplotlib qt
xM_sum = np.sum( xM, axis = 0)
plt.plot( xM_sum)
plt.xlabel('fingerprint bit')
plt.ylabel('Aggreation number')
plt.show()
def gen_input_files( A, yV, fname_common = 'ann'):
"""
Input files of ann_in.data and ann_run.dat are gerneated.
ann_in.data and ann_run.data are training and testing data, respectively
where ann_run.data does not includes output values.
The files can be used in ann_aq.c (./ann_aq)
* Input: A is a matrix, yV is a vector with numpy.mat form.
"""
# in file
no_of_set = A.shape[0]
no_of_input = A.shape[1]
const_no_of_output = 1 # Now, only 1 output is considerd.
with open("{}_in.data".format( fname_common), "w") as f:
f.write( "%d %d %d\n" % (no_of_set, no_of_input, const_no_of_output))
for ix in range( no_of_set):
for iy in range( no_of_input):
f.write( "{} ".format(A[ix,iy]))
f.write( "\n{}\n".format( yV[ix,0]))
print(("{}_in.data is saved for trainig.".format( fname_common)))
# run file
with open("{}_run.data".format( fname_common), "w") as f:
#In 2015-4-9, the following line is modified since it should not be
#the same to the associated line in ann_in data but it does not include the output length.
f.write( "%d %d\n" % (no_of_set, no_of_input))
for ix in range( no_of_set):
for iy in range( no_of_input):
f.write( "{} ".format(A[ix,iy]))
f.write( "\n")
print(("{}_run.data is saved for testing.".format( fname_common)))
def gen_input_files_valid( At, yt, Av):
"""
Validation is also considerd.
At and yt are for training while Av, yv are for validation.
Input files of ann_in.data and ann_run.dat are gerneated.
The files are used in ann_aq.c (./ann_aq)
* Input: At, Av is matrix, yt, yv is vector
"""
const_no_of_output = 1 # Now, only 1 output is considerd.
# in file
no_of_set = At.shape[0]
no_of_input = At.shape[1]
with open("ann_in.data", "w") as f:
f.write( "%d %d %d\n" % (no_of_set, no_of_input, const_no_of_output))
for ix in range( no_of_set):
for iy in range( no_of_input):
f.write( "{} ".format(At[ix,iy]))
f.write( "\n{}\n".format( yt[ix,0]))
print(("ann_in.data with {0} sets, {1} inputs is saved".format( no_of_set, no_of_input)))
# run file
no_of_set = Av.shape[0]
no_of_input = Av.shape[1]
with open("ann_run.data", "w") as f:
f.write( "%d %d\n" % (no_of_set, no_of_input))
for ix in range( no_of_set):
for iy in range( no_of_input):
f.write( "{} ".format(Av[ix,iy]))
f.write( "\n")
print(("ann_run.data with {0} sets, {1} inputs is saved".format( no_of_set, no_of_input)))
def get_valid_mode_output( aV, yV, rate = 3, more_train = True, center = None):
"""
Data is organized for validation. The part of them becomes training and the other becomes validation.
The flag of 'more_train' represents tranin data is bigger than validation data, and vice versa.
"""
ix = list(range( len( yV)))
if center == None:
center = int(rate/2)
if more_train:
ix_t = [x for x in ix if x%rate != center]
ix_v = [x for x in ix if x%rate == center]
else:
ix_t = [x for x in ix if x%rate == center]
ix_v = [x for x in ix if x%rate != center]
aM_t, yV_t = aV[ix_t, 0], yV[ix_t, 0]
aM_v, yV_v = aV[ix_v, 0], yV[ix_v, 0]
return aM_t, yV_t, aM_v, yV_v
def get_valid_mode_data( aM, yV, rate = 3, more_train = True, center = None):
"""
Data is organized for validation. The part of them becomes training and the other becomes validation.
The flag of 'more_train' represents tranin data is bigger than validation data, and vice versa.
"""
ix = list(range( len( yV)))
if center == None:
center = int(rate/2)
if more_train:
ix_t = [x for x in ix if x%rate != center]
ix_v = [x for x in ix if x%rate == center]
else:
ix_t = [x for x in ix if x%rate == center]
ix_v = [x for x in ix if x%rate != center]
aM_t, yV_t = aM[ix_t, :], yV[ix_t, 0]
aM_v, yV_v = aM[ix_v, :], yV[ix_v, 0]
return aM_t, yV_t, aM_v, yV_v
def _estimate_accuracy_r0( yv, yv_ann, disp = False):
"""
The two column matrix is compared in this function and
It calculates RMSE and r_sqr.
"""
e = yv - yv_ann
se = e.T * e
aae = np.average( np.abs( e))
RMSE = np.sqrt( se / len(e))
# print "RMSE =", RMSE
y_unbias = yv - np.mean( yv)
s_y_unbias = y_unbias.T * y_unbias
r_sqr = 1.0 - se/s_y_unbias
if disp:
print("r_sqr = {0:.3e}, RMSE = {1:.3e}, AAE = {2:.3e}".format( r_sqr[0,0], RMSE[0,0], aae))
return r_sqr[0,0], RMSE[0,0]
def estimate_accuracy( yv, yv_ann, disp = False):
"""
The two column matrix is compared in this function and
It calculates RMSE and r_sqr.
"""
print(yv.shape, yv_ann.shape)
if not( yv.shape[0] > 0 and yv.shape[1] == 1 and yv.shape == yv_ann.shape):
raise TypeError( 'Both input data matrices must be column vectors.')
e = yv - yv_ann
se = e.T * e
aae = np.average( np.abs( e))
RMSE = np.sqrt( se / len(e))
# print "RMSE =", RMSE
y_unbias = yv - np.mean( yv)
s_y_unbias = y_unbias.T * y_unbias
r_sqr = 1.0 - se/s_y_unbias
if disp:
print("r_sqr = {0:.3e}, RMSE = {1:.3e}, AAE = {2:.3e}".format( r_sqr[0,0], RMSE[0,0], aae))
yv_a = np.array(yv).reshape(-1)
yv_ann_a = np.array(yv_ann).reshape(-1)
pr, _ = stats.pearsonr(yv_a, yv_ann_a)
#pr, _ = stats.pearsonr(yv, yv_ann)
print("Pearson R = {:.3e}".format(pr))
#print "len(e) = ", len(e)
#print "se = ", se
#print "s_y_unbias =", s_y_unbias
return r_sqr[0,0], RMSE[0,0]
def estimate_accuracy3( yv, yv_ann, disp = False):
"""
The two column matrix is compared in this function and
It calculates RMSE and r_sqr.
"""
print(yv.shape, yv_ann.shape)
if not( yv.shape[0] > 0 and yv.shape[1] == 1 and yv.shape == yv_ann.shape):
raise TypeError( 'Both input data matrices must be column vectors.')
e = yv - yv_ann
se = e.T * e
aae = np.average( np.abs( e))
RMSE = np.sqrt( se / len(e))
# print "RMSE =", RMSE
y_unbias = yv - np.mean( yv)
s_y_unbias = y_unbias.T * y_unbias
r_sqr = 1.0 - se/s_y_unbias
if disp:
print("r_sqr = {0:.3e}, RMSE = {1:.3e}, AAE = {2:.3e}".format( r_sqr[0,0], RMSE[0,0], aae))
#print "len(e) = ", len(e)
#print "se = ", se
#print "s_y_unbias =", s_y_unbias
return r_sqr[0,0], RMSE[0,0], aae
def to1D( A):
"""
Regardless of a type of A is array or matrix,
to1D() return 1D numpy array.
"""
return np.array(A).flatten()
def estimate_score3( yv, yv_ann, disp = False):
"""
The two column matrix is compared in this function and
It calculates RMSE and r_sqr.
"""
yv = to1D( yv)
yv_ann = to1D( yv_ann)
if disp:
print("The shape values of yv and yv_ann are", yv.shape, yv_ann.shape)
if not( yv.shape[0] > 0 and yv.shape[0] == yv_ann.shape[0]):
raise TypeError("The length of the input vectors should be equal and more than zero.")
e = yv - yv_ann
MAE = np.average( np.abs( e))
RMSE = np.sqrt( np.average( np.power( e, 2)))
r_sqr = 1.0 - np.average( np.power( e, 2)) / np.average( np.power( yv - np.mean( yv), 2))
if disp:
print("r_sqr = {0:.3e}, RMSE = {1:.3e}, MAE = {2:.3e}".format( r_sqr, RMSE, MAE))
return r_sqr, RMSE, MAE
class FF_W:
"""