-
Notifications
You must be signed in to change notification settings - Fork 1
/
pdb_analysis.py
2054 lines (1599 loc) · 82.4 KB
/
pdb_analysis.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
# -*- coding: utf-8 -*-
import os.path
import sys
import gzip
sys.path.append('/user/tmeyer/git/')
sys.path.append('/user/tmeyer/workspace/script/python/bivalent_ligands')
sys.path.append('/scratch/scratch/tmeyer/lib')
#import pyximport; pyximport.install()
import numpy
def find_collisions(atom_coord, min_dist):
cutoff_sq = 0.5 * 0.5
noa = len(atom_coord)
coord = np.zeros(3)
coord_comp = np.zeros(3)
dist_v = np.zeros(3)
atoms_delete_list = []
# cdef float atom_coord[2,3]
# for coor in atom_coord_np:
# for d in range(3):
# atom_coord[i,d] = atom_coord_np[i,d]
for i in range( noa - 1):
for d in range(3):
coord[d] = atom_coord[i,d]
#print i
for j in range(i+1, noa):
for d in range(3):
coord_comp[d] = atom_coord[j,d]
for d in range(3):
dist_v[d] = coord[d] - coord_comp[d]
dist_sq = 0
for d in range(3):
dist_sq = dist_sq + dist_v[d] * dist_v[d]
#dist = np.sqrt(np.dot( dist_v, dist_v ))
if dist_sq < cutoff_sq:
atoms_delete_list.append(j)
return atoms_delete_list
import numpy as np
from Bio.PDB.PDBParser import PDBParser
from Bio.PDB.PDBIO import PDBIO
from Bio.PDB.PDBIO import Select
from Bio.PDB.StructureBuilder import StructureBuilder
from Bio.PDB.Structure import Structure
from Bio.PDB.Model import Model
from Bio.PDB.Chain import Chain
import re
def is_std_aa(name):
std_aa = {'ARG' : 'R', \
'HIS' : 'H', \
'LYS' : 'K', \
'ASP' : 'D', \
'GLU' : 'E', \
'SER' : 'S', \
'THR' : 'T', \
'ASN' : 'N', \
'GLN' : 'Q', \
'CYS' : 'C', \
'SEC' : 'U', \
'GLY' : 'G', \
'PRO' : 'P', \
'ALA' : 'A', \
'ILE' : 'I', \
'LEU' : 'L', \
'MET' : 'M', \
'PHE' : 'F', \
'TRP' : 'W', \
'TYR' : 'Y', \
'VAL' : 'V'}
if name in std_aa > 0:
return 1
else:
return 0
class Warnings():
def __init__(self):
self.messages = []
self.old_messages = []
def warn(self, value):
self.messages.append( str(value) )
def has_warnings(self):
if len(self.messages) > 0:
return 1
else:
return 0
def get_warnings(self):
for wrn in self.messages:
self.old_messages.append( wrn )
w = list(self.messages)
self.messages = []
return w
class pdb_from_biopython(object):
class HeaderError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class MergeError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class IO_Error(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def __init__(self):
self.c_file_parsed = 0
self.all_structs = None
self.all_structs_merged = None
self.warnings = Warnings()
self.too_many_chains = False
# This function overwrites the default function in the PDBParser class
def _handle_PDB_exception(self, message, line_counter):
"""
This method catches an exception that occurs in the StructureBuilder
object (if PERMISSIVE), or raises it again, this time adding the
PDB line number to the error message.
"""
message="%s at line %i." % (message, line_counter)
# if self.PERMISSIVE:
# # just print a warning - some residues/atoms may be missing
# warnings.warn("PDBConstructionException: %s\n"
# "Exception ignored.\n"
# "Some atoms or residues may be missing in the data structure."
# % message, PDBConstructionWarning)
# else:
# # exceptions are fatal - raise again with new message (including line nr)
# raise PDBConstructionException(message)
def __analyse_header(self):
# Analyse LINK entries if available
self.header_link = []
if "LINK" in self.header:
for line in self.header["LINK"]:
# use columwise definition
entries = []
# 1 - 6 Record name "LINK "
entries.append( line[0:6].strip() )
# 13 - 16 Atom name1 Atom name.
entries.append( line[12:16].strip() )
# 17 Character altLoc1 Alternate location indicator.
entries.append( line[16] )
# 3 # 18 - 20 Residue name resName1 Residue name.
entries.append( line[17:20].strip() )
# 4 # 22 Character chainID1 Chain identifier.
entries.append( line[21] )
# 5 # 23 - 26 Integer resSeq1 Residue sequence number.
entries.append( line[22:26].strip() )
# 27 AChar iCode1 Insertion code.
entries.append( line[26] )
# 43 - 46 Atom name2 Atom name.
entries.append( line[42:46].strip() )
# 47 Character altLoc2 Alternate location indicator.
entries.append( line[46] )
# 9 # 48 - 50 Residue name resName2 Residue name.
entries.append( line[47:50].strip() )
#10 # 52 Character chainID2 Chain identifier.
entries.append( line[51] )
#11 # 53 - 56 Integer resSeq2 Residue sequence number.
entries.append( line[52:56].strip() )
# 57 AChar iCode2 Insertion code.
entries.append( line[56] )
# 60 - 65 SymOP sym1 Symmetry operator atom 1.
entries.append( line[59:65].strip() )
# 67 - 72 SymOP sym2 Symmetry operato
entries.append( line[66:72].strip() )
# entries for resname and reidue number are required
if entries[3] != '' and entries[5] != '' and \
entries[9] != '' and entries[11] != '':
entries[5] = int(entries[5])
entries[11] = int(entries[11])
else:
s = 'ERROR in \"pdb_from_biopython.__analyse_header\": '
s += 'invalid LINK entry'
s += ' "' + line + '"'
#print '# ERROR in \"pdb_from_biopython.__analyse_header\": '
#print ' invalid LINK entry'
#print ' "' + line + '"'
self.header_link = []
raise self.HeaderError(s)
# # use regular expressions
# #LINK MN MN 200 OD1 ASP A 64
# #LINK SG CYS B 388 CU CUB B3921
# re_link = re.compile(r'(\w+)\s+([^\s]+)\s*([^\s]+)\s*([^\s\d]?)\s*([-\d]+)\s+([^\s]+)\s*([^\s]+)\s*([^\s\d]?)\s*([-\d]+)[\s\w]*')
# mo = re_link.match(line)
# if mo != None:
# entries = mo.groups()
# else:
# s = 'ERROR in \"pdb_from_biopython.__analyse_header\": '
# s += 'invalid LINK entry'
# s += ' "' + line + '"'
# #print '# ERROR in \"pdb_from_biopython.__analyse_header\": '
# #print ' invalid LINK entry'
# #print ' "' + line + '"'
# self.header_link = []
# raise self.HeaderError(s)
# #warn(s)
# #continue
# use split
#entries = line.split()
# if len(entries) != 9:
# # trying to fix LINK entry:
# # Is chain ID missing?
#
# #if isinstance(entries[3], str) == False:
# if entries[3].isdigit():
# entries.insert(3, "-")
# if entries[7].isdigit():
# entries.insert(7, "-")
# Skip entry if chain id does not exist in pdb file. This can
# occur if biounit files are used, where parts of the protein
# have been deleted.
chain_list = {' ' : 1}
for c in self.struct.get_list():
chain_list[c.get_id()] = 1
if entries[4] not in chain_list or \
entries[10] not in chain_list:
continue
# Skip entry if "altLoc Alternate location indicator" is not
# " " or A
if entries[2] != " " and entries[2] != "A":
continue
if entries[8] != " " and entries[8] != "A":
continue
pep_found = 0
for i, item1 in enumerate(self.header_link):
for j, item2 in enumerate(item1):
if item2["name"] == entries[3] and \
item2["chain"] == entries[4] and \
item2["resid"] == entries[5]:
new_monomer = {}
new_monomer["name"] = entries[9]
new_monomer["chain"] = entries[10]
new_monomer["resid"] = entries[11]
self.header_link[i].append(new_monomer)
pep_found = 1
break
if pep_found == 1:
break
if pep_found == 0:
new_monomer1 = {}
new_monomer1["name"] = entries[3]
new_monomer1["chain"] = entries[4]
new_monomer1["resid"] = entries[5]
new_monomer2 = {}
new_monomer2["name"] = entries[9]
new_monomer2["chain"] = entries[10]
new_monomer2["resid"] = entries[11]
self.header_link.append([new_monomer1, new_monomer2])
# for entry in self.header_link:
# print "#"
# for res in entry:
# print res["name"] + " " + res["chain"] + " " + res["resid"]
# model:
# 0 : if the structure is an NMR structure the first frame is used
# name : An arbitrary name used to describe the structure.
def parse_pdb_file(self, filename, name='PROTEIN', quiet=False,\
model=-1):
reg = re.compile(r'.+([\d\w]{4})\.pdb\d')
reg_m = reg.match(filename)
if reg_m != None:
self.pdb_code_from_filename = reg_m.groups()[0].upper()
else:
self.pdb_code_from_filename = 'unknown'
self.parser = PDBParser(QUIET=quiet)
# to prevent the parser to print unnecessary warnings
self.parser._handle_PDB_exception = self._handle_PDB_exception
# to use the functionalliy of XStructure
#self.all_structs = XStructure.from_file(f)
# If files are not zipped.
#f = open(filename)
f = gzip.open(filename, "rt")
self.all_structs = self.parser.get_structure(name, f)
if model == -1:
self.struct = self.all_structs[0]
else:
self.struct = self.all_structs[model]
f.seek(0)
self.header = {}
self.header_fields = []
for line in f:
fields = line.split()
if fields[0] != "ATOM" and fields[0] != "TER" and fields[0] != "HETATM":
# bio files have no REMARK entries anymore.
if fields[0] == 'REMARK':
entry_name = fields[0] + ' ' + fields[1]
else:
entry_name = fields[0]
if entry_name in self.header:
self.header[entry_name].append( line )
else:
self.header[entry_name] = []
self.header[entry_name].append( line )
self.header_fields.append(entry_name)
self.__analyse_header()
self.c_file_parsed = 1
f.close()
# self.is_nmr = False
# if self.header.has_key('EXPDTA'):
# if self.header['EXPDTA'][0].find('NMR') != -1:
# #print "NMR structure found: " + filename
# self.is_nmr = True
# if model == -1:
# if len(self.all_structs) > 1 and self.header['EXPDTA'][0].find('NMR') == -1:
# self.all_structs_merged = self.merge_models()
#
# self.struct = self.all_structs_merged[0]
#
## # save structure
## io = PDBIO()
## io.set_structure(self.all_structs_clean)
## io.save('/user/tmeyer/bio_struct.pdb')
return 1
def write_pdb_file(self, filename, merged=True):
#PDBIO.save = pdb_from_biopython.save
io = PDBIO()
# replace original function with modified one.
io.save = self.save
if self.c_file_parsed == 1:
if merged and self.all_structs_merged != None:
io.set_structure(self.all_structs_merged)
# Add some information from the original header.
org_header = []
org_header_fields = ['HEADER', 'TITLE', 'COMPND', 'KEYWDS', 'EXPDTA', 'AUTHOR', 'JRNL', 'HETNAM',
'FORMUL', 'CAVEAT']
#org_header.append('')
#org_header.append('The following remarks are an excerpt from the header of the original PDB file.')
for key in org_header_fields:
if key in self.header:
for line in self.header[key]:
org_header.append( line.strip('\n') )
header = []
header.append('')
#header.append('')
# Add status.
header.append("This is a modified biological assembly. All models have been merged ")
header.append("into a single one. Chain and residue IDs have been changed if necessary.")
header.append("The header above is just an excerpt from the header of the original")
header.append("biological assembly.")
header.append('')
header.append('The file was created by \'pdb-bio-merger\'.')
header.append('version: 1.10')
header.append('PDB-code of the original structure: ' + self.pdb_code_from_filename)
if not self.too_many_chains:
header.append('status: ' + 'ok')
else:
header.append('status: ' + 'Too many chains, chain ID is set to \' \'')
header.append('')
if self.too_many_chains:
message = 'WARNING: There are too many chains in the '
message += 'structure to represent them with a single character.'
header.append(message)
message = ' Chain ID is set to " "! Please use segname instead.'
header.append(message)
header.append('')
header += self.change_log
header.append('')
header.append('HET-atoms deleted (distanced < 0.5A to an other atom): '\
+ str(len(self.deleted_atoms)) )
if len(self.deleted_atoms) > 0:
for del_atm in self.deleted_atoms:
id_str = str( del_atm['model'] ) + ' ' \
+ del_atm['resname'].rjust(4) + ' ' \
+ del_atm['chain'] + ' ' \
+ '{0:.0f}'.format( del_atm['resid'] ).rjust(5) + ' '\
+ del_atm['name']
header.append(id_str)
header.append('')
else:
#header.append('None')
header.append('')
elif merged and self.all_structs_merged == None:
s = 'ERROR in \"pdb_from_biopython.write_pdb_file\": '
s += 'Merge flag is set, but no merged structure is available.'
raise self.IO_Error(s)
else:
io.set_structure(self.all_structs)
org_header = []
for key in self.header_fields:
for line in self.header[key]:
org_header.append( line.strip('\n') )
header = []
io.save(io, filename, header_list=header, org_header_list=org_header)
else:
s = 'ERROR in \"pdb_from_biopython.write_pdb_file\": '
s += 'No structure loaded that could be written.'
raise self.IO_Error(s)
# This is a copy of the 'PDBIO.save' function. An option to store a header is added.
def save(pdb_from_biopython, self, file, select=Select(), write_end=0, header_list=[], org_header_list=[]):
"""
@param file: output file
@type file: string or filehandle
@param select: selects which entities will be written.
@type select:
select hould have the following methods:
- accept_model(model)
- accept_chain(chain)
- accept_residue(residue)
- accept_atom(atom)
These methods should return 1 if the entity
is to be written out, 0 otherwise.
Typically select is a subclass of L{Select}.
"""
get_atom_line=self._get_atom_line
if isinstance(file, str):
fp=open(file, "w")
close_file=1
else:
# filehandle, I hope :-)
fp=file
close_file=0
# write original header
for line in org_header_list:
fp.write(line + '\n')
# write custom header
for line in header_list:
fp.write('REMARK 99 ' + line + '\n')
# multiple models?
if len(self.structure)>1 or self.use_model_flag:
model_flag=1
else:
model_flag=0
for model in self.structure.get_list():
if not select.accept_model(model):
continue
# necessary for ENDMDL
# do not write ENDMDL if no residues were written
# for this model
model_residues_written=0
atom_number=1
if model_flag:
fp.write("MODEL %s\n" % model.serial_num)
for chain in model.get_list():
if not select.accept_chain(chain):
continue
chain_id=chain.get_id()
# necessary for TER
# do not write TER if no residues were written
# for this chain
chain_residues_written=0
for residue in chain.get_unpacked_list():
if not select.accept_residue(residue):
continue
hetfield, resseq, icode=residue.get_id()
resname=residue.get_resname()
segid=residue.get_segid()
for atom in residue.get_unpacked_list():
if select.accept_atom(atom):
chain_residues_written=1
model_residues_written=1
# The following lines have been modified by Tim:
#s=get_atom_line(atom, hetfield, segid, atom_number, resname,
# resseq, icode, chain_id[0])
if atom_number > 99999:
index = 99999
else:
index = atom_number
if len(chain_id) != 1:
c_id = ' '
else:
c_id = chain_id
s=get_atom_line(atom, hetfield, segid, index, resname,
resseq, icode, c_id)
fp.write(s)
atom_number=atom_number+1
if chain_residues_written:
fp.write("TER\n")
if model_flag and model_residues_written:
fp.write("ENDMDL\n")
if write_end:
fp.write('END\n')
if close_file:
fp.close()
def incr_chainid(self, cid):
if len(cid) != 1:
s = 'ERROR in \"pdb_from_biopython.incr_chainid\": '
s += 'invalid chain ID (wrong length):'
s += 'Chainid to be increased: ' + cid
raise self.MergeError(s)
uc = ord( cid )
if uc == 90:
# Z -> a
uc = 97
elif uc == 122:
# z -> 0
uc = 48
else:
uc += 1
if not ( (65 <= uc <= 90) or (97 <= uc <= 122) or (48 <= uc <= 57)):
s = 'ERROR in \"pdb_from_biopython.incr_chainid\": '
s += 'invalid chain ID (unicode not in range):'
s += 'Chainid to be increased: ' + cid
raise self.MergeError(s)
return chr(uc)
def merge_models(self, overwrite=False):
"""
Merges all models found in self.all_structs. Usefull to convert a\
multi-model biological assembly pdb from the PDB-database into a
single-model structure.
Parameter:
overwrite: True -> Overwrite self.all_structs_merged if it exits.
False-> (Default) do nothing, if self.all_structs_merged exits.
-> Returns a Bio.PDB.Structure object, containing a single model with
the merged structure.pdb.merge
---------------------------------------------------------------------
Chains are renamed obeying the following rules:
- The chain IDs of protein chains in the first model are kept.
- Starting with the second model the chain IDs are increased as
long, until an unused ID is found. (Chain IDs used for HETATOM
are overwritten.)
- Chain IDs of pure HETATOM chains in the original pdb-file are
ignored. Chain IDs higher than the last protein-chain ID are
used for them.
The chain assignment is changed obeying the following rules:
- A HEATATOM in a protein chain, that is covalent bound to the
protein chain remain in this chain. It can be bound indirect
through other HEATOMs.
- A HEATATOM in a protein chain, that is NOT bound to the protein
chain are moved to a new chain.
- A HETATOM that is NOT in a protein chain is placed in a new
chain.
- If HEATATOMs in chains without protein are covalent bound, their
chains are merged.
- All monomeric HETATOM residues are merged into one chain.
- All water molecules are placed in one chain. This chain gets the
highest unsused chain ID.
Resids are changed obeying the following rules:
- ATOM resids are not changed.
- HETATOM resids are increased if the RESID exists already in the
same chain. This is needed when chains are merged.
- Waters are completely renumbered, starting with 1.
Residues are completely removed, if all of their atoms do overlap
(distance < 0.5 Angtröm). Residues with higer model IDs are deleted
preferably. Only the first altloc atoms are compared (' ' or 'A'), if
there is more than one conformation available.
If only some atoms of two residue overlap, an error is raised.
"""
if self.all_structs == None:
s = 'ERROR in \"pdb_from_biopython.merge_models\": '
s += 'Cannot merge structures if no structures have been loaded.'
raise self.MergeError(s)
# Only x-ray structures are merged.
is_xray = False
if 'EXPDTA' in self.header:
if self.header['EXPDTA'][0].find('X-RAY') == -1:
s = 'ERROR in \"pdb_from_biopython.merge_models\": '
s += 'Structure is not resolved by x-ray diffraction: '
s += self.header['EXPDTA'][0].strip('EXPDTA').strip(' ')
raise self.MergeError(s)
if self.all_structs_merged != None and not overwrite:
# Merged structure exits already and overwrite parameter is not set.
return -1
for m, model in enumerate(self.all_structs):
for chainid in model.child_dict.keys():
for res in model.child_dict[chainid]:
resid = res.get_id()[1]
resname = res.get_resname()
id_str = str(m) + ' ' \
+ resname.rjust(4) + ' ' \
+ str(chainid) + ' ' \
+ '{0:.0f}'.format( resid ).rjust(5)
res.old_identity = id_str
# Count the number of atoms to make sure, that no atom is lost.
noa_start = 0
for i,m in enumerate(self.all_structs):
x = [x for x in m.get_atoms()]
noa_start += len(x)
#print "### starting ###"
###############################################################
# preparation step: Generate a List of bonds between HETATOM residues
# and other HETATOM or ATOM residues.
##############################################################
all_het_connections = []
for struct in self.all_structs:
model_connections = {}
# create residue list
res_list = []
for chainid in struct.child_dict.keys():
for i, res in enumerate( struct.child_dict[chainid].child_list ):
res_list.append( (chainid, res) )
for i, (chainid, res) in enumerate( res_list[:-1] ):
# Compare "res" with next residue in the chain.
(chainid_comp, res_comp) = res_list[i+1]
# Check if the two residues are connected.
is_bond = False
# Do not compare ATOM with ATOM residues.
if res.get_id()[0] != ' ' or res_comp.get_id()[0] != ' ':
for atom in res.child_list:
if atom.element == 'H':
continue
coord = atom.get_coord()
for atom_comp in res_comp.child_list:
if atom.element == 'H':
continue
coord_comp = atom_comp.get_coord()
dist = coord_comp - coord
if 0.5 < np.sqrt(np.dot( dist, dist )) < 1.7:
# Bond between the atoms found.
is_bond = True
break
if is_bond:
break
# If they are bond add an connection entry.
# A residue is define by: (chainid and residue ID)
res_description = ( chainid, res.get_id() )
if res_description not in model_connections:
model_connections[ res_description ] = {}
if is_bond:
res_comp_description = ( chainid_comp, res_comp.get_id() )
model_connections[ res_description ][ res_comp_description ] = True
if res_comp_description not in model_connections:
model_connections[ res_comp_description ] = {}
model_connections[ res_comp_description ][ res_description ] = True
# To be complete add the last residue to the connection dictionary.
(chainid, res) = res_list[-1]
res_description = ( chainid, res.get_id() )
model_connections[ res_description ] = {}
all_het_connections.append( model_connections )
#print '### preparation step done ###'
#######################################################################
# first step: Split ATOM and HETATOM chains.
# Store alle chains seperatly, they will be merged later.
# Only chain IDs of ATOMs are kept.
#######################################################################
# One entry for every model
all_p_chains = []
all_h_chains = []
# each model
for struct_id, struct in enumerate( self.all_structs ):
p_chains = []
h_chains = []
chain_list = [c[0] for c in struct.child_dict.keys()]
chain_list.sort()
# each chain
for cid in chain_list:
# Each chain is split into ATOM and HETATOM residues
# This will be used for ATOMS (chain id is kept for now)
atom_residues = Chain(cid)
# This will be used for HEATOMS (chain id is lost)
het_residues = Chain(cid)
# each residue
for res in struct.child_dict[cid].child_list:
if res.get_id()[0] == ' ':
#if is_std_aa(res.get_resname()):
# ATOM residue found
atom_residues.add(res)
else:
# HETATOM residue found
res_description = ( cid, res.get_id() )
for (x, bound_res_id) in all_het_connections[ struct_id ][ res_description ]:
if bound_res_id[0] == ' ':
# HETATOM residue is bound to ATOM residue
atom_residues.add(res)
break
else:
# Will be deleted from this list later, if neccesary.
# This is required to keep the residue order.
atom_residues.add(res)
# Residues in here will be checked later.
het_residues.add(res)
# Check if the HETATOMs are covalent bound to another ATOM
# residue in the same chain. -> If yes: Keep it in the
# protein chain.
something_changed = True
while something_changed:
something_changed = False
for i, res in enumerate(het_residues.child_list):
res_description = ( cid, res.get_id() )
for res_comp in atom_residues.child_list:
res_comp_description = ( cid, res_comp.get_id() )
# 'res_comp' is only a valid connection partner, if
# it is not contained in 'het_residues'. That means
# it is ether a ATOM Residue or a resdidue that is
# directly or indirectly connected to an ATOM residue.
if not het_residues.has_id( res_comp.get_id() ):
if res_comp_description in all_het_connections[ struct_id ][ res_description ]:
het_residues.detach_child( res.get_id() )
something_changed = True
break
if something_changed:
break
# remove all entries from atom_residues that are still in het_residues
something_changed = True
while something_changed:
something_changed = False
for res_atom in atom_residues.child_list:
if het_residues.has_id( res_atom.get_id() ):
atom_residues.detach_child( res_atom.get_id() )
something_changed = True
break
if len(atom_residues.child_list) > 0:
p_chains.append(atom_residues)
if len(het_residues.child_list) > 0:
h_chains.append(het_residues)
all_p_chains.append(p_chains)
all_h_chains.append(h_chains)
#print "### first step done ###"
######################################################################
# second step: Look for covalent bound HETATOM residues for each model.
# Make sure, they are in the same chain.
######################################################################
# merge chains that are covalent connected through at least one residue pair
all_h_chains_new = []
# All monomeric HETATOMs are merged into one chain.
monomer_chain_list = []
# All waters are merged into one chain
water_chain = Chain('')
used_water_residues = {}
# each model
for m_id, model in enumerate( all_h_chains ):
# generate list with all residues in the model
res_descr_list = []
for chain in model:
chainid = chain.get_id()
for res in chain.child_list:
res_description = ( chainid, res.get_id() )
res_descr_list.append( res_description )
res_done = {}
# first get all waters
for res_description in res_descr_list:
if res_description[1][0] == 'W':
res_done[res_description] = True
#resid = res_description[1][1]
resid = 1
while resid in used_water_residues:
resid += 1
used_water_residues[resid] = True
res = self.all_structs[m_id]\
.child_dict[ res_description[0] ]\
.child_dict[ res_description[1] ]
res.id = (res.id[0],\
resid,\
res.id[2])
# The attribute "chainid" is not standart for a
# chiain-object. But it will be neded later.
res.chainid_old = res_description[0]
res.resid_old = res_description[1][1]
water_chain.add( res )
while True:
new_chain = Chain('')
used_resid = {}
# each residue
# Find a new residue to start with
for res_description in res_descr_list:
if res_description not in res_done:
break
else:
# All residues have been added to the new chain list. -> stopping
break
to_look_at_list = [res_description]
res_done[res_description] = True
# Make sure, that no resid is used twice.
resid = res_description[1][1]
while resid in used_resid:
resid += 1
used_resid[resid] = True
res = self.all_structs[m_id]\
.child_dict[ res_description[0] ]\
.child_dict[ res_description[1] ]
res.id = (res.id[0],\
resid,\
res.id[2])
# The attribute "chainid" is not standart for a
# chiain-object. But it will be neded later.
res.chainid_old = res_description[0]
res.resid_old = res_description[1][1]
new_chain.add( res )
while len(to_look_at_list) > 0:
res_description = to_look_at_list.pop()
for res_desc_partner in all_het_connections[m_id][ res_description ].keys():
if res_desc_partner not in res_done:
to_look_at_list.append( res_desc_partner )
res_done[res_desc_partner] = True
res = self.all_structs[m_id]\
.child_dict[ res_desc_partner[0] ]\
.child_dict[ res_desc_partner[1] ]
while resid in used_resid:
resid += 1
used_resid[resid] = True
res.id = (res.id[0],\
resid,\