-
Notifications
You must be signed in to change notification settings - Fork 2
/
pp.py
2211 lines (2112 loc) · 82 KB
/
pp.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
#functions to process pdb lists
from __future__ import print_function
from modeller import *
import re
import os
import time
import urllib
from modeller.automodel import *
from modeller.automodel.autosched import *
# Load in optimizer and schedule support
from modeller import optimizers
from modeller.schedule import Schedule, Step
from modeller.optimizers import actions
import sys
import pdb
import numpy as np
import pickle
if sys.version_info[0] >= 3:
cPickle = pickle
else:
import cPickle
from operator import itemgetter, attrgetter
import copy
import SOAP
import traceback
from SOAP import *
basedir='/bell2/gqdong/statpot/'
pfd=basedir+'pdbpir/'
resolre=re.compile("\s{2}RESOLUTION RANGE HIGH \(ANGSTROMS\)\s*:\s*([0-9\.]+)")
completenessre=re.compile("\s{2}COMPLETENESS.+\(%\)\s*:\s*([0-9\.]+)")
rfre=re.compile("R VALUE.{1,40}:\s*(0\.\d+)")
rfactorre=re.compile("FREE R VALUE\s*\(WORKING SET\)\s*:\s*(0\.\d+)")
frfactorre=re.compile("\s{2}FREE R VALUE\s{14}.{1,20}:\s*(0\.\d+)")
norre=re.compile("NUMBER OF REFLECTIONS.{1,30}:\s*([0-9\.]+)")
atomre=re.compile("\\nATOM.{52}1.00\s*|\\nHETATM.{50}1.00\s*")
bre=re.compile("\\nATOM.{57}\s?([0-9\.]+)\s*")
abfactorre=re.compile("\s{2}MEAN B VALUE\s*\(OVERALL, A\*\*2\)\s*:\s*([0-9\.]+)")
originaldir='/bell2/gqdong/pdb/pdb1/'
flippeddir='/bell2/gqdong/pdb/pdb2/'
finaldir='/bell2/gqdong/pdb/pdb3/'
decoysdir={'ppd4s':'/bell2/gqdong/rawdecoyfiles/ppd/ppd4s/'}
debug=False
class entirepdb(object):
#key:code
#['code', 'medianCbeta', 'aveB', 'MolProbityScore', 'numRama', 'nucacids', 'pct_badangles', 'pir',
#'completeness', 'maxCbeta', 'pct_badbonds', 'aveerr', 'numRota', 'meanCbeta', 'n_samples', 'ramaOutlier',
#'maxresol', 'ph', 'type', 'Mol_pct_rank', 'errorscale', 'pct_rank40', 'residues', 'clashscoreB<40',
#'clashscore', 'rota<1%', 'r', 'ramaAllowed', 'chains', 'pct_rank', 'minresol', 'numCbeta', 'ramaFavored',
#'rfree', 'atomnum', 'numofreflections', 'resolution', 'cbeta>0.25']
#chains:chainid
#['missingresnum', 'length', 'missingatomnum', 'atomnum', 'type', 'pir']
def __init__(self,originalpdbdir='',update=False):
self.originalpdbdir=originalpdbdir
self.xslist=[]
self.update=update
if update:
with open('xslist.pickle', 'rb') as fh:
self.oxslist=cPickle.load(fh)
else:
self.oxslist=[]
self.nxslist=self.xslist
self.errfh=open('/bell2/gqdong/pdb/errors','a')
self.minchainlen=30
self.pdbdict={}
self.pdbdictname='pdbdict.pickle'
def get_xray_structure_list(self,path=originaldir):
os.chdir(path)
print(os.system('scp gqdong@baton2:/netapp/database/pdb/remediated/pdball.pir '+basedir+'pdbpir/pdball.pir'))
fh=open(basedir+'pdbpir/pdball.pir')
fc=fh.read()
pl=fc.split('>P1;')
pl=pl[1:]
for p in pl:
code=p[0:4]
psl=p.split('\n')
if psl[1].startswith('structureX'):
self.xslist.append(code)
self.xslist=list(set(self.xslist))
if self.update:
with open('xslist.pickle', 'rb') as fh:
self.oxslist=cPickle.load(fh)
self.nxslist=[item for item in self.xslist if not item in self.oxslist]
else:
self.nxslist=self.xslist
self.oxslist=[]
#pdb.set_trace()
with open('xslist.pickle','wb') as fh:
cPickle.dump(self.xslist,fh)
def copy_xray_structures(self,path=originaldir):
os.chdir(path)
for code in self.nxslist:
print(os.system('cp /salilab/park2/database/pdb/divided/'+code[1:3]+'/pdb'+code+'.ent.gz ./'))
print(os.system('gunzip pdb'+code+'.ent.gz'))
print(os.system('mv '+'pdb'+code+'.ent '+'pdb'+code+'.pdb'))
def load_xslist(self):
os.chdir(originaldir)
with open('xslist.pickle', 'rb') as fh:
self.xslist=cPickle.load(fh)
self.nxslist=self.xslist
def preprocess(self):
import sp
if debug:
for code in self.nxslist:
self.preprocess_one(code)
else:
sp.task().parallel_local(self.preprocess_one,self.nxslist,10)
def preprocess_one(self,code):
if not os.path.isfile(originaldir+'pdb'+code+'.pdb'):
return 0
if os.path.isfile(finaldir+code+'.pickle'):# or code in ['3lmf','3alp','3ajn','3bcr','2c28','2c5h','2c5b','3e3n','9ga2','9ga1']:#or code in ['3a01','3a6p','2a79','3a9c','1abw']'3aej','3aem','1abw','3aen','2ajh','3ajn','3alp'
return 0
if debug:
ss=SingleStructure(code)
ss.preprocess()
else:
try:
ss=SingleStructure(code)
ss.preprocess()
except Exception as e:
print(code)
print(e)
self.errfh.write(code+'\n'+str(e))
def collect_dict(self):
os.chdir(finaldir)
fl=os.listdir('./')
fl=[f for f in fl if f[5:]=='pickle']
pdbdict={}
for f in fl:
print(f)
fh=open(f)
sd=cPickle.load(fh)
fh.close
if 1:
ss=SingleStructure(f[0:4])
ss.pdict=sd
ss.write_xray_rfactor()
sd['type']='X'
ss.save_dict()
pdbdict[f[0:4]]=sd
os.chdir('..')
self.pdbdict=pdbdict
self.save_dict()
def save_dict(self):
os.chdir('/bell2/gqdong/pdb/')
with open(self.pdbdictname,'w') as fh:
cPickle.dump(self.pdbdict,fh)
def load_dict(self):
os.chdir('/bell2/gqdong/pdb/')
with open(self.pdbdictname) as fh:
self.pdbdict=cPickle.load(fh)
def get_seqlist(dsname):
dsdir=decoysdir[dsname]
fl=os.listdir(dsdir)
env=Environ()
aln=Alignment(env)
asl=[]
for f in fl:
cl,sl=mymodel(f+'_r_u.pdb.HB').get_structure_chain_sequence()
asl=asl+sl
cl,sl=mymodel(f+'_l_u.pdb.HB').get_structure_chain_sequence()
asl=asl+sl
return asl
def get_pir(self,ppdict={}):#X-xray, U-biological unit, T-transmembrane protein, M-membrane protein,S-single chain, W-non-membrane protein,1-single chain pir or none, 2-multiple chain pir, H-helical protein, B-beta protein
#pdb.set_trace()
if len(self.pdbdict)==0:
self.load_dict()
if 'similar' in ppdict:
similarlist=ppdict['similar']
similarfilter=True
decoysseqlist=self.get_seqlist(similarlist[0])
del ppdict['similar']
else:
similarfilter=False
pirlist=[]
cp=['T','H','B'] #all possible chain types
ctype=''
#pdb.set_trace()
for cpi in cp:
if cpi in ppdict['type']:
ctype=ctype+cpi
for code in self.pdbdict:
codedict=self.pdbdict[code]
collect=True
complexpir=0
ctype=''
cnom=False#the chain/s can not have missing atoms/residues
for key in ppdict:
if key=='type': #X-xray, U-biological unit, T-transmembrane protein, M-membrane protein,S-single chain, W-non-membrane protein,1-single chain pir or none, 2-multiple chain pir, H-helical protein, B-beta protein
for item in ppdict[key]:
if item=='S':
if len(codedict['chains'].keys())>1:
collect=False
break
elif item in ['X','U','T','M','S','W','H','B']:
if not item in codedict[key]:
collect=False
break
elif item in ['2','3','4']:
complexpir=int(item)
elif key=='ph':
#pdb.set_trace()
if codedict[key]<ppdict[key][0] or codedict[key]>ppdict[key][1]:
collect=False
break
elif key=='cnom':#the single chain has no missing atoms or residues
cnom=True
elif key in ['r','rfree','resolution']:
if codedict[key]>ppdict[key]:
collect=False
break
else:
raise Exception('Do not know the property: '+key)
if not collect:
continue
print(code)
if complexpir==2:
if len(codedict['chains'])>1:
pirlist.append((codedict['pir'],codedict['resolution'],codedict['rfree']))
else:
continue
elif complexpir==3:
if len(codedict['chains'])==2:
pirlist.append((codedict['pir'],codedict['resolution'],codedict['rfree']))
else:
continue
elif complexpir==4:
if len(codedict['chains'])>1:
for cc in codedict['chains']:
cd=codedict['chains'][cc]
pirlist.append((cd['pir'],codedict['resolution'],codedict['rfree']))
else:
continue
else:
for cc in codedict['chains']:
cd=codedict['chains'][cc]
ctc=True
for item in ctype: #check whether the chain type matches the type dict
if not item in cd['type']:
ctc=False
break
if not ctc:
continue
print(cd['missingatomnum'])
if cnom and cd['missingatomnum']>0:
continue
if (cd['length']-cd['missingresnum'])>self.minchainlen:
pirlist.append((cd['pir'],codedict['resolution'],codedict['rfree']))
pirlist.sort(key=itemgetter(1,2))
pirstring='\n'.join([pir[0] for pir in pirlist])
return pirstring
def takethischain(self,seqid,decoysseqlist,csl):
env
for cs in csl:
for dss in decoysseqlist:
aln=Alignment(env)
aln.append_sequence(cs)
aln.append_sequence(dss)
sid=aln.id_table()
if sid>seqid:
return False
return True
def update_S2C(self):
pass
def get_alltm_codes(self):
paths=['http://pdbtm.enzim.hu/data/pdbtm_all.list','http://pdbtm.enzim.hu/data/pdbtm_alpha.list','http://pdbtm.enzim.hu/data/pdbtm_beta.list']
keynames=['T','H','B']
dictlist={}
for i in range(0,len(paths)):
path=paths[i]
ld={}
mlf=urllib.urlopen(path)
mlfc=mlf.read()
mll=mlfc.split('\n')
mpl=[item for item in mll if len(item)>3]
for item in mpl:
if item[0:4] in ld:
ld[item[0:4]]=ld[item[0:4]]+item[-1]
else:
ld[item[0:4]]=item[-1]
dictlist[keynames[i]]=ld
self.THBdict=dictlist
def update_THB(self):
self.get_alltm_codes()
self.load_dict()
for code in self.pdbdict:
for dictkey in ['T','H','B']:
if code in self.THBdict[dictkey]:
print(code)
self.pdbdict[code]['type']=self.pdbdict[code]['type']+dictkey
for cc in self.pdbdict[code]['chains']:
if cc in self.THBdict[dictkey][code]:
if 'type' in self.pdbdict[code]['chains'][cc]:
self.pdbdict[code]['chains'][cc]['type']=self.pdbdict[code]['chains'][cc]['type']+dictkey
else:
self.pdbdict[code]['chains'][cc]['type']=dictkey
self.save_dict()
def update_U(self):
pass
def update_ph(self):
os.chdir(originaldir)
env=Environ()
self.load_dict()
for code in self.pdbdict:
self.pdbdict[code]['ph']=sp.get_ph(code)
self.save_dict()
class tmhpdb(entirepdb):
def __init__(self):
self.minchainlen=1
self.pdbdictname='tmhpdbdict.pickle'
self.pdbdict={}
def convert_tochains(self,path=''):
self.path=path
env=Environ()
os.chdir(path)
fl=os.listdir('./')
fl=[item[:-4] for item in fl if item.endswith('pdb')]
self.fl=fl
ep=entirepdb()
ep.load_dict()
for f in fl:
os.chdir(path)
if f[0:4] not in ep.pdbdict:
print('skipping because of not in pdbdict'+f)
continue
if not os.path.isfile(path+f+'.log'):
print('skipping because of no log'+f)
continue
#mdlo=mymodel(env,code=f+'.pdb')
#mdlo.convert_tmh_tochains(path,f)
mdl=mymodel(env,code='THAC'+f+'.pdb')
key='THAC'+f
self.pdbdict[key]=copy.deepcopy(ep.pdbdict[f[0:4]])
self.pdbdict[key]['code']=key
self.pdbdict[key]['pir']=mdl.get_structure_sequence()
cd=mdl.build_chain_dict('TH')
self.pdbdict[key]['chains']=cd
mdl=[]
self.save_dict()
def copy_pdb(self):
os.chdir(self.path)
os.system('cp THAC*pdb '+finaldir)
os.system('scp THAC*pdb gqdong@baton2:~/pdb/')
class tmhmcpdb(entirepdb):
def __init__(self):
self.minchainlen=1
self.pdbdictname='tmhmcpdbdict.pickle'
self.pdbdict={}
def convert_tochains(self,path=''):
self.path=path
env=Environ()
os.chdir(path)
fl=os.listdir('./')
fl=[item for item in fl if item.startswith('THAC') and item.endswith('pdb')]
fd={}
for f in fl:
if f[4:8] in fd:
fd[f[4:8]].append(f)
else:
fd[f[4:8]]=[f]
self.fl=fl
ep=entirepdb()
ep.load_dict()
for pdbkey in fd:
os.chdir(path)
if pdbkey not in ep.pdbdict:
print('skipping because of not in pdbdict'+f)
continue
combine_models(fd[pdbkey],'THMC'+pdbkey+'.pdb')
mdl=mymodel(env,code='THMC'+pdbkey+'.pdb')
key='THMC'+pdbkey
self.pdbdict[key]=copy.deepcopy(ep.pdbdict[pdbkey])
self.pdbdict[key]['code']=key
self.pdbdict[key]['pir']=mdl.get_structure_sequence()
cd=mdl.build_chain_dict('TH')
self.pdbdict[key]['chains']=cd
mdl=[]
self.save_dict()
def copy_pdb(self):
os.chdir(self.path)
os.system('cp THMC*pdb '+finaldir)
os.system('scp THMC*pdb gqdong@baton2:~/pdb/')
class bioupdb(entirepdb):
#Biounit dictionary
def __init__(self):
self.minchainlen=30
self.pdbdictname='bioupdbdict.pickle'
self.pdbdict={}
def build_pdbdict(self,opath,tpath):
env=Environ()
ep=entirepdb()
ep.load_dict()
fl=os.listdir(opath)
for f1 in fl:
if len(f1)!=2:
continue
cdir=opath+f1+'/'
os.chdir(cdir)
print(os.system('gunzip *gz'))
print(os.system('rm *r'))
print(os.system('rm *.model*'))
fl2=os.listdir(cdir)
for f2 in fl2:
print(f2)
os.chdir(cdir)
pdbcode=f2[0:4]
mycode='BIOU'+pdbcode+f2[-1]
if pdbcode not in ep.pdbdict or pdbcode in ['1smv']:
print('skipping because of not in pdbdict'+f2)
continue
mdl=Model(env)
try:
if not os.path.isfile(tpath+mycode+'.pdb'):
try:
mdl.read(f2)
except:
continue
if len(mdl.chains)<=1:
print("single chain structure, skipping....")
continue
self.rebuild_model(f2)
print(os.system('cp '+f2+'r '+tpath+mycode+'.pdb'))
except Exception as e:
if re.search('Too many chains',str(e)):
print(os.system('touch '+opath+f2))
continue
else:
traceback.print_exc()
pdb.set_trace()
os.chdir(tpath)
mdl2=mymodel(env,code=mycode)
self.pdbdict[mycode]=copy.deepcopy(ep.pdbdict[pdbcode])
self.pdbdict[mycode]['code']=mycode
self.pdbdict[mycode]['pir']=mdl2.get_structure_sequence()
cd=mdl2.build_chain_dict('')
self.pdbdict[mycode]['chains']=cd
self.save_dict()
def rebuild_model(self,fp):
ml=seperate_models(fp)
if ml:
combine_models(ml,fp+'r')
else:
print(os.system('cp '+fp+' '+fp+'r'))
def copy_pdb(self,tpath):
os.chdir(self.tpath)
os.system('scp *pdb gqdong@baton2:~/biounits/')
def get_dockgroundlist(self): #label,G
lp='http://dockground.bioinformatics.ku.edu/BOUND/REPRESENTATIVES/result/represent.easy.dataset/represent_res_cluster_id_30_dimer.txt'
pass
class loop(object): #loopchain,looplength,loopstart,loopend,looptype
def __init__(self,env=env()):
self.env=env
self.nofloops=3000
self.refpot=['$(LIB)/atmcls-melo.lib','$(LIB)/melo1-dist.lib']
self.bm='slow'
self.j=[]
self.pn=8
self.calc_rmsds=111
self.input=''
self.pe='local'
def read_dssp_for_allpdb(self,dir='',filelist=[]):
if dir:
os.chdir(dir)
else:
os.chdir('/bell2/gqdong/S2C/')
dssplist=os.listdir('./')
if filelist:
dssplist=filelist
dsspdict={}
try:
for file in dssplist:
print(file)
if file[-4:]!='dssp':
continue
try:
fh=open(file,'r')
except:
print('Open file problem '+file)
continue
dssplist=[]
startrecord=False
for line in fh:
if line[0:25]==' # RESIDUE AA STRUCTURE':
startrecord=True
continue
if startrecord:
try:
resnum=int(line[6:10])
chain=line[11]
resname=line[13]
ssc=line[16]
except Exception as e:
traceback.print_exc()
print(line)
continue
dssplist.append([chain,resnum,resname,ssc])
dsspdict[file[:-5]]=dssplist
except Exception as e:
traceback.print_exc()
return dsspdict
def define_loops(self,dslist=[],filelist=[]):
dsspdict=self.read_dssp_for_allpdb(filelist=filelist)
if dslist:
dslist=set(dslist)
else:
dslist=set([' ','T','S','B'])
loopdict={}
for key in dsspdict:
dssplist=dsspdict[key]
inloop=False
looplist=[]
loopchain=0
loopstart=0
loopend=0
looplength=0
looptype=0# good loop:0, broken loops:1, sterminal loops:10, end terminal loop:100
for i in range(0,len(dssplist)):
item=dssplist[i]
if ((not item[3] in dslist) or (item[0]!=dssplist[i-1][0])) and inloop:
inloop=False
loopend=dssplist[i-1][1]
if i==1 or item[0]!=dssplist[i-1][0]:
looptype=looptype+100
if looplength!=loopend-loopstart+1:
looptype=looptype+1
looplist.append([loopchain,looplength,loopstart,loopend,looptype])
if item[3] in dslist:
if not inloop:
inloop=True
loopchain=item[0]
loopstart=item[1]
if i==0 or i==(len(dssplist)-1) or item[0]!=dssplist[i-1][0]:
looptype=10
else:
looptype=0
looplength=1
else:
looplength=looplength+1
if i==(len(dssplist)-1):
loopend=dssplist[i][1]
looptype=looptype+100
if looplength!=loopend-loopstart+1:
looptype=looptype+1
looplist.append([loopchain,looplength,loopstart,loopend,looptype])
loopdict[key]=looplist
dslistname=''.join(dslist).strip()
with open('/bell3/gqdong/statpot/loop/'+dslistname+'loop.pickle','wb') as fh:
cPickle.dump(loopdict,fh)
def filter_loops(self,pdbset='pdb_SX.pir',Xray=2.0,Rfactor=0.25,looplength=[4,25],nonstdres=False,
terminal=False,broken=False,occ=1,accessibilitycutoff=[5,60],phrange=[6.5,7.5], sid=60,
missingatoms=False,isotempfactorstd=2,minhetamdist=1,metaliondist=3.5,maxcacadist=3.7,dslist=[' ','T','S','B']):
os.chdir('/bell3/gqdong/statpot/loop/')
dslistname=''.join(dslist).strip()
with open('/bell3/gqdong/statpot/loop/SBTloop.pickle','rb') as fh:
loopdict=cPickle.load(fh)
selectedloopdict={}
env = Environ()
log.minimal()
env.io.atom_files_directory=['/salilab/park2/database/pdb/divided/']
env.libs.topology.read(file='$(LIB)/top_heav.lib')
env.libs.parameters.read(file='$(LIB)/par.lib')
env.io.hetatm=True
aln=Alignment(env)
from sp import *
po=pir(self.env,runenv.pdbpirdir+pdbset)
po.filter_pir(xray=Xray,rfactor=Rfactor,phrange=phrange,sid=sid)
po=pir(self.env,po.pirpath[:-4]+'_'+str(Xray)+'_'+str(Rfactor)+'_'+str(phrange[0])+'-'+str(phrange[1])+'_'+str(sid)+'.pir')
codelist=po.get_codelist()
resatoms=get_residues_atoms()
nofloops=0
aacc=[]
numofloops=0
for code in codelist:
if code[0:4] in loopdict:
loops=loopdict[code[0:4]]
else:
continue
selectedloops=[]
mdl=Model(env)
mdl.read(file=code[0:4])
accmdl=Model(env)
accmdl.read(file=code[0:4])
accmdl.write_data('PSA',accessibility_type=2,file=None)
asel=Selection(mdl)
nonstds=Selection(mdl)-asel.only_std_residues()
meanbiso=0
bisomean,bstd=self.calc_model_biso(mdl)
bisothresd=bisomean+isotempfactorstd*bstd
clash,contact=Mymodel(env).clash_contact(code[0:4])
self.clash=clash
self.contact=contact
for loop in loops:
print(loop)
sacc=self.aveacc(loop,accmdl)
aacc.append(str(sacc))
#try:
if 1:
if not (terminal or broken):
if loop[4]>0:
continue
if loop[1]<looplength[0] or loop[1]>looplength[1]:
print('loop length '+str(loop[1]))
continue
if not (nonstdres or missingatoms):
try:
s=Selection(mdl.residue_range(str(loop[2])+':'+loop[0],str(loop[3])+':'+loop[0]))
except:
continue
s=s.only_std_residues()
residuedict={}
for atom in s:
if atom.residue.name in ['ASX','GLX']:
continue
if not atom.residue.num in residuedict:
residuedict[atom.residue.num]=[atom.residue.name,[atom.name],atom.biso]
else:
residuedict[atom.residue.num][1].append(atom.name)
residuedict[atom.residue.num][2]=residuedict[atom.residue.num][2]+atom.biso
if len(residuedict)!=loop[1]:
print('missing residue')
continue
select=True
for key in residuedict:
if (not (set(residuedict[key][1])>=set(resatoms['resatomdict'][residuedict[key][0]]))):
select=False
print('missing atoms')
print(residuedict[key][1])
print(resatoms['resatomdict'][residuedict[key][0]])
break
if (residuedict[key][2]/len(residuedict[key][1]))>bisothresd:
print('disorder')
select=False
break
if select==False:
continue
else:
print('please update filter_loops function to do this, non implemented yet')
if sacc>accessibilitycutoff[1] or sacc<accessibilitycutoff[0]:
print('Accessibility too high '+str(sacc))
continue
if self.clash_filter(loop):
continue
if self.contact_filter(loop,mdl,mindist=minhetamdist,ionmindist=metaliondist):
continue
if self.ca_distance_filter(loop,mdl,maxcacadist=maxcacadist):
continue
#except Exception as e:
# print(loop)
# traceback.print_exc()
print('selected:', loop)
selectedloops.append(loop)
if selectedloops:
print("#######################################"+code+' '+str(mdl.rfactor)+' '+str(mdl.resolution))
selectedloopdict[code[0:4]]=selectedloops
numofloops=numofloops+len(selectedloops)
print('num of selected loops: '+str(numofloops))
print('numof structures: '+str(len(selectedloopdict)))
with open('/bell3/gqdong/statpot/acc','w') as fh:
fh.write(','.join(aacc))
with open('/bell3/gqdong/statpot/loop/selectedloop.pickle','wb') as fh:
cPickle.dump(selectedloopdict,fh)
def filter_bs(self,pdbset='pdb_SX.pir',Xray=2.0,Rfactor=0.25,looplength=[4,25],nonstdres=False,
terminal=False,broken=False,occ=1,accessibilitycutoff=[5,60],phrange=[6.5,7.5], sid=60,
missingatoms=False,isotempfactorstd=2,minhetamdist=1,metaliondist=3.5,maxcacadist=3.7,dslist=[' ','T','S','B']):
os.chdir('/bell3/gqdong/statpot/loop/')
dslistname=''.join(dslist).strip()
with open('/bell3/gqdong/statpot/loop/SBTloop.pickle','rb') as fh:
loopdict=cPickle.load(fh)
selectedloopdict={}
env = Environ()
log.minimal()
env.io.atom_files_directory=['/salilab/park2/database/pdb/divided/']
env.libs.topology.read(file='$(LIB)/top_heav.lib')
env.libs.parameters.read(file='$(LIB)/par.lib')
env.io.hetatm=True
aln=Alignment(env)
from sp import *
po=pir(self.env,runenv.pdbpirdir+pdbset)
po.filter_pir(xray=Xray,rfactor=Rfactor,phrange=phrange,sid=sid)
po=pir(self.env,po.pirpath[:-4]+'_'+str(Xray)+'_'+str(Rfactor)+'_'+str(phrange[0])+'-'+str(phrange[1])+'_'+str(sid)+'.pir')
codelist=po.get_codelist()
resatoms=get_residues_atoms()
nofloops=0
aacc=[]
numofloops=0
for code in codelist:
if code[0:4] in loopdict:
loops=loopdict[code[0:4]]
else:
continue
selectedloops=[]
mdl=Model(env)
mdl.read(file=code[0:4])
accmdl=Model(env)
accmdl.read(file=code[0:4])
accmdl.write_data('PSA',accessibility_type=2,file=None)
asel=Selection(mdl)
nonstds=Selection(mdl)-asel.only_std_residues()
meanbiso=0
bisomean,bstd=self.calc_model_biso(mdl)
bisothresd=bisomean+isotempfactorstd*bstd
clash,contact=Mymodel(env).clash_contact(code[0:4])
self.clash=clash
self.contact=contact
for loop in loops:
print(loop)
sacc=self.aveacc(loop,accmdl)
aacc.append(str(sacc))
#try:
if 1:
if not (terminal or broken):
if loop[4]>0:
continue
if loop[1]<looplength[0] or loop[1]>looplength[1]:
print('loop length '+str(loop[1]))
continue
if not (nonstdres or missingatoms):
try:
s=Selection(mdl.residue_range(str(loop[2])+':'+loop[0],str(loop[3])+':'+loop[0]))
except:
continue
s=s.only_std_residues()
residuedict={}
for atom in s:
if atom.residue.name in ['ASX','GLX']:
continue
if not atom.residue.num in residuedict:
residuedict[atom.residue.num]=[atom.residue.name,[atom.name],atom.biso]
else:
residuedict[atom.residue.num][1].append(atom.name)
residuedict[atom.residue.num][2]=residuedict[atom.residue.num][2]+atom.biso
if len(residuedict)!=loop[1]:
print('missing residue')
continue
select=True
for key in residuedict:
if (not (set(residuedict[key][1])>=set(resatoms['resatomdict'][residuedict[key][0]]))):
select=False
print('missing atoms')
print(residuedict[key][1])
print(resatoms['resatomdict'][residuedict[key][0]])
break
if (residuedict[key][2]/len(residuedict[key][1]))>bisothresd:
print('disorder')
select=False
break
if select==False:
continue
else:
print('please update filter_loops function to do this, non implemented yet')
if sacc>accessibilitycutoff[1] or sacc<accessibilitycutoff[0]:
print('Accessibility too high '+str(sacc))
continue
if self.clash_filter(loop):
continue
if self.contact_filter(loop,mdl,mindist=minhetamdist,ionmindist=metaliondist):
continue
if self.ca_distance_filter(loop,mdl,maxcacadist=maxcacadist):
continue
#except Exception as e:
# print(loop)
# traceback.print_exc()
print('selected:', loop)
selectedloops.append(loop)
if selectedloops:
print("#######################################"+code+' '+str(mdl.rfactor)+' '+str(mdl.resolution))
selectedloopdict[code[0:4]]=selectedloops
numofloops=numofloops+len(selectedloops)
print('num of selected loops: '+str(numofloops))
print('numof structures: '+str(len(selectedloopdict)))
with open('/bell3/gqdong/statpot/acc','w') as fh:
fh.write(','.join(aacc))
with open('/bell3/gqdong/statpot/loop/selectedloop.pickle','wb') as fh:
cPickle.dump(selectedloopdict,fh)
def clash_filter(self,loop):
loopres=set([loop[0]+str(lnum) for lnum in range(loop[2],loop[3]+1)])
clashlist=[]
for item in self.clash:
if item[0][0]=='0':
clashlist.append(item[0][1]+item[0][2])
if item[1][0]=='0':
clashlist.append(item[1][1]+item[1][2])
for item in clashlist:
if item in loopres:
print('clash with '+','.join(item)+' ')
return True
return False
def contact_filter(self,loop,mdl,mindist,ionmindist):
loopres=[loop[0]+str(lnum) for lnum in range(loop[2],loop[3]+1)]
metalset=set(metalions())
for item in self.contact:
try:
if not (item[0][1]+item[0][2]) in loopres:
continue
if item[1][3]=='WAT' or item[1][3]=='HOH':
continue
else:
atomname=item[1][4].split('.')[0]
if item[1][3]=='MSE' and atomname=='SE':
element='SE'
elif atomname[0]=='H' or atomname[0:2] in ['1H', '2H','3H']:
element='H'
else:
element=mdl.residues[item[1][2]+':'+item[1][1]].atoms[atomname].element
if element in metalset:
if -float(item[2])<ionmindist:
print('metal ion too close, ',item)
return True
else:
if -float(item[2])<mindist:
print('other atoms too close, ',item)
return True
except:
pdb.set_trace()
return False
def ca_distance_filter(self,loop,mdl,maxcacadist):
atom1=mdl.residues[str(loop[2])+':'+loop[0]].atoms['CA']
atom2=mdl.residues[str(loop[3])+':'+loop[0]].atoms['CA']
dist=np.sqrt((atom1.x-atom2.x)**2+(atom1.y-atom2.y)**2+(atom1.z-atom2.z)**2)
if dist>maxcacadist*(loop[1]-1):
print('distance between ca atoms are too large: '+str(dist))
return True
return False
def hetatm_filter(self,loopsel,haa,mindist=4): #not used anymore
laa=np.zeros([len(loopsel),3])
i=0
for atom in loopsel:
laa[i,0]=atom.x
laa[i,1]=atom.y
laa[i,2]=atom.z
i=i+1
for i in range(0,haa.shape[0]):
for j in range(0,len(loopsel)):
if np.sqrt(np.sum((haa[i]-laa[j])**2))<mindist:
print('hetatm too close')
print(haa[i])
print(laa[j])
return False
return True
def aveacc(self,loop,mdl):
for i in range(0,len(mdl.residues)):
try:
if int(mdl.residues[i].num)==loop[2]:
break
except Exception as e:
print(e)
aveacc=0
for j in range(i,i+loop[1]):
aveacc=aveacc+mdl.residues[j].atoms[0].biso
return aveacc/loop[1]
def calc_model_biso(self,mdl):
biso=np.zeros(len(mdl.atoms))
for i in range(0,len(mdl.atoms)):
biso[i]=mdl.atoms[i].biso
return (biso.mean(), biso.std())
def get_loop_subset(self,inputloop='selectedloop.pickle', outputloop='m5l4t20.pickle',length=range(4,21),maxn=20):
with open(inputloop, 'rb') as fh:
als=pickle.load(fh)
nld={}
length.reverse()
for ll in length:
k=0
for code in als:
if code in nld:
continue
loops=als[code]
nll=[]
for loop in loops:
if loop[1]==ll:
nll.append(loop)
break
if len(nll)>0:
nld[code]=nll
k=k+1
if k>=maxn:
break
pdb.set_trace()
with open(outputloop,'wb') as fh:
pickle.dump(nld,fh)
def list2pir(pdblist):
pdb.set_trace()
class mymodel(Model):
def __init__(self,env,code):
if code.endswith('pdb'):
model.__init__(self,env,file=code)
self.code=code[:-4]
elif code.startswith('BIOU'):
model.__init__(self,env,file=code+'.pdb')
self.code=code
else:
model.__init__(self,env,file=code)#'pdb'+code+'.pdb'
self.code=code
self.type='structureX'
def read_tm_region(self,fp=''):
with open(fp) as fh:
fc=fh.read()
rer=re.findall('TMH\s+[0-9]+\s+residue\s+([0-9]+)\s+([0-9]+)',fc)
tmrl=[]
for item in rer:
tmrl.append([int(item[0]),int(item[1])])
return rer
def select_loop_atoms(self,loops):
s=Selection()
for loop in loops:
try:
s.add(Selection(self.residue_range(str(loop[2])+':'+loop[0],str(loop[3])+':'+loop[0])))
except:
lind=self.residues[str(loop[2])+':'+loop[0]].index
s.add(Selection(self.residues[lind:(lind+loop[1])]))
return s
def convert_tmh_tochains(self,path='',fn=''):
#convert different transmembrane helix to different chains
os.chdir(path)
tmrl=self.read_tm_region(path+fn+'.log')
self.read(fn+'.pdb')
cl=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T']
k=-1
for tmr in tmrl:
k=k+1
self.chains[0].name=cl[k]
s=self.select_loop_atoms([[self.chains[0].name,-1,tmr[0],tmr[1]]])
s.write('tmregiontemp'+cl[k])
print(os.system('cat tmregiontemp* > THAC'+fn+'.pdb'))
print(os.system('rm tmregiontemp*'))
def get_ph(self):
return sp.get_ph(self.code)
def get_structure_sequence(self):
code=self.code
env=Environ()
m=Model(env,file=code)
aln=Alignment(env)
aln.append_model(self,align_codes=code,atom_files=code)
aln.write(code+'.s.pir')
with open(code+'.s.pir') as fh:
fc=fh.read()
return replace_structure_type(fc,self.type)
def get_structure_chain_sequence(self):
e=Environ()
cc=[]
cs=[]
for c in self.chains:
filename=self.code
print("Wrote out ",' ',filename, self.seq_id)
atom_file, align_code = c.atom_file_and_code(filename)
#print(os.system('touch '+code+'.pir'))
c.write('temp.pir', atom_file, align_code, format='PIR',
chop_nonstd_termini=False)
cc.append(align_code[-1])
with open('temp.pir') as fh: