-
Notifications
You must be signed in to change notification settings - Fork 1
/
FAAHA.py
3864 lines (3008 loc) · 107 KB
/
FAAHA.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
''' FAAHA: top-level full-workflow module for FAAH only
Created on 26 May 16
@author: rik
'''
from collections import defaultdict
import ConfigParser
import cPickle
import csv
import datetime
import glob
import json
import math
import os
import re
import socket
import string
import subprocess
import sys
import pwd
import grp
import os
import random
import numpy as np
import scipy.cluster.hierarchy as sch
# NB, using scipy's spatial distance (not SKLearn's metrics)
import scipy.spatial.distance as distance
from scipy.sparse.dok import dok_matrix
import matplotlib
from operator import irepeat
from sets import ImmutableSet
matplotlib.use('Agg') # ASSUME no windowing; prevent figures from popping up with savefig()
# Although many examples use pylab, it is no longer recommended.
# import pylab as p
import matplotlib.pyplot as p
import matplotlib.gridspec as gridspec
import matplotlib.cm as cm
import pandas as pd
import pybel
ob = pybel.ob
import recap3 as recap
import macrocycleopener
import fastcluster
## other FAAHA modules
import config
import crawl_ADV
import plot
import getPDBQT
## Global variables, constants
config.RunName = ''
LowEDir = ''
InterTblDir = ''
RLIFDir = ''
L2FDir = ''
FragSimDir = ''
R2FDir = ''
LigCoordDir = ''
PlotDir = ''
ArffDir = ''
HIFDir = ''
InterTypes = ('hba', 'hbd', 'mtl','ppi','tpi','vdw')
BinaryITypes = ('hba', 'hbd', 'mtl','ppi','tpi')
FE_coeff_tors = 0.2983 # cf AD4.1_bound.dat
TooBigE = 30.
# 2DO: appropriate limits on LigEff, LigEnth?
TooBigLigEff = 30.
TooBigLigEnth = 30.
LibList = ['NF','EN','CB','AS','VM']
LigDOFTbl = {}
AADict = {'ASP':'D', 'GLU':'E', 'LYS':'K', 'HIS':'H', 'ARG':'R',
'GLN':'Q', 'ASN':'N', 'SER':'S', 'ASX':'B', 'GLX':'Z',
'PHE':'F', 'TRP':'W', 'TYR':'Y',
'GLY':'G', 'ALA':'A', 'ILE':'I', 'LEU':'L', 'CYS':'C',
'MET':'M', 'THR':'T', 'VAL':'V', 'PRO':'P',
'HID':'H', 'HIE':'H', 'HIP':'H',
'ASH':'D', 'GLH':'E',
'LYN':'K', 'ARN':'R',
'HOH':'U', 'CL': 'J' }
SmartsPat = None # initialized to ob.OBSmartsPattern() in bldLig2Frag()
## utilities
def basicStats(l):
"Returns avg and stdev"
if len(l) == 0:
return(0.,0.)
tot = 0
for n in l:
tot += n
avg = float(tot) / len(l)
sumDiffSq = 0.
for n in l:
sumDiffSq += (n-avg)*(n-avg)
stdev = math.sqrt(sumDiffSq) / float(len(l))
return (avg,stdev)
def jaccardSim(set1,set2):
return float(len(set1.intersection(set2))) / len(set1.union(set2))
def freqHist(tbl):
"Assuming values are frequencies, returns sorted list of (val,freq) items in descending freq order"
def cmpd1(a,b):
"decreasing order of frequencies"
return cmp(b[1], a[1])
flist = tbl.items()
flist.sort(cmpd1)
return flist
def entropy2(ix,iy):
x = float(ix)
y = float(iy)
if x==0:
e=0.
else:
e = -(x / (x+y)) * math.log( x / (x+y) , 2.0)
if y > 0.:
e += -(y / (x+y)) * math.log( y / (x+y) , 2.0)
return e
def infoGain(tp,fp,tn,fn):
all = tp+fp+tn+fn
prob = float(tp+fp) / all
pnot = 1. - prob
ig = entropy2(tp+fn,fp+tn)
pos = entropy2(tp,fp)
neg = entropy2(fn,tn)
ig -= prob * pos
ig -= pnot * neg
assert ig >= 0., 'Negative info gain?!'
return (ig,prob,pos,neg)
def ranges2list(rangeList):
'invert bldRanges()'
l = []
for e in rangeList:
if type(e)==type(1): # singleton int
l.append(e)
else:
l += range(e[0],e[1]+1)
return l
def rndEstr(e,ndig=0):
"round to nearest integral +ndig kcal"
fstr = '{0:0%d.%df}' % (ndig+4,ndig) # so two-digit energies sort correctly as strings!
rstr = fstr.format(e)
return rstr
def touchTimeDiff(f1,f2):
'''given two files (earlyFile, lateFile), return seconds between their touch times
'''
t1 = os.stat(f1).st_mtime
t2 = os.stat(f2).st_mtime
return t2 - t1
def setConfigOptions(cfg,module='',verbose=True):
'''bind all config options to variables (in module)
option type (Pred,Int,Float) stripped from variable name before binding
ASSUME cfg has cfg.optionxform=str so case is maintained
'''
# NB: DEFAULT parameters included by ALL sections!
if verbose: print '<setConfigOptions>'
for section in cfg.sections():
for k,v in cfg.items(section):
# import pdb; pdb.set_trace()
if v == 'None':
v = None
elif k.endswith('Pred'):
v = cfg.getboolean(section,k)
k = k[:-4]
elif k.endswith('Int'):
v = cfg.getint(section,k)
k = k[:-3]
elif k.endswith('Float'):
v = cfg.getfloat(section,k)
k = k[:-5]
else:
v = '"' + v + '"'
# print '%s %s' % (k,v),
if module=='':
exec('%s = %s' % (k,v))
if verbose: print '%s \t = %s' % (k,eval(k))
else:
exec('%s.%s = %s' % (module,k,v))
if verbose: print '%s.%s \t = %s' % (module,k,eval('%s.%s' % (module,k)))
if verbose: print '</setConfigOptions>'
## eo utilities
def bldExptTbl(inf):
'''return summary table of experiments
exptKey = (exptNo,prot,recept,site,lib)
experiment attributes: bstart bend sys lib protein receptor site
'''
reader = csv.DictReader(open(inf))
# bstart,bend,receptor,protein,site,library,experiment,pdb,gpf,dpf,program,config
# 5398,5398,x1k6_EqMD,PR,Exo_ChnA,CB_bb,27,1KZK,faah_ExpandedExo_4_Jan2009.gpf,faah_template_EndByGen_March09.dpf,AD
redunKeyFnd = False
exptTbl = {}
for i,entry in enumerate(reader):
if entry['bstart'].startswith('# '):
continue
# HACK:
# replace any '_' in receptor, site, library with '-'
# to avoid interactions with underbar concatenations later
exptData = {}
try:
exptNo = entry['experiment']
# 160217: require consistent hyphens within prot (experiment) name
# prot = entry['protein'].replace('_','-')
prot = entry['protein']
if prot.find('_') != -1:
sys.exit('bldExptTbl: require hyphens within protein name?!')
recept = entry['receptor'].replace('_','-')
recept = entry['receptor'].replace('.pdbqt','')
site = entry['site'].replace('_','-')
lib = entry['library'].replace('_','-')
exptData['bstart'] = int(entry['bstart'])
exptData['bend'] = int(entry['bend'])
exptData['sys'] = config.RunType
except Exception,e:
print 'bldExptTbl: bad entry?! %s %s' % (e,entry)
continue
exptData['lib'] = lib
exptData['protein'] = prot
exptData['receptor'] = recept
exptData['site'] = site
exptKey = (exptNo,prot,recept,site,lib)
if exptKey in exptTbl:
print 'bldExptTbl: dup key?! %s \n\twas: %s\n\tnew: %s' % (exptKey,exptTbl[exptKey],exptData)
redunKeyFnd = True
continue
exptTbl[exptKey] = exptData
print 'bldExptTbl: NExpt=%d' % (len(exptTbl))
if redunKeyFnd:
print 'bldExptTbl: redun keys disallowed!'
return None
return exptTbl
def FAAHA_expt(exptTbl,exptList,faahDirParent,outDir):
''' Identify top ncand and top frac4Thresh for each experiment
first pass sorts all energies, identifies threshold,
outputs best ncand candidates ACROSS ALL EXPERIMENTS to best_*.csv
two thresholds computed: threshold=thresh@frac4Thresh; bestCandThresh=thresh@ncand
computes, saves NonZincLigTbl in getThresh()
NB: exptTbl augmented with threshold!
'''
thresh = config.Frac4Thresh
ncand = config.NCand
dcrit = config.Criterion
## Process experiments in exptList
# print 'Expt,Lib,NBatch,NRcd,NLigand,NLowE,NDup,AvgRcd,FracLowE'
allExpt = exptTbl.keys()
expt2do = []
for exptKey in allExpt:
(exptNo,prot,recept,site,lib) = exptKey
# NB: accept exptList with 'Exp' ala processed, crawled directories
if exptList:
if exptNo in exptList:
expt2do.append(exptKey)
else:
print 'skipping',exptKey
else:
expt2do.append(exptKey)
print 'FAAHA_expt: exptList=%s NExpt=%d' % (exptList,len(expt2do))
candf = outDir+('bestLig_%d.csv' % ncand)
cands = open(candf,'w')
cands.write('Expt,Batch,Ligand,E,FullExpt\n')
runType = config.RunType
newExptTbl = {}
expt2do.sort()
for exptKey in expt2do:
exptNo,prot,recept,site,lib = exptKey
exptData = exptTbl[exptKey]
exptName = bldExptStr(exptKey)
# Experiments collapse all results into single file;
batchList = ranges2list( [(exptData['bstart'],exptData['bend'])] )
lib = exptTbl[exptKey]['lib']
nbatch = len(batchList)
faahDir = faahDirParent + exptNo + '/' + recept + '/'
frac4Thresh=config.Frac4Thresh
uniqLigTbl, thresh, bestCandThresh = getThresh(exptKey,runType,batchList,faahDir,frac4Thresh, \
ncand=config.NCand,dcrit=config.Criterion,initRun=True)
newExptTbl[exptKey] = exptData.copy()
# NB: exptTbl augmented with threshold!
newExptTbl[exptKey]['thresh'] = thresh
# 150930 keep ncand thresh info too
newExptTbl[exptKey]['ncand'] = ncand
newExptTbl[exptKey]['bestCandThresh'] = bestCandThresh
## 2d pass
outs = open(LowEDir+('%s_lowE.csv' % exptName),'w')
# cf. mglTop_visit_AD() for header line
fldNameLine = 'Batch,Ligand,E,Eff,DCVal,Nvdw,Ninter\n'
outs.write(fldNameLine)
nrcd = 0
nlowE = 0
ndup = 0
nbadE = 0
nmissUniq = 0
nbadZinc = 0
lowETbl = {}
ligTblE = {}
runType = config.RunType
exptLigDir = EliteDir + exptName + '/'
nnrtiDrop = 0
for isf,batchNo in enumerate(batchList):
summPath = faahDir+('summ/%s_summ_%07d.csv' % (runType,batchNo))
try:
inStr = open(summPath)
except Exception,e:
# ASSUME counted as nmissf above
# print "FAAHA_expt: can't open2 %s?!" % (summPath)
continue
for il,line in enumerate(inStr.readlines()):
if il == 0:
# Expt,Recept,Ligand,E,Eff,Nvdw,Ninter
# written by get_ADInfo.rptData()
continue
nrcd += 1
try:
flds =line[:-1].split(',')
(expt,batch,ligRecept,ligand,e,eff,nvdv,ninter) = flds
if dcrit == 'energy':
dval = float(e)
elif dcrit == 'ligEff':
dval = float(eff)
elif dcrit == 'ligEnth':
# Assume LigDOFTbl already loaded
if ligand not in LigDOFTbl:
print 'FAAHA_expt: lig missing from LigDOFTbl?!',ligand
continue
dof = LigDOFTbl[ligand]
natom = float(e) / float(eff)
natomi = int(natom)
assert natomi-natom > 1e-2, 'huh?'
dval = (float(e) + (dof * FE_coeff_tors)) / natom
except Exception, exp:
print "FAAHA_expt: bad line(2) %s %d %s?!" % (summPath,il,exp)
break # don't try to read other lines from inStr
# Pass2: need to make this thresh criterion-sensitive, too
if (dcrit == 'energy' and abs(dval) > TooBigE) or \
(dcrit == 'ligEff' and abs(dval) > TooBigLigEff) or \
(dcrit == 'ligEnth' and abs(dval) > TooBigLigEnth):
nbadE += 1
continue
ligIdx = normLigand(ligand)
if ligIdx == -1:
nbadZinc += 1
continue
ligand2 = ligIdx2zinc(ligIdx)
if ligand2 != ligand:
# NB: two ligand cleanups!
if not (ligand.endswith('.VS') or ligand.find('pras') != -1):
print 'FAAHA_expt: bad ligand indexing?!', ligand, ligIdx, ligand2
import pdb; pdb.set_trace()
continue
# 160122: Remove redundant ligands
if ligIdx not in uniqLigTbl:
nmissUniq += 1
print 'FAAHA_expt: ligand not seen by getThresh()?!',ligand, batchNo
continue
# only keep one (first) docking result wrt/ same ligand
ubatch,udval = uniqLigTbl[ligIdx]
if ubatch != batchNo:
ndup += 1
continue
## thresh
# NB: thresh set EQUAL to highest energy in getThresh()
if dval <= thresh:
nlowE += 1
## NB: all 3 vals (e,eff,dval) written to lowE file; why not!
newline = '%d,%s,%s,%s,%s,%s,%s\n' % (batchNo,ligand,e,eff,dval,nvdv,ninter)
outs.write(newline)
if dval < bestCandThresh:
cands.write('%s,%d,%s,%f,%s\n' % (exptNo,batchNo,ligand,dval,exptName))
inStr.close() # eo-batch file
nlig = len(uniqLigTbl)
outs.close()
try:
avgRcd = float(nrcd)/nbatch
except:
avgRcd = 0
print 'FAAHA_expt: %s NBatch=%d NRcd=%d NLigand=%d NBadZinc=%d NNonUniq=%d NLowE=%d NDup=%d NBadE=%d AvgRcd/File=%f NNRTIDrop=%d' % \
(exptName,nbatch,nrcd,nlig,nbadZinc,nmissUniq,nlowE,ndup,nbadE,avgRcd,nnrtiDrop)
cands.close()
return newExptTbl
def getThresh(exptKey,runType,batchList,faahDir,frac4Thresh,ncand,initRun=False,dcrit='energy'):
'''set threshold, return uniqLigTbl,
141219: selection criterion made a parameter
'''
exptNo,prot,exptRecept,site,lib = exptKey
exptName = bldExptStr(exptKey)
allE = []
noddE = 0
nmissf = 0
nrcd=0
ndup=0
ndupOut=0
nnrtiDrop = 0
nbadZinc = 0
ligTblE = {} # ligidx -> [batchNo,dval]
if initRun:
dupLigFile = SummRptDir + 'dupDockedLig.csv'
# multiple experiments share same dupLigFile
if os.path.isfile(dupLigFile):
dupStream = open(dupLigFile,'a')
else:
dupStream = open(dupLigFile,'w')
dupStream.write('Ligand, PrevBNo, PrevDval, BNo, Dval\n')
config.NonZincLigTbl = {} # ligand name -> nonzincID
config.NZIdx2LigTbl = {} # nonzincID -> ligand name
config.NNonZincLig = 0
else:
loadNonZinc(exptName)
for isf,batchNo in enumerate(batchList):
summPath = faahDir+('summ/%s_summ_%07d.csv' % (runType,batchNo))
try:
inStr = open(summPath)
except Exception,e:
print "getThresh: can't open1 %s?!" % (summPath)
nmissf += 1
continue
for il,line in enumerate(inStr.readlines()):
if il == 0:
# Expt,Recept,Ligand,E,Eff,Nvdw,Ninter
# written by crawl_ADV.rptData_ADV()
continue
nrcd += 1
try:
flds =line[:-1].split(',')
(expt,batch,ligRecept,ligand,e,eff,nvdv,ninter) = flds
## 141219: Pass 1: selection criterion made a parameter
if dcrit == 'energy':
dval = float(e)
elif dcrit == 'ligEff':
dval = float(eff)
elif dcrit == 'ligEnth':
# Assume LigDOFTbl already loaded
if ligand not in LigDOFTbl:
print 'getThresh: lig missing from LigDOFTbl?!',ligand
continue
dof = LigDOFTbl[ligand]
natom = float(e) / float(eff)
natomi = int(natom)
assert natomi-natom > 1e-2, 'huh?'
dval = (float(e) + (dof * FE_coeff_tors)) / natom
except Exception, e:
print "getThresh: bad line(1) %s %d %s?!" % (summPath,il,e)
noddE += 1
break # don't try to read other lines from inStr
# 160122: Remove redundant ligands
ligIdx = normLigand(ligand)
if ligIdx == -1:
nbadZinc += 1
continue
if ligIdx in ligTblE:
ndup += 1
if ligTblE[ligIdx][1] != dval and initRun:
# print 'getThresh: same ligand with differing dval?!',ligand, ligTblE[ligIdx][0], ligTblE[ligIdx][1], batchNo, dval
dupStream.write('%s,%s,%s,%s,%f\n' % (ligand, ligTblE[ligIdx][0], ligTblE[ligIdx][1], batchNo, dval))
ndupOut += 1
continue
else:
ligTblE[ligIdx] = [batchNo,dval]
# Pass1: need to make this thresh criterion-sensitive, too
if (dcrit == 'energy' and abs(dval) > TooBigE) or \
(dcrit == 'ligEff' and abs(dval) > TooBigLigEff) or \
(dcrit == 'ligEnth' and abs(dval) > TooBigLigEnth):
noddE += 1
continue
allE.append(dval)
inStr.close() # eo-batch file
if initRun:
dupStream.close() # eo all batches
if config.NNonZincLig>0:
# cf. bldNonZincIdx()
allLig = config.NonZincLigTbl.keys()
allLig.sort()
nzligFile = LowEDir + 'nonZincLig.csv'
print 'getThresh: Writing %d NonZinc ligands to %s' % (config.NNonZincLig,nzligFile)
# multiple experiments share same nzligFile
if os.path.isfile(nzligFile):
outs = open(nzligFile,'a')
else:
outs = open(dupLigFile,'w')
outs.write('Ligand,NZIdx\n')
for lig in allLig:
outs.write('%s,%d\n' % (lig,config.NonZincLigTbl[lig]))
outs.close()
# NB: dval used as generic value from here forward
# "E" name is no longer correct, but doesn't hurt anything!
if len(allE)==0:
# print 'getThresh: No good summ files1?! Expt=%s NBatch=%d' % (exptName,len(batchList))
# return ({}, 0.,0.)
sys.exit('getThresh: No good summ files1?! Expt=%s NBatch=%d' % (exptName,len(batchList)))
# ASSUME all algorithms require n log n??
allE.sort()
if frac4Thresh==1.0:
# NB: thresh set to EQUAL highest energy found
thresh = allE[-1]
threshIdx = len(allE)
else:
threshIdx = int(round(float(len(allE) * frac4Thresh)))
thresh = allE[threshIdx]
if ncand > len(allE):
print 'getThresh: ncand < allLig=%d; using all' % (len(allE))
ncand = len(allE)-1
bestCandThresh = allE[ncand]
print 'getThresh: Expt=%s NLigand=%d NBadZinc=%d NDup=%d NDupOut=%d NMissf=%d NOddE=%d ThreshFrac=%5.2f ThreshIdx=%d Thresh=%f BestCandThresh=%f NNRTIDrop=%d' % \
(exptName,len(ligTblE),nbadZinc,ndup,ndupOut,nmissf,noddE,frac4Thresh,threshIdx,thresh,bestCandThresh,nnrtiDrop)
return ligTblE, thresh, bestCandThresh
def bldZincIdx(zstr):
# ASSUME no more than two digit ZINC suffices
if zstr.find('_') != -1:
bpos = zstr.find('_')
zno = int(zstr[4:bpos])
# 2do where is "ZINC06648739_10_" with trailing '_' getting produced?!
zsuf = zstr[bpos+1:].strip(' _')
if len(zsuf)==0:
zsuf = 0
else:
zsuf = int(zsuf)
zidx = 100 * zno + zsuf
else:
zno = int(zstr[4:].strip())
zidx = 100 * zno
return zidx
def ligIdx2zinc(ligIdx):
zid = ligIdx / 100
sufId = ligIdx % 100
if ligIdx < 0:
if ligIdx in config.NZIdx2LigTbl:
return config.NZIdx2LigTbl[ligIdx]
else:
print 'ligIdx2zinc: missing nonZincIdx?!',ligIdx
return 'Lig??'
zincid = 'ZINC%08d' % (zid)
if sufId != 0:
zincid += '_%d' % (sufId)
return zincid
def bldNonZincIdx(lig):
'assign arbitrary (negative) numbers to non-Zinc ligands'
if lig in config.NonZincLigTbl:
return config.NonZincLigTbl[lig]
else:
config.NNonZincLig += 1
config.NonZincLigTbl[lig] = (-(config.NNonZincLig))
config.NZIdx2LigTbl[(-(config.NNonZincLig))] = lig
return (-(config.NNonZincLig))
def normLigand(lig):
'''HACK: reduce ZINC id to integer, for reduced storage
'''
if lig.find('ZINC') != -1:
try:
zincIdx = bldZincIdx(lig)
except:
print 'normLigand: odd ligand?!',lig
# import pdb; pdb.set_trace()
return -1
else:
# 160526: no nonZINC allowed!
# zincIdx = bldNonZincIdx(lig)
return -1
return zincIdx
def getIsoRAtom(raa,ratom):
'''map any references to (ratom2) -> (ratom1) for
OD2 in D, OE2 in E, and CD2 or CE2 in F and Y
'''
if raa == 'D':
if raa == 'OD2':
isoRAtom = 'OD1'
elif raa == 'E':
if raa == 'OE2':
isoRAtom = 'OE1'
elif raa == 'F' or raa == 'Y':
if raa == 'CD2':
isoRAtom = 'CD1'
elif raa == 'CE2':
isoRAtom = 'CE1'
else:
isoRAtom = ratom
return isoRAtom
def bldFocalInterTbl(exptName,faahDir,batch2ligTbl):
'''retrieval of interaction data for just focal ligands (collected by batch)
returns receptInterTbl: (rchain,raa,ratom) -> {itype - > {liname -> [ ligID ] } }
NB: receptor AA naming normalized
NB: ALL interactions included in interTbl;
exclusions applied later via bldFeature2() in analRLIF(), analBldHIFeature
'''
# NB: receptInterTbl retains lig atom distinctions
receptInterTbl = defaultdict( lambda: defaultdict(lambda: defaultdict( list )))
# (rchain,raa,ratom) -> {itype - > {liname -> [ ligID ] } }
nrcd = 0
nmissf = 0
nactive = 0
nVDWonly = 0
ligFndSet = set()
for ib,bno in enumerate(batch2ligTbl.keys()):
inf = faahDir+('inter/%s_inter_%07d.json' % (config.RunType,int(bno)))
try:
inStr = open(inf)
allInter = json.load(inStr)
inStr.close()
except:
nmissf += 1
continue
focalLigTbl = batch2ligTbl[bno]
if len(focalLigTbl)==0:
print 'bldFocalInterTbl: empty batch?!',ib,bno
continue
for il,interInfo in enumerate(allInter):
nrcd += 1
# cf crawl_ADV.rptData_ADV()
# [ [Expt,BatchNo,Recept,Lig, [IType,[InterEnum] ] ] ]
(expt,batchNo,recept,ligand, interList) = interInfo
ligIdx = normLigand(ligand)
if ligIdx not in focalLigTbl:
continue
nonVDWfnd = False
for interTypeList in interList:
itypeIdx, interEnum = interTypeList
itype = InterTypes[itypeIdx]
if itype != 'vdw':
nonVDWfnd = True
for iinfo in interEnum:
if itype == 'vdw':
if config.vdwLigandAtom:
(rchain,raa,ratom,liname) = iinfo
elif config.ADFeatures == 'nonVDW':
continue
else:
(rchain,raa,ratom) = iinfo
liname = ''
elif itype == 'tpi' or itype=='ppi':
(rchain,raa,ratom,liname) = iinfo
# NB: drop ligand ring center; use X's to fill out feature
ratom = 'X'
liname = 'X'
else:
(rchain,raa,ratom,liname) = iinfo
# NB: normalize receptor AA naming
raas = bldFeaturePrefix(rchain, raa)
rchain, newRAA = raas.split('_')
## 160610: Handle isomorphic atom naming
# References made to EITHER of alternative ratom names treated as reference to FIRST NAME
# NB: no checking here for interactions with BOTH of ambiguous ratom names
if config.MapIsoRAtoms:
isoRAtom = getIsoRAtom(raa,newRAA)
else:
isoRAtom = newRAA
k = (rchain,newRAA,isoRAtom)
receptInterTbl[k][itype][liname].append( ligIdx )
ligFndSet.add(ligIdx)
if not nonVDWfnd:
nVDWonly += 1
print 'bldFocalInterTbl: %s NLigand=%d NVDWOnly=%d N(Chain+RAA+RAtom)=%d NMissFile=%d NAllLig=%d' % \
(exptName,len(ligFndSet),nVDWonly,len(receptInterTbl),nmissf,nrcd)
## NB: need to make serializable, for pickel!
interTbl2 = {}
for rfeat,ligTbl in receptInterTbl.items():
# (rchain,raa,ratom) -> {itype - > {latom -> [ ligID ] } }
newLigTbl = {}
for itype,ligFeatTbl in ligTbl.items():
newLFTbl = {}
for latom,ligIDList in ligFeatTbl.items():
newLFTbl[latom] = ligIDList[:]
# for ligIdx in ligIDList:
# if ligIdx<0 and itype != 'vdw':
# print '2,%s,%s,%s,%s' % (rfeat,itype,latom,ligIdx)
newLigTbl[itype] = newLFTbl
assert len(newLFTbl)==len(ligFeatTbl), 'bldFocalInterTbl: bad newLFTbl?!'
assert len(newLigTbl)==len(ligTbl), 'bldFocalInterTbl: bad newLigTbl?!'
interTbl2[rfeat] = newLigTbl
assert len(interTbl2)==len(receptInterTbl), 'bldFocalInterTbl: bad interTbl2?!'
return interTbl2
def analBldHIFeatures(faahDir,exptName,bnoList,thresh,r2lTbl,uniqLigTbl,featFile):
'''build energy discrimination predicate
v3 use thresh, dont build explicit energy distribution
160122: summ files may contain redundant references to ligands!
use classTbl to maintain ALL referenced ligands (vs nrcd)
'''
print "analBldHIFeatures: %s NBatch=%d" % (exptName,len(bnoList))
classTbl = {} # ligand -> aboveThreshP
noddE = 0
npos = 0
nmissf = 0
ndup = 0
ncdup = 0
nmissUniq = 0
nnrtiDrop = 0
## first pass: build energy distribution
for ib,bno in enumerate(bnoList):
summPath = faahDir+('summ/%s_summ_%07d.csv' % (config.RunType,bno))
try:
inStr = open(summPath)
except:
nmissf += 1
# import pdb; pdb.set_trace()
continue
for il,line in enumerate(inStr.readlines()):
if il == 0:
continue
flds =line[:-1].split(',')
try:
(expt,batch,recept,ligand,e,eff,nvdv,ninter) = flds
except Exception,e:
print "analBldHIFeatures: bad line %s %d %s?!" % (summPath,il,e)
noddE += 1
break # don't try to read other lines from inStr
# HACK: reduce ZINC id to integer, for reduced storage
zincIdx = normLigand(ligand)
if abs(float(e)) > TooBigE:
# print 'FAAHA: odd energy?!',isf,summF,il,e
noddE += 1
continue
# 160122: Remove redundant ligands
if zincIdx not in uniqLigTbl:
nmissUniq += 1
# print 'analBldHIFeatures: ligand not seen by getThresh()?!',ligand, bno
continue
# only keep one (first) docking result wrt/ same ligand
ubatch,udval = uniqLigTbl[zincIdx]
if ubatch != bno:
ndup += 1
continue
if zincIdx in classTbl:
ncdup += 1
tst = float(e)<=thresh
if tst != classTbl[zincIdx]:
print "analBldHIFeatures: differing test for same ligand?!",ligand,classTbl[zincIdx]
continue
classTbl[zincIdx] = float(e)<=thresh
if float(e)<=thresh:
npos += 1
inStr.close()
print "analBldHIFeatures: %s NLigand=%d NMissLig=%d NDupLig=%d NDupCat=%d NOddE=%d Thresh = %f NPos=%d NMissFile=%d NDropNRTI=%d" % \
(exptName,len(classTbl),nmissUniq,ndup,ncdup,noddE,thresh,npos,nmissf,nnrtiDrop)
if len(classTbl)==0:
print 'analBldHIFeatures: no ligands?!'
return None
featInfoTbl = {}
ncnt = 0
for rlif,ligList in r2lTbl.items():
# rlif -> [(ligIdx,latom)]
if rlif not in featInfoTbl:
featInfoTbl[rlif] = [0,0]
for ligInfo in ligList:
ligIdx,latom = ligInfo
ncnt += 1
if classTbl[ligIdx]:
featInfoTbl[rlif][0] += 1
else:
featInfoTbl[rlif][1] += 1
print "analBldHIFeatures: %s NLigand=%d NPos=%d NRLIFxLig=%d Nfeatures=%d" % \
(exptName,len(classTbl),npos,ncnt,len(featInfoTbl))
allFeat = featInfoTbl.keys()
allFeat.sort()
nbadEntropy = 0
totLig = len(classTbl)
# Read by analCluster()
outs = open(featFile,'w')
outs.write('F,Pr,Info,PosEnt,NegEnt\n')
for f in allFeat:
# TP: in low-mode, feature present
# FN: in low-mode, no feature
# FP: not in low-mode, feature present
# TN: not in low-mode, no feature
tp = featInfoTbl[f][0]
fn = npos - tp
fp = featInfoTbl[f][1]
tn = totLig - npos - fp
all = tp+fp+tn+fn
# assert (fn>0 and tn>0), 'analBldHIFeatures: bad counts1?!'
# assert all == nrcd, 'analBldHIFeatures: bad counts2?!'
if not(fn>=0 and tn>=0 and all == totLig):
nbadEntropy += 1
outs.write('"%s",,,,,?1,%d,%d,%d,%d\n' % (f,tp,fp,npos,totLig))
continue
try:
ig, prFeat, posEnt,negEnt = infoGain(tp,fp,tn,fn)
except Exception,ex:
# print 'analHIFeatures: badEntropy?!',exptName,ex,ifeat,npos,nrcd,tp,fp,tn,fn
nbadEntropy += 1
outs.write('"%s",,,,,?2,%d,%d,%d,%d\n' % (f,tp,fp,npos,totLig))
continue
outs.write('"%s",%f,%f,%f,%f\n' % \
(f,prFeat,ig,posEnt,negEnt))
outs.close()
print "analBldHIFeatures: %s NBadEntropy=%d" % (exptName,nbadEntropy)
def loadRLIFInfo(hifFile):
'''return rlifInfoTbl: rlif -> info
'''
nerr = 0
rlifTbl = {}
reader = csv.DictReader(open(hifFile))
# first pass: read them all
for i,entry in enumerate(reader):
# F,Pr,Info,PosEnt,NegEnt
if None in entry:
# cf analBldHIFeatures() error reporting
print 'loadRLIFInfo: bad info?!',entry['F'],entry[None]
nerr += 1
continue
rlifTbl[ entry['F'] ] = float( entry['Info'] )
if nerr>0: