-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDBFile.py
More file actions
executable file
·1399 lines (1281 loc) · 38.7 KB
/
Copy pathPDBFile.py
File metadata and controls
executable file
·1399 lines (1281 loc) · 38.7 KB
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
#!/usr/bin/env python2.1
#from Numeric import *
#from LinearAlgebra import *
#from numarray import *
from numpy import *
from numpy.linalg import *
#from numarray.linear_algebra import *
from string import *
import time, math, gzip
"""Utilities for accessing PDB files from Python
scripts in a sensible way"""
#class reference:
# def __init__(self, authors, title, editor, journal, publisher):
# update this to include additional modified AA from pdb
# files
aalist = { 'ALA': 'A', 'GLY': 'G', 'THR': 'T', 'TYR': 'Y',
'VAL': 'V', 'LEU': 'L', 'ILE': 'I', 'TRP': 'W',
'GLU': 'E', 'ASP': 'D', 'SER': 'S', 'ASN': 'N',
'GLN': 'Q', 'PRO': 'P', 'PHE': 'F', 'ARG': 'R',
'CYS': 'C', 'HIS': 'H', 'LYS': 'K', 'MET': 'M',
'CGU': 'E', 'DBY': 'Y', 'GLZ': 'G', 'GLQ': 'E',
'HSD': 'H', 'HEM': 'X', 'ABA': 'B', 'CSO': 'C',
'ASPP': 'D'}
# ABA aminobutyric acid
# this does not need updating as protonation states will not
# be indicated
aamap = { 'A':'ALA', 'G':'GLY', 'T':'THR', 'Y':'TYR',
'V':'VAL', 'L':'LEU', 'I':'ILE', 'W':'TRP',
'E':'GLU', 'D':'ASP', 'S':'SER', 'N':'ASN',
'Q':'GLN', 'P':'PRO', 'F':'PHE', 'R':'ARG',
'C':'CYS', 'H':'HIS', 'K':'LYS', 'M':'MET' }
def onel (threel):
"""Map a three letter amino acid code to one letter"""
try:
return aalist[ threel.upper() ]
except KeyError:
return 'X'
#print "Unknown three-letter code: ", threel
#print "Need to update aalist"
#import sys
#sys.exit(1)
def threel(onel):
"""Map a one letter amino acid code to three letter"""
try:
return aamap[ onel.upper() ]
except KeyError:
print "Unknown one-letter code: ", onel
import sys
sys.exit(1)
def onel_seq(threel_seq):
"""Map three letter AA sequence to one letter sequence"""
os = ""
for x in threel_seq:
os += onel(x)
return os
def translate( X, Y, Z, delta ):
X += delta[0]
Y += delta[1]
Z += delta[2]
def transform( X, Y, Z, symop, box ):
for i in range(len(X)):
X[i] = X[i]*symop[0][0] + symop[0][1]*box[0]
Y[i] = Y[i]*symop[1][0] + symop[1][1]*box[1]
Z[i] = Z[i]*symop[2][0] + symop[2][1]*box[2]
#X[i] = -X[i]+0.5*box[0]
#Y[i] = -Y[i]+0.0*box[1]
#Z[i] = Z[i]+0.5*box[0]
#xtr =
#print xtr
#ytr = symop[1][1]*box[1]
#print ytr
#ztr = symop[2][1]*box[2]
#print ztr
#X += xtr
#Y += ytr
#Z += ztr
def calcrotmat( XS, YS, ZS, XR, YR, ZR, notrans = 0 ):
R_trans = -array([ sum(XR)/len(XR), sum(YR)/len(YR), sum(ZR)/len(ZR) ], float64)
S_trans = -array([ sum(XS)/len(XS), sum(YS)/len(YS), sum(ZS)/len(ZS) ], float64)
if not notrans:
translate( XR, YR, ZR, R_trans )
translate( XS, YS, ZS, S_trans )
# Rij = sum( Rni * Snj )
R = array( [[ dot(XR,XS), dot(XR,YS), dot(XR,ZS)],
[ dot(YR,XS), dot(YR,YS), dot(YR,ZS)],
[ dot(ZR,XS), dot(ZR,YS), dot(ZR,ZS)] ], float64 )
RTR = dot( transpose(R), R )
evalues, evectors = eig(RTR)
evalues, evectors = esort(evalues, evectors)
# force right-handed system
evectors[2] = crossp( evectors[0], evectors[1] )
b = transpose(dot( R, transpose(evectors) ))
b[0] = b[0] / sqrt(dot(b[0], b[0]))
b[1] = b[1] / sqrt(dot(b[1], b[1]))
b[2] = crossp( b[0], b[1] )
U = dot( transpose(b), evectors )
return U
#class PDBFile(object):
class PDBFile:
"""Represents a pdb file, gives header info, allows random
access to coordinate records. Aimed at I/O rather than
data manipulation"""
def __init__( self, filename ):
if filename[-2:] == 'gz':
self.file = gzip.GzipFile( filename )
else:
self.file = open( filename )
self.olist = []
self.title = ""
self.expdata = ""
self.seqmap = {}
self.nmodel = 0
self.compnd = ""
self.temperature = 0.0
self.resolution = 0.0
for line in self.file.readlines():
self.parseline(line)
if len(self.olist) != self.olist.count(""):
print "Warning: pdb file ", self.idCode, "withdrawn"
print "from database, replaced by "
self.file.seek(0)
def close(self):
self.file.close()
def get_nmodel(self):
return self.nmodel
def parseline(self, line):
rkey = line[0:6]
if rkey == "HEADER":
self.depDate = line[50:59]
self.classification = line[10:50]
self.idCode = line[62:66]
elif rkey == "OBSLTE":
olist.append(line[31:35]).append(line[31:35])
olist.append(line[36:40]).append(line[41:45])
olist.append(line[46:50]).append(line[51:55])
olist.append(line[56:60]).append(line[61:65])
olist.append(line[66:70])
elif rkey == "TITLE ":
self.title += line[10:70].strip() + ' '
elif rkey == "COMPND":
self.compnd += line[10:70].strip() + ' '
elif rkey == "EXPDTA":
self.expdata += line[10:70].strip() + ' '
# elif line[0:6] == "AUTHOR":
# self.expdata += line[10:70].strip() + ' '
elif rkey == "SEQRES":
chainid = line[11]
if chainid in self.seqmap.keys():
self.seqmap[chainid] += line[19:70].split()
else:
self.seqmap[chainid] = line[19:70].split()
# elif rkey == "HELIX ":
# elif rkey == "SEQRES":
elif rkey == "MODEL ":
self.nmodel+=1
elif rkey == "REMARK":
if line[7:10] == '200' and line.find('TEMPERATURE') > 0:
ls = line.split()
T = ls[-1]
if T != "NULL" and T[0].isdigit():
self.temperature = float(T)
if line[9] == '2' and line.find('RESOLUTION') > 0:
ls = line.split()
R = ls[3]
if R != "NULL" and R[0].isdigit():
self.resolution = float(R)
def get_title(self):
return self.title
def get_compnd(self):
return self.compnd
def get_depdate(self):
return self.depdate
def get_resolution(self):
return self.resolution
def get_temperature(self):
return self.temperature
def get_expdata(self):
return self.expdata
def get_chains(self):
return self.seqmap.keys()
def get_seq(self, chainid):
return self.seqmap[chainid]
def find_subseq(self, subseq):
"""Finds a single-letter code subsequence, by searching
all chains. Returns id of first matching chain and offset
within it"""
# TODO: consider case where there are no SEQRES records
if len(self.seqmap.keys()) > 0:
for key in self.seqmap.keys():
off = onel_seq(self.seqmap[key]).find(subseq)
if (off >= 0):
print "Found subseq in chain " + key + \
" in SEQRES, looking in coordinates"
# check coordinate records
# actually there!
offset = \
self.check_records( subseq, key )
if offset >= 0:
print "Found subseq in coords too!"
return key, offset
else:
print "Could not find subseq in coords!"
return "NULL", -1
else:
offset = self.check_records( subseq, "ignore" )
if offset >= 0:
return "ignore", offset
else:
return "NULL", -1
def chop_model(self, model, lines):
for line in lines:
if line[0:6] == "MODEL " and model == int(line[10:14]):
lines = lines[ lines.index(line)+1 : ]
break
for line in lines:
if line[0:6] == "ENDMDL":
lines = lines[ : lines.index(line) ]
break
return lines
def check_records(self, subseq, chain, model = 0):
"""Recursive, incremental search routine to find a subsequence
in the actual coordinate records"""
self.file.seek(0)
lines = self.file.readlines()
if model > 0:
lines = self.chop_model(model, lines)
sequence = ""
resnum = -1
if chain != "ignore":
for x in lines:
if x[0:6] == "ATOM " and resnum != x[22:26] \
and chain == x[21]:
resnum = x[22:26]
sequence += onel(x[17:20])
else:
for x in lines:
if x[0:6] == "ATOM " and resnum != x[22:26]:
resnum = x[22:26]
sequence += onel(x[17:20])
return sequence.find(subseq)
def find_chain(self,chain):
"""Is a certain chain actually in the ATOM records??!"""
for line in self.file.readlines():
if line[0:6] == "ATOM ":
c = line[21]
if c == chain:
return 1
return 0
def res_offset(self, chain, resn, model=0):
"""What is the offset of residue number resn from
the start of chain 'chain'?"""
self.file.seek(0)
lines = self.file.readlines()
if model > 0:
lines = self.chop_model(model, lines)
resnum = -1
offset = found = 0
for x in lines:
if x[0:6] == "ATOM " and resnum != x[22:26] and chain == x[21]:
if int(x[22:26]) == int(resn):
found =1
break
resnum = x[22:26]
offset += 1
if found:
return offset
else:
return -1
#class PDBData(object):
class PDBData:
"""Class to contain PDB atom records only; does not
support multiple chains, models, etc!"""
def __init__(self, pfile, chain='ignore', offset=0, nres=-1, model=0, resrenum=1,allowhet=0):
"not very OO, but ..."
if allowhet:
atomrec = [ "ATOM ", "HETATM" ]
else:
atomrec = [ "ATOM " ]
self.chain = chain
self.nres = nres
self.seq = ""
# find right model
pfile.file.seek(0)
if model > 0:
m=-1
while m != model:
input = pfile.file.readline()
if input[0:6] == "MODEL ":
m = int(input.split()[1]) # more robust
#m = int(input[10:14])
# now find right chain
c = "ignore"
if chain == "ignore":
input = pfile.file.readline()
while input[0:6] not in atomrec: #!= "ATOM ":
input = pfile.file.readline()
else:
while c != chain:
input = pfile.file.readline()
if input[0:6] in atomrec: # "ATOM ":
c = input[21]
# and correct residue offset
resseq = int(input[22:26])
resnum=0
while offset != resnum:
input = pfile.file.readline()
cres = int(input[22:26])
if cres != resseq:
resnum+=1 #(cres - resseq)
resseq = cres
# rewind to start of line
pfile.file.seek(pfile.file.tell() - len(input))
# now read ze coordinates
# for now, use fixed-size arrays; can change later
self.X = zeros(20000, float64)
self.Y = zeros(20000, float64)
self.Z = zeros(20000, float64)
self.wght = zeros(20000, float64)
self.natom = 0
self.atom = []
self.resname = []
self.chain = []
self.resnum = []
self.segid = []
self.arec = []
curres = 0
curresseq = -1
for x in pfile.file.readlines():
if x[0:6] == "ANISOU":
continue
if x[0:6] == "TER ":
continue
elif x[0:6] not in atomrec: #!= "ATOM ":
break
if x[21] != chain and chain != 'ignore':
break
if curresseq != x[22:26]:
oldresseq = curresseq
curresseq = x[22:26]
#if curres != 0:
# diff = int(curresseq) - int(oldresseq)
#else:
# diff = 1
diff=1
curres+=diff
if curres > nres and nres > 0:
break
else:
if diff > 1: ## residues missing in pdb
dummy = ""
for i in range(diff-1):
dummy += "X"
self.seq += dummy
self.seq += onel( x[17:20] )
# skip lower of two partial occupancies
occ = float(x[54:60])
if model == 0: ## only consider occup. for x-ray structures
if occ < 0.5 and occ != 0.0:
continue
elif occ == 0.5 and x[16] != 'A':
continue
self.arec.append(x[0:6])
self.atom.append(x[12:16])
self.resname.append(x[17:20])
self.chain.append(x[21])
if resrenum:
self.resnum.append(curres)
else:
self.resnum.append(int(x[22:26]))
self.segid.append(x[72:76])
self.X[self.natom] = float(x[30:38])
self.Y[self.natom] = float(x[38:46])
self.Z[self.natom] = float(x[46:54])
self.wght[self.natom] = float(x[60:66])
self.natom+=1
if self.nres < 0: # catch "select all" case
self.nres = curres
def zero(self):
for i in range(self.natom):
self.X[i] = 0.0
self.Y[i] = 0.0
self.Z[i] = 0.0
self.wght[i] = 0.0
def zero_weight(self):
"""Zeros the entire weight array"""
for i in range(self.natom):
self.wght[i] = 0.0
def assign_weight(self, val):
"""Sets the entire weight array to val"""
for i in range(self.natom):
self.wght[i] = val
def set_weight(self, wmap):
"""Sets the weight array using the map wmap of the
form weight[(residue,atomtype)]; residues not specified will be
left unchanged"""
wkeys = wmap.keys();
print wkeys
for i in range(self.natom):
k = (str(self.resnum[i]),self.atom[i])
if k in wkeys:
self.wght[i] = wmap[k]
def rms_from_bfact(self):
rms = map(lambda x: math.sqrt(3.0*x/(8.0*(math.pi)**2)), self.wght)
return rms
def get_index(self,resn,at):
for i in range(self.natom):
if self.resnum[i] == resn and self.atom[i].strip() == at:
return i
#for i in range(self.natom):
# print i, self.resnum[i], self.atom[i]
return -1
def get_degenerate_indices(self,resn,at):
indices = []
if at.find('#') >= 0:
at=at[:at.find('#')]
for i in range(self.natom):
if self.resnum[i] == resn and self.atom[i].find(at)>=0:
indices.append(i)
else:
for i in range(self.natom):
if self.resnum[i] == resn and self.atom[i].strip()==at:
indices.append(i)
#for i in range(self.natom):
# print i, self.resnum[i], self.atom[i]
return indices
def get_weight(self, key):
for i in range(self.natom):
k = (str(self.resnum[i]),self.atom[i])
if k == key:
return self.wght[i]
return 0
def angle(self,i,j,k):
xji = self.X[j]-self.X[i]
yji = self.Y[j]-self.Y[i]
zji = self.Z[j]-self.Z[i]
xjk = self.X[j]-self.X[k]
yjk = self.Y[j]-self.Y[k]
zjk = self.Z[j]-self.Z[k]
rji = math.sqrt(xji**2+yji**2+zji**2)
rjk = math.sqrt(xjk**2+yjk**2+zjk**2)
xji /= rji; yji /= rji; zji /= rji;
xjk /= rjk; yjk /= rjk; zjk /= rjk;
dotp = xji*xjk + yji*yjk + zji*zjk;
crossp = math.sqrt(1.0 - dotp**2)
acos_angle = math.acos(dotp)
asin_angle = math.asin(crossp)
if asin_angle >= 0.0:
angle = 180.0/math.pi*acos_angle
else:
angle = 360.0-180.0/math.pi*acos_angle
return angle
def out_of_plane_angle(self, i,j,k,l):
"return angle by which jl is out of plane ijk"
xij = self.X[i]-self.X[j]
yij = self.Y[i]-self.Y[j]
zij = self.Z[i]-self.Z[j]
xjk = self.X[j]-self.X[k]
yjk = self.Y[j]-self.Y[k]
zjk = self.Z[j]-self.Z[k]
xjl = self.X[j]-self.X[l]
yjl = self.Y[j]-self.Y[l]
zjl = self.Z[j]-self.Z[l]
ax = yij*zjk-zij*yjk
ay = zij*xjk-xij*zjk
az = xij*yjk-yij*xjk
#bx = ylk*zjk-zlk*yjk
#by = zlk*xjk-xlk*zjk
#bz = xlk*yjk-ylk*xjk
ra2 = ax**2 + ay**2 + az**2
rjl2 = xjl**2 + yjl**2 + zjl**2
#ra = math.sqrt(ra2)
#ax/=ra
#ay/=ra
#az/=ra
cosphi = ( ax*xjl + ay*yjl + az*zjl ) / math.sqrt(ra2*rjl2)
phi = math.acos(cosphi)
return phi
#rb2 = bx**2 + by**2 + bz**2
#rjk2 = xjk**2 + yjk**2 + zjk**2
#rjk = math.sqrt(rjk2)
#rjkr = 1.0/rjk
#ra2r = 1.0/ra2
#rb2r = 1.0/rb2
#rabr = math.sqrt(ra2r*rb2r)
#cosphi = ( ax*bx + ay*by + az*bz ) * rabr
#print 'cosphi = ', cosphi
#sinphi = rjk*rabr*(ax*xlk + ay*ylk + az*zlk)
#print 'sinphi = ', sinphi
#acos = math.acos(cosphi)
#asin = math.asin(sinphi)
##print cosphi,sinphi,acos, asin
#if acos < math.pi/2.0:
# return asin/math.pi*180.0
#elif asin >= 0:
# return acos/math.pi*180.0 #(math.pi-asin)/math.pi*180.0
#else:
# return -acos/math.pi*180.0 #(asin-math.pi)/math.pi*180.0
def torsion(self, i,j,k,l):
"return torsion angle between specified atoms"
xij = self.X[i]-self.X[j]
yij = self.Y[i]-self.Y[j]
zij = self.Z[i]-self.Z[j]
xjk = self.X[j]-self.X[k]
yjk = self.Y[j]-self.Y[k]
zjk = self.Z[j]-self.Z[k]
xlk = self.X[l]-self.X[k]
ylk = self.Y[l]-self.Y[k]
zlk = self.Z[l]-self.Z[k]
ax = yij*zjk-zij*yjk
ay = zij*xjk-xij*zjk
az = xij*yjk-yij*xjk
bx = ylk*zjk-zlk*yjk
by = zlk*xjk-xlk*zjk
bz = xlk*yjk-ylk*xjk
ra2 = ax**2 + ay**2 + az**2
rb2 = bx**2 + by**2 + bz**2
rjk2 = xjk**2 + yjk**2 + zjk**2
rjk = math.sqrt(rjk2)
rjkr = 1.0/rjk
ra2r = 1.0/ra2
rb2r = 1.0/rb2
rabr = math.sqrt(ra2r*rb2r)
cosphi = ( ax*bx + ay*by + az*bz ) * rabr
#print 'cosphi = ', cosphi
sinphi = rjk*rabr*(ax*xlk + ay*ylk + az*zlk)
#print 'sinphi = ', sinphi
acos = math.acos(cosphi)
asin = math.asin(sinphi)
#print cosphi,sinphi,acos, asin
if acos < math.pi/2.0:
return asin/math.pi*180.0
elif asin >= 0:
return acos/math.pi*180.0 #(math.pi-asin)/math.pi*180.0
else:
return -acos/math.pi*180.0 #(asin-math.pi)/math.pi*180.0
def get_seq(self):
return self.seq
def get_wght(self, i):
return self.wght[i]
def set_wght(self, i, wght):
self.wght[i] = float(wght) # to be on the safe side
def average(self, list):
"""Makes self the average of structures in list,
puts rms from avg in weight"""
self.zero()
nmodel = len(list)
for x in list:
if x.natom != self.natom:
print "wrong number of atoms!!!"
sys.exit(1)
for i in range(self.natom):
self.X[i] += x.X[i]
self.Y[i] += x.Y[i]
self.Z[i] += x.Z[i]
for i in range(self.natom):
self.X[i] /= nmodel
self.Y[i] /= nmodel
self.Z[i] /= nmodel
for x in list:
for i in range(self.natom):
dx = x.X[i] - self.X[i]
dy = x.Y[i] - self.Y[i]
dz = x.Z[i] - self.Z[i]
self.wght[i] += dx*dx + dy*dy + dz*dz
for i in range(self.natom):
self.wght[i] = sqrt(self.wght[i]/nmodel)
def set_segid(self, s):
for a in range(self.natom):
self.segid[a] = s
def map_segid(self, cur_s, new_s):
for a in range(self.natom):
if self.segid[a] == cur_s:
self.segid[a] = new_s
def charmm19ify(self):
for a in range(self.natom):
if self.resname[a] == 'ILE' and self.atom[a] == ' CD1':
self.atom[a] = ' CD '
if self.resname[a] == 'GLN' and self.atom[a] == '1HE2':
self.atom[a] = 'HE21'
if self.resname[a] == 'GLN' and self.atom[a] == '2HE2':
self.atom[a] = 'HE22'
if self.atom[a] == ' OXT':
self.atom[a] = ' OT1'
def charmm22ify(self):
for a in range(self.natom):
if self.resname[a] == 'ILE' and self.atom[a] == ' CD1':
self.atom[a] = ' CD '
if self.resname[a] == 'GLN' and self.atom[a] == '1HE2':
self.atom[a] = 'HE21'
if self.resname[a] == 'GLN' and self.atom[a] == '2HE2':
self.atom[a] = 'HE22'
if self.atom[a] == ' OXT':
self.atom[a] = ' OT1'
if self.resname[a] == 'HIS':
self.resname[a] = 'HSD'
def pdbify(self):
for a in range(self.natom):
if self.atom[a] == ' HN ':
self.atom[a] = ' H '
if self.resname[a] == 'ILE' and self.atom[a] == ' CD ':
self.atom[a] = ' CD1'
if self.resname[a] == 'GLN' and self.atom[a] == 'HE21':
self.atom[a] = '1HE2'
if self.resname[a] == 'GLN' and self.atom[a] == 'HE22':
self.atom[a] = '2HE2'
if self.atom[a] == ' OT1':
self.atom[a] = ' OXT'
if self.resname[a] == 'HSD':
self.resname[a] = 'HIS'
def mutate(self, res, target):
"n.v. intelligent, but..."
for a in range(self.natom):
if self.resnum[a] == res:
self.resname[a] = target #aamap[target]
self.seq = self.seq[:res-1] + aalist[target] + self.seq[res:]
def dist(self, a, b):
"distance between atoms a and b"
dx = self.X[a]-self.X[b]
dy = self.Y[a]-self.Y[b]
dz = self.Z[a]-self.Z[b]
return sqrt( dx*dx + dy*dy + dz*dz )
def selcontacts(self, sel, cutoff=6.0, excl=2, type="all"):
"""calculate heavy atom contacts between a list of atoms
sel and all other atoms (not in sel)"""
contacts = 0;
for i in range(self.natom):
if ('H' not in self.atom[i]) and (i not in sel):
for j in sel:
if self.dist(i,j) < cutoff \
and math.sqrt((self.resnum[i]-self.resnum[j])**2)\
>= excl:
contacts +=1
return contacts
def sin2contacts(self, p, q, cutoff=6.0, excl=2, type="all"):
contacts = 0.0;
xpq = self.X[p]-self.X[q]
ypq = self.Y[p]-self.Y[q]
zpq = self.Z[p]-self.Z[q]
rpq = math.sqrt(xpq**2 + ypq**2 + zpq**2)
xpq /= rpq
ypq /= rpq
zpq /= rpq
for i in range(self.natom):
if ('H' not in self.atom[i]) and i!=p and i!=q:
if self.dist(i,p) < cutoff \
and math.sqrt((self.resnum[i]-self.resnum[p])**2)\
>= excl:
xpi = self.X[p] - self.X[i]
ypi = self.Y[p] - self.Y[i]
zpi = self.Z[p] - self.Z[i]
rpi = math.sqrt(xpi**2 + ypi**2 + zpi**2)
xpi/=rpi
ypi/=rpi
zpi/=rpi
dotp = xpi*xpq + ypi*ypq + zpi*zpq
contacts += 1.0 - dotp**2
return contacts
def contacts(self, i, j, cutoff=6.0, type="all"):
"""calculate all heavy atom contacts between residues i and j
within a certain cutoff"""
if i == j:
print "can't calculate contacts within same residue"
import sys
sys.exit(1)
bb = [ ' CA ', ' C ', ' N ', ' O ' ]
ilist, jlist = [], []
clist = []
for a in range(self.natom):
if self.resnum[a] == i and self.atom[a][1] != 'H':
if self.atom[a] in bb:
if type == "bb" or type == "all":
ilist.append(a)
else:
if type == "sc" or type == "all":
ilist.append(a)
elif self.resnum[a] == j and self.atom[a][1] != 'H':
if self.atom[a] in bb:
if type == "bb" or type == "all":
jlist.append(a)
else:
if type == "sc" or type == "all":
jlist.append(a)
for ii in ilist:
for jj in jlist:
if ii in bb and jj in backbone and abs(ii-jj)==1:
continue
d = self.dist(ii,jj)
if d < cutoff:
clist.append((self.atom[ii],self.resname[ii],
self.resnum[ii],self.atom[jj],self.resname[jj],
self.resnum[jj], d))
return clist
def contacts2(self, i, cutoff=6.0, type="all"):
"""calculate all heavy atom contacts between residue i and other
atoms within a certain cutoff"""
bb = [ ' CA ', ' C ', ' N ', ' O ' ]
ilist, jlist = [], []
clist = []
for a in range(self.natom):
if self.resnum[a] == i and self.atom[a][1] != 'H':
if self.atom[a] in bb:
if type == "bb" or type == "all":
ilist.append(a)
else:
if type == "sc" or type == "all":
ilist.append(a)
elif self.atom[a][1] != 'H':
if self.atom[a] in bb:
if type == "bb" or type == "all":
jlist.append(a)
else:
if type == "sc" or type == "all":
jlist.append(a)
for ii in ilist:
for jj in jlist:
if ii in bb and jj in backbone and abs(ii-jj)==1:
continue
d = self.dist(ii,jj)
if d < cutoff:
clist.append((self.atom[ii],self.resname[ii],
self.resnum[ii],self.atom[jj],self.resname[jj],
self.resnum[jj], d))
return clist
def write(self):
print "writing"
def align(self, ref, slist, rlist, type="BB"):
"""Align self to ref (rotate & translate) using residue selections
slist and rlist for self and ref respectively. Only selected type
of backbone atoms used for fitting. Type = "CA" or "BB".
Works for any proteins (i.e. don't need matching residues)"""
if type == "CA":
stypes = [ ' CA ' ]
elif type == "C1'":
stypes = [ " C1'" ]
elif type == "BB":
stypes = [ ' CA ', ' C ', ' N ', ' O ' ]
# if type != "CA":
# print "Only CA selection supported at present!"
# import sys
# sys.exit(1)
if len(slist) != len(rlist):
print "RESIDUE SELECTIONS OF DIFFERENT LENGTH, QUITTING!"
import sys
sys.exit(1)
lsel = len(slist)
ltype = len(stypes)
latom = ltype * lsel
XR = zeros(latom, float64)
YR = zeros(latom, float64)
ZR = zeros(latom, float64)
XS = zeros(latom, float64)
YS = zeros(latom, float64)
ZS = zeros(latom, float64)
# fill arrays with CA coordinates
for i in range(lsel):
for a in range(ltype):
idx = i*ltype + a
XS[idx],YS[idx],ZS[idx],u=self.get_crd(stypes[a],slist[i])
XR[idx],YR[idx],ZR[idx],u=ref.get_crd(stypes[a],rlist[i])
#print XS[idx],YS[idx],ZS[idx]
#print XR[idx],YR[idx],ZR[idx]
# coords missing for some reason ...
if XR[idx] < -999 or XS[idx] < -999:
print "GOT HERE"
print stypes[a],rlist[i]
rlist = rlist[:i] + rlist[i+1:]
slist = slist[:i] + slist[i+1:]
slist, rlist = self.align(ref, slist, rlist, type)
return slist, rlist
# now calculate translation and rotation operations
#print sum(XS), len(XS)
#print sum(XR), len(XR)
S_trans = -array([ sum(XS)/len(XS), sum(YS)/len(YS), sum(ZS)/len(ZS) ], float64)
R_trans = -array([ sum(XR)/len(XR), sum(YR)/len(YR), sum(ZR)/len(ZR) ], float64)
U = calcrotmat( XS, YS, ZS, XR, YR, ZR )
# (I) translate self to centre of geometry
translate( self.X, self.Y, self.Z, S_trans )
# (II) rotate self
self.rotate( U )
# (III) translate self to centre of geometry of reference
self.translate( -R_trans )
return slist, rlist
def homoalign(self, ref, slist, rlist,twofold=0):
"""Align two structures of a protein using all available heavy
atom coordinates. Can probably be used with any two proteins,
but only makes sense for comparing identical sequences"""
# get heavy atom lists from each protein
atomlist = []
satoms = []
ratoms = []
for i in range(self.natom):
if self.resnum[i] in slist and self.atom[i].strip()[0] != 'H':
atomlist.append( ( self.resnum[i], self.atom[i] ) )
satoms.append(i)
found = -1
for j in atomlist:
for x in range(ref.natom):
if (ref.resnum[x], ref.atom[x]) == j:
found = x
break
if found >= 0:
ratoms.append(found)
else:
atomlist = atomlist[:j] + atomlist[j+1:]
satoms = satoms[:j] + satoms[j+1:]
if len(ratoms) != len(satoms):
print ratoms
print satoms
print "woops!"
import sys
sys.exit(1)
#lsel = len(slist)
#ltype = len(stypes)
latom = len(atomlist)
XR = zeros(latom, float64)
YR = zeros(latom, float64)
ZR = zeros(latom, float64)
XS = zeros(latom, float64)
YS = zeros(latom, float64)
ZS = zeros(latom, float64)
# fill arrays with CA coordinates
for i in range(latom):
si, ri = satoms[i], ratoms[i]
XS[i],YS[i],ZS[i]=self.X[si],self.Y[si],self.Z[si]
XR[i],YR[i],ZR[i]=ref.X[ri],ref.Y[ri],ref.Z[ri]
# now calculate translation and rotation operations
S_trans = -array([ sum(XS)/len(XS), sum(YS)/len(YS), sum(ZS)/len(ZS) ], float64)
R_trans = -array([ sum(XR)/len(XR), sum(YR)/len(YR), sum(ZR)/len(ZR) ], float64)
U = calcrotmat( XS, YS, ZS, XR, YR, ZR )
# (I) translate self to centre of geometry
translate( self.X, self.Y, self.Z, S_trans )
# (II) rotate self
if twofold == 1:
nx = math.sqrt(0.5*(U[0][0]+1.0))
ny = math.sqrt(0.5*(U[1][1]+1.0))
nz = math.sqrt(0.5*(U[2][2]+1.0))
print nx,ny,nz, math.sqrt(nx**2+ny**2+nz**2)
if nx < ny:
if nz < nx:
nz = math.sqrt(1.0-nx**2-ny**2)
else:
nx = math.sqrt(1.0-ny**2-nz**2)
else:
if nz < ny:
nz = math.sqrt(1.0-nx**2-ny**2)
else:
ny = math.sqrt(1.0-nx**2-nz**2)
print nx,ny,nz, math.sqrt(nx**2+ny**2+nz**2)
U[0][0] = 2.0*nx**2-1.0
U[1][1] = 2.0*ny**2-1.0
U[2][2] = 2.0*nz**2-1.0
U[0][0] = 2.0*nx**2-1.0
U[1][1] = 2.0*ny**2-1.0
U[2][2] = 2.0*nz**2-1.0
U[0][1] = 2.0*nx*ny
U[0][2] = 2.0*nx*nz
U[1][0] = 2.0*nx*ny
U[1][2] = 2.0*ny*nz
U[2][0] = 2.0*nx*nz
U[2][1] = 2.0*ny*nz
print U
print dot(U,U)
self.rotate( U )
# (III) translate self to centre of geometry of reference
self.translate( -R_trans )
rms = 0.0
for i in range(latom):
si, ri = satoms[i], ratoms[i]
dx = self.X[si] - ref.X[ri]
dy = self.Y[si] - ref.Y[ri]
dz = self.Z[si] - ref.Z[ri]
rms += dx**2 + dy**2 + dz**2
return math.sqrt(rms/float(latom))
def symmetrize(self, ref, slist, rlist,twofold=0):
"""Align two structures of a protein using all available heavy
atom coordinates. Can probably be used with any two proteins,
but only makes sense for comparing identical sequences"""
# get heavy atom lists from each protein
atomlist = []
satoms = []
ratoms = []
for i in range(self.natom):
if self.resnum[i] in slist and self.atom[i].strip()[0] != 'H':
atomlist.append( ( self.resnum[i], self.atom[i] ) )
satoms.append(i)
found = -1
for j in atomlist:
for x in range(ref.natom):
if (ref.resnum[x], ref.atom[x]) == j:
found = x
break
if found >= 0:
ratoms.append(found)
else:
atomlist = atomlist[:j] + atomlist[j+1:]
satoms = satoms[:j] + satoms[j+1:]
if len(ratoms) != len(satoms):
print ratoms
print satoms
print "woops!"
import sys
sys.exit(1)
#lsel = len(slist)
#ltype = len(stypes)
latom = len(atomlist)
XR = zeros(latom, float64)
YR = zeros(latom, float64)
ZR = zeros(latom, float64)
XS = zeros(latom, float64)
YS = zeros(latom, float64)
ZS = zeros(latom, float64)
# fill arrays with CA coordinates
for i in range(latom):
si, ri = satoms[i], ratoms[i]
XS[i],YS[i],ZS[i]=self.X[si],self.Y[si],self.Z[si]
XR[i],YR[i],ZR[i]=ref.X[ri],ref.Y[ri],ref.Z[ri]
# now calculate translation and rotation operations
S_trans = -array([ sum(XS)/len(XS), sum(YS)/len(YS), sum(ZS)/len(ZS) ], float64)
R_trans = -array([ sum(XR)/len(XR), sum(YR)/len(YR), sum(ZR)/len(ZR) ], float64)
print S_trans
print R_trans
trans_ave = (S_trans+R_trans)/2.0
print trans_ave
trans_ave = -array([(sum(XS)+sum(XR))/(len(XS)+len(XR)), \
(sum(YS)+sum(YR))/(len(YS)+len(YR)), \
(sum(ZS)+sum(ZR))/(len(ZS)+len(ZR)) ], float64)
print trans_ave
#self.translate( -R_trans )