forked from rpavlovicz/AutoRotLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_rotlib_phi_psi.py
executable file
·1420 lines (1158 loc) · 60.8 KB
/
make_rotlib_phi_psi.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
#!/usr/bin/env python3
##!/Users/rpavlovicz/anaconda3/envs/oepython3/bin/python
##!/usr/bin/env python
import os,sys
import fileinput
import itertools
import argparse
from operator import itemgetter, attrgetter
from collections import defaultdict
from numpy import average, std, linspace, sin, cos, deg2rad, rad2deg, arctan2, sqrt, e
from numpy import pi as PI
from openeye.oechem import *
from openeye.oeomega import *
from openeye.oequacpac import *
from openeye.oeszybki import *
### ALL ANGLES ARE KEPT IN DEGREES FROM 0 TO 360
### MakeRotLibMover.cc uses kbT = 1.4 which they found to reproduce reasonable rotamer probabilities
### for 'noncanonical' LEU compared to Dunbrack LEU
# global
#kbt = 0.616033 ## for T = 37 C = 310 K
kbt = 4.0
# global
class ChiDef:
""" stores information regarding rotamer CHI definitions """
""" including atoms names from the mol_file_to_params_polymer output """
""" as well as symmetry information and ideal torision values """
def __init__(self, atoms):
self.atom_names = atoms # list of chi values
self.symmetry = None # symmetry number
self.ideal_torsions = None # list of expected values
self.semi_rotameric = None # real value of starting value if rotamer is determined semi_rotameric
self.proton_chi = None # currently not used?
def set_symmetry(self, symm_no):
self.symmetry = symm_no
def set_ideal_torsions(self, torsions):
self.ideal_torsions = torsions
def set_semi_rotameric(self, sr):
self.semi_rotameric = sr
class SemiRot:
""" class to aid in the claculation of semirotameric probabilities/distributions """
def __init__(self, chis, probability, stds):
self.chis = chis # list of chi values
self.prob = probability # probability of rotamer
self.stds = stds # list of standard deviations
self.prob_dist = None # list of probabilities over range
self.bins = None # list of rotameric CHI bins
def set_chis(self, new_chis):
self.chis = new_chis
def append_chi(self, new_chi):
self.chis.append(new_chi)
def append_std(self, new_std):
self.stds.append(new_std)
def set_probability(self, prob):
self.probability = prob
def set_prob_dist(self, prob_distribution):
self.prob_dist = prob_distribution
def set_std_devs(self, std_dev_list):
self.stds = std_dev_list
def set_bins(self, bin_list):
self.bins = bin_list
class Rotamer:
""" stores rotamer chi values and minimized energy """
### TODO? make sure chis is a list and all entries are of the same length ###
def __init__(self, chis, energy):
self.chis = chis # list of chi values
self.energy = energy # minimized energy of computed rotamer
self.cluster_id = None # id of closest centroid
self.centroid_distances = None # the distance to each centroid
self.ncentroids = None # only assigned to Rotamers[0]
self.boltzmann_weight = None # boltzmann-weighted probability based on current cluster
self.bins = None # list of 4 bin values, originally only assoicated with centroids
self.stds = None # standard deviations for each chi value
self.conf = None # energy-minimzied OEConfBase object that defines this Rotamer object
self.initial_chis = None # list of initial CHI values used to get chis after Szybki minimization
def set_chis(self, chi_list):
self.chis = chi_list
def set_cent_dist(self, cent_distances):
self.centroid_distances = cent_distances
def set_cluster_id(self, clust_id):
self.cluster_id = clust_id
def set_ncentroids(self, ncent):
self.ncentroids = ncent
def set_boltzmann_weight(self, boltz):
self.boltzmann_weight = boltz
def set_bins(self, bin_list):
self.bins = bin_list
def set_stds(self, std_list):
self.stds = std_list
def set_conf(self, min_conf):
self.conf = min_conf
def set_initial_chis(self, initial_chi_list):
self.initial_chis = initial_chi_list
def pad_list_with_zeros( inlist, final_length ):
while len(inlist) < final_length:
inlist.append(0)
return inlist
def circ_mean( angles ):
""" compute circular mean of input list of angles (in degrees) """
x = 0; y = 0
for angle in angles:
x += sin(deg2rad(angle))
y += cos(deg2rad(angle))
final_ave = rad2deg(arctan2(x,y))
### keep return value in range of 0 to 360
if final_ave < 0:
return final_ave+360.0
else:
return final_ave
def weighted_circ_mean( rotamers, chi_index ):
""" compute weighted circular mean for given list of rotamers and chi_index """
""" rotamers[x].chis is expected to be in degrees """
x = 0; y = 0
for rotamer in rotamers:
x += sin(deg2rad(rotamer.chis[chi_index]))*rotamer.boltzmann_weight
y += cos(deg2rad(rotamer.chis[chi_index]))*rotamer.boltzmann_weight
final_ave = rad2deg(arctan2(x,y))
### keep return value in range of 0 to 360
if final_ave < 0:
return final_ave+360.0
else:
return final_ave
def circ_mean_symm( angles, symm_no ):
""" compute circular mean of input list of angles (in degrees) """
### compute two means
### 1.) normal circular mean
### 2.) circular mean for data wrapped from 0->180 to -90->90 or -60->60
### return the value for the mean with the smallest average distance of all data to centroid
### 1.) normal circular mean
x = 0; y = 0
for angle in angles:
x += sin(deg2rad(angle))
y += cos(deg2rad(angle))
final_ave = rad2deg(arctan2(x,y))
if final_ave < 0:
final_ave_1 = final_ave+360.0
else:
final_ave_1 = final_ave
dist_1 = [ angle_dist( angle, final_ave_1, symm_no ) for angle in angles ]
### 2.) circular mean for data wrapped from -90->90 or -60->60
new_angles = [wrap_angle(angle, -180/float(symm_no), 180/float(symm_no), symm_no) for angle in angles]
x = 0; y = 0
for angle in new_angles:
x += sin(deg2rad(angle))
y += cos(deg2rad(angle))
final_ave = rad2deg(arctan2(x,y))
if final_ave < 0:
final_ave_2 = final_ave+360.0/float(symm_no)
else:
final_ave_2 = final_ave
dist_2 = [ angle_dist( angle, final_ave_2, symm_no ) for angle in angles ]
if average(dist_1) < average(dist_2):
return final_ave_1
else:
return final_ave_2
def weighted_circ_mean_symm( rotamers, chi_index, symm_no ):
""" compute weighted circular mean for given list of rotamers and chi_index """
## TODO: try to merge weighted and normal circ_mean_symm
## TODO: also try to merge with non-symm version
### compute two means
### 1.) normal circular mean
### 2.) circular mean for data wrapped from 0->180 to -90->90 or -60->60
### return the value for the mean with the smallest average distance of all data to centroid
angles = [ rotamer.chis[chi_index] for rotamer in rotamers ]
### 1.) normal circular mean
x = 0; y = 0
for rotamer in rotamers:
x += sin(deg2rad(rotamer.chis[chi_index]))*rotamer.boltzmann_weight
y += cos(deg2rad(rotamer.chis[chi_index]))*rotamer.boltzmann_weight
final_ave = rad2deg(arctan2(x,y))
if final_ave < 0:
final_ave_1 = final_ave+360.0
else:
final_ave_1 = final_ave
dist_1 = [ angle_dist( angle, final_ave_1, symm_no ) for angle in angles ]
### 2.) circular mean for data wrapped from -90->90 if symm_no == 2
### or wrapped from -60->60 if symm_no == 3
new_angles = [wrap_angle(angle, -180/float(symm_no), 180/float(symm_no), symm_no) for angle in angles]
x = 0; y = 0
for rotamer in rotamers:
wrapped_angle = wrap_angle(rotamer.chis[chi_index], -180/float(symm_no), 180/float(symm_no), symm_no)
x += sin(deg2rad( wrapped_angle ))*rotamer.boltzmann_weight
y += cos(deg2rad( wrapped_angle ))*rotamer.boltzmann_weight
final_ave = rad2deg(arctan2(x,y))
if final_ave < 0:
final_ave_2 = final_ave+360.0/float(symm_no)
else:
final_ave_2 = final_ave
dist_2 = [ angle_dist( angle, final_ave_2, symm_no ) for angle in angles ]
if average(dist_1) < average(dist_2):
return final_ave_1
else:
return final_ave_2
def wrap_angle(angle_in, min_val, max_val, symm_no):
""" return angle in range of [min_val,max_val) """
if max_val < min_val:
sys.exit('error: angle range of %f to %f is not valid'%(min_val,max_val))
new_angle = angle_in
while new_angle < min_val:
new_angle += 360/float(symm_no)
while new_angle >= max_val:
new_angle -= 360/float(symm_no)
return new_angle
def periodic_range( angle_in ):
""" return angle in range of [-180,180) """
if ( angle_in >= 180.0 ):
return angle_in-360
elif ( angle_in < -180 ):
return angle_in+360
else:
return angle_in
def check_angle_range( angle_in, boundary ):
""" make sure angle is within range of 0.0 to boundary """
""" normally boundary is 360, but for symmetric cases, """
""" boundary may be 180 or 120 if C2 or C3 symmetry """
if ( angle_in < 0.0 ) or ( angle_in > boundary ):
return False
else:
return True
def angle_dist( angle1, angle2, symm_no = 1 ):
""" calculate dis return atan( x/y )tance between two angles """
""" angles should be between 0 and 360 """
wrap_boundary = 360/symm_no
if not check_angle_range( angle1, wrap_boundary ):
sys.exit('ERROR: angle_dist requires angles to be within 0.0 and %i.0. input angle = %6.1f'%(wrap_boundary,angle1))
elif not check_angle_range( angle2, wrap_boundary ):
sys.exit('ERROR: angle_dist requires angles to be within 0.0 and %i.0. input angle = %6.1f'%(wrap_boundary,angle2))
d1 = abs(angle1-angle2)
d2 = wrap_boundary-d1
return d1 if d1<d2 else d2
def calc_rot_dist( rot1, rot2, chi_defs ):
""" calculate distance between two rotamers """
""" this is the squared mean distance between chi values """
""" use chi_defs only for symmetry information """
### make sure number of chis is the same beween rot1 and rot2
if len(rot1.chis) != len(rot2.chis):
sys.exit('ERROR: unequal number of CHI values between %s and %s'%(rot1.chis,rot2.chis))
### also assure number of chi_defs is the same as the number of chis in each rotamer
### although this doesn't necessarily have to be true in the case of a proton chi that is not parameterized?
if len(rot1.chis) != len(chi_defs):
sys.exit('ERROR: number of torsions in rotamer != number of CHI definitions')
square_distance = 0
for x in range(len(rot1.chis)):
if chi_defs[x].symmetry == 2:
### in case of symmetric torsion, compute two angle distances
### d1 = normal distance with wrapping around 0/360 boundary
### d2 = distance with wrapping around 0/180 C2 boundary
d1 = angle_dist(rot1.chis[x], rot2.chis[x])**2
d2 = angle_dist(rot1.chis[x], rot2.chis[x], 2)**2
square_distance += min(d1,d2)
elif chi_defs[x].symmetry == 3:
d1 = angle_dist(rot1.chis[x], rot2.chis[x])**2
d2 = angle_dist(rot1.chis[x], rot2.chis[x], 3)**2
square_distance += min(d1,d2)
else:
square_distance += angle_dist(rot1.chis[x], rot2.chis[x])**2
return sqrt( square_distance/float(len(rot1.chis)) )
def calc_all_dist( rotamers, centroids, chi_defs ):
""" calculate distance between all rotamers and all centroid positions """
""" store this info in the Rotamers class for later centroid assignment """
""" chi_defs used only for symmetry information """
### set number of centroids in rotamers
if rotamers[0].ncentroids == None:
rotamers[0].set_ncentroids( len(centroids) )
else:
if rotamers[0].ncentroids != len(centroids):
sys.exit('ERROR: attempting to recalculate centroid distances for number of cluster centers differing from previous calculation')
for rotamer in rotamers:
distances = []
for centroid in centroids:
distances.append( calc_rot_dist( rotamer, centroid, chi_defs ) )
rotamer.set_cent_dist(distances)
def assign_cluster_number( rotamers ):
""" assign a cluster for each rotamer in rotamers """
""" based on closest distance to a centroid position calculated in calc_all_dist """
for rotamer in rotamers:
rotamer.set_cluster_id( min(enumerate(rotamer.centroid_distances), key=itemgetter(1))[0] )
def calc_boltzmann_weights( rotamers ):
""" calculate boltzmann-weighted probability for each rotamer """
""" where partition function is calculated for each cluster """
for x in range(rotamers[0].ncentroids):
cluster_rotamers = [rotamer for rotamer in rotamers if rotamer.cluster_id == x]
if len(cluster_rotamers) == 0: continue # this is usually due to low sampling interval or high number of CHI bins
min_energy = min([rotamer.energy for rotamer in cluster_rotamers])
print('cluster %i has %i members with min_energy = %f'%(x,len(cluster_rotamers),min_energy))
clust_Z = sum([e**(-float(rotamer.energy-min_energy)/float(kbt)) for rotamer in cluster_rotamers])
for rotamer in cluster_rotamers:
rotamer.set_boltzmann_weight( e**(-float(rotamer.energy-min_energy)/float(kbt))/clust_Z )
def calc_cluster_centroids( rotamers, chi_defs ):
""" recenter centroids based on previous assignment """
""" computer probability-weighted average if boltzmann_weight field is filled """
if rotamers[0].cluster_id == None:
sys.exit('ERROR: rotamers have not yet been assigned centroid values')
### TODO? add check if rotamers[0].ncentroids == len(product(*[chi.ideal_torsions for chi in chi_defs]))?
### the use of ncentroids in first member of rotamers is very ugly
### TODO: there can also be problems in that len(rotamers[0].chis) may not == len(chi_defs)
nchi = len(rotamers[0].chis); new_centroids = []
### iterate over centroids numbers and compute avereage chi angles for all cluster current members
for x in range(rotamers[0].ncentroids):
clust_rotamers = [rotamer for rotamer in rotamers if rotamer.cluster_id == x]
new_chis = []
for chi_index in range(nchi):
### check if CHI is symmetric
if (chi_defs[chi_index].symmetry == 2) or (chi_defs[chi_index].symmetry == 3):
if rotamers[0].boltzmann_weight != None:
new_chis.append( weighted_circ_mean_symm( clust_rotamers, chi_index, chi_defs[chi_index].symmetry ) )
else:
new_chis.append( circ_mean_symm( [rotamer.chis[chi_index] for rotamer in clust_rotamers], chi_defs[chi_index].symmetry ) )
else:
### arithmetic mean is not appropriate here due to circular quantities!
### if rotamer.boltzman_weights present, compute weighted circular average
if rotamers[0].boltzmann_weight != None:
new_chis.append( weighted_circ_mean( clust_rotamers, chi_index ) )
### else compute un-weighted circular average
else:
new_chis.append( circ_mean( [rotamer.chis[chi_index] for rotamer in clust_rotamers] ) )
### append new centroid rotamers with empty energy fields
new_centroids.append(Rotamer(new_chis,None))
return new_centroids
def angle_wrap( chi_list ):
""" convert 0-360 chi lists to -180-180 chi lists """
wrapped_data = []
for chi in chi_list:
if chi > 180.0:
wrapped_data.append(chi-360.0)
else:
wrapped_data.append(chi)
return wrapped_data
def get_bin_assignments(chis,torsions):
""" create bin assignments for initial centroids """
if len(chis) > 4:
sys.exit('ERROR: Rosetta cannot handle side chains with more than 4 torsions')
bins = []
for x in range(len(chis)):
bins.append(torsions[x].index(chis[x])+1)
while len(bins) < 4:
bins.append(0)
return bins
def get_torlib(rotlib_file):
""" read torsion library info generated in OE stderr """
""" this includes info on symmetric bonds """
with open(rotlib_file) as f:
torlib = f.readlines()
symmetric_bonds = []
tors = defaultdict(list)
for line in fileinput.input(rotlib_file):
if line.startswith('torsion between'):
ls = line.rsplit()
key = '%s,%s'%(ls[5],ls[7])
tor_list = [float(x) for x in ls[8:]]
tors[key] = tor_list
if line.startswith('Symmetric'):
ls = line.rsplit()
symmetric_bonds.append('%s,%s'%(ls[3],ls[4]))
symmetric_bonds.append('%s,%s'%(ls[4],ls[3]))
return tors, symmetric_bonds
def get_chis( conf, chi_defs, atom_map, symm ):
""" get CHI values from OEConf using atom names defined in chis """
""" return values in degrees between 0 and 360 """
chi_vals = []
for chi in chi_defs:
a = conf.GetAtom( OEHasAtomName(atom_map[ chi.atom_names[0] ]) )
b = conf.GetAtom( OEHasAtomName(atom_map[ chi.atom_names[1] ]) )
c = conf.GetAtom( OEHasAtomName(atom_map[ chi.atom_names[2] ]) )
d = conf.GetAtom( OEHasAtomName(atom_map[ chi.atom_names[3] ]) )
chi_val = OEGetTorsion(conf, a, b, c, d)*180.0/PI
### bring initial chi_val into [0,360)
chi_val = chi_val if chi_val >= 0.0 else chi_val+360.0
# print('chi for %s %s %s %s = %f'%(a.GetName(),b.GetName(),c.GetName(),d.GetName(),chi_val))
### perform symmetry correction here
if symm and (chi.symmetry == 2 or chi.symmetry == 3):
symm_corr_chi = chi_val
while symm_corr_chi > 360/float(chi.symmetry):
symm_corr_chi -= 360/float(chi.symmetry)
chi_vals.append(symm_corr_chi)
else:
chi_vals.append(chi_val)
chi_vals.append(conf.GetEnergy())
return chi_vals
def get_chi_atoms( conf, chi, atom_map ):
""" read atom_map files and return OEAtom object for given chi """
a1 = conf.GetAtom( OEHasAtomName(atom_map[ chi[0] ]) )
a2 = conf.GetAtom( OEHasAtomName(atom_map[ chi[1] ]) )
a3 = conf.GetAtom( OEHasAtomName(atom_map[ chi[2] ]) )
a4 = conf.GetAtom( OEHasAtomName(atom_map[ chi[3] ]) )
return a1, a2, a3, a4
def detect_symmetry( conf, ba1, ba2 ):
""" atoms ba1 and ba2 were determined to be a symmetric bond """
""" ba2 should be the atom that is furthest from the backbone """
""" check how many substituents are on ba2 that are not ba1 """
""" make sure they are the same, then report the number """
""" this should be the symmetry number """
sub = [];
for bond in ba2.GetBonds():
if bond.GetBgn() == ba1 or bond.GetEnd() == ba1: continue
elif bond.GetBgn() == ba2:
sub.append(bond.GetEnd().GetType())
else:
sub.append(bond.GetBgn().GetType())
print('atom types bound to %s = '%(ba2.GetName()),sub)
if len(sub) == sub.count(sub[0]):
print(' identified bond with %i-fold symmetry'%(len(sub)))
return len(sub)
elif (ba2.GetType() == "N.pl3") and ("O.3" in sub) and ("O.2" in sub) and (len(sub) == 2):
print(' identified nitro group with 2-fold symmetry')
return 2
else:
sys.exit('found more than one type of substituent extending from "symmetric" bond')
def get_final_rotamers( rotamers, centroids ):
""" from Rotamer set, and initial centroids (for # and bin info of final rotamers) """
""" get lowest energy conformer per cluster and calculate probabilities """
final_rotamers = []
Z = 0 ### partition function for probability calculation
for x in range(len(centroids)):
### get conformer info for those clustered into cluster_id x
energies = [ [rotamer.energy, rotamer.centroid_distances[x], rotamer.chis, rotamer.conf] for rotamer in rotamers if rotamer.cluster_id == x]
### check if a cluster_id has no members, if so, create a dummy rotamer for this id with ideal CHI angles and zero probability
if len(energies) == 0:
### make this a warning -- assign chi bin cluster to ideal values with 0 probability
dummy_rot = Rotamer(list(centroids[x].chis),1e6)
dummy_rot.set_bins( centroids[x].bins )
dummy_rot.set_boltzmann_weight( 0.0 )
final_rotamers.append(dummy_rot)
print('WARNING: found cluster with no members')
else:
### sort by energies, with distance from centroid as second sorting criteria
energies.sort()
rot_chis = energies[0][2]; rot_energy = energies[0][0]
final_rotamers.append(Rotamer(rot_chis,rot_energy))
final_rotamers[-1].set_conf(energies[0][3])
final_rotamers[-1].set_bins( centroids[x].bins )
Z += e**(-float(rot_energy)/float(kbt))
min_energy = min([rotamer.energy for rotamer in final_rotamers])
Z = sum([e**(-float(rotamer.energy-min_energy)/float(kbt)) for rotamer in final_rotamers])
for rotamer in final_rotamers:
rotamer.set_boltzmann_weight( e**(-float(rotamer.energy-min_energy)/float(kbt)) / Z )
return final_rotamers
def get_std_devs( mol, chi_vals, chi_defs, cut_bonds, cut_bonds_2, atom_map ):
""" compute std_dev for all chis """
### create single point SZYBKI object for rescoring conformers
szybOpts_sp = OESzybkiOptions()
szybOpts_sp.SetRunType(OERunType_SinglePoint)
szybOpts_sp.GetGeneralOptions().SetForceFieldType(OEForceFieldType_MMFF94S) # MMFF94S, MMFF94, MMFF_AMBER, MMFFS_AMBER
szybOpts_sp.GetSolventOptions().SetSolventModel(OESolventModel_Sheffield) # Sheffield, NoSolv
szybOpts_sp.GetSolventOptions().SetSolventDielectric(3.0)
szybOpts_sp.GetSolventOptions().SetChargeEngine(OEChargeEngineNoOp())
sz_sp = OESzybki(szybOpts_sp)
sz_results_sp = OESzybkiResults()
### compute std_dev for all chis of an input conformation
std_devs = []
for x in range(len(chi_vals)):
### for each CHI, start with the original conformation
### requires creating copy of original mol, otherwise maintains final state of CHI sweep
mol_copy = mol.CreateCopy()
conf = mol_copy.GetActive()
### TODO: check that phi/psi are set correctly!!!
### get atoms that are part of the CHI torsion to be sampled
### read in from ChiDefs (Rosetta naming) using atom_map to convert to OE naming
a = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[x].atom_names[0] ]) )
b = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[x].atom_names[1] ]) )
c = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[x].atom_names[2] ]) )
d = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[x].atom_names[3] ]) )
initial_chi = conf.GetTorsion(a,b,c,d)*180/PI
initial_energy = conf.GetEnergy()
print('*** initial CHI%i = %6.2f; score = %f'%(x+1,initial_chi,conf.GetEnergy()))
### move CHI by +/- 0.1 degree intervals until
### energy difference >= 0.5 or degree change >= 30.0
### store final degree change and std_dev for CHI
bin_energy_tolerance = 0.5; chi_delta = 0.1
energy_change = 0; y = 0
while (energy_change <= bin_energy_tolerance and y*chi_delta <= 30.0):
y += 1
# + delta degrees
new_chi_plus = initial_chi + chi_delta*y
if (len(cut_bonds_2) > 0) and (chi_defs[x].atom_names[3] == 'N' or chi_defs[x].atom_names[3] == 'NV'):
delete_cut_bonds( conf, cut_bonds_2, atom_map )
elif len(cut_bonds) > 0:
delete_cut_bonds( conf, cut_bonds, atom_map )
conf.SetTorsion(a,b,c,d,new_chi_plus*PI/180.0)
if (len(cut_bonds_2) > 0) and (chi_defs[x].atom_names[3] == 'N' or chi_defs[x].atom_names[3] == 'NV'):
rebuild_cut_bonds( conf, cut_bonds_2, atom_map )
elif len(cut_bonds) > 0:
rebuild_cut_bonds( conf, cut_bonds, atom_map )
sz_sp(conf,sz_results_sp)
energy_change_plus = abs(initial_energy-conf.GetEnergy())
# - delta degrees
new_chi_minus = initial_chi - chi_delta*y
if (len(cut_bonds_2) > 0) and (chi_defs[x].atom_names[3] == 'N' or chi_defs[x].atom_names[3] == 'NV'):
delete_cut_bonds( conf, cut_bonds_2, atom_map )
elif len(cut_bonds) > 0:
delete_cut_bonds( conf, cut_bonds, atom_map )
conf.SetTorsion(a,b,c,d,new_chi_minus*PI/180.0)
if (len(cut_bonds_2) > 0) and (chi_defs[x].atom_names[3] == 'N' or chi_defs[x].atom_names[3] == 'NV'):
rebuild_cut_bonds( conf, cut_bonds_2, atom_map )
elif len(cut_bonds) > 0:
rebuild_cut_bonds( conf, cut_bonds, atom_map )
energy_change_minus = abs(initial_energy-conf.GetEnergy())
energy_change = max([energy_change_plus,energy_change_minus])
print('step %3i: delta = %4.1f; max energy change = %7.4f'%(y,chi_delta*y,energy_change))
print('final energy_change = %4.2f at %4.2f degree change'%(energy_change, chi_delta*y))
std_devs.append(chi_delta*y)
conf.Delete()
while len(std_devs) < 4:
std_devs.append(0)
return std_devs
def get_semirotameric( mol, chis, chi_defs, atom_map, semirange ):
### create single point SZYBKI object for rescoring conformers
szybOpts_sp = OESzybkiOptions()
szybOpts_sp.SetRunType(OERunType_SinglePoint)
szybOpts_sp.GetGeneralOptions().SetForceFieldType(OEForceFieldType_MMFF94S) # MMFF94S, MMFF94, MMFF_AMBER, MMFFS_AMBER
szybOpts_sp.GetSolventOptions().SetSolventModel(OESolventModel_Sheffield) # Sheffield, NoSolv
szybOpts_sp.GetSolventOptions().SetSolventDielectric(3.0)
szybOpts_sp.GetSolventOptions().SetChargeEngine(OEChargeEngineNoOp())
sz_sp = OESzybki(szybOpts_sp)
sz_results_sp = OESzybkiResults()
### create working copy of molecule
mol_copy = mol.CreateCopy()
conf = mol_copy.GetActive()
### set rotameric chi values
for x in range(len(chis)):
a1 = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[x].atom_names[0] ]) )
a2 = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[x].atom_names[1] ]) )
a3 = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[x].atom_names[2] ]) )
a4 = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[x].atom_names[3] ]) )
initial_chi = conf.GetTorsion(a1,a2,a3,a4)*180/PI
conf.SetTorsion(a1,a2,a3,a4,chis[x]*PI/180.0)
### scan semirotmeric range
a1 = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[-1].atom_names[0] ]) )
a2 = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[-1].atom_names[1] ]) )
a3 = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[-1].atom_names[2] ]) )
a4 = conf.GetAtom( OEHasAtomName(atom_map[ chi_defs[-1].atom_names[3] ]) )
energy_distribution = []
for sr_angle in semirange:
conf.SetTorsion(a1,a2,a3,a4,sr_angle*PI/180.0)
sz_sp(conf,sz_results_sp)
energy_distribution.append(conf.GetEnergy())
return energy_distribution
def boltzmann_dist( energy_list ):
""" calculate boltzmann weighted probabilities given a list of energies """
min_energy = min(energy_list)
Z = sum([ e**(-float(energy-min_energy)/float(kbt)) for energy in energy_list ])
return [ e**(-float(energy-min_energy)/float(kbt))/Z for energy in energy_list ]
def delete_cut_bonds( conf, cut_bonds, atom_map ):
### check if bond is in cut_bonds. if so, delete the bond
for bond in conf.GetBonds():
for i,cb in enumerate(cut_bonds):
if bond.GetBgn().GetName() == atom_map[ cb[0] ] and bond.GetEnd().GetName() == atom_map[ cb[1] ]:
conf.DeleteBond(bond)
#print('deleting bond between %s and %s'%(bond.GetBgn().GetName(), bond.GetEnd().GetName()))
OEFindRingAtomsAndBonds(conf)
# add bond order to cb in cut_bonds for when we rebuild later
cut_bonds[i].append(bond.GetOrder())
continue
if bond.GetBgn().GetName() == atom_map[ cb[1] ] and bond.GetEnd().GetName() == atom_map[ cb[0] ]:
conf.DeleteBond(bond)
#print('deleting bond between %s and %s'%(bond.GetBgn().GetName(), bond.GetEnd().GetName()))
OEFindRingAtomsAndBonds(conf)
# add bond order to cb in cut_bonds for when we rebuild later
cut_bonds[i].append(bond.GetOrder())
continue
def rebuild_cut_bonds( conf, cut_bonds, atom_map ):
### rebuild any cut bonds
for cb in cut_bonds:
a1 = conf.GetAtom( OEHasAtomName(atom_map[ cb[0] ]) )
a2 = conf.GetAtom( OEHasAtomName(atom_map[ cb[1] ]) )
conf.NewBond(a1,a2,cb[2]) # cb[2] should be bond order set in delete_cut_bonds
def read_properties(infile):
""" read footer of mol2 files made by charge_and_correct script """
PEPTOID = NMETH = NCYCLE = False
for line in fileinput.input(infile):
if line.startswith('M POLY_PROPERTIES'):
ls = line.rsplit()
fileinput.close()
if 'PEPTOID' in ls:
PEPTOID = True
if 'NMETH' in ls:
NMETH = True
if 'NCYCLE' in ls:
NCYCLE = True
return(PEPTOID,NMETH,NCYCLE)
def check_arg(args=None):
parser = argparse.ArgumentParser(description="create N input files for MakeRotLib, where N = n_phi_bins*n_psi_bins")
parser.add_argument('-n', '--aa_name', required=True, type=str, help='three letter name for residue')
parser.add_argument('--phi', required=True, type=int, help='phi angle')
parser.add_argument('--psi', required=True, type=int, help='psi angle')
parser.add_argument('--omega', required=False, type=int, default=180, help='omega angle')
parser.add_argument('--allow_semirotameric', required=False, type=bool, default=False, help='allow autodetection and generation of semirotameric residue libraries')
parser.add_argument('--test', required=False, type=bool, default=False, help='set 45 degree increments for all chis, print out mol2 of final rotamers')
results = parser.parse_args(args)
return (results.aa_name, results.phi, results.psi, results.omega, results.allow_semirotameric, results.test)
def main(argv=[__name__]):
aa_name, phi, psi, omega, allow_semirotameric, TEST_RUN = check_arg(sys.argv[1:])
### make sure input aa_name is three characters long
if len(aa_name) != 3:
sys.exit('aa_name should be three characters long')
pwd = os.getcwd()
infile = '%s/%s_AM1BCC.mol2'%(pwd,aa_name)
ifs = oemolistream()
if not ifs.open(infile):
OEThrow.Fatal("Unable to open %s for reading" % infile)
workdir = os.path.dirname(infile)
print('workdir = %s'%(workdir))
workdir = '.'
PEPTOID, NMETH, NCYCLE = read_properties(infile)
print('PEPTOPID = %s'%(PEPTOID))
print('NMETH = %s'%(NMETH))
print('NCYCLE = %s'%(NCYCLE))
print('TEST = %s'%(TEST_RUN))
torlib_log = '%s_torlib_OE'%(aa_name)
### make sure torsion library exists
if not os.path.isfile(torlib_log):
sys.exit('could not find torsion library file: %s'%(torlib_log))
### set up Szybki for side chain minimization with fixed backbone
### dependent on single CC(=O)NCC(=O)NC match
szybOpts = OESzybkiOptions()
szybOpts.GetOptOptions().SetOptimizerType(OEOptType_SD) # options = OEOptType_NEWTON, OEOptType_BFGS, OEOptType_CG, OEOptType_SD, OEOptType_SD_BFGS, SD_CG
szybOpts.GetOptOptions().SetGradTolerance(0.001) # default = 0.1 except for Newton-Raphson = 0.00001
szybOpts.GetGeneralOptions().SetForceFieldType(OEForceFieldType_MMFF94S)
szybOpts.GetSolventOptions().SetSolventModel(OESolventModel_Sheffield) # OESolventModel_Sheffield, OESolvent_NoSolv
szybOpts.GetSolventOptions().SetSolventDielectric(3.0)
szybOpts.GetSolventOptions().SetChargeEngine(OEChargeEngineNoOp())
sz = OESzybki(szybOpts)
sz.FixAtoms("CC(=O)NCC(=O)NC") # N-to-C
sz_results = OESzybkiResults()
### map Rosetta params file atom names [ keys ] to OE names [ values ]
### atom_map file currently created in molfile_to_params_polymer.py
atom_map = {}
for line in fileinput.input('%s/%s.atom_map'%(workdir, aa_name)):
ls = line.rsplit()
atom_map[ ls[1] ] = ls[0]
### get OEOmega torsion library
torlib, symmetric_bonds = get_torlib(torlib_log)
### read CHI definitions from params file
### ChiDef class constitutes atom_names, ideal torsions, and symmetry
### only the names are initially detected upon params file reading
### ideal torsions and symmetry are detected from OE torsion library output
# TODO: detect and define CHI values within OE scripts
chi_defs = []
cut_bonds = []
cut_bonds_2 = []
virtuals = {}
PARAMS_BINS = False
for line in fileinput.input('%s.params'%(aa_name)):
if line.startswith('NAME '):
aa_name = line.rsplit()[1]
if line.startswith('CHI '):
ls = line.rsplit()
print(ls,ls[3],ls[4])
if ls[3] == 'N' and ls[4] == 'CM':
# skip N-methyl group chi
continue
else:
chi_defs.append(ChiDef([ ls[2], ls[3], ls[4], ls[5] ]))
if line.startswith('VIRTUAL_SHADOW'):
virtuals[ line.rsplit()[1] ] = line.rsplit()[2]
if line.startswith('CUT_BOND'):
cut_bonds.append([ line.rsplit()[1], line.rsplit()[2] ])
if line.startswith('NCAA_ROTLIB_NUM_ROTAMER_BINS'):
PARAMS_BINS = True
if len(chi_defs) == 0:
sys.exit('ERROR: no CHI definitions found in params file: %s.params'%(aa_name))
### if we have an N-cyclize AA find the opposing 'cut_bond'
### actually, this should go for any backbone-cyclized AA
if NCYCLE and len(cut_bonds) > 0:
print('verifying cut_bonds:')
N_cut = False
for bond in cut_bonds:
for atom in bond:
if atom == 'N':
N_cut = True
if N_cut == False:
sys.exit('ERROR: could not identify N-cyclizing bond from params file')
for chi in chi_defs:
if chi.atom_names[1] == 'CA':
cut_bonds_2.append( [chi.atom_names[1], chi.atom_names[2]] )
### proton CHI defs
proton_chi_atom_names = []
### get single conf from input OEMol object
### identify backbone and torsions, and assign CHI bins
for mol in ifs.GetOEMols():
single_conf = mol.GetActive()
### assure only one identified instance of ACE/NME-capped backbone
ss = OESubSearch("CC(=O)NCC(=O)NC")
OEPrepareSearch(single_conf,ss)
if not ss.SingleMatch(single_conf):
sys.exit('ERROR: single backbone match not found in input')
### get atoms for setting phi/psi; match results are 0-indexed
for match in ss.Match(single_conf):
for ma in match.GetAtoms():
if ma.pattern.GetIdx() == 0: bb0 = ma.target # n-1 CA (for setting omega angle)
elif ma.pattern.GetIdx() == 1: bb1 = ma.target # n-1 C
elif ma.pattern.GetIdx() == 3: bb2 = ma.target # n N
elif ma.pattern.GetIdx() == 4: bb3 = ma.target # n CA
elif ma.pattern.GetIdx() == 5: bb4 = ma.target # n C
elif ma.pattern.GetIdx() == 7: bb5 = ma.target # n+1 N
elif ma.pattern.GetIdx() == 8: bb6 = ma.target # n+1 CA (for setting omega angle)
for x in range(len(chi_defs)):
print('chidef %i: '%(x+1),chi_defs[x].atom_names)
### match
torsions = []; chi_atom_names = []; del_list = []
print('length of chi_defs = %i'%(len(chi_defs)))
print('\n\nprocessing %s'%(infile))
for x in range(len(chi_defs)):
symmetry = None; skip = 0
print('length of chi_defs = %i'%(len(chi_defs)))
print('chi_defs[%i] = '%(x),chi_defs[x])
c1, c2, c3, c4 = get_chi_atoms(single_conf, chi_defs[x].atom_names, atom_map)
chi_atom_names.append([c1.GetName(), c2.GetName(), c3.GetName(), c4.GetName()])
print('\nCHI%i: center atoms = %s %s'%(x+1,chi_defs[x].atom_names[1],chi_defs[x].atom_names[2]))
print(' corresponds to atom names %s %s'%(atom_map[ chi_defs[x].atom_names[1] ], atom_map[ chi_defs[x].atom_names[2] ]))
idx2 = c2.GetIdx()+1
idx3 = c3.GetIdx()+1
print(' corresponds to atom indices %s %s'%(idx2, idx3))
if ('%s,%s'%(idx2,idx3)) in symmetric_bonds:
print(' *** bond identified as symmetric by OE ***')
symm_no = detect_symmetry(single_conf, c2, c3)
chi_defs[x].set_symmetry(symm_no)
### torsions from library can be defined in either direction, check both
key1 = '%s,%s'%(idx2,idx3); key2 = '%s,%s'%(idx3,idx2)
foundkey = 0
if (c1.GetType() == 'H') or (c4.GetType() == 'H'):
proton_chi_atom_names.append(chi_atom_names[-1])
print(' *** adding proton rotamer: ',chi_defs[x].atom_names)
skip = 1
elif torlib[key1]:
foundkey = key1
elif torlib[key2]:
foundkey = key2
else:
### this should probably be an error?
### or prompt user for input?
### or use default values?
### currently happening when proton torsion is detected in molfile_to_params_polymer
# if (c1.GetType() == 'H') or (c4.GetType() == 'H'):
# proton_chi_atom_names.append(chi_atom_names[-1])
# print(' *** adding proton rotamer: ',chi_defs[x].atom_names)
# skip = 1
if (c2.IsInRing() and c3.IsInRing()):
foundkey = key1 # arbitrarily select key1 over key2
torlib[key1] = [-60.0, 60.0, 180.0]
else:
sys.exit('ERROR: no torsion values found for CHI%s'%(x+1))
if foundkey:
print(' found %s torsions in %s'%(len(torlib[foundkey]),torlib_log))
print(' ',torlib[foundkey])
print(' torsion atom types = %s %s %s %s'%(c1.GetType(),c2.GetType(),c3.GetType(),c4.GetType()))
### check for internal guanadinium torsion and remove from chi list if found
if (c2.GetType() == 'N.pl3' and c3.GetType() == 'C.cat') or (c2.GetType() == 'C.cat' and c3.GetType() == 'N.pl3'):
print(' *** detected torsion in guanadinium group -- removing from CHI list ***')
### TODO: if we get to this point, the .params file needs to be edited to remove this CHI definition
skip = 1
### adjust torsion bin that rotate guanidinium groups
if (c2.GetType() == 'C.3' and c3.GetType() == 'N.pl3' and c4.GetType() == 'C.cat') or (c3.GetType() == 'C.3' and c2.GetType() == 'N.pl3' and c1.GetType() == 'C.cat'):
print(' *** detected torsion rotating guanidinium group -- setting to bin values to -60, 60, 180')
torlib[foundkey] = [-60.0, 60.0, 180.0]
### fix CHI1 if about C.3-C.3 bond -- force -60, 60, 180 bins
### this is a weird case, where OE torsion library wants to define 9 torsions about this angle
### which it defines very generically: 2 7 6 20 [*:1]~[^3:2]-[^3:3]~[*:4]
if chi_defs[x].atom_names[0] == 'N' and c2.GetType() == 'C.3' and c3.GetType() == 'C.3':
print(' *** found CHI1 about sp3 carbon atoms -- adjusting bin values to -60, 60, 180')
torlib[foundkey] = [-60.0, 60.0, 180.0]
### detect if CHI rotates a ring
if c2.IsInRing() and c3.IsInRing():
same_ring = False
nrings, parts = OEDetermineRingSystems(single_conf)
if (parts[c2.GetIdx()] == parts[c3.GetIdx()]):
same_ring = True
if same_ring:
ring_size = OEAtomGetSmallestRingSize(c2)
print('both central torsion atoms are in the same ring')
### if this is CHI1, then set the number of ring confo0rmations
### and keep all other CHI at 0
if x == 0:
if ring_size == 5:
print(' *** setting torsions for chi %i for ring of size %i -- adjusting bin values to -30 and 30'%(x,ring_size))
torlib[foundkey] = [-30.0,30.0]
elif ring_size == 6:
print(' *** setting torsions for chi %i for ring of size %i -- adjusting bin values to -30 and 30'%(x,ring_size))
torlib[foundkey] = [-30.0,30.0]
else:
sys.exit('not yet configured to handle rings of size %i'%(ring_size))
else:
print(' *** setting torsion for chi %i for ring of size %i -- adjusting bin values to 0'%(x,ring_size))
torlib[foundkey] = [0.0]
if ( c3.IsInRing() and c4.IsInRing() ) and not ( c1.IsInRing() and c2.IsInRing() and c3.IsInRing() and c4.IsInRing()):
print(' * this torsion rotates a ring')
if (x+1 == len(chi_defs)) and allow_semirotameric:
print(' *** found terminal CHI rotating a ring; setting to semi-rotameric')
chi_defs[x].set_semi_rotameric(-30.0)
elif (x+1 == len(chi_defs)-1) and allow_semirotameric:
c1_2, c2_2, c3_2, c4_2 = get_chi_atoms(single_conf ,chi_defs[x+1].atom_names, atom_map)
if (c1_2.GetType() == 'H') or (c4_2.GetType() == 'H'):
print(' *** found non-terminal CHI rotating a ring with terminal proton chi; setting to semi-rotameric')
chi_defs[x].set_semi_rotameric(-30.0)
### detect if CHI rotates carboxyl group
if c1.GetType() == 'O.co2':
print(' *** found O.co2 type')
nbrs = [atm.GetType() for atm in c2.GetAtoms() if atm not in [c1, c2, c3, c4]]
if 'O.co2' in nbrs:
print(' *** idenitified torsion rotating a carboxyl group -- adjusting bin values to -60, -30, 0, 30, 60, 90')
torlib[foundkey] = [0.0,30.0,60.0,90.0,120.0,150.0]
if (x+1 == len(chi_defs)) and allow_semirotameric:
print(' *** found terminal carboxylate -- setting CHI to semi-rotameric')
chi_defs[x].set_semi_rotameric(-90.0)
elif c4.GetType() == 'O.co2':