-
Notifications
You must be signed in to change notification settings - Fork 1
/
pdbtool.py
3276 lines (2835 loc) · 128 KB
/
pdbtool.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
'''
Module for reading PDB-files.
Includes pdbatom and pdbmolecule classes
'''
import gzip, urllib.request, os, random, math, sys, re, copy, logging, time
import pdbnames, SpaceGroups
from helper import progressbar
from rotate import transform_list
from tinertia import TInertia
from numpy.linalg import eigh
from numpy import array, cos, sin, pi, radians, sqrt, dot, cross, \
zeros, matrix, ones, floor, nonzero, \
degrees, arccos, arctan2
from numpy.random import randn
from collections import Counter
def read_multi_model_pdb(pdbin, remark_parser=None):
if type(pdbin) == file:
source = pdbin
elif type(pdbin) == str:
try:
source = open(pdbin)
except IOError:
return None
else:
return None
cell = None
models = []
if remark_parser is not None:
remarks = [remark_parser()]
for line in source:
if line[:5] == 'MODEL':
atoms, anisous = [], []
elif line[:6] == 'ENDMDL':
models.append(pdbmolecule(atoms=atoms, cell=cell, anisous=anisous))
if remark_parser is not None:
remarks.append(remark_parser())
elif line[:6] == 'CRYST1':
cell = pdbcell(line)
elif line[:6] == 'ATOM ' or line[:6] == 'HETATM':
atoms.append(pdbatom(line))
elif line[:6] == 'ANISOU':
anisou = pdbanisou(line)
if anisou == atoms[-1]:
atoms[-1].SetUij(anisou.GetUij())
else:
anisous.append(anisou)
elif line[:6] == 'REMARK':
if remark_parser is not None:
remarks[-1].parse_line(line)
source.close()
if remark_parser is not None:
return models, remarks
else:
return models
def ReadPDBfile(pdbin, readcell=True):
atoms, anisous = [], []
modelN = 0
if type(pdbin) == str:
try:
source = open(pdbin)
except IOError:
return None
else:
source = pdbin
cell = None
for line in [x.decode() if type(x) is not str else x for x in source ]:
if line[:5] == 'MODEL':
modelN += 1
if line[:6] == 'ATOM ' or line[:6] == 'HETATM':
atoms.append(pdbatom(line))
# xyz.append(atoms[-1].GetR())
elif line[:6] == 'CRYST1':
if readcell:
cell = pdbcell(line)
elif line[:6] == 'ANISOU':
anisou = pdbanisou(line)
if anisou == atoms[-1]:
atoms[-1].SetUij(anisou.GetUij())
else:
anisous.append(anisou)
if type(pdbin) == str:
source.close()
mol = pdbmolecule(atoms=atoms, cell=cell, anisous=anisous)
if modelN > 0:
sys.stderr.write('Warning: Input of ReadPDBfile appears to be multi-model (N=%d). Use read_multi_model_pdb instead.\n' % modelN)
mol.modelN = modelN
else:
mol.modelN = 1
return mol
def ReadPDBremarks(pdbin):
if type(pdbin) == file:
source = pdbin
elif type(pdbin) == str:
try:
source = open(pdbin)
except IOError:
return None
else:
return None
remarks = RemarkParser(source)
if type(pdbin) == str:
source.close()
return remarks
def ReadPDBCell(pdbin):
if type(pdbin) == file:
source = pdbin
elif type(pdbin) == str:
try:
source = open(pdbin)
except IOError:
return None
else:
return None
for line in source:
if line[:6] == 'CRYST1':
if type(pdbin) == str:
source.close()
return pdbcell(line)
return None
def ReadPDBTLS(pdbin):
if type(pdbin) == file:
source = pdbin
elif type(pdbin) == str:
try:
source = open(pdbin)
except IOError:
return None
else:
return None
tls = TLSparser(source)
if type(pdbin) == str:
source.close()
return tls
def WritePDBTLS(tls, tlspath):
if tls.GetGroupNumber():
ftls = open(tlspath,'w')
for (i,group) in enumerate(tls.GetGroups()):
ftls.write('TLS '+str(i)+'\n')
for rng in group.GetRanges():
ftls.write('RANGE '+rng+'\n')
if tls.GetGroupNumber():
ftls.close()
def ReadPDBNCS(pdbin):
if type(pdbin) == file:
source = pdbin
elif type(pdbin) == str:
try:
source = open(pdbin)
except IOError:
return None
else:
return None
ncs = NCSparser(source)
if type(pdbin) == str:
source.close()
return ncs
def WriteNCScode(ncs, ncspath):
''' Deduces the NCS definitions from the ncs object and writes them into
the ncspath. Returns True on success and False otherwise (e.g. if
the ncs definitions are corrupted and the resulting output file
has zero length; the zero length output file is also deleted). '''
if ncs.GetGroupNumber():
fncs = open(ncspath,'w')
for (i,group) in enumerate(ncs.GetGroups()):
ncs_line = group.GetCommand()
if ncs_line:
fncs.write(ncs_line + '\n')
ncs_bytes = fncs.tell()
fncs.close()
if ncs_bytes:
return True
else:
os.remove(ncspath)
return False
def WriteNMRstyle(models, name, header=None):
fout = open(name, 'w')
tyhe = type(header)
if tyhe is str:
fout.write(header)
elif tyhe is list or tyhe is tuple:
for line in header:
fout.write(line)
for (ix,model) in enumerate(models):
fout.write('MODEL %4d\n' % (ix+1))
for atom in model.GetAtoms():
fout.write(atom.GetAtomRecord())
fout.write('ENDMDL\n')
fout.close()
def cell_and_center(molecule, scale=1.0, cushion=0.0):
''' The method returns the CRYST1 line for the P1 cell that could hold
the entire molecule and the copy of the molecule with shifted
coordinates that place it in the center. '''
r = molecule.GetCoordinateArray()
gabarit = r.ptp(0) + 2*cushion
abc = scale * gabarit
retmol = molecule.copy()
retmol.shift(0.5 * scale * gabarit - r.mean(0))
celline = 'CRYST1'
celline += '%9.3f%9.3f%9.3f' % tuple(abc)
celline += ' 90.00 90.00 90.00 P 1 \n'
return (celline, retmol)
def getatomid(atom):
return atom.atomid()
class pdbcell:
def __init__(self, line):
self.cryst=line
self.sg_HM = line[55:66].strip()
self.cell=line.split()[1:7]
self.sg = SpaceGroups.xHMN.get(self.sg_HM)
ang = radians(array([float(self.cell[3]), float(self.cell[4]), float(self.cell[5])]))
a,b,c = float(self.cell[0]),float(self.cell[1]),float(self.cell[2])
cang = cos(ang)
sing = sin(ang[-1])
v = math.sqrt(1-(cang**2).sum()+(cang**2).prod())
self.Mcf = array([ [1.0/a, 0.0, 0.0],
[-cang[2]/a/sing, 1.0/b/sing, 0.0],
[(cang[0]*cang[2]-cang[1])/(a*v*sing), (cang[1]*cang[2]-cang[0])/(b*v*sing), sing/c/v]]).T
self.Mfc = array([ [a, 0.0, 0.0 ],
[b*cang[2], b*sing, 0.0 ],
[c*cang[1], c*(cang[0]-cang[1]*cang[2])/sing, c*v/sing]]).T
def GetLine(self):
return self.cryst
def GetSGHM(self):
return self.sg_HM
def GetSG(self):
return self.sg
def GetMcf(self):
return self.Mcf
def GetMfc(self):
return self.Mfc
def GetCellParameters(self):
return self.cell
def GetA(self):
return self.cell[0]
def GetB(self):
return self.cell[1]
def GetC(self):
return self.cell[2]
def GetAlpha(self):
return self.cell[3]
def GetBeta(self):
return self.cell[4]
def GetGamma(self):
return self.cell[5]
class pdbanisou:
''' Defines ANISOU record. '''
def __init__(self, line):
self.record = pdbrecord(line)
self.uij = pdbuij(line[28:70])
def __eq__(self, other):
return (self.resid()==other.resid()) and (self.name()==other.name()) and (self.altLoc()==other.altLoc())
def __ne__(self, other):
return not self==other
# --- Elements of the ATOM line
def charge(self):
return self.record.charge()
def element(self):
return self.record.element()
def altLoc(self):
return self.record.altLoc()
def segid(self):
return self.record.segid()
def atomid(self):
return self.record.atomid()
def serial(self):
return self.record.serial()
def name(self):
return self.record.name()
def resid(self):
return self.record.resid()
# ---
def GetAnisouRecord(self):
return ('ANISOU' + '%5d ' % self.serial() + self.atomid() + ' ' + self.uij.GetString() + self.segid().rjust(6) + self.element() + self.charge()).rstrip('\n') + '\n'
def GetUij(self):
return self.uij
class pdbuij:
''' Defines anisotropic thermal parameters, Uij. Input values must be
the tuple in the following order:
uij = (u11, u22, u33, u12, u13, u23)
or the string conforming to the Uij part of the PDB formatted
ANISOU record, i.e. 6 integers 7 symbols wide each.'''
def __init__(self, uij):
if type(uij) == str:
self.uij = (int(uij[:7]),
int(uij[7:14]),
int(uij[14:21]),
int(uij[21:28]),
int(uij[28:35]),
int(uij[35:]))
elif type(uij) == tuple:
self.uij = uij
else:
raise ValueError('Tuple or string expected to define Uij, got "'+str(type(uij))+'" instead')
def GetString(self):
return '%7d%7d%7d%7d%7d%7d' % self.uij
def GetAnisotropy(self):
u = self.uij
Uij = [[u[0],u[3],u[4]],[u[3],u[1],u[5]],[u[4],u[5],u[2]]]
v = eigh(Uij)[0]
return min(v)/max(v)
def GetValues(self):
return self.uij
def SetValues(self, uij):
if type(uij) == str:
self.uij = (int(uij[:7]),
int(uij[7:14]),
int(uij[14:21]),
int(uij[21:28]),
int(uij[28:35]),
int(uij[35:]))
elif type(uij) == tuple:
self.uij = uij
class pdbrecord:
def __init__(self, line):
line = line.strip().ljust(80)+'\n'
if line[76:78] == ' ':
if line[12].isdigit():
self.line = line[:76] + ' ' + line[13] + line[78:]
else:
self.line = line[:76] + line[12:14] + line[78:]
else:
self.line = line
def iCode(self):
return self.line[26]
def occupancy(self):
return self.line[54:60]
def element(self):
return self.line[76:78]
def charge(self):
return self.line[78:80]
def altLoc(self):
return self.line[16]
def segid(self):
return self.line[72:76].strip()
def atomid(self):
return self.line[12:27]
def chainID(self):
return self.line[21]
def serial(self):
return int(self.line[6:11])
def name(self):
return self.line[12:16].strip()
def resName(self):
return self.line[17:20].strip()
def rat(self):
return self.line[17:20]+self.line[12:16].strip()
def resSeq(self):
return int(self.line[22:26])
def resid(self):
return self.line[21:27]
def tempFactor(self):
return float(self.line[60:66])
def SetOccupancy(self, o):
self.line = self.line[:54] + '%6.2f' % o + self.line[60:]
def SetAltLoc(self, value):
self.line = self.line[:16]+value+self.line[17:]
def SetSegid(self, value):
self.line = self.line[:72] + value.ljust(4)[:4] + self.line[76:]
def SetChain(self, value):
self.line = self.line[:21]+value[0]+self.line[22:]
def SetSerial(self, value):
self.line = self.line[:6] + '%5d' % value + self.line[11:]
def SetB(self, value):
self.line = self.line[:60] + '%6.2f' % value + self.line[66:]
def SetResID(self, resid):
self.line = self.line[:21]+resid+self.line[27:]
def set_res_name(self, name):
self.line = self.line[:17]+name+self.line[20:]
def set_name(self, name):
self.line = self.line[:12]+name+self.line[16:]
class pdbatom:
def __init__(self, line):
self.record = pdbrecord(line)
self.xyz = array([float(line[30:38]), float(line[38:46]), float(line[46:54])])
self.uij = None
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
return (self.resid()==other.resid()) and (self.name()==other.name()) and (self.altLoc()==other.altLoc())
def __ne__(self, other):
return not self==other
def alt(self, other):
return (self.resid()==other.resid()) and (self.name()==other.name())
def same_alt(self, other):
return self.altLoc()==' ' or other.altLoc()==' ' or self.altLoc()==other.altLoc()
def same_residue(self, other):
return (self.resid()==other.resid())
def same_chain(self, other):
return self.chainID() == other.chainID()
def test(self,name=None,altloc=None,resn=None,resid=None):
if name != None and self.name() != name:
return False
elif altloc != None and self.altLoc() != altloc:
return False
elif resn != None and self.resName() != resn:
return False
elif resid != None and self.resid() != resid:
return False
else:
return True
def test_resid(self, resid):
return self.resid() == resid
# --- Elements of the ATOM line
def iCode(self):
return self.record.iCode()
def occupancy(self):
return self.record.occupancy()
def charge(self):
return self.record.charge()
def element(self):
return self.record.element()
def altLoc(self):
return self.record.altLoc()
def segid(self):
return self.record.segid()
def atomid(self):
return self.record.atomid()
def chainID(self):
return self.record.chainID()
def serial(self):
return self.record.serial()
def name(self):
return self.record.name()
def mass(self):
return pdbnames.GetMass(self.record.element().strip())
def resName(self):
return self.record.resName()
def resSeq(self):
return self.record.resSeq()
def resid(self):
return self.record.resid()
def tempFactor(self):
return self.record.tempFactor()
# ---
def SetUij(self, uij):
self.uij = uij
def GetUij(self):
return self.uij
def GetUijValues(self):
return self.uij.GetValues()
def SetUijValues(self, uij):
self.uij.SetValues(uij)
def prime_uij(self, overwrite=False):
''' Initializes the anisotropic ADPs for the atom using its isotropic
B-factor. Use the overwrite flag to force the anisotropic ADP
reset when they are alreay present. '''
if not self.IsAnisotropic() or overwrite:
ueq = 126.65148*self.GetB()
self.uij = pdbuij((ueq,ueq,ueq,0.0,0.0,0.0))
def GetAnisotropy(self):
if self.uij:
return self.uij.GetAnisotropy()
else:
return 1.0
def GetChain(self):
''' Returns atom's chain ID. '''
return self.chainID()
def SetChain(self, value):
''' Sets atom chain ID to value (must be a single character). '''
self.record.SetChain(value)
def GetAtomID(self):
return self.record.atomid()
def GetResID(self):
return self.resid()
def SetResID(self, resid):
''' Sets the atom resid (must be in correct format, i.e. "A 156B"). '''
self.record.SetResID(resid)
def get_alt_resid(self):
return (self.resid() + '-' + self.altLoc()).strip().strip('-')
def GetElement(self):
return self.element().strip()
def GetName(self):
return self.record.name()
def GetAtomRecord(self):
return self.record.line[:30]+'%8.3f%8.3f%8.3f' % tuple(self.xyz)+self.record.line[54:]
def IsAnisotropic(self):
return bool(self.uij)
def GetAnisouRecord(self):
if self.uij:
return ('ANISOU' + '%5d ' % self.serial() + self.atomid() + ' ' + self.uij.GetString() + self.segid().rjust(6) + self.element() + self.charge()).rstrip('\n') + '\n'
else:
return ''
def GetAtomTitle(self):
return self.resName() + ' ' + self.chainID() + ('%d' % self.resSeq() + self.iCode()).ljust(6) + ' ' + self.name()
def GetAltLoc(self):
return self.altLoc()
def SetAltLoc(self, value):
self.record.SetAltLoc(value)
def GetSegid(self):
return self.segid()
def SetSegid(self,value):
self.record.SetSegid(value)
def HasAltConf(self):
return bool(self.altLoc().strip())
def HasCNSAltConf(self):
return bool(re.search('AC[0-9]+',self.segid()))
def GetCNSAltLoc(self):
return re.search('AC[0-9]+',self.segid()).group()[-1]
def get_res_name(self):
return self.record.resName()
def set_res_name(self, name):
self.record.set_res_name(name)
def rjust_res_name(self):
self.record.set_res_name(self.record.resName().strip().rjust(3))
def GetResTitle(self):
return self.resName() + ' ' + self.chainID() + '%d' % self.resSeq() + self.iCode()
def GetB(self):
''' Return the atomic ADP. '''
return self.record.tempFactor()
def SetB(self, B):
''' Set the atomic ADP. '''
self.record.SetB(B)
def GetOccupancy(self):
return float(self.occupancy())
def SetOccupancy(self, o):
self.record.SetOccupancy(o)
def IsWater(self):
return self.resName() == 'HOH'
def IsPolar(self):
return pdbnames.IsPolar(self.element().strip())
def IsProteinBackbone(self):
''' True if atom belongs to protein backbone, False otherwise. '''
return pdbnames.Is3Amino(self.resName()) and pdbnames.MaybeBackbone(self.name())
def IsProtein(self):
''' True if atom belongs to a protein, False otherwise. '''
return pdbnames.Is3Amino(self.resName())
def IsHetero(self):
''' True if atom is a heteroatom (i.e. not protein or water). '''
return pdbnames.IsHetero(self.resName())
def IsMetal(self):
''' True if atom is a metal (as defined in pdbnames). '''
return pdbnames.IsMetal(self.resName().strip())
def IsBackbone(self):
''' True if atom belongs to protein/DNA backbone, False otherwise. '''
return pdbnames.MaybeBackbone(self.name()) and pdbnames.NotWater(self.resName())
def NotBackbone(self):
''' True if atom does not belong protein/DNA backbone, False otherwise. '''
return pdbnames.NotBackbone(self.name())
def IsProteinSidechain(self):
''' True if atom belongs to protein side chain, False otherwise. '''
return self.IsProtein() and pdbnames.NotBackbone(self.name())
def shift(self, xyz):
self.xyz += xyz
def transform(self, M):
self.xyz = array(dot(M,self.xyz.T))[0]
def GetR(self): #convert to GetXYZarray
return self.xyz
def SetR(self, vector): #convert to SetXYZarray
self.xyz = vector
def GetXYZarray(self): #convert to GetR
return self.xyz
def SetXYZarray(self, xyz): #convert to SetR
self.xyz = xyz
def GetSerial(self):
return self.serial()
def SetSerial(self, value):
self.record.SetSerial(value)
def ApplyOperator(self, op):
self.xyz = array(op(self.xyz[0],self.xyz[1],self.xyz[2]))
def copy(self):
return copy.deepcopy(self)
def get_vdw_radius(self):
return pdbnames.GetVDWRadius(self.element().strip())
def set_name(self, name):
self.record.set_name(name)
def rat(self):
return self.record.rat()
def dx(self, other):
return other.xyz[0]-self.xyz[0]
def dy(self, other):
return other.xyz[1]-self.xyz[1]
def dz(self, other):
return other.xyz[2]-self.xyz[2]
def dr(self, other):
return other.xyz-self.xyz
def distance(self, other):
return sqrt((self.dr(other)**2).sum())
def R2(self, other):
return (self.dr(other)**2).sum()
def noise(self, xnoise=0.1, bnoise=0.1, occnoise=0.0):
self.xyz += xnoise*randn(3)
self.SetB(math.fabs(self.GetB()*random.gauss(1,bnoise)))
if self.IsAnisotropic():
self.SetUijValues(tuple((array(self.GetUijValues())*abs(1.0+bnoise*randn(6))).astype(int)))
atomocc = float(atom.GetOccupancy())
if atomocc<1.0 and atomocc>0.0:
newocc = random.gauss(atomocc,occnoise)
while newocc>1.0 or newocc<0.0:
newocc = random.gauss(atomocc,occnoise)
self.SetOccupancy(newocc)
class single_pdbatom(pdbatom):
def __init__(self, line):
self.record = pdbrecord(line)
self.xyz = array([float(line[30:38]), float(line[38:46]), float(line[46:54])],dtype=float)
self.uij = None
class pdbmolecule:
def __init__(self, code=None, atoms=None, cell=None, anisous=None):
self.modelN = 0
if atoms:
self.atoms = atoms
else:
self.atoms = []
self.cell = cell
if code != None:
self.pdbid = code.lower()
self.pdbname = self.pdbid+'.pdb'
if not os.access('pdb-download',os.R_OK):
os.mkdir('pdb-download')
if not os.access('pdb-download/'+self.pdbname,os.R_OK):
try:
pdbfile=urllib.request.urlretrieve('http://www.rcsb.org/pdb/files/'+self.pdbid+'.pdb.gz')
fout = open('pdb-download/'+self.pdbname, 'w')
fin = gzip.open(pdbfile[0])
for line in fin:
fout.write(line)
fin.close()
fout.close()
except IOError:
fin.close()
fout.close()
sys.stderr.write("PDBMOLECULE: I/O error. File "+self.pdbname+" can't be opened or retrieved from PDB\n")
fin = open('pdb-download/'+self.pdbname)
for line in fin:
if line[:6] == 'ATOM ' or line[:6] == 'HETATM':
self.atoms.append(pdbatom(line))
if line[:5] == 'MODEL':
self.modelN += 1
fin.close()
if anisous:
for anisou in anisous:
i = self.find(anisou)
if i>=0:
self.atoms[i].SetUij(anisou.GetUij())
if self.modelN == 0:
self.modelN = 1
self.cartesian = True
def __len__(self):
return self.GetAtomNumber()
def __iter__(self):
return self.atoms.__iter__()
def parse_range(self, ranges):
retdix, lims = {}, self.get_chain_lims()
for k,v in [(k,v.split(',')) for k,v in [rr.split(':') for rr in ranges.split('/')]]:
retdix[k] = []
for r in v:
retdix[k].append([lims[k][i] if t=='' else int(t) for (i,t) in enumerate(r.split('-'))])
return retdix
def get_chain_lims(self):
resnums = [(a.chainID(),a.resSeq()) for a in self.atoms]
return dict([(k,(min(v),max(v))) for k,v in [(chid, [v for k,v in resnums if k==chid]) for chid in set([k for k,v in resnums])]])
def backbone(self):
return backbone(self)
def is_multi_model(self):
return self.modelN > 1
def rjust_res_names(self):
for atom in self.atoms:
atom.rjust_res_name()
def prime_uij(self, overwrite=False, what='all', listik=False, *args, **kwargs):
''' Initializes anisotropic ADPs. The overwrite flag defines if
the ANISOU record will be overwritten if already persent.
Selection syntax the same as in atom_lister method.'''
for atom in self.atom_getter(what, listik, *args, **kwargs):
atom.prime_uij(overwrite=overwrite)
def GetSpaceGroup(self):
if self.cell:
return self.cell.GetSG()
def SerialReset(self):
''' Reset serial numbers of atoms. Use this after atom insertion/removal/rearrangement.'''
for (i,atom) in enumerate(self.atoms):
atom.SetSerial(i+1)
def BfactorReset(self, b=20.0):
''' Reset B-factors of all atoms to the supplied value. '''
for atom in self.atoms:
atom.SetB(b)
def SetBfactorValues(self, bvalues, what='all', listik=False, *args, **kwargs):
''' Sets the atomic B-factors using the provided values mapped
into the list of atoms. If bvalues is a single number, all
the atoms in the list will have the same B-factor.
Selection syntax the same as in atom_lister method. '''
if type(bvalues) == float:
for atom in self.atom_getter(what, listik, *args, **kwargs):
atom.SetB(bvalues)
else:
atoms = self.atom_getter(what, listik, *args, **kwargs)
assert len(bvalues)==len(atoms), 'Shape mismatch between selection and Bvalues vector.'
for (i, atom) in enumerate(atoms):
atom.SetB(bvalues[i])
def set_occupancies(self, values, what='all', listik=False, *args, **kwargs):
''' Sets the atomic occupancies using the provided values mapped
into the list of atoms. If values is a single number, all
the atoms in the list will have the same occupancy.
Selection syntax the same as in atom_lister method. '''
if type(values) == float:
for atom in self.atom_getter(what, listik, *args, **kwargs):
atom.SetOccupancy(values)
else:
atoms = self.atom_getter(what, listik, *args, **kwargs)
assert len(values)==len(atoms), 'Shape mismatch between selection and values vector.'
for (i, atom) in enumerate(atoms):
atom.SetOccupancy(values[i])
def PopAtom(self, atomi):
''' Return the atom and delete it from the molecule. Use with caution. '''
return self.atoms.pop(atomi)
def DeleteAtoms(self, listik):
''' Delete atoms from the molecule. Use with caution. Atoms
with indices in listik are removed. '''
for i in sorted(listik, reverse=True):
del self.atoms[i]
self.SerialReset()
def DeleteWaters(self):
self.DeleteAtoms(self.atom_lister('water'))
def InsertAtom(self, atoms, atomi=0):
''' Insert atoms before position atomi in the atom list. Notice that an atom
cannot be inserted at the end, use AppendAtom() for that. By default,
atom is inserted at the beginning of the atom list. Notice that syntax
provides different order of parameters as compared to insert method of
a regular python list. Insert either a single atom object or list of atoms.'''
if type(atoms) == list:
self.atoms = self.atoms[:atomi]+atoms+self.atoms[atomi:]
else:
self.atoms.insert(atomi, atoms)
def AppendAtom(self, atoms):
''' Append atoms at the end of the atom list. '''
if type(atoms) == list:
self.atoms += atoms
else:
self.atoms.append(atoms)
self.SerialReset()
def AppendMolecule(self, other):
''' Append atoms from another molecule. No sanity checks. '''
self.AppendAtom(other.GetAtoms())
def matchAlts(self, other):
listik1 = self.resid_lister(listik=self.merge_listers(['altconf','protein']))
listik2 = other.resid_lister(listik=other.merge_listers(['altconf','protein']))
listik = list(set(listik1).union(listik2))
residues1 = self.get_residues('resids', resids=listik)
residues2 = other.get_residues('resids', resids=listik)
listik = list(set(residues1.keys()).intersection(residues2.keys()))
for resid in listik:
n1, n2 = residues1[resid].GetAltNum(), residues2[resid].GetAltNum()
if n1<2:
if n2==0:
residues1[resid].AssignAlts(' ')
else:
residues1[resid].renameSingle2Alt(residues2[resid])
else:
if n1==n2:
residues1[resid].renameAlt2Alt(residues2[resid])
elif n2<2:
residues1[resid].renameAlt2Single(residues2[resid])
else:
sys.stdout.write(resid+": different number of alt confs not yet supported\n")
def GetChangedAlts(self, other, fProteinOnly=True):
''' Returns the tuple containing two lists. First lists the residues that
have alternate conformers that are missing in the other model. The second
lists the single conformer residues that expand into multiple conformations
in the other model. '''
listik1 = self.ListAltResidues(fProteinOnly=fProteinOnly)
listik2 = other.ListAltResidues(fProteinOnly=fProteinOnly)
return (list(set(listik1).difference(listik2)), list(set(listik2).difference(listik1)))
def acCNS2PDB(self):
''' Looks for CNS-styled alternate conformers and converts them to PDB format. '''
altlist = []
for (i,atom) in enumerate(self.atoms):
if atom.HasCNSAltConf():
altlist.append(i)
atom.SetAltLoc(atom.GetCNSAltLoc())
while altlist:
lead = altlist.pop(0)
acgroup = self.findalt(self.GetAtom(lead),altlist)
for (i,atomi) in enumerate(acgroup):
self.InsertAtom(self.PopAtom(atomi),lead+1+i)
altlist.remove(atomi)
for (j,atomj) in enumerate(altlist):
if atomj < atomi:
altlist[j] += 1
self.SerialReset()
def acPDB2CNS(self):
''' Converts alternate conformers into CNS style. '''
altlist = self.ListAltConf()
while altlist:
lead = altlist.pop(0)
self.GetAtom(lead).SetSegid('AC1 ')
acgroup = self.findalt(self.GetAtom(lead),altlist)
for (i,atomi) in enumerate(acgroup):
self.AppendAtom(self.PopAtom(atomi))
self.GetAtom(-1).SetSegid(('AC'+str(i+2)).ljust(4))
altlist.remove(atomi)
for j in range(len(altlist)):
altlist[j] -= 1
self.SerialReset()
def find(self, atom2find, subset=None):
''' Finds the atom in the molecule matching atom2find and returns its index. If no such atom exists, returns None.
Atoms are matched by residue ID (chain ID + residue number), atom name and alternate conformer ID.
Searching within part of the molecule will speed things up and can be accomplished by passing subset
parameter, which is a list of atom indices to include in the search. Such lists can be generated by
some class methods, including atom_lister().
'''
if subset is None:
for (i,atom) in enumerate(self.atoms):
if atom == atom2find:
return i
else:
for i in subset:
if self.atoms[i] == atom2find:
return i
return None
def find_atom(self, atom2find, listik=False):
''' Finds the atom in the molecule matching atom2find and returns the
atom object. If no such atom exists, returns None. Atoms are matched
by residue ID (chain ID + residue number), atom name and alternate
conformer ID. Searching within part of the molecule will speed
things up and can be accomplished by passing subset parameter,
which is a list of atom indices to include in the search. Such
lists can be generated by atom_lister() method.