-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathClass_PDB.py
More file actions
2449 lines (2159 loc) · 98.3 KB
/
Class_PDB.py
File metadata and controls
2449 lines (2159 loc) · 98.3 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
from math import exp, ceil
import os
import re
from subprocess import run, CalledProcessError
from random import choice
from AmberMaps import *
from wrapper import *
from Class_Structure import *
from Class_line import *
from Class_Conf import Config, Layer
from Class_ONIOM_Frame import *
from helper import decode_atom_mask, get_center, get_field_strength, line_feed, mkdir
try:
from pdb2pqr.main import main_driver as run_pdb2pqr
from pdb2pqr.main import build_main_parser as build_pdb2pqr_parser
except ImportError:
raise ImportError('PDB2PQR not installed.')
try:
import propka.lib
except ImportError:
raise ImportError('PropKa not installed.')
try:
import openbabel
import openbabel.pybel as pybel
except ImportError:
raise ImportError('OpenBabel not installed.')
__doc__='''
This module handles file I/O and external programs.
-------------------------------------------------------------------------------------
Class PDB
-------------------------------------------------------------------------------------
__init__(self, PDB_input, wk_dir = '', name = '', input_type='path')
-------------------------------------------------------------------------------------
Information collecting methods:
-------------------------------------------------------------------------------------
get_stru(self, ligand_list=None)
get_seq(self)
get_if_ligand = get_seq # alias
get_if_art_resi = get_seq # alias
get_missing(self, seq)
-------------------------------------------------------------------------------------
PDB operating methods: (changes the self.path to indicated new pdb)
-------------------------------------------------------------------------------------
PDB2PDBwLeap(self, Flag):
PDBMin(self,cycle):
rm_wat(self): remove water and ion for current pdb. (For potential docking)
loopmodel_refine(self): Use different method to model the missing sequence
-------------------------------------------------------------------------------------
Mutation Tools:
-------------------------------------------------------------------------------------
Add_MutaFlag(self,Flag): User assigned Flag or Random Flag using "random"
PDB_check(self):
-------------------------------------------------------------------------------------
Input file generating methods:
-------------------------------------------------------------------------------------
PDB2FF(self):
PDBMD(self):
-------------------------------------------------------------------------------------
>>>>>>> Develop Note <<<<<<<<<
For every potential first use of self.file_str or self.path or self.stru
Will do nothing if the correct var is already exist.
- use _get_file_str
- use _get_file_path
- use get_stru
'''
class PDB():
def __init__(self, PDB_input, wk_dir = '', name = '', input_type='path'):
'''
initiate PDB object
-------------------
PDB_input
wk_dir : working directory (default: current dir ) **all file in the workflow are constructed base on this.**
name : self assigned filename (default: from path or UNKNOW if no path)
input_type : path (default) / file_str / file
-------------------
'''
# Nessessary initilize for empty judging
self.stru = None
self.path = None
self.prmtop_path = None
self.MutaFlags = []
self.nc=None
self.frames=None
# default MD conf.
self._init_MD_conf()
# default ONIOM layer setting
self.layer_preset = Config.Gaussian.layer_preset
self.layer_atoms = Config.Gaussian.layer_atoms
if wk_dir == '':
#current dir by default
self.dir = '.'
else:
if wk_dir[-1] == '/':
self.dir = wk_dir[:-1]
else:
self.dir = wk_dir
if input_type == 'path':
self.path = PDB_input
self._update_name()
if input_type == 'file_str':
self.file_str = PDB_input
if name == '':
# default name
name = 'UNKNOW'
self.name = name
self.path_name = self.dir+'/'+self.name
if input_type == 'file':
self.file_str = PDB_input.read()
if name == '':
# default name
name = 'UNKNOW'
self.name = name
self.path_name = self.dir+'/'+self.name
if input_type not in ['path', 'file_str', 'file']:
raise Exception('PDB.__init__: only take path or file_str or file.')
# make cache
self.cache_path = self.dir+'/cache'
mkdir(self.cache_path)
def _update_name(self):
'''
update name
'''
suffix_len = len(self.path.split('.')[-1]) + 1
self.name=self.path.split(os.sep)[-1][:-suffix_len]
self.path_name = self.dir+'/'+self.name
def get_stru(self, ligand_list=None, renew = 0):
'''
Convert current PDB file (self.path) to a Struture object (self.stru).
------
input_name : a name tag for the object (self.name by default)
ligand_list : a list of user assigned ligand residue names.
renew : 1: force generate a new stru_obj
'''
# indicated by self.name
input_name = self.name
# if get new stru
get_flag = 0
if self.stru is not None:
if self.stru.name != self.name:
get_flag = 1
# warn if possible wrong self.stru
if Config.debug >= 1:
print('PDB.get_stru: WARNING: self.stru has a different name')
print(' -self.name: '+self.name)
print(' -self.stru.name: '+self.stru.name)
print('Getting new stru')
else:
get_flag = 1
if get_flag or renew:
if self.path is not None:
self.stru = Structure.fromPDB(self.path, input_name=input_name, ligand_list=ligand_list)
else:
self.stru = Structure.fromPDB(self.file_str, input_type='file_str', input_name=input_name, ligand_list=ligand_list)
def _get_file_str(self):
'''
read file_str from path is not pre-exist.
-------------
recommend before every potential first use of self.file_str
'''
if self.path is None:
return self.file_str
else:
return open(self.path).read()
def _get_file_path(self):
'''
save a file and get path if self.path is None
-------------
recommend before every potential first use of self.path
'''
if self.path is None:
self.path = self.path_name+'.pdb'
with open(self.path,'w') as of:
of.write(self.file_str)
return self.path
def _init_MD_conf(self):
'''
initialize default MD configuration. Replaced by manual setting if assigned later.
'''
self.conf_min = Config.Amber.conf_min
self.conf_heat = Config.Amber.conf_heat
self.conf_equi = Config.Amber.conf_equi
self.conf_prod = Config.Amber.conf_prod
def set_oniom_layer(self, atom_list=[], preset=0):
'''
set oniom layer with san check
layer_atoms are in higher pirority
'''
if len(atom_list) != 0:
if all(type(x) is str for x in atom_list):
self.layer_atoms = atom_list
else:
raise Exception('set_oniom_layer: atom_list require a list of str. e.g.: [\'1-9\',\'11,13-15\']')
else:
if preset == 0:
raise Exception('set_oniom_layer: please assign one of the argument: atom_list (a list of layer_atoms) or preset (other than 0)')
else:
self.layer_preset = preset
def get_last_A_id(self):
'''
get last atom id in PDB
'''
with open(self.path) as f:
fl = f.readlines()
for i in range(len(fl)-1,-1,-1):
pdbl = PDB_line(fl[i])
if pdbl.line_type == 'ATOM' or pdbl.line_type == 'HETATM':
return pdbl.atom_id
'''
=========
Sequence TODO: reform
=========
'''
def topology_sort(self):
'''
sort the sequence of the lasso peptide into sections
representative of its topology -Reecan
'''
self.upperLoop=[]
self.tail=[]
self.plugs=[]
self.ring=[]
self.upperPlug=[]
self.lowerPlug=[]
self.essentialRes=[] #this residue (ASX) connects the ring and tail
#these ranges can be changed to accomodate for
#different lasso peptide structures.
upperRange=range(7)
plugRange=range(7,9)
tailRange=range(10,14)
ringRange=range(15,21) # 21 = 7mr, 22 = 8mr, 23 = 9mr
#pluglocation
uPlugRes = 7
lPlugRes = 8
#sort the PDB
with open(self.path) as f:
lines = [line.split() for line in f]
i = 4 #by residue number
for l in lines:
if i < len(l): #avoid 'END'
if int(l[i]) in upperRange:
self.upperLoop.append(str(l[i]))
if int(l[i]) in plugRange:
self.plugs.append(str(l[i]))
if int(l[i]) == uPlugRes:
self.upperPlug.append(str(l[i]))
if int(l[i]) == lPlugRes:
self.lowerPlug.append(str(l[i]))
if int(l[i]) in tailRange:
self.tail.append(str(l[i]))
if int(l[i]) in ringRange:
self.ring.append(str(l[i]))
if (l[i-1]) == 'ASX':
self.essentialRes.append(str(l[i]))
else:
None
self.upperLoop = list(set(self.upperLoop))
self.tail = list(set(self.tail))
self.plugs = list(set(self.plugs))
self.ring = list(set(self.ring))
self.upperPlug = list(set(self.upperPlug))
self.lowerPlug = list(set(self.lowerPlug))
self.essentialRes = list(set(self.essentialRes))
return self.upperLoop, self.tail, self.plugs, self.ring, self.upperPlug, self.lowerPlug, self.essentialRes
def get_seq(self, Oneletter=0):
'''
get_seq(self, Oneletter=0)
Support most PDB types
----------------------------
Oneletter
= 0 // use 3-letter format to represet each residue
= 1 // use 1-letter format to represet each residue
----------------------------
Get sequence for current PDB (self.path) // A general function to obtain the missing residue
+ Use "NAN"/"-" as a filler to store missing residues (detect internal missing)
+ Check if contain non-standard residue with the Resi_map --> self.if_art_resi
+ Check if contain ligand with the Resi_map and TIP3P_map --> self.if_ligand
- (WARNING) Require the ligand in seperate chains
- Re-assign the chain_index base on the order in the file
- Do not include the original residue index
- Do not include any HETATM (ligand/solvent)
----------------------------
save the info to self.sequence/self.sequence_one and return it
----------------------------
self.sequence:
Format: {'Chain_index':['res','res',...]
'Chain_index':['res','res',...]
...
}
self.raw_sequence:
Internal used, containing HETATM
self.sequence_one: (when Oneletter=1)
Format: {'Chain_index':'seq'
'Chain_index':'seq'
...
}
!!NOTE!! the self.sequence needs to be updated after mutation
'''
PDB_str = self._get_file_str()
self.raw_sequence = {}
self.sequence = {}
self.sequence_one = {}
Chain_str = PDB_str.split(line_feed+'TER') # Note LF is required
for chain,i in enumerate(Chain_str):
Chain_index = chr(65+chain) # Covert to ABC using ACSII mapping
Chain_sequence=[]
# Get the Chain_sequence
lines=i.split(line_feed)
for line in lines:
pdb_l = PDB_line(line)
if pdb_l.line_type == 'ATOM' or pdb_l.line_type == 'HETATM':
# Deal with the first residue
if len(Chain_sequence) == 0:
Chain_sequence.append(pdb_l.resi_name)
last_resi_index = pdb_l.resi_id
continue
# find next new residue
if pdb_l.resi_id != last_resi_index:
# Deal with missing residue, fill with "NAN"
missing_length = pdb_l.resi_id - last_resi_index - 1
if missing_length > 0:
Chain_sequence = Chain_sequence + ['NAN',] * missing_length
# Store the new resi
Chain_sequence.append(pdb_l.resi_name)
# Update for next loop
last_resi_index = pdb_l.resi_id
self.raw_sequence[Chain_index] = Chain_sequence
self._strip_raw_seq() # strip the raw_sequence and save to sequence
self.get_if_complete()
if Oneletter == 1:
self._get_Oneletter()
return self.sequence_one
else:
return self.sequence
get_if_ligand = get_seq # alias
get_if_art_resi = get_seq
def _strip_raw_seq(self):
'''
(Used internally) strip the raw_sequence.
- Delete ligand and solvent
- Delete chains without residue
save changes to self.sequence
Judge if containing any ligand or artificial residue
save to self.if_ligand and self.if_art_resi
'''
new_index=0
#if the value is not changed to 1 then it's 0
self.if_art_resi = 0
self.if_ligand = 0
if len(self.raw_sequence) == 0:
print("The self.raw_sequence should be obtained first")
raise IndexError
for chain in self.raw_sequence:
chain_seq=[]
if_realchain = 0
# Judge if real chain
for name in self.raw_sequence[chain]:
clean_name = name.strip(' ')
if clean_name in Resi_map2.keys():
if_realchain = 1
if if_realchain:
for name in self.raw_sequence[chain]:
clean_name = name.strip(' ')
chain_seq.append(clean_name)
# An artificial residue will be a residue in a realchain but not included in force field map
if clean_name not in Resi_map2 and clean_name != 'NAN':
self.if_art_resi = 1
## PLACE HOLDER for further operation on artificial residue ##
else:
# Judge if containing any ligand
for name in self.raw_sequence[chain]:
clean_name = name.strip(' ')
if clean_name not in TIP3P_map and clean_name != 'NAN':
self.if_ligand = 1
## PLACE HOLDER for further operation on artificial residue ##
# only add realchain to the self.sequence
if len(chain_seq) != 0:
chain_Index=chr(new_index+65)
self.sequence[chain_Index]=chain_seq
new_index=new_index+1
def _get_Oneletter(self):
'''
(Used internally) convert sequences in self.sequence to oneletter-based str
- The 'NAN' is convert to '-'
- Present unnature residue as full 3-letter name
save to self.sequence_one
'''
if len(self.sequence) == 0:
print("The self.sequence should be obtained first")
raise IndexError
for chain in self.sequence:
chain_Seq=''
for name in self.sequence[chain]:
c_name=name.strip(' ')
if c_name == 'NAN':
chain_Seq=chain_Seq+'-'
else:
if c_name in Resi_map2:
chain_Seq=chain_Seq+Resi_map2[c_name]
else:
chain_Seq=chain_Seq+' '+c_name+' '
self.sequence_one[chain]=chain_Seq
def get_if_complete(self):
'''
Judge if the self.sequence (from the get_seq) has internal missing parts
Save the result to:
self.if_complete ------- for intire PDB
self.if_complete_chain - for each chain
'''
if len(self.sequence.keys()) == 0:
print('Please get the sequence first')
raise IndexError
self.if_complete=1 # if not flow in then 1
self.if_complete_chain = {}
for chain in self.sequence:
self.if_complete_chain[chain]=1 # if not flow in then 1
for resi in self.sequence[chain]:
if resi == 'NAN':
self.if_complete=0
self.if_complete_chain[chain]=0
break
return self.if_complete, self.if_complete_chain
def get_missing(self, seq):
'''
get_missing(self, seq)
Compare self.sequence (from the get_seq) with the seq (str from the uniport)
1. No missing
2. Terminal missing
3. Internal missing
'''
pass
def PDB_loopmodel_refine(self, method='Rosetta'):
'''
Use different methods to model the missing sequence
Methods:
- pyRosetta
- trRosetta
remember to update the name.
'''
pass
'''
========
Protonation
========
'''
def get_protonation(self, ph=7.0, keep_id=0):
'''
Get protonation state based on PDB2PQR:
1. Use PDB2PQR, save output to self.pqr_path
2. Fix problems:
- Metal center:
(detect donor(base on atom type) in a metal type based radiis) --> open for customize
- Fix1: deprotonate all.
- Fix2: rotate if there're still lone pair left
- Fix3: run pka calculate containing ion (maybe pypka) and run Fix2 based on the result
- Ligand:
- Use OpenBable to protonate ligand by default
# switch HIE HID when dealing with HIS
save to self.path
'''
out_path=self.path_name+'_aH.pdb'
self._get_file_path()
self._get_protonation_pdb2pqr(ph=ph)
self._protonation_Fix(out_path, ph=ph, keep_id=keep_id)
self.path = out_path
self._update_name()
self.stru.name=self.name
def _get_protonation_pdb2pqr(self,ffout='AMBER',ph=7.0,out_path=''):
'''
Use PDB2PQR to get the protonation state for current PDB. (self.path)
current implementation just use the outer layer of PDB2PQR. Update to inner one and get more infomation in the furture.
(TARGET: 1. what is deleted from the structure // metal, ligand)
save the result to self.pqr_path
'''
# set default value for output pqr path
if len(out_path) == 0:
self.pqr_path = self.path_name+'.pqr'
else:
self.pqr_path = out_path
# input of PDB2PQR
pdb2pqr_parser = build_pdb2pqr_parser()
args = pdb2pqr_parser.parse_args(['--ff=PARSE','--ffout='+ffout,'--with-ph='+str(ph),self.path,self.pqr_path])
# use context manager to hide output
with HiddenPrints('./._get_protonation_pdb2pqr.log'):
run_pdb2pqr(args)
def _protonation_Fix(self, out_path, Metal_Fix='1', ph = 7.0, keep_id=0):
'''
Add in the missing atoms and run detailed fixing
save to self.path
'''
# Add missing atom (from the PDB2PQR step. Update to func result after update the _get_protonation_pdb2pqr func)
# Now metal and ligand
old_stru = Structure.fromPDB(self.path)
new_stru = Structure.fromPDB(self.pqr_path)
# find Metal center and combine with the pqr file
metal_list = old_stru.get_metal_center()
if len(metal_list) > 0:
new_stru.add(metal_list, sort = 0)
# fix metal environment
new_stru.protonation_metal_fix(Fix = 1)
# protonate ligands and combine with the pqr file
if len(old_stru.ligands) > 0:
lig_dir = self.dir+'/ligands/'
mkdir(lig_dir)
lig_paths = [(i,k) for i,j,k in old_stru.build_ligands(lig_dir, ifname=1)]
new_ligs = []
for lig_path, lig_name in lig_paths:
new_lig_path, net_charge = self.protonate_ligand(lig_path, ph=ph)
new_ligs.append(Ligand.fromPDB(new_lig_path, resi_name=lig_name, net_charge=net_charge, input_type='path'))
new_stru.add(new_ligs, sort = 0)
# PLACE HOLDER for other fix
# build file
if not keep_id:
new_stru.sort()
new_stru.build(out_path, keep_id=keep_id)
self.stru = new_stru
@classmethod
def protonate_ligand(cls, path, method='PYBEL', ph = 7.0, keep_name=1):
'''
Protonate the ligand from 'path' with 'method', provide out_path and net charge.
TODO "obabel -ipdb ligand_1.pdb -opdb pdb -O ligand_1_aHt.pdb -h" can keep names, but how is it accessed by pybel
---------------
method : PYBEL (default)
Dimorphite (from https://durrantlab.pitt.edu/dimorphite-dl/) TODO seems better and with better python API.
OPENBABEL (not working if block warning output)
ph : 7.0 by default
keep_name : if keep original atom names of ligands (default: 1)
- check if there're duplicated names, add suffix if are.
'''
outp1_path = path[:-4]+'_badname_aH.pdb'
out_path = path[:-4]+'_aH.pdb'
# outm2_path = path[:-4]+'_aH.mol2'
if method == 'OPENBABEL':
# not working if block warning output for some reason
# openbabel.obErrorLog.SetOutputLevel(0)
obConversion = openbabel.OBConversion()
obConversion.SetInAndOutFormats("pdb", "pdb")
mol = openbabel.OBMol()
obConversion.ReadFile(mol, path)
mol.AddHydrogens(False, True, ph)
obConversion.WriteFile(mol, out_path)
if method == 'PYBEL':
pybel.ob.obErrorLog.SetOutputLevel(0)
mol = next(pybel.readfile('pdb', path))
mol.OBMol.AddHydrogens(False, True, ph)
mol.write('pdb', outp1_path, overwrite=True)
# fix atom label abd determing net charge
if keep_name:
cls._fix_ob_output(outp1_path, out_path, ref_name_path=path)
else:
cls._fix_ob_output(outp1_path, out_path)
# determine partial charge
# > METHOD 1<
net_charge = cls._ob_pdb_charge(outp1_path)
# > METHOD 2 <
# mol.write('mol2', outm2_path, overwrite=True)
# mol = next(pybel.readfile('mol2', outm2_path))
# net_charge=0
# for atom in mol:
# net_charge=net_charge+atom.formalcharge
if method == 'Dimorphite':
pass
return out_path, net_charge
@classmethod
def _fix_ob_output(cls, pdb_path, out_path, ref_name_path=None):
'''
fix atom label in pdb_pat write to out_path
---------
ref_name_path: if use original atom names from pdb
- default: None
according to tleap output, the name could be just *counting* the element start from ' ' to number
- : not None
check if there're duplicated names originally, add suffix if there are.
'''
if ref_name_path != None:
ref_a_names = []
with open(ref_name_path) as rf:
pdb_ls = PDB_line.fromlines(rf.read())
ref_resi_name = pdb_ls[0].resi_name
for pdb_l in pdb_ls:
if pdb_l.line_type == 'HETATM' or pdb_l.line_type == 'ATOM':
# pybel use line order (not atom id) to assign new atom id
ref_a_names.append(pdb_l.atom_name)
with open(pdb_path) as f:
with open(out_path, 'w') as of:
# count element in a dict
ele_count={}
pdb_ls = PDB_line.fromlines(f.read())
line_count = 0
for pdb_l in pdb_ls:
if pdb_l.line_type == 'HETATM' or pdb_l.line_type == 'ATOM':
if ref_name_path == None:
ele = pdb_l.get_element()
else:
if line_count < len(ref_a_names):
ele = ref_a_names[line_count]
else:
ele = pdb_l.get_element() # New atoms
pdb_l.resi_name = ref_resi_name
line_count += 1
# determine the element count
try:
# rename if more than one (add count)
ele_count[ele] += 1
pdb_l.atom_name = ele+str(ele_count[ele])
except KeyError:
ele_count[ele] = 0
pdb_l.atom_name = ele
of.write(pdb_l.build())
@classmethod
def _ob_pdb_charge(cls, pdb_path):
'''
extract net charge from openbabel exported pdb file
'''
with open(pdb_path) as f:
net_charge=0
pdb_ls = PDB_line.fromlines(f.read())
for pdb_l in pdb_ls:
if pdb_l.line_type == 'HETATM' or pdb_l.line_type == 'ATOM':
if len(pdb_l.get_charge()) != 0:
charge = pdb_l.charge[::-1]
if Config.debug > 1:
print('Found formal charge: '+pdb_l.atom_name+' '+charge)
net_charge = net_charge + int(charge)
return net_charge
'''
========
Mutation
========
'''
def PDB2PDBwLeap(self):
'''
Apply mutations using tleap. Save mutated structure PDB in self.path
------------------------------
Use MutaFlag in self.MutaFlags
Grammer (from Add_MutaFlag):
X : Original residue name. Leave X if unknow.
Only used for build filenames. **Do not affect any calculation.**
A : Chain index. Determine by 'TER' marks in the PDB file. (Do not consider chain_indexs in the original file.)
11: Residue index. Strictly correponding residue indexes in the original file. (NO sort applied)
Y : Target residue name.
**WARNING** if there are multiple mutations on the same index, only the first one will be used.
'''
#Judge if there are same MutaIndex (c_id + r_id)
for i in range(len(self.MutaFlags)):
for j in range(len(self.MutaFlags)):
if i >= j:
pass
else:
if (self.MutaFlags[i][1], self.MutaFlags[i][2]) == (self.MutaFlags[j][1], self.MutaFlags[j][2]):
if Config.debug >= 1:
print("PDB2PDBwLeap: There are multiple mutations at the same index, only the first one will be used: "+self.MutaFlags[i][0]+self.MutaFlags[i][1]+self.MutaFlags[i][2])
# Prepare a label for the filename
tot_Flag_name=''
for Flag in self.MutaFlags:
Flag_name=self._build_MutaName(Flag)
tot_Flag_name=tot_Flag_name+'_'+Flag_name
# Operate the PDB
out_PDB_path1=self.cache_path+'/'+self.name+tot_Flag_name+'_tmp.pdb'
out_PDB_path2=self.path_name+tot_Flag_name+'.pdb'
self._get_file_path()
with open(self.path,'r') as f:
with open(out_PDB_path1,'w') as of:
chain_count = 1
for line in f:
pdb_l = PDB_line(line)
TER_flag = 0
if pdb_l.line_type == 'TER':
TER_flag = 1
# add chain count in next loop for next line
if TER_flag:
chain_count += 1
match=0
# only match in the dataline and keep all non data lines
if pdb_l.line_type == 'ATOM':
for Flag in self.MutaFlags:
# Test for every Flag for every lines
t_chain_id=Flag[1]
t_resi_id =Flag[2]
if chr(64+chain_count) == t_chain_id:
if pdb_l.resi_id == int(t_resi_id):
# do not write old line if match a MutaFlag
match=1
# Keep OldAtoms of targeted old residue
resi_2 = Flag[3]
OldAtoms=['N','H','CA','HA','CB','C','O']
#fix for mutations of Gly & Pro
if resi_2 == 'G':
OldAtoms=['N','H','CA','C','O']
if resi_2 == 'P':
OldAtoms=['N','CA','HA','CB','C','O']
for i in OldAtoms:
if i == pdb_l.atom_name:
new_line=line[:17]+Resi_map[resi_2]+line[20:]
of.write(new_line)
break
#Dont run for other Flags after first Flag matches.
break
if not match:
of.write(line)
# Run tLeap
#make input
#Reecan: added custom frcmod and atom bonds
leapin_path = self.cache_path+'/leap_P2PwL.in'
leap_input=open(leapin_path,'w')
leap_input.write('source leaprc.protein.ff14SBmod\n')
Nring=int(self.name[:1])
Nring+=1
ring_num = str(Nring)
if 'd' in self.name:
leap_input.write('loadAmberParams ligands/ligand_ASX.frcmod1\n')
leap_input.write('loadAmberParams ligands/ligand_ASX.frcmod2\n')
leap_input.write('loadAmberPrep ligands/ligand_ASX.prepin\n')
leap_input.write('a = loadpdb '+out_PDB_path1+'\n')
#TODO: bond atoms based on upper loop
leap_input.write('bond a.'+ring_num+'.N a.ASX.C\n')
leap_input.write('bond a.ASX.CG a.1.N\n') #isopeptide bond
leap_input.write('remove a a.ASX.OD2\n')
leap_input.write('remove a a.ASX.H02\n')
leap_input.write('remove a a.ASX.HB3\n')
leap_input.write('remove a a.1.H1\n')
leap_input.write('remove a a.1.H2\n')
leap_input.write('remove a a.1.H3\n')
leap_input.write('remove a a.9.H1\n')
leap_input.write('remove a a.9.H2\n')
leap_input.write('remove a a.9.H3\n')
leap_input.write('deletebond a.ASX.CG a.'+ring_num+'.N\n')
leap_input.write('deletebond a.ASX.C a.2.N\n')
else:
leap_input.write('loadAmberParams ligands/ligand_GLX.frcmod1\n')
leap_input.write('loadAmberParams ligands/ligand_GLX.frcmod2\n')
leap_input.write('loadAmberPrep ligands/ligand_GLX.prepin\n')
leap_input.write('a = loadpdb '+out_PDB_path1+'\n')
#TODO: bond atoms based on upper loop
#leap_input.write('bond a.'+ring_num+'.N a.GLX.C01\n')#peptide bond
leap_input.write('bond a.GLX.CD a.1.N\n') #isopeptide bond
#leap_input.write('deletebond a.GLX.O a.GLX.HG2\n')
leap_input.write('bond a.GLX.CA a.GLX.C01\n')
leap_input.write('deletebond a.GLX.CD a.GLX.C01\n') #artifact
#leap_input.write('deletebond a.GLX.CD a.'+ring_num+'.N\n')#artifact
leap_input.write('savepdb a '+out_PDB_path2+'\n')
#
leap_input.write('saveamberparm a '+out_PDB_path2+'.prmtop '+out_PDB_path2+'.inpcrd'+line_feed)
#
leap_input.write('quit\n')
leap_input.close()
#run
os.system('tleap -s -f '+leapin_path+' > '+self.cache_path+'/leap_P2PwL.out')
if Config.debug <= 1:
os.system('rm leap.log')
#Update the file
self.path = out_PDB_path2
self._update_name()
return self.path
def partition(self):
'''
partition the lasso structure into parts -Reecan
'''
a = list(self.topology_sort())
upperLoop = a[0] #loop
tail = a[1] #tail
plugs = a[2] #plugs
ring = a[3] #ring
upperPlug = a[4] #upper plug
lowerPlug = a[5] #lower plug
essentialRes = a[6]
sect = 'loop' #blank string: mutate any topological section.
self.get_stru()
chain = choice(self.stru.chains)
resi = choice(chain.residues)
if sect == 'loop':
if str(resi.id) not in upperLoop:
while str(resi.id) not in upperLoop:
resi = choice(chain.residues)
elif sect == 'tail':
while str(resi.id) not in tail:
resi = choice(chain.residues)
elif sect == 'plugs':
while str(resi.id) not in plugs:
resi = choice(chain.residues)
elif sect == 'ring':
while str(resi.id) not in ring:
resi = choice(chain.residues)
elif sect == 'upper plug':
while str(resi.id) not in upperPlug:
resi = choice(chain.residues)
elif sect == 'lower plug':
while str(resi.id) not in lowerPlug:
resi = choice(chain.residues)
elif sect == '':
resi = choice(chain.residues)
if str(resi.id) in essentialRes:
while str(resi.id) in essentialRes:
resi = choice(chain.residues)
return chain, resi
def Add_MutaFlag(self,Flag = 'r', if_U = 0, if_self=0):
'''
Input:
Flags or "random"
----------------------------------------------------
Flag :(e.g. XA11Y) Can be a str or a list of str (a list of flags).
if_U :if consider mutation to U in random generation (Selenocysteine)
if_self:if consider mutation to the residue itself in random generation(wt)
----------------------------------------------------
Append self.MutaFlags with the Flag.
Grammer:
X : Original residue name. Leave X if unknow.
Only used for build filenames. **Do not affect any calculation.**
A : Chain index. Determine by 'TER' marks in the PDB file. (Do not consider chain_indexs in the original file.)
11: Residue index. Strictly correponding residue indexes in the original file. (NO sort applied)
Y : Target residue name.
----------------------------------------------------
'random' or 'r' (default)
----------------------------------------------------
return a label of mutations
'''
'''
lasso Peptide topology.
-Reecan
'''
a = self.topology_sort()
mutaNum = int(5)#number of random mutations on the structure.
if mutaNum > len(a[0]): #todo: adjust based on chosen structure to mutate.
sys.exit("Number of mutations greater than number of section residues")
if type(Flag) == str:
if Flag == 'r' or Flag == 'random':
resi_1 = ''
resi_2 = ''
Muta_c_id = ''
Muta_r_id = ''
#make multiple, random mutations on the same structure
#avoid mutations on duplicate residues - Reecan
alteredRes = []
for i in range(mutaNum):
# Flag Generation
# Random over the self.stru. Strictly correponding residue indexes in the original file. (no sort applied)
#self.get_stru()
# random over the structure "protein" part.
#chain = choice(self.stru.chains)
#resi = choice(chain.residues)
chain, resi = self.partition()
Muta_r_id = str(resi.id)
Muta_c_id = chain.id
if resi.name in Resi_map2:
resi_1 = Resi_map2[resi.name]
else:
resi_1 = resi.name
# random over the residue list
if if_U:
m_Resi_list = Resi_list
else:
m_Resi_list = Resi_list[:-1]
resi_2 = choice(m_Resi_list)
# avoid or not mutation to self
if not if_self:
while resi_2 == resi_1:
resi_2 = choice(m_Resi_list)
MutaFlag = (resi_1, Muta_c_id, Muta_r_id ,resi_2)
if not self.MutaFlags:
self.MutaFlags.append(MutaFlag)
alteredRes.append(Muta_r_id)
else: #if there is something in MutaFlags