forked from salilab/SOAP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statsTable.py
2124 lines (2024 loc) · 82.8 KB
/
statsTable.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
"""
SOAP statistical table
"""
from feature import *
from env import *
import shutil
import subprocess
from sequences import *
from decoys import DecoySets
class rawsp(object):
"""Statistics from a set of structures
:param str pdbset: the name of the set of PDB or decoy structures
:param str features: the name of the features, see :mod:`feature`
:param str genmethod: the filters used for generating the table, see :func:`utility.decode_genmethod` for more detail.
:param str decoy: True if the :attr:`rawsp.pdbset` represent decoys
:param dict model: the parameters for this class can also be passed by a dict
.. _genmethod:
Example genmethod:
* `bs2dsp`: bond separation 2 with disulfide bond taken into consideration
* `cs1`: chain separation >=1
* `ss1`: sequence separation >=1
"""
def __init__(self,pdbset='',features='',genmethod='',tlib=None,decoy=False,routine='calc_sp_all', model={}):
if model:
features=model['features']
genmethod=model['genmethod']
pdbset=model['pdbset']
if len(pdbset)>0 and pdbset[0]=='o': # o indicate that we want to use unprocessed pdb.
self.opdb=True
pdbset=pdbset[1:]
else:
self.opdb=False
self.features=features
self.genmethod=genmethod
self.pdbset=pdbset
self.decoy=decoy
self.routine=routine
self.tlib=tlib
if self.opdb:
pdbset='o'+pdbset
if runenv.hostn==0:
try:
self.dir=runenv.basedir+pdbset+'/'+features+'-'+genmethod+'/'
except:
pdb.set_trace()
self.spname=pdbset+'.'+features+'.'+genmethod
self.sppath=self.dir+self.spname
elif runenv.hostn==1:
self.dir='./'
self.spname=pdbset+'.'+features+'.'+genmethod
self.sppath=self.dir+self.spname
self.nors=200
self.flagdict={}
self.currentdsname='dummy'
self.genmethodlist=decode_genmethod(self.genmethod)
if self.features:
self.fo=feature(self.features)
self.bins=self.fo.get_all_bins_centers()
for i in range(0,len(self.bins)):
if len(self.bins[i])>0:
self.bl=len(self.bins[i])
self.bp=i
rl1,rl2=self.fo.get_featuretypepos()
self.ifl=len(rl1)
self.rs1=rl1+rl2
self.rs2=copy.copy(self.rs1)
for i in range(0,len(self.rs1)):
self.rs2[self.rs1[i]]=i
if self.rs1==range(0,len(self.rs1)):
self.permute=False
else:
self.permute=True
glib=self.fo.get_lib()
self.tlib=glib
self.bndsepcalc=False
self.runpath='./'
if self.pdbset=='Otherpot':
self.mkdir()
self.justwait=False
self.waittarget=[]
if routine=='calc_sp_i':
self.prd='no-backupi'
self.ftype='.npy'
else:
self.prd='no-backup'
self.ftype='.hdf5'
self.mkdir() #make data dir: IT IS NOT THE RUNDIR-THE TEMP DIR
self.isatompairclustering()
def mkdir(self):
if runenv.hostn:
return 0
basedir=runenv.basedir
pdbset=self.pdbset
if self.opdb:
pdbset='o'+pdbset
genmethod=self.genmethod
features=self.features
newdir = os.path.join(basedir, pdbset, features+'-'+genmethod)
if not os.path.exists(newdir):
os.makedirs(newdir)
os.chdir(newdir)
if self.tlib:
shutil.copy(os.path.join(runenv.libdir, self.tlib), '.')
def isatompairclustering(self):
genmethod=self.genmethod
self.atompairclustering=False;
self.apca=0
if re.search('(ap[0-9]{1,2})',genmethod):
rer=re.search('(ap[0-9]{1,2})',genmethod)
apname=rer.group(1)
self.atompairclustering=True
self.apca=np.load(runenv.libdir+apname+'.npy')
def subset_of_existing(self):
if not os.path.isdir(os.path.join(runenv.basedir, self.pdbset)):
return []
rangelist=self.get_allsp_range()
nal=[]
rl=[]
revelentsp=[]
for sprange in rangelist:
if sprange[2][0:4]==self.genmethodlist[0:4] and sprange[2][-2:]==self.genmethodlist[-2:]:
subsetindex=self.fo.issubset(feature(sprange[1]))
if len(subsetindex)==0:
continue
bsrange=sprange[2][4:6]
if not bsrange in rl:
rl.append(bsrange)
revelentsp.append([sprange[0],bsrange,subsetindex])
na=np.zeros([20,1])
if bsrange[0]==-1 and bsrange[1]==-1:
na[...]=1
else:
na[bsrange[0]:min(bsrange[1]+1,20)]=1
nal.append(na)
if len(nal)==0:
return []
existingsparray=np.hstack(nal)
na=np.zeros([20,1])
if self.genmethodlist[4]==-1 and self.genmethodlist[5]==-1:
na[...]=1
else:
na[self.genmethodlist[4]:min(self.genmethodlist[5]+1,20)]=1
mixweight=numpy.linalg.lstsq(existingsparray,na)[0]
residue=sum((np.dot(existingsparray,mixweight)-na)**2)
logstr=''
if np.allclose(residue,0):
spl=[]
for r1,r2 in zip(list(mixweight),revelentsp):
if np.abs(r1[0])>0.0001:
spl.append([r1[0],r2[0],r2[2]]) #target
logstr=str(r1[0])+'*'+str(r2[1])+' + '
print logstr
return spl
else:
return []
def get_allsp_range(self):
fl=os.listdir(os.path.join(runenv.basedir, self.pdbset))
fl=[f for f in fl if os.path.isdir(os.path.join(runenv.basedir,
self.pdbset, f))]
rangelist=[]
for f in fl:
fs=f.split('-')
fs=['-'.join(fs[:-1]),fs[-1]]
spdir=os.path.join(runenv.basedir, self.pdbset, f, '.'.join([self.pdbset]+fs))
if os.path.isfile(os.path.join(spdir, self.ftype)) or os.path.isdir(os.path.join(runenv.basedir, self.pdbset, f, self.prd)):
rangelist.append([spdir, fs[0],decode_genmethod(fs[1])])
return rangelist
def calc_sp_all(self,runnumber):
"""Methods to generate the statistical potential from PDB files in the currnt directory."""
self.runpath=runenv.basedir
features=self.features
pdbfile='pdbs'+str(runnumber)
print 'running pdb: '+pdbfile
env = environ()
#log.minimal()
io=env.io
if self.opdb:
pdbfdir=runenv.opdbdir
io.atom_files_directory=[scratchdir]
else:
pdbfdir=runenv.pdbdir
io.atom_files_directory=pdbfdir+[scratchdir]
mlib=mdt.Library(env)
mlib.bond_classes.read('${LIB}/bndgrp.lib')
featurelist=feature(self.features,mlib).get_featurelist()
#print featurelist
m=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
fl=len(featurelist)
a=alignment(env)
f=modfile.File(self.runpath+pdbfile,'r')
csmin, csmax,kcut, kcut1, bs,bsm, errsv,ssp=decode_genmethod(self.genmethod)
refy=0
rmdt=None
if re.search('ref(.*)$',self.genmethod):
env2=environ()
mlib2=mdt.Library(env2)
featurelist=feature(self.features,mlib2).get_featurelist()
refrer=re.search('ref(.*)$',self.genmethod)
refname=refrer.group(1)
refy=1
rmdt=mdt.Table(mlib2,features=featurelist,shape=[-1]*len(featurelist))
rmdt.read_hdf5(refname+'.h5.lib')
k=0
lstartpos=0
lendpos=0
lscale=0
if re.search('s([0-9\.]*)e([0-9\.]*)s([0-9\.]*)',self.genmethod):
rer=re.search('s([0-9\.]*)e([0-9\.]*)s([0-9\.]*)',self.genmethod)
lstartpos=float(rer.group(1))
lendpos=float(rer.group(2))
lscale=float(rer.group(3))
while a.read_one(f, allow_alternates=True):
k=k+1
print k
fd,naln=self.get_pdbfile(pdbfdir,[],a[0].code,env,a,scratchdir)
try:
if self.opdb:
aln=alignment(env)
mdl=model(env)
if len(a[0].code)==5:
cc=a[0].code[-1]
m2=model(env)
m2.read(a[0].code[0:4])
cl=[c.name for c in m2.chains]
ci=ord(cc)-65
cc=cl[ci]
mdl.read(a[0].code[0:4],model_segment=('FIRST:'+cc,'LAST:'+cc))
elif len(a[0].code)==4:
mdl.read(a[0].code[0:4])
else:
raise Bugs('Do not know how to calculate mdt table using opdb for '+a[0].code)
aln.append_model(mdl,align_codes=a[0].code)
toaln=aln
else:
toaln=a
print toaln[0].code
m.add_alignment_witherr(toaln,chain_span_range=(-csmax,-csmin,csmin,csmax),residue_span_range=(-kcut1,-kcut,kcut,kcut1),bond_span_range=(bs,bsm),errorscale=errsv,disulfide=ssp)
except Exception,e:
traceback.print_exc()
if re.search('fork failure',str(e)):
raise Exception('fork failure, quiting')
pdbfilel=re.match('.*(pdb.*)',pdbfile)
pdbfilename=pdbfilel.group(1)
if pdbfilename[-4:]=='.pir':
pdbfilename=pdbfilename[:-4]
if m.sum() != 0:
try:
temppath=scratchdir
runsuccess=True
m.write_hdf5(temppath+str(runnumber)+'.result.hdf5',gzip=True)
except:
try:
temppath=os.path.join(runenv.serverScrathPath, os.getenv('JOB_ID'))
os.makedirs(temppath)
m.write_hdf5(os.path.join(temppath,
str(runnumber)+'.result.hdf5'),gzip=True)
runsuccess=True
except:
runsuccess=False
else:
runsuccess=False
print m.sum()
print 'mdt sum to 0, code problem'
report_job_runstatus(self.runpath, runsuccess, runnumber, '.result',inputname='runme.py',temppath=temppath)
def calc_sp_cluster(self):
sj=self.get_task()
tasklist(tasklist=[sj]).monitor2end()
def get_task(self):
if re.search('(ap[0-9]+n[0-9]+)$',self.genmethod):
rer=re.search('(ap[0-9]+)(n[0-9]+)$',self.genmethod)
ngm=self.genmethod[:-len(rer.group(2))]
nsp=rawsp(pdbset=self.pdbset,features=self.features,genmethod=ngm,tlib=self.tlib,decoy=self.decoy,routine=self.routine)
return nsp.get_task()
print 'getting task '+self.spname
if self.routine=='calc_sp_all':
self.targetfile=self.sppath+'.hdf5'
self.filetype='.hdf5'
tc=os.path.isfile(self.sppath+'.hdf5')
self.nors=200
elif self.routine=='calc_sp_i':
pdbsets=self.pdbset.split('_')
if len(pdbsets)==1:
self.targetfile=self.sppath+'.npy'
self.filetype='.npy'
tc=os.path.isfile(self.sppath+'.npy')
self.nors=1000
else:
tl=[]
for pset in pdbsets:
nspo=rawsp(pset,self.features,self.genmethod,self.tlib,self.decoy,self.routine)
tl.append(nspo.get_task())
print "running break down sps"
return tasklist(tasklist=tl,afterprocessing=dummy)
self.nors=1000
if not tc:
sj=task(os.path.join(self.dir, self.prd),self.spname,afterprocessing=self,preparing=self,targetfile=self.sppath+self.filetype)
return sj
else:
return 0
def afterprocessing(self):
print "run finished -> processing result"
if self.justwait and len(self.waittarget)==0:
pass
elif self.justwait and len(self.waittarget)>0: # the sp need to be combined with others
os.chdir(os.path.join(self.dir, self.prd))
self.get_targetsp_fromexistingsps()
else:
os.chdir(os.path.join(self.dir, self.prd))
if self.routine=='calc_sp_all':
self.sp_sum()
shutil.copy('sum.hdf5', self.sppath+'.hdf5')
if 0:
self.sp_stderr2(nolog=True)
shutil.move('ostderr2.hdf5', self.sppath+'.ostderr2.hdf5')
shutil.move('omean.hdf5', self.sppath+'.omean.hdf5')
self.sp_stderr2(nolog=False)
shutil.move('stderr2.hdf5', self.sppath+'.stderr2.hdf5')
shutil.move('mean.hdf5', self.sppath+'.mean.hdf5')
elif self.routine=='calc_sp_i':
allarray=self.cat_spi()
if self.atompairclustering:
#process atom pair features
for i in range(allarray.shape[1]):
sdir = os.path.join(runenv.basedir, self.pdbset, self.features+'-'+self.genmethod+'n'+str(i))
scorepath=os.path.join(sdir, self.pdbset+'.'+self.features+'.'+self.genmethod+'n'+str(i))
if not os.path.isdir(sdir):
os.mkdir(sdir)
np.save(scorepath,allarray[:,i,...].squeeze())
shutil.move('all.npy', os.path.join('..', self.spname+'.npy'))
print os.system('rm -r *')
os.chdir('..')
shutil.rmtree(os.path.join(self.dir, self.prd))
return 1
def get_targetsp_fromexistingsps(self):
sparray=[]
for target in self.waittarget:
sa=self.get_sp_subset(target[1],target[2])
try:
if len(sparray)==0:
if self.routine=='calc_sp_i':
nas=[item for item in [sa.shape[0]]+self.fo.fdlist if item!=1]
sparray=np.zeros(nas)
else:
sparray=np.zeros(self.fo.fdlist)
sparray=sparray+target[0]*sa
except:
print traceback.print_exc()
pdb.set_trace()
self.save_npy(sparray)
def get_empty_table(self,write=True):
env = environ()
mlib=mdt.Library(env)
featurelist=feature(self.features,mlib).get_featurelist()
m=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
if write:
m.write_hdf5(self.sppath+'.hdf5')
return m
def save_npy(self,sparray):
if self.routine=='calc_sp_all':
self.get_empty_table()
f=h5py.File(self.sppath+'.hdf5','r+')
mdtb=f['mdt']
mdtb[...]=sparray[...]
f.close()
elif self.routine=='calc_sp_i':
np.save(self.sppath+'.npy',sparray)
def get_sp_subset(self,f,subsetindex):
if self.routine=='calc_sp_i':
subsetindex[0]=[[0]]+subsetindex[0]
mdta=self.load2npy(f)
return self.get_array_subset(mdta,subsetindex)
def get_array_subset(self,mdta,subsetlist):
subsetindex=subsetlist[0]
subsetindex.reverse()
nsubsetindex=copy.deepcopy(subsetindex)
rr=range(len(subsetindex))
rr.reverse()
for si,i in zip(subsetindex,rr): #eliminate the dimensions summed over first
if len(si)==0:
mdta=mdta.sum(axis=i)
nsubsetindex.pop(i)
rr=range(len(nsubsetindex))
rr.reverse()
if len(mdta.shape)!=len(nsubsetindex):
for si,i in zip(subsetindex,rr): #delete dimension with size 1
if si==[0,1]:
nsubsetindex.pop(i)
rr=range(len(nsubsetindex))
rr.reverse()
try:
for si,i in zip(nsubsetindex,rr):
nas=list(mdta.shape)
if len(si)>1 and nas[i]>(len(si)-1):
nas[i]=len(si)-1
na=np.zeros(nas)
for j,ej in zip(range(si[0],si[1]),range(si[-2]+1,si[-1]+1)):
nai=[':' for item in rr]
nai[i]=str(j)+':'+str(ej)+':'+str(si[1]-si[0])
try:
na=na+eval('mdta['+','.join(nai)+']')#there must be a simple way that does not need permuation.
except:
print "line 1071 in sp"
pdb.set_trace()
mdta=na
except:
print traceback.print_exc()
pdb.set_trace()
if subsetlist[1]!=range(len(subsetlist[1])):
na=np.transpose(na,subsetlist[1])
return na
def load2npy(self,f):
print "loading "+f
if self.routine=='calc_sp_all':
f=h5py.File(f,'r')
mdtb=f['mdt']
ms=mdtb.shape
print ms
mdta=np.zeros(np.array(list(ms)))
mdta[...]=mdtb[...]
f.close()
elif self.routine=='calc_sp_i':
mdta=np.load(f)
return mdta
def calc_sp_local(self,nors,routine='calc_sp_all'):
self.routine=routine
self.nors=nors
self.filetype='.npy'
self.targetfile=self.spname+'.npy'
self.prepare_task_input()
sj=task(self.dir+'no-backup/')
if routine=='calc_sp_all':
sj.run_task_local(self.calc_sp_all)
self.sp_mean()
#self.sp_stderr()
print os.system('mv sum.hdf5 ../'+self.spname+'.hdf5')
#print os.system('mv stderr.hdf5 ../'+self.spname+'.stderr.hdf5')
elif routine=='calc_sp_i':
sj.run_task_local(self.calc_sp_i)
self.cat_spi()
print os.system('mv all.npy ../'+self.spname+'.npy')
def sp_sum(self,wdir=None):
if wdir:
#wdir=self.sppath
os.chdir(wdir)
#combine mdts in the current directory
env = environ()
mlib=mdt.Library(env)
featurelist=feature(self.features,mlib).get_featurelist()
m1=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
m2=mdt.Table(mlib, features=featurelist,shape=[-1]*len(featurelist))
k=0
files=os.listdir('./')
for name in files:
try:
if name.endswith('.result.hdf5'):
fname=name
else:
continue
print 'Adding '+name
k=k+1
if k==1:
m1.read_hdf5(fname)
else:
m2.read_hdf5(fname)
m1+=m2
print 'Adding '+name+'Finished'
except Exception, e:
pdb.set_trace()
traceback.print_exc()
return 1
m1.write_hdf5('sum.hdf5',gzip=True)
m1=[]
m2=[]
print "Combining finished"
return 0
def should_wait(self):
if self.atompairclustering:
return []
self.waittarget=self.subset_of_existing()
if len(self.waittarget)>0: # the sp can be calculated by combining other sps
self.justwait=True
wl=[item[1]+self.filetype for item in self.waittarget]
for item in self.waittarget:
item[1]=item[1]+self.filetype
print "waiting for other runs to finish to combine to our sp"
print wl
self.mkdir()
print os.system('rm -r '+self.dir+self.prd)
os.mkdir(self.dir+self.prd)
return wl
else:
return []
def prepare_task_input(self):
wl=self.should_wait()
if len(wl)>0:
return wl
nors=self.nors
routine=self.routine
print "prepare task input for generating"+self.spname
os.chdir(self.dir)
#os.system('rm -r '+self.prd)
freememory=feature(self.features).get_runmem()
self.runpath=runenv.serverUserPath+self.spname+'/'
if not (os.access(self.prd,os.F_OK)):
os.mkdir(self.prd)
freememory=freememory+0.2
if freememory>2:
self.nors=min(int(1800/freememory),50)
else:
self.nors=nors
nors=self.nors
os.chdir(self.prd)
if self.tlib:
shutil.copy(os.path.join(runenv.libdir, self.tlib), '.')
if 'l' in self.fo.fclist:
residuepower=1
else:
residuepower=2
if self.decoy:
pir(DecoySets( self.pdbset.split('_')).pirpath).sep_pir('./',nors,permin=scoreminnumber,residuepower=residuepower)
else:
shutil.copy(os.path.join(runenv.basedir, 'pdbpir', 'pdb_'+self.pdbset+'.pir'), '.')
pir('pdb_'+self.pdbset+'.pir').sep_pir('./',nors,residuepower=residuepower)
nors=int(os.popen('ls | grep -c pdbs').read())
self.nors=nors
inputlist=open('inputlist','w')
inputlist.write(','.join(['pdbs'+str(i) for i in range(1,nors+1)]))
inputlist.close()
makemdt=open('runme.py','w')
makemdt.write('keeptry=5\nwhile keeptry:\n try:\n from SOAP.statsTable import *\n keeptry=0\n except:\n keeptry-=1\n'
+'import sys \n \nrsp=rawsp(\''+self.pdbset+'\',\''
+self.features+'\',\''+self.genmethod+'\')\n'+'rsp.opdb='+str(self.opdb)+'\n'
+'rsp.'+routine+'(sys.argv[1])')
makemdt.flush()
generate_job_submit_script(freememory,self.spname,runtime,nors)
return []
def calc_sp_i(self,runnumber,reportstatus=True):
self.runpath=runenv.basedir
pirfile='pdbs'+str(runnumber)
dnlist=pir(pirfile).get_codelist()
if self.atompairclustering:
idist=self.calc_individual_sp(pirfile,dnlist,'apidist')
else:
idist=self.calc_sp_individual1D_frompir(pirfile,dnlist)
if reportstatus:
try:
temppath=scratchdir
runsuccess=True
np.save(temppath+str(runnumber)+'.result.npy',idist)
except:
try:
temppath=os.path.join(runenv.serverScrathPath, os.getenv('JOB_ID'))
os.mkdir(temppath)
np.save(os.path.join(temppath, str(runnumber)+'.result.npy'),idist)
runsuccess=True
except:
runsuccess=False
report_job_runstatus(self.runpath, True, runnumber, '.result',inputname='runme.py',temppath=temppath)
else:
return idist
def calc_sp_individual1D_frompir(self, pirfile,dnlist):
#generate distributions for calculate benchmark score for reference state
features=self.features
bm=self.genmethod
tmpdir=scratchdir
env = environ()
log.minimal()
mlib=mdt.Library(env)
mlib.bond_classes.read('${LIB}/bndgrp.lib')
env.io.atom_files_directory=[scratchdir,'./']+runenv.pdbdir
io=env.io
featurelist=feature(self.features,mlib).get_featurelist()
csmin, csmax,kcut, kcut1, bs,bsm, errsv,ssp=decode_genmethod(self.genmethod)
m=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
fl=len(featurelist)
#m=m.reshape(featurelist,[0 for i in range(0,fl)], [-1 for i in range(0,fl)])
tal=1
ms=m.shape
for si in ms:
tal=tal*si
refdista=np.zeros([len(dnlist)]+[tal])
f=modfile.File(pirfile,'r')
aln=alignment(env)
k=0
while aln.read_one(f):
sr=0;
alncode=aln[0].code
print alncode
codelist=alncode.split('.')
if len(codelist)>1:#decoys
print runenv.ddbdir+codelist[0]+'/'+codelist[1]+'/'
fd,naln=self.get_pdbfile(runenv.ddbdir+codelist[0]+'/'+codelist[1]+'/',codelist,alncode,env,aln,tmpdir)
io.atom_files_directory=[fd]+io.atom_files_directory
else:#pdbs
io.atom_files_directory=runenv.pdbdir+io.atom_files_directory
#fd,naln=self.get_pdbfile(runenv.pdbdir,[],alncode,env,aln,tmpdir)
print k
m.add_alignment_witherr(naln,chain_span_range=(-csmax,-csmin,csmin,csmax),residue_span_range=(-kcut1,-kcut,kcut,kcut1),bond_span_range=(bs,bsm),errorscale=errsv,io=io,disulfide=ssp)#,startpos=0,endpos=0,scale=0,refyes=False,refmdt='',io=io)
if len(m.shape)>1 and (np.array(m.shape)>1).sum()>1:
raise Bugs('Currently the code does not support 2-d rawsp-i')
else:
for i in range(0,tal):
if len(m.shape)==2:
refdista[k,i]=m[0,i]
#np.unravel_index(i,ms)
else:
refdista[k,i]=m[i]
k=k+1
m=[]
aln=[]
m=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
fl=len(featurelist)
#m=m.reshape(featurelist,[0 for i in range(0,fl)], [-1 for i in range(0,fl)])
aln=alignment(env)
#print os.system('rm -rf '+tmpdir)
return refdista
def calc_sp_individual1D_fromlist(self, dnlist):
#generate distributions for calculate benchmark score for reference state
features=self.features
bm=self.genmethod
env = environ()
log.minimal()
mlib=mdt.Library(env)
mlib.bond_classes.read('${LIB}/bndgrp.lib')
env.io.atom_files_directory=[scratchdir,'./'] +runenv.pdbdir
featurelist=feature(self.features,mlib).get_featurelist()
csmin, csmax,kcut, kcut1, bs,bsm, errsv,ssp=decode_genmethod(self.genmethod)
k=0
m=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
fl=len(featurelist)
#m=m.reshape(featurelist,[0 for i in range(0,fl)], [-1 for i in range(0,fl)])
refdista=np.zeros([len(dnlist)]+ m.shape)
tal=1
ms=m.shape
for si in ms:
tal=tal*si
for k in range(0,len(dnlist)):
mdl=model(env)
mdl.read(file=dnlist[k])
aln=alignment(env)
codelist=dnlist[k].split('.')
if len(codelist)>1:
print runenv.ddbdir+codelist[0]+'/'+codelist[1]+'/'
fd,naln=self.get_pdbfile(runenv.ddbdir+codelist[0]+'/'+codelist[1]+'/',codelist,dnlist[k],env,aln)
env.io.atom_files_directory=[fd]+env.io.atom_files_directory
else:
fd,naln=self.get_pdbfile(runenv.ddbdir+codelist[0]+'/'+codelist[1]+'/',[],alncode,env,aln,tmpdir)
aln.append_model(mdl,align_codes=dnlist[k],atom_files=dnlist[k])
print k
#if k> 100:
# return refdista
m.add_alignment_witherr(aln,chain_span_range=(-csmax,-csmin,csmin,csmax),residue_span_range=(-kcut1,-kcut,kcut,kcut1),bond_span_range=(bs,bsm),errorscale=errsv,disulfide=ssp)
for i in range(0,tal):
id=np.unravel_index(i,ms)
rid=tuple([k]+list(id))
refdista[rid]=m[id]
m=[]
aln=[]
mdl=[]
m=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
fl=len(featurelist)
return refdista
def calc_individual_sp(self, pirfile,dnlist,ptype):
#get the mdt tables only for ddb
features=self.features
env = environ()
tmpdir=scratchdir
log.minimal()
mlib=mdt.Library(env)
mlib.bond_classes.read('${LIB}/bndgrp.lib')
env.io.atom_files_directory=[scratchdir,'./']+runenv.pdbdir
io=env.io
featurelist=feature(self.features,mlib).get_featurelist()
m=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
ma=m.get_array_view()
mshape=[]
mshape=[i for i in m.shape if i>1]
m1s=m.shape[0]
m2s=1
for item in m.shape[1:]:
m2s*=item
#decode generation method
bm=self.genmethod
#initialize the array for storing result
if ptype=='idist':
ra=np.zeros([len(dnlist)]+ mshape)
csmin, csmax,kcut, kcut1, bs,bsm, errsv,ssp=decode_genmethod(self.genmethod)
elif ptype=='apidist':
apc=self.apca
apcl=[]
apcn=apc.max()+1
pairdim=len(apc.shape)
sds=list(mshape[:-pairdim])
sdl=[]
for i in range(len(sds)):
indexshape=[1 for j in range(len(sds)+1)]
indexshape[i]=sds[i]
sdl.append(np.arange(0,sds[i]).reshape(indexshape))
for i in range(apcn):
cdl=sdl+[]
apci=np.nonzero(apc==i)
indexshape=[1 for j in range(len(sds)+1)]
indexshape[-1]=len(apci[0])
for item in apci:
cdl.append(item.reshape(indexshape))
apcl.append(tuple(cdl))
ra=np.zeros([len(dnlist),apcn]+ sds)
csmin, csmax,kcut, kcut1, bs,bsm, errsv,ssp=decode_genmethod(self.genmethod)
elif ptype=='apdecompscore':
apc=self.apca
apcl=[]
apcn=apc.max()+1
pairdim=len(apc.shape)
sds=list(mshape[:-pairdim])
sumaxis=range(1,len(mshape)-pairdim)
sumaxis.reverse()
for i in range(apcn):
cdl=[]
apci=np.nonzero(apc==i)
for item in apci:
cdl.append(item.reshape([len(item)]))
apcl.append(tuple(cdl))
ms=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
ms.read_hdf5(self.ssppath+'.hdf5')
msa=ms.get_array_view()
self.svdu,self.svdv=self.get_svd()
ra=np.zeros([len(dnlist),apcn,self.svdu.shape[0]])
csmin, csmax,kcut, kcut1, bs,bsm, errsv,ssp=decode_genmethod(self.bm)
elif ptype=='apscore':
apc=self.apca
apcl=[]
apcn=apc.max()+1
pairdim=len(apc.shape)
sds=list(mshape[:-pairdim])
sumaxis=range(0,len(mshape)-pairdim)
sumaxis.reverse()
for i in range(apcn):
cdl=[]
apci=np.nonzero(apc==i)
for item in apci:
cdl.append(item.reshape([len(item)]))
apcl.append(tuple(cdl))
ms=mdt.Table(mlib,features=featurelist,shape=[-1]*len(featurelist))
ms.read_hdf5(self.ssppath+'.hdf5')
msa=ms.get_array_view()
ra=np.zeros([len(dnlist),apcn])
csmin, csmax,kcut, kcut1, bs,bsm, errsv,ssp=decode_genmethod(self.bm)
elif ptype=='decompscore':
self.svdu,self.svdv=self.get_svd()
ra=np.zeros([len(dnlist),self.svdu.shape[0]])
csmin, csmax,kcut, kcut1, bs,bsm, errsv,ssp=decode_genmethod(self.bm)
#loop through all the structures to generate the table for individual structures
f=modfile.File(pirfile,'r')
aln=alignment(env)
k=0
while aln.read_one(f):
sr=0;
alncode=aln[0].code
print alncode
codelist=alncode.split('.')
if len(codelist)>1:
print runenv.ddbdir+codelist[0]+'/'+codelist[1]+'/'
fd,naln=self.get_pdbfile(runenv.ddbdir+codelist[0]+'/'+codelist[1]+'/',codelist,alncode,env,aln,tmpdir)
io.atom_files_directory=[fd]+io.atom_files_directory
else:
naln=aln
io.atom_files_directory=runenv.pdbdir+io.atom_files_directory
print k
m.add_alignment_witherr(naln,chain_span_range=(-csmax,-csmin,csmin,csmax),residue_span_range=(-kcut1,-kcut,kcut,kcut1),bond_span_range=(bs,bsm),errorscale=errsv,io=io,disulfide=ssp)#,startpos=0,endpos=0,scale=0,refyes=False,refmdt='',io=io)
#process the result from this single table
#sma=np.squeeze(np.copy(ma))
sma=ma
if ptype=='idist':
try:
ra[k,...]=sma[i]
except:
pdb.set_trace()
elif ptype=='apdecompscore':
rso=(np.dot(self.svdu.T,sma.reshape([m1s,m2s]))*self.svdv).reshape(m.shape)
for ax in sumaxis:
rso=rso.sum(axis=ax)
ra[k,:]=rso[:,apcl[i]].sum(axis=1)
elif ptype=='apidist':
for i in range(apcn):
ra[k,i,...]=sma[apcl[i]].sum(axis=-1)
elif ptype=='apscore':
for i in range(apcn):
nma=(sma*msa)
for ax in sumaxis:
nma=nma.sum(axis=ax)
ra[k,i]=nma[apcl[i]].sum()
elif ptype=='decompscore':
ra[k,:]=(np.dot(self.svdu.T,sma.reshape([m1s,m2s]))*self.svdv).sum(axis=1)
k=k+1
m.clear()
#print os.system('rm -rf '+tmpdir)
return ra
def cat_spi(self,name='result'):
filelist=[str(item)+'.'+name+'.npy' for item in range(1, self.nors+1)]
al=[]
alen=0
aw=0
alp=[]
for name in filelist:
temp=np.load(name)
alen=alen+temp.shape[0]
aw=temp.shape[1:]
alp.append(temp.shape[0])
al.append(name)
ddist=np.zeros([alen]+list(aw),dtype=np.float32)
sp=0
for i in range(0,len(al)):
ddist[sp:sp+alp[i]]=np.load(al[i])
sp=sp+alp[i]
np.save('all.npy',ddist)
return ddist
def sp_stderr2(self,wdir=None,nolog=False):
##!!!!!!!!!!!!!!!will calculate the stderr here
if wdir:
os.chdir(wdir)
print "Calculating Standard deviation"
filelist=[]
files=os.listdir('./')
for filename in files:
if filename!='sum.hdf5' and filename.endswith('.result.hdf5'):
filelist.append(filename)
if nolog:
prefix='o'
else:
prefix=''
os.system('cp sum.hdf5 '+prefix+'mean.hdf5')
os.system('cp sum.hdf5 '+prefix+'stderr2.hdf5')
f=[]
f2=[]
f=h5py.File(prefix+'mean.hdf5','r+')
f2=h5py.File(prefix+'stderr2.hdf5','r+')
mdtmean=f['mdt']
mdtmean[...]=0
if nolog:
ssp=scaledsp('nbsumnolog',self)
else:
ssp=scaledsp('nbsum',self)
for filename in filelist:
print 'calcting error for '+filename
ssp.scalesp(ssppath=filename[:-5])
for filename in filelist:
#try:
ft=h5py.File(filename,'r')
mdtmean[...]=mdtmean[...]+ft['mdt'][...]
ft.close()
ft=[]
#except:
# print 'error in sp_stderr2 1'
# pdb.set_trace()
mdtmean[...]=mdtmean[...]/len(filelist)
mdtstd=f2['mdt']
mdtstd[...]=0
for filename in filelist:
#try:
ft=h5py.File(filename,'r')
mdtstd[...]=mdtstd[...]+(ft['mdt'][...]-mdtmean[...])**2
ft.close()
ft=[]
#except:
# print 'error in sp_stderr2 2'
# pdb.set_trace()
mdtstd[...]=mdtstd[...]/len(filelist)**2
f.flush()
f.close()
f2.flush()
f2.close()
print "Calculating Standard error square Finished"
def load_i(self):
idist=np.load(self.sppath+'.npy')
ms=idist.shape
if 0 and self.bl<ms[self.bp+1]: #outdated
print "reshaping the original stats array"
if len(ms)==2:
idist=np.copy(idist[:,:-1])
elif len(ms)==3:
idist=np.copy(idist[:,:-1,:-1])
elif len(ms)==4:
idist=np.copy(idist[:,:-1,:-1,:-1])
elif len(ms)==5:
idist=np.copy(idist[:,:-1,:-1,:-1,:-1])
np.save(self.sppath+'.npy',idist)
if idist.dtype!='float32':
idist=idist.astype(np.float32)
np.save(self.sppath+'.npy',idist)
return idist
def get_i(self,nors=600):
self.nors=nors
self.routine='calc_sp_i'
pdbsets=self.pdbset.split('_')
nalen=0
if len(pdbsets)==1:
if not os.path.isfile(self.sppath+'.npy'):
self.calc_sp_cluster()
return self.load_i()
else:
if os.path.isfile(self.sppath+'.npy'):
return self.load_i()
else:
al=[]
self.calc_sp_cluster()
for pset in pdbsets:
nspa=rawsp(pset,self.features,self.genmethod,self.tlib,self.decoy,self.routine).load_i()
al.append(nspa)
nalen+=nspa.shape[0]
if len(nspa.shape)>1:
newshape=tuple([nalen]+list(nspa.shape[1:]))
else:
newshape=(nalen)
print newshape
na=np.empty(newshape,dtype=np.float32)
k=0
for nspa in al:
na[k:k+nspa.shape[0]]=nspa[...]
k+=nspa.shape[0]
#os.makedirs(os.path.split(self.sppath)[0])
np.save(self.sppath+'.npy',na)
return na
def combine_flag(self,pdbdir):
pass
def get_pdbfile(self,pdbdir,codelist,alncode,env,aln,tmpdir='./'):
code=alncode
if isinstance(pdbdir, list) and len(pdbdir)==1:
pdbdir=pdbdir[0]
print "unziping "+code
if isinstance(pdbdir, list):
return [pdbdir,aln]
if os.path.isfile(pdbdir+'needattachtobase'):
basefile=pdbdir+codelist[1]+'.base.pdb'
if not os.path.isfile(basefile):
basefile=pdbdir+codelist[0]+'.'+codelist[1]+'.base.pdb'
fh=open(basefile,'r')
fc=fh.read()
fh.close()
fh=gzip.open(pdbdir+alncode+'.pdb.gz','r')
dfc=fh.read()
fh.close()
fc=fc+'\n'+dfc
fh=open(os.path.join(tmpdir,alncode+'.pdb'),'w')
fh.write(fc)
fh.close()
return [tmpdir,aln]
elif os.path.isfile(pdbdir+'needcombinewithbase'):
basefile=pdbdir+codelist[1]+'.base.pdb'
if not os.path.isfile(basefile):
basefile=pdbdir+codelist[1]+'.base'
if not os.path.isfile(basefile):
basefile=pdbdir+codelist[0]+'.'+codelist[1]+'.base.pdb'
if not os.path.isfile(basefile):
basefile=pdbdir+codelist[1]+'.base.gz'
fh=gzip.open(basefile)
else:
fh=open(basefile,'r')
fc=fh.read()
fh.close()
fh=gzip.open(pdbdir+alncode+'.pdb.gz','r')
dfc=fh.read()
fh.close()
fc=fc.replace('replacethis',dfc)
fh=open(os.path.join(tmpdir,alncode+'.pdb'),'w')
fh.write(fc)