forked from masoudk/AsiteDesign
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MoversRosetta.py
3490 lines (2808 loc) · 147 KB
/
MoversRosetta.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
# Global imports
import os, sys
import re
import itertools
import copy, time
from numpy import exp, sum, array, where, sqrt, any, std, mean
from numpy.random import randint, normal, uniform
from numpy.linalg import norm
from io import StringIO
from mpi4py import MPI
from itertools import cycle
from random import choice
# PyRosetta import
import pyrosetta as pr
# PyRosetta mover and pakcer imports
from pyrosetta.rosetta.core.kinematics import MoveMap
from pyrosetta.rosetta.core.pack.task.operation import ReadResfile
from pyrosetta.rosetta.core.pack.task import TaskFactory
from pyrosetta.rosetta.protocols.minimization_packing import PackRotamersMover, MinMover
from pyrosetta.rosetta.protocols.constraint_movers import ClearConstraintsMover
from pyrosetta.rosetta.protocols.relax import FastRelax
from pyrosetta.rosetta.protocols.denovo_design.movers import FastDesign
from pyrosetta.rosetta.core.scoring.constraints import BoundFunc, AtomPairConstraint, AmbiguousConstraint, ResidueTypeConstraint
from pyrosetta.rosetta.core.scoring import ScoreType
from pyrosetta.rosetta.utility import vector1_std_shared_ptr_const_core_conformation_Residue_t
from pyrosetta.rosetta.std import ostringstream, istringstream
from pyrosetta.rosetta.protocols.geometry import centroid_by_residues, centroid_by_chain
from pyrosetta.rosetta.core.scoring import score_type_from_name
from pyrosetta.rosetta.protocols.docking import setup_foldtree
from pyrosetta.rosetta.protocols.rigid import RigidBodyPerturbMover
from pyrosetta.rosetta.protocols.simple_moves import ShearMover
from pyrosetta.rosetta.core.kinematics import FoldTree
from pyrosetta.rosetta.numeric import xyzVector_double_t
from pyrosetta.rosetta.core.select.residue_selector import ChainSelector, NeighborhoodResidueSelector, \
ResidueIndexSelector
from pyrosetta import Pose
# Biotite import
from biotite.structure.io.pdb import PDBFile
from biotite.structure import sasa, annotate_sse, apply_residue_wise
# BIO Python imports
from Bio.PDB.Polypeptide import one_to_three
# Local imports
import Constants
from BaseClases import BaseConstraint, Residue, AminoAcids, DesignDomainWildCards
from MiscellaneousUtilityFunctions import killProccesses, getKT, printDEBUG, getScoreFunction
from Docking import LigandMover
# This is for testing
# pr.init(''' -out:level 0 ''')
# This is for production run
# pr.init(''' -out:level 0 -no_his_his_pairE -extrachi_cutoff 1 -multi_cool_annealer 10 -ex1 -ex2 -use_input_sc ''')
# TODO LOGGING
# reff:
# http://www.programmersought.com/article/97651668888/
# https://colab.research.google.com/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/06.02-Packing-design-and-regional-relax.ipynb#scrollTo=9DTnXbppN9OT
# https://www.rosettacommons.org/docs/latest/full-options-list
class DesignPose(object):
"""
DesignPose is combines a pose with necessary methods to keep track of state of
pose during active site design.
"""
def __init__(self):
# if you add
self.pose = pr.Pose()
self.designInitiated = False
self.design = list()
self.designDict = dict()
self.nDesignResidues = 0
self.catalyticInitiated = False
self.catalytic = list()
self.catalyticTargetAA = dict()
self.catalyticDict = dict()
self.catalyticDesign = False
self.nCatalyticResidues = 0
self.nNoMutateCatalyticResidues = 0
self.catalyticAction = dict()
self.activeResidues = list()
self.constraintInitiated = False
self.constraints = list()
self.noMutate = dict() # Hold the catalytic index of non-mutatable residues
self.currentNoneCatalyticMutants = list()
self.originalSequence = list()
def __iter__(self):
for res in self.design:
yield res
def assign(self, other):
"""
This method copies the attributes of one DesignDomainMover object
to another one.
"""
self.pose.assign(other.pose)
self.designInitiated = copy.deepcopy(other.designInitiated)
self.design = copy.deepcopy(other.design)
self.designDict = copy.deepcopy(other.designDict)
self.nDesignResidues = copy.deepcopy(other.nDesignResidues)
self.catalyticInitiated = copy.deepcopy(other.catalyticInitiated)
self.catalytic = copy.deepcopy(other.catalytic)
self.catalyticTargetAA = copy.deepcopy(other.catalyticTargetAA)
self.catalyticDict = copy.deepcopy(other.catalyticDict)
self.catalyticDesign = copy.deepcopy(other.catalyticDesign)
self.nCatalyticResidues = copy.deepcopy(other.nCatalyticResidues)
self.nNoMutateCatalyticResidues = copy.deepcopy(other.nNoMutateCatalyticResidues)
self.catalyticAction = copy.deepcopy(other.catalyticAction)
self.activeResidues = copy.deepcopy(other.activeResidues)
self.constraintInitiated = copy.deepcopy(other.constraintInitiated)
self.constraints = copy.deepcopy(other.constraints)
self.noMutate = copy.deepcopy(other.noMutate)
self.currentNoneCatalyticMutants = copy.deepcopy(other.currentNoneCatalyticMutants)
self.originalSequence = copy.deepcopy(other.originalSequence)
def initiateDesign(self, residues, pose):
if not all(map(lambda x: isinstance(x, Residue), residues)):
raise ValueError('Failed during initiating the design residues. Only list of Residue(s) is allowed.')
# set the pose
self.pose.assign(pose)
self.design = residues
self.nDesignResidues = len(self.design)
# Set the design dictionary for rapid access (needed during non-catalytic design constraints update)
# The keys are the (ID, chain) tuples. The values are the res index in the design list
for index, res in enumerate(self.design):
self.designDict[(res.ID, res.chain)] = index
# Set the pose index of the design residues
self.setPoseIndex()
# get the original sequence for design domain
self.originalSequence = self.getPdbSequence()
# Set the allowed aa for each design position. This is independent of job type and only
# Fill the positions that are not defined by user 'X'.
self.setAllowedAA()
# Set the nativeAA of design residues.
self.setNativeAAtoPdbAA()
# Initiate the currentAA of design residues.
# Try to initiate close to PDB structure
self.mutateNonCatalyticAll(keepNativeAA=True)
self.designInitiated = True
def initiateCatalytic(self, catalytic):
if catalytic is None:
self.catalyticInitiated = False
return
if not self.designInitiated:
raise ValueError('Failed during initiating the catalytic residues. Design residues are not initiated yet.')
self.catalyticTargetAA = dict()
for resName, aa in catalytic:
# Check the non-mutable residues
designIndex = self.designDict.get(resName, False)
# If resName is already in design domain, the residue is non-mutable.
if designIndex is not False:
self.noMutate[resName] = designIndex
self.design[designIndex].mutate = False
# Assign the targetAA
if resName in self.noMutate.keys():
poseIndex = self.design[designIndex].poseIndex
nativeAA = self.pose.residue(poseIndex).name1()
# Use native amino acid and native rotamer
if aa[0] in DesignDomainWildCards('frozen'):
self.catalyticTargetAA[resName] = list(nativeAA)
self.design[designIndex].allowedAA = list(nativeAA)
self.catalyticAction[resName] = 'NATRO'
self.design[designIndex].designAction = 'NATRO'
self.design[designIndex].currentAction = 'NATRO'
# Use native amino acid but calculate rotamer
elif aa[0] in DesignDomainWildCards('noneMutablePackable'):
self.catalyticTargetAA[resName] = list(nativeAA)
self.design[designIndex].allowedAA = list(nativeAA)
self.catalyticAction[resName] = 'PIKAA'
self.design[designIndex].designAction = 'PIKAA'
self.design[designIndex].currentAction = 'PIKAA'
# New amino acid and calculate rotamer
else:
self.catalyticTargetAA[resName] = list(aa)
self.design[designIndex].allowedAA = list(aa)
self.catalyticAction[resName] = 'PIKAA'
self.design[designIndex].designAction = 'PIKAA'
self.design[designIndex].currentAction = 'PIKAA'
# Ambiguous residues where catalytic residues that are not defined yet (RES1, ...)
# Presence of Ambiguous residues indicate catalytic design
else:
self.catalyticDesign = True
self.catalyticTargetAA[resName] = list(aa)
self.catalyticAction[resName] = 'PIKAA'
# Check for non-mutable that are not in design residues
if re.match('ZZ', aa[0]):
raise ValueError('residue {} is declared non mutable but could not be found in the design domain'.
format(resName))
# Assign the number of catalytic residues
self.nCatalyticResidues = len(self.catalyticTargetAA)
self.nNoMutateCatalyticResidues = len(self.noMutate)
# initiate
if self.catalyticDesign:
# If it is a catalytic design, initial choice of the Ambiguous catalytic residues
# is assigned by random
self.mutateCatalyticAll()
# If no Ambiguous catalytic residues is given, the positions are already known
# just initiate catalytic list, catalyticDict and set the currentAA
else:
self.catalytic = list()
self.catalyticDict = dict()
for catalyticResName, catalyticResAA in self.catalyticTargetAA.items():
index = self.designDict[catalyticResName]
self.catalytic.append(index)
self.design[index].catalyticName = copy.deepcopy(catalyticResName)
self.design[index].currentAA = copy.deepcopy(catalyticResAA)
for index in self.catalytic:
# Get the catalytic residues Names
name = copy.deepcopy(self.design[index].catalyticName)
self.catalyticDict[name] = index
self.catalyticInitiated = True
def initiateConstraints(self, constraints):
if constraints == None:
self.constraintInitiated = False
return
elif type(constraints) != list:
raise ValueError('failed during initiating constraints. Only list of constraint(s) is allowed.')
elif not all(map(lambda constraint: isinstance(constraint, BaseConstraint), constraints)):
raise ValueError('failed during initiating constraints. Only list of constraint(s) is allowed.')
else:
self.constraints = constraints
self.constraintInitiated = True
def setPoseIndex(self):
posInfo = self.pose.pdb_info()
for res in self.design:
res.poseIndex = posInfo.pdb2pose(res.chain, res.ID)
# TODO ADD LOGGING
# print((res.chain, res.poseIndex, res.ID), pose.residue(res.poseIndex).name1())
def getNonCatalyticPoseIndex(self):
nonCatalyticPoseIndex = list()
for res in self.design:
if res.catalyticName:
continue
else:
nonCatalyticPoseIndex.append(res.poseIndex)
return nonCatalyticPoseIndex
def setAllowedAA(self):
"""
Calculates acceptable AA composition for a given site(s) based on
solvent-accessible surface area (SASA) ans secondary structure (SSE)
:param pdbFile:
:param residueList:
:return:
"""
# Ref: https://github.com/sarisabban/RosettaDesign
# Ref: https://doi.org/10.1371/journal.pone.0080635
# Ref: The Molecules of Life: Physical and Chemical Principles. Page 216.
# Get the pdb file out of the pose
posePdb = ostringstream()
self.pose.dump_pdb(posePdb)
pdbFile = StringIO(posePdb.str())
# Get the PDB file
pdb = PDBFile.read(pdbFile)
pdbStruc = pdb.get_structure()[0]
# Amino acids properties
aminoAcids = AminoAcids()
# Calculate SASA
atomsSASA = sasa(pdbStruc, vdw_radii="Single")
strucSASA = apply_residue_wise(pdbStruc, atomsSASA, sum)
# Calculate SSE
strucSSE = annotate_sse(pdbStruc, pdbStruc.chain_id)
# Calculate the AA compositions
for res in self.design:
# Get the pdb restype if XX+ or ZX.
# The allowedAA will be updated later for catalytic residues.
nativeAA = None
if res.allowedAA[0] in DesignDomainWildCards('nativePlus'):
nativeAA = self.pose.residue(res.poseIndex).name1()
# Calculate the aa compositions
if res.allowedAA[0] in DesignDomainWildCards('mutable'):
resIndex = res.poseIndex - 1 # The index in Biotite starts from 0, while in PyRosetta starts from 1
resName = pdbStruc.res_name[0]
resRASA = strucSASA[resIndex] / aminoAcids.maxSASA3(resName) # RASA refers to the relative SASA
resSSE = strucSSE[resIndex]
# label res based on RASA
if resRASA <= 0.25:
resRASA = 'C'
elif 0.25 < resRASA < 0.75:
resRASA = 'B'
elif resRASA >= 0.75:
resRASA = 'S'
# get the AA composition
if resRASA == 'S' and resSSE == 'c':
aa = list('PGNQSTDERKH')
elif resRASA == 'S' and resSSE == 'a':
aa = list('EHKQR')
elif resRASA == 'S' and resSSE == 'b':
aa = list('DEGHKNPQRST')
elif resRASA == 'B' and resSSE == 'c':
aa = list('ADEFGHIKLMNPQRSTVWY')
elif resRASA == 'B' and resSSE == 'a':
aa = list('ADEHIKLMNQRSTVWY')
elif resRASA == 'B' and resSSE == 'b':
aa = list('DEFHIKLMNQRSTVWY')
elif resRASA == 'C' and resSSE == 'c':
aa = list('AFGILMPVWY')
elif resRASA == 'C' and resSSE == 'a':
aa = list('AFILMVWY')
elif resRASA == 'C' and resSSE == 'b':
aa = list('FILMVWY')
res.allowedAA = aa
res.designAction = "PIKAA"
res.currentAction = "PIKAA"
# Add the native AA if asked
if nativeAA is not None and nativeAA not in res.allowedAA:
res.allowedAA.append(nativeAA)
# Assign the native
elif res.allowedAA[0] in ['ZX']:
res.allowedAA = [nativeAA]
res.designAction = "PIKAA"
res.currentAction = "PIKAA"
elif res.allowedAA[0] in ['ZZ']:
res.allowedAA = [nativeAA]
res.designAction = "NATRO"
res.currentAction = "NATRO"
elif res.allowedAA[0] in DesignDomainWildCards('aminoAcids'):
res.allowedAA = aminoAcids.selection(res.allowedAA[0])
res.designAction = "PIKAA"
res.currentAction = "PIKAA"
else:
res.designAction = "PIKAA"
res.currentAction = "PIKAA"
def setNativeAAtoPdbAA(self):
""" Set the native AA based on given pose"""
for res in self.design:
res.nativeAA = self.pose.residue(res.poseIndex).name1()
def setCurrentAAtoPdbAA(self):
for res in self.design:
res.currentAA = self.pose.residue(res.poseIndex).name1()
def mutateNonCatalyticToNativeAA(self):
#self.activeResidues = list()
for index, res in enumerate(self.design):
if res.catalyticName:
continue
res.currentAA = res.nativeAA
res.currentAction = res.designAction
res.active = True
self.activeResidues.append(index)
def mutateNonCatalyticToAllowedAA(self, poseIndices=()):
#self.activeResidues = list()
designIndex = list()
for poseIndex in poseIndices:
resID, resChain = self.pose.pdb_info().pose2pdb(poseIndex).split()
designIndex.append(self.designDict[(int(resID), resChain)])
#print(MPI.COMM_WORLD.Get_rank(), 'previous: ', self.currentNoneCatalyticMutants, 'current: ', designIndex)
# first stage the previous mutated residue(s) for mutation again. Gives them a chance to recover if possible.
for index in self.currentNoneCatalyticMutants:
res = self.design[index]
# Skip the previous ones that are now assigned to catalytic
if res.catalyticName:
continue
res.currentAA = ''.join(res.allowedAA)
res.currentAction = res.designAction
res.active = True
self.activeResidues.append(index)
# reset the current mutants list and stage the given residues for mutation
self.currentNoneCatalyticMutants = list()
for index, res in enumerate(self.design):
if res.catalyticName:
continue
if index not in designIndex:
continue
self.currentNoneCatalyticMutants.append(index)
res.currentAA = ''.join(res.allowedAA)
res.currentAction = res.designAction
res.active = True
self.activeResidues.append(index)
#string = ''
#string += '{} after non cat: {}\n'.format(MPI.COMM_WORLD.Get_rank(), self.activeResidues)
#print(string)
def mutateNonCatalyticToAla(self):
"""
Set the currentAA of Non-catalytic residues to AA
"""
#self.activeResidues = list()
for index, res in enumerate(self.design):
if res.catalyticName:
continue
res.currentAA = ['A']
res.currentAction = 'PIKAA'
res.designAction = 'PIKAA'
res.active = True
self.activeResidues.append(index)
def mutateNonCatalyticAll(self, keepNativeAA=True, setNonCatalyticTo='One'):
"""
Initiate the currentAA of nonCatalytic resides randomly from allowedAA.
If keepNativeAA is True, the pdb res type is chosen if it is among allowed res.
:param keepNativeAA:
"""
if setNonCatalyticTo not in ['One', 'All']:
raise ValueError('Bad setNonCatalyticTo parameter, expected one of [One, All] received {}'.format(setNonCatalyticTo))
# reset the list of current mutants at the beginning of initiation
self.currentNoneCatalyticMutants = list()
for index, res in enumerate(self.design):
# Ignore catalytic residues.
# Note: In the design initiation all residue are non catalytic.
if res.catalyticName:
continue
res.active = True
self.activeResidues.append(index)
# Try to set the currentAA to keepNativeAA if it is allowed.
if keepNativeAA and res.nativeAA in res.allowedAA:
res.currentAA = list(res.nativeAA[0])
res.currentAction = res.designAction
# if not keepNativeAA or not found in allowedAA mutate
else:
self.currentNoneCatalyticMutants.append(index)
if setNonCatalyticTo == 'One':
nallowedAA = len(res.allowedAA)
indexAA = randint(0, nallowedAA, 1)[0]
res.currentAA = list(res.allowedAA[indexAA])
res.currentAction = res.designAction
elif setNonCatalyticTo == 'All':
res.currentAA = list(res.allowedAA)
res.currentAction = res.designAction
def mutateCatalyticAll(self):
# If Ambiguous catalytic residues present, randomly assign them
if self.catalyticDesign:
# Reset the name of the catalytic residues if exist
for index in self.catalytic:
self.design[index].catalyticName = None
# Clear the previous residues if exist
self.catalytic = list()
self.catalyticDict = dict()
# Pick up random design indices to assign initial choice of the catalytic residues
indices = list()
for i in range(self.nCatalyticResidues - self.nNoMutateCatalyticResidues):
for j in range(10000):
index = randint(0, self.nDesignResidues, 1)[0]
if index not in self.noMutate.values() and index not in indices:
indices.append(index)
break
if j == 9999:
raise ValueError('Failed in randomizeAll. Could not randomize catalytic residue.')
for catalyticResName, catalyticResAA in self.catalyticTargetAA.items():
# If none mutable the residue is already known
if catalyticResName in self.noMutate.keys():
index = self.noMutate[catalyticResName]
# Otherwise, assign a random residue
else:
index = indices.pop()
# Select a the index of a random target AA from catalyticResAA
indexAA = randint(0, len(catalyticResAA), 1)[0]
# Set up the catalytic res info
self.catalytic.append(index)
self.design[index].catalyticName = catalyticResName
self.design[index].currentAA = list(catalyticResAA[indexAA])
self.design[index].currentAction = self.catalyticAction[catalyticResName]
self.design[index].active = True
self.activeResidues.append(index)
# Initiate a dictionary which its values point to the catalytic res for fast access
for index in self.catalytic:
# Get the catalytic residues Names
name = self.design[index].catalyticName
self.catalyticDict[name] = index
def mutateNonCatalyticOne(self, setNonCatalyticTo='All', poseIndex=None):
"""
Randomly select a non-catalytic residue and sets its currentAA to one of its allowedAA by random
"""
if setNonCatalyticTo not in ['One', 'All']:
raise ValueError('Bad setNonCatalyticTo parameter, expected one of [One, All] received {}'.
format(setNonCatalyticTo))
# clear the previous active residues
#for index in self.activeResidues:
# self.design[index].active = False
#self.activeResidues = list()
# Choose a random residue in the design domain
if poseIndex is None:
for i in range(1000):
#nDesignRes = len(self.design)
indexDesign = randint(0, self.nDesignResidues, 1)[0]
# Skip the catalytic residues, only applies to DesignNoneCatalytic
if indexDesign in self.catalytic:
continue
else:
break
# otherwise get the indexDesign from poseIndex
else:
resID, resChain = self.pose.pdb_info().pose2pdb(poseIndex).split()
indexDesign = self.designDict[(int(resID), resChain)]
res = self.design[indexDesign]
nallowedAA = len(res.allowedAA)
self.activeResidues.append(indexDesign)
# Choose a random AA and set the current AA
if nallowedAA > 1:
# print('BBB nonCatalytic: ', self.design[indexDesign].name)
if setNonCatalyticTo == 'One':
indexAA = randint(0, nallowedAA, 1)[0]
res.currentAA = res.allowedAA[indexAA]
res.currentAction = res.designAction
re.active = True
elif setNonCatalyticTo == 'All':
res.currentAA = list(res.allowedAA)
res.currentAction = res.designAction
re.active = True
# Just set it to be active
else:
res.currentAction = res.designAction
re.active = True
if Constants.DEBUG:
printDEBUG(msg=self.state(), rank=MPI.COMM_WORLD.Get_rank())
# TODO frozen non-mutatable residues are treated as PIKAA. No correct. The non-mute is not picked if it has only one targetAA
# TODO All is not active
def mutateCatalyticOne(self, replacePreviousCatalyticWith='A', setPreviousCatalyticNativeAAtoAllowedAA=True):
"""
Randomly select a non-catalytic residue and sets it switch it with one the catalytic residues
by random.
:param replacePreviousCatalyticWith if set to 'A' the currentAA of old catalytic residue is set to Ala
if set to 'One', the currentAA of old catalytic residue is set to randomly
chosen aa from allowedAA
if set to 'All', the currentAA of old catalytic residue is set to allowedAA
"""
# return if nothing to do
if not self.catalyticDesign:
return
#elif self.nNoMutateCatalyticResidues == self.nCatalyticResidues:
# return
# clear the previous active residues
#for index in self.activeResidues:
# self.design[index].active = False
#self.activeResidues = list()
if replacePreviousCatalyticWith not in ['A', 'One', 'All']:
raise ValueError('Bad replacePreviousCatalyticWith parameter, expected one of [A, One, All] received {}'.
format(replacePreviousCatalyticWith))
#string = ''
#string += '{} before cat: {}\n'.format(MPI.COMM_WORLD.Get_rank(), [(i, res.currentAA) for i, res in enumerate(self.design) if res.catalyticName])
# Pick a random index in the catalytic list
# and get its index in the design list
old_index_Found = False
for i in range(1000):
oldCatalyticIndex = randint(0, self.nCatalyticResidues, 1)[0]
oldDesignIndex = self.catalytic[oldCatalyticIndex]
# Accept the move if it is not part of fixed position
if oldDesignIndex not in self.noMutate.values():
catalyticName = self.design[oldDesignIndex].catalyticName
targetAA = self.catalyticTargetAA[catalyticName]
old_index_Found = True
break
# If it is fixed position make sure has multiple target values
elif oldDesignIndex in self.noMutate.values():
catalyticName = self.design[oldDesignIndex].catalyticName
targetAA = self.catalyticTargetAA[catalyticName]
if len(targetAA) > 1:
old_index_Found = True
break
if not old_index_Found:
raise ValueError(' failed in randomizeOne. Could not randomize catalytic residue.')
# Choose a random targetAA in case multiple target AA is given for catalytic residues
#indexAA = randint(0, len(targetAA), 1)[0]
#currentAA = targetAA[indexAA]
# Only mutate the amino acid type if a fixed position is chosen
if oldDesignIndex in self.noMutate.values():
self.design[oldDesignIndex].currentAA = targetAA
self.design[oldDesignIndex].currentAction = 'PIKAA'
self.design[oldDesignIndex].designAction = 'PIKAA'
self.design[oldDesignIndex].active = True
self.activeResidues .append(oldDesignIndex)
else:
new_index_Found = False
for i in range(10000):
newDesignIndex = randint(0, self.nDesignResidues, 1)[0]
if newDesignIndex not in self.catalytic:
new_index_Found = True
break
if not (new_index_Found and old_index_Found):
raise ValueError(' failed in randomizeOne. Could not randomize catalytic residue.')
#string += '{} mutate {}->{}\n'.format(MPI.COMM_WORLD.Get_rank(), oldDesignIndex, newDesignIndex)
# print('BBB Catalytic', catalyticName, ' from ', self.design[oldDesignIndex].name, ' to ', self.design[newDesignIndex].name)
# Update the catalytic res names
self.design[newDesignIndex].catalyticName = catalyticName
self.design[oldDesignIndex].catalyticName = None
# Update currentAA and currentAction
self.design[newDesignIndex].currentAction = self.catalyticAction[catalyticName]
self.design[newDesignIndex].currentAA = ''.join(targetAA)
# Set the new active residue list
self.design[newDesignIndex].active = True
self.design[oldDesignIndex].active = True
self.activeResidues.append(oldDesignIndex)
self.activeResidues.append(newDesignIndex)
if replacePreviousCatalyticWith == 'A':
self.design[oldDesignIndex].currentAA = ['A']
self.design[oldDesignIndex].currentAction = 'PIKAA'
self.design[oldDesignIndex].designAction = 'PIKAA'
elif replacePreviousCatalyticWith == 'One':
nAllowedAA = len(self.design[oldDesignIndex].allowedAA)
indexAA = randint(0, nAllowedAA, 1)[0]
self.design[oldDesignIndex].currentAA = list(self.design[oldDesignIndex].allowedAA[indexAA])
self.design[oldDesignIndex].currentAction = 'PIKAA'
self.design[oldDesignIndex].designAction = 'PIKAA'
elif replacePreviousCatalyticWith == 'All':
self.design[oldDesignIndex].currentAA = list(self.design[oldDesignIndex].allowedAA)
self.design[oldDesignIndex].currentAction = 'PIKAA'
self.design[oldDesignIndex].designAction = 'PIKAA'
# This used during recovering the native residues,
if setPreviousCatalyticNativeAAtoAllowedAA:
self.design[oldDesignIndex].nativeAA = list(self.design[oldDesignIndex].allowedAA)
# Update the list of catalytic residues with the index of the new residue
self.catalytic[oldCatalyticIndex] = newDesignIndex
# Update the dictionary
self.catalyticDict[catalyticName] = newDesignIndex
#string += '{} before cat: {}\n'.format(MPI.COMM_WORLD.Get_rank(), [(i, res.currentAA) for i, res in enumerate(self.design) if res.catalyticName])
#print(string)
def clearActive(self):
for index in self.activeResidues:
self.design[index].active = False
self.activeResidues = list()
def getCurrentAASequence(self):
seq = list()
for res in self.design:
seq.extend(res.currentAA)
return ''.join(seq)
def getPdbSequence(self):
seq = list()
for res in self.design:
seq.extend(self.pose.residue(res.poseIndex).name1())
return ''.join(seq)
def getSeuenceDiff(self):
diff = list()
seqCurrent = list()
for res in self.design:
seqCurrent.extend(self.pose.residue(res.poseIndex).name1())
seqCurrent = ''.join(seqCurrent)
#print(self.originalSequence, seqCurrent)
diff = [i for i in range(len(self.originalSequence)) if self.originalSequence[i] != seqCurrent[i]]
return diff
def getCatalyticPoseIndex(self):
catalyticPoseIndex = list()
for index in self.catalytic:
catalyticPoseIndex.append(self.design[index].poseIndex)
return catalyticPoseIndex
def getDesignPoseIndex(self):
designPoseIndex = list()
for res in self.design:
designPoseIndex.append(res.poseIndex)
return designPoseIndex
def isPdbCatalyticSynced(self):
for cataltyName, catalyticDesignIndex in self.catalyticDict.items():
res = self.design[catalyticDesignIndex]
if self.pose.residue(res.poseIndex).name1() not in self.catalyticTargetAA[cataltyName]:
return False
return True
def isPdbNonCatalyticSynced(self):
for res in self.design:
# Ignore catalytic
if res.catalyticName:
continue
if self.pose.residue(res.poseIndex).name1() not in res.currentAA:
return False
return True
def isPdbSynced(self):
for res in self.design:
if self.pose.residue(res.poseIndex).name1() not in res.currentAA:
return False
return True
def updateConstraints(self):
# Clear the previous constraints
cst_remover = ClearConstraintsMover()
cst_remover.apply(self.pose)
# Over the constrains
for cst in self.constraints:
if re.match('B', cst.type, re.IGNORECASE):
self._getBondConstraints(cst)
elif re.match('S', cst.type, re.IGNORECASE):
self._getSequenceConstraints(cst)
else:
raise ValueError("{} constraint is not implemented yet. Coming soon".format(cst.type))
def _getBondConstraints(self, cst):
# Create ambiguous constraints for each constraints group
ambiguous_constraint = AmbiguousConstraint()
# Get the residue index "i"
if cst.res_i in self.catalyticDict.keys():
designIndex_res_i = self.catalyticDict[cst.res_i]
elif cst.res_i in self.designDict.keys():
designIndex_res_i = self.designDict[cst.res_i]
else: # To allow for constraints with residues outside domains
designIndex_res_i = None
# raise ValueError("Could not find res_i {} in constraint {}.".format(cst.res_i, cst.tag))
# Get the residue index "j"
if cst.res_j in self.catalyticDict.keys():
designIndex_res_j = self.catalyticDict[cst.res_j]
elif cst.res_j in self.designDict.keys():
designIndex_res_j = self.designDict[cst.res_j]
else: # To allow for constraints with residues outside domains
designIndex_res_j = None
# raise ValueError("Could not find res_j {} in constraint {}.".format(cst.res_j, cst.tag))
if designIndex_res_i is not None:
i_resID = self.design[designIndex_res_i].poseIndex
else:
i_resID = self.pose.pdb_info().pdb2pose(cst.res_i[1], cst.res_i[0])
if designIndex_res_j is not None:
j_resID = self.design[designIndex_res_j].poseIndex
else:
j_resID = self.pose.pdb_info().pdb2pose(cst.res_j[1], cst.res_j[0])
# Over all possible atom combinations
for atomName_i in cst.atom_i_list:
for atomName_j in cst.atom_j_list:
try:
# Try to add cst only if atoms are available
if self.pose.residue(i_resID).has(atomName_i) and self.pose.residue(j_resID).has(atomName_j):
i_atomID = self.pose.residue(i_resID).atom_index(atomName_i)
j_atomID = self.pose.residue(j_resID).atom_index(atomName_j)
# Set the new constraints
i = pr.AtomID(i_atomID, i_resID)
j = pr.AtomID(j_atomID, j_resID)
func = BoundFunc(cst.lb, cst.hb, cst.sd, cst.tag)
distance_constraint = AtomPairConstraint(i, j, func)
# Add individual constraint to the ambiguous_constraint
ambiguous_constraint.add_individual_constraint(distance_constraint)
except Exception as e:
pass
self.pose.add_constraint(ambiguous_constraint)
def _getSequenceConstraints(self, cst):
for residue, targetAA in cst.res.items():
targetAA = one_to_three(targetAA)
designIndex = self.designDict[residue]
poseIndex = self.design[designIndex].poseIndex
seqCst = ResidueTypeConstraint(poseIndex, str(poseIndex), targetAA, cst.weight * 1)
self.pose.add_constraint(seqCst)
def writeResfile(self, resfileName='.resfile', activeResidues=False):
resfileString = ''
action = ''
with open(resfileName, 'w') as resfile:
resfile.write('NATRO\n')
resfile.write('START\n')
for res in self.design:
# if active residues are True write only active residues
if activeResidues and not res.active:
continue
action = res.currentAction
# Write to the file
if action == 'NATRO':
resfile.write('{} {} {} \n'.format(res.ID, res.chain, action))
else:
resfile.write('{} {} {} {}\n'.format(res.ID, res.chain, action, ''.join(res.currentAA)))
if Constants.DEBUG:
if action == 'NATRO':
resfileString += '{} {} {} \n'.format(res.ID, res.chain, action)
else:
resfileString += '{} {} {} {}\n'.format(res.ID, res.chain, action, ''.join(res.currentAA))
if Constants.DEBUG:
printDEBUG(msg=resfileString, rank=MPI.COMM_WORLD.Get_rank())
def state(self):
state = ''
# state += 'Type: {}\n'.format(self.type)
state += 'Catalytic indices: {}\n'.format(self.catalytic)
state += 'Catalytic Dict: {}\n'.format(self.catalyticDict)
state += 'Catalytic noMutate: {}\n'.format(self.noMutate)
state += 'Catalytic Target AA: {}\n'.format(self.catalyticTargetAA)
state += 'Catalytic Actions AA: {}\n'.format(self.catalyticAction)
state += '------------------------------------------------------------------------------------------------\n'
state += 'Design residues: \n'
for res in self.design:
state += 'ID: {}, chain: {}, designAction: {}, currentAction: {}, CatalyticName: {}, pose Index: {} \n'. \
format(res.ID, res.chain, res.designAction, res.currentAction, res.catalyticName, res.poseIndex)
state += 'Current residues: {}\n'.format(''.join(res.currentAA))
state += 'Native residues: {}\n'.format(''.join(res.nativeAA))
state += 'Allowed residues: {}\n'.format(''.join(res.allowedAA))
state += '------------------------------------------------------------------------------------------------\n'
print('Constraints:')
for index, cst in enumerate(self.constraints):
print('{}, {}'.format(index, cst.show()))
state += '------------------------------------------------------------------------------------------------\n'
return state
def statePretty(self):
print("Design domain with catalytic assignments: ")
for index, res in enumerate(self.design):
resname = (res.ID, res.chain)
print('position: {}'.format(index))
print(' residue: {}'.format(':'.join(map(str, resname))))
print(' Pose Index: {}'.format(res.poseIndex))
if res.catalyticName:
print(' catalytic assignment: {}'.format(res.catalyticName))
if res.catalyticName in self.noMutate:
print(' mutate: False')
else:
print(' mutate: True')
if self.catalyticAction[res.catalyticName] == 'NATRO':
print(' frozen: True')
else:
print(' frozen: False')
print(' allowedAA: {}'.format(''.join(self.catalyticTargetAA[res.catalyticName])))
print(' currentAA: {}'.format(''.join(res.currentAA)))
print(' PDB AA: {}'.format(self.pose.residue(res.poseIndex).name1()))
else:
print(' catalytic assignment: None')
print(' mutate: True')
if res.designAction == 'NATRO':
print(' frozen: True')
else:
print(' frozen: False')
print(' allowedAA: {}'.format(''.join(res.allowedAA)))
print(' currentAA: {}'.format(''.join(res.currentAA)))
print('Constraints:')
for index, cst in enumerate(self.constraints):
print('{}, {}'.format(index, cst.show()))
def stateCatalytic(self):
state = ''
state += 'Catalytic indices: {}\n'.format(self.catalytic)
state += 'Catalytic Dict: {}\n'.format(self.catalyticDict)
state += 'Catalytic noMutate: {}\n'.format(self.noMutate)
state += 'Catalytic Target AA: {}\n'.format(self.catalyticTargetAA)
state += 'Catalytic Actions AA: {}\n'.format(self.catalyticAction)
for designIndex, res in enumerate(self.design):
if not res.catalyticName:
continue
state += 'ID: {}, chain: {}, designAction: {}, currentAction: {}, CatalyticName: {}, pose Index: {} , designIndex {}\n'. \
format(res.ID, res.chain, res.designAction, res.currentAction, res.catalyticName, res.poseIndex, designIndex)
state += 'Current residues: {}\n'.format(''.join(res.currentAA))
state += 'Native residues: {}\n'.format(''.join(res.nativeAA))
state += 'Allowed residues: {}\n'.format(''.join(res.allowedAA))
state += 'Current PDB AA: {}\n'.format(self.pose.residue(res.poseIndex).name1())
state += '------------------------------------------------------------------------------------------------\n'
return state
class ActiveSiteMover(object):
"""Active Site Mover implement medium level algorithms for perturbing the active site (catalytic, non-catalytic) residues"""
def __init__(self, activeSiteDesignMode='MC', mimimizeBackbone=False, activeSiteLoops=1, nNoneCatalytic=5, scratch=''):
# Initiate Rosetta classes
self.taskFactory = TaskFactory()
self.scorefxn = getScoreFunction(mode='fullAtomWithConstraints')
self.scorefxn.set_weight(score_type_from_name('fa_dun'), 0.1)
self.packer = PackRotamersMover()
self.packer.score_function(self.scorefxn)
self.fastRelax = FastRelax(self.scorefxn)
self.activeSiteMinMover = MinMover()
self.activeSiteMinMoveMap = MoveMap()
self.cst_remover = ClearConstraintsMover()
self.proccessName = '{}-{}.resfile'.format(MPI.COMM_WORLD.Get_rank(), os.getpid())
self.resfileName = os.path.join(scratch, self.proccessName)
# Temporary design pose
self.dPoseTemp = DesignPose()
self.dPoseOrig = DesignPose()
self.activeSiteLoops = activeSiteLoops
self.nNoneCatalytic = nNoneCatalytic
# Design mode
self.acticeSiteDesignMode = activeSiteDesignMode # ['MIN', 'MC', 'None']