-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcomput_util.py
2190 lines (1887 loc) · 74.2 KB
/
comput_util.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
"""
Copyright (C) <2010> Autin L.
This file ePMV_git/comput_util.py is part of ePMV.
ePMV is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ePMV is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ePMV. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>.
"""
## Automatically adapted for numpy.oldnumeric Apr 10, 2008 by
##
## Copyright (C) The Scripps Research Institute 2006
##
## Authors: Alexandre Gillet <[email protected]>
##
## $Header: /opt/cvs/python/packages/share1.5/Pmv/hostappInterface/comput_util.py,v 1.22 2010/11/30 07:23:01 autin Exp $
## $Id: comput_util.py,v 1.22 2010/11/30 07:23:01 autin Exp $
##
##
## utils function use for computation during pattern detection
import numpy.oldnumeric as Numeric
from MolKit.pdbWriter import PdbWriter
#from MolKit.chargeCalculator import KollmanChargeCalculator,GasteigerChargeCalculator
from PyAutoDock.MolecularSystem import MolecularSystem
from PyAutoDock.AutoDockScorer import AutoDock305Scorer, AutoDock4Scorer
#from PyAutoDock.AutoDockScorer import AutoDockTermWeights305, AutoDockTermWeights4
#from PyAutoDock.trilinterp_scorer import TrilinterpScorer,TrilinterpScorer_AD3
from PyAutoDock.scorer import WeightedMultiTerm
from PyAutoDock.electrostatics import Electrostatics
from PyAutoDock.vanDerWaals import VanDerWaals,HydrogenBonding
#from PyAutoDock.vanDerWaals import HydrogenBonding
from PyAutoDock.desolvation import Desolvation
#import warnings
from MolKit.molecule import Atom
#######################MATH FUNCTION##########################################################
def transformedCoordinatesWithMatrice(mol,matrice):
""" for a nodeset, this function returns transformed coordinates.
This function will use the pickedInstance attribute if found.
@type mol: MolKit node
@param mol: the molecule to be transfromed
@type matrice: 4x4array
@param matrice: the matrix to apply to the molecule node
@rtype: array
@return: the transformed list of 3d points from the molecule atom coordinates
"""
vt = []
#transfo = matrice#Numeric.transpose(Numeric.reshape(pat.mat_transfo,(4,4)))
scaleFactor = 1.#pat.scaleFactor
#for node in nodes:
#find all atoms and their coordinates
coords = mol.allAtoms.coords# nodes.findType(Atom).coords
#g = nodes[0].top.geomContainer.geoms['master']
# M1 = g.GetMatrix(g.LastParentBeforeRoot())
# apply the AR transfo matrix
M = matrice#Numeric.dot(transfo,M1)
for pt in coords:
ptx = (M[0][0]*pt[0]+M[0][1]*pt[1]+M[0][2]*pt[2]+M[0][3]) /scaleFactor
pty = (M[1][0]*pt[0]+M[1][1]*pt[1]+M[1][2]*pt[2]+M[1][3]) /scaleFactor
ptz = (M[2][0]*pt[0]+M[2][1]*pt[1]+M[2][2]*pt[2]+M[2][3]) /scaleFactor
vt.append( (ptx, pty, ptz) )
return vt
def rotatePoint(pt,m,ax):
x=pt[0]
y=pt[1]
z=pt[2]
u=ax[0]
v=ax[1]
w=ax[2]
ux=u*x
uy=u*y
uz=u*z
vx=v*x
vy=v*y
vz=v*z
wx=w*x
wy=w*y
wz=w*z
sa=sin(ax[3])
ca=cos(ax[3])
pt[0]=(u*(ux+vy+wz)+(x*(v*v+w*w)-u*(vy+wz))*ca+(-wy+vz)*sa)+ m[0]
pt[1]=(v*(ux+vy+wz)+(y*(u*u+w*w)-v*(ux+wz))*ca+(wx-uz)*sa)+ m[1]
pt[2]=(w*(ux+vy+wz)+(z*(u*u+v*v)-w*(ux+vy))*ca+(-vx+uy)*sa)+ m[2]
return pt
def matrixToEuler(mat):
"""
code from 'http://www.euclideanspace.com/maths/geometry/rotations/conversions/'
notes : this conversion uses conventions as described on page:
'http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm'
Coordinate System: right hand
Positive angle: right hand
Order of euler angles: heading first, then attitude, then bank
matrix row column ordering:
[m00 m01 m02]
[m10 m11 m12]
[m20 m21 m22]
@type mat: 4x4array
@param mat: the matrix to convert in euler angle (heading,attitude,bank)
@rtype: 3d array
@return: the computed euler angle from the matrice
"""
#Assuming the angles are in radians.
#3,3 matrix m[0:3,0:3]
#return heading,attitude,bank Y,Z,X
import math
if (mat[1][0] > 0.998) : # singularity at north pole
heading = math.atan2(mat[0][2],mat[2][2])
attitude = math.pi/2.
bank = 0
return (heading,attitude,bank)
if (mat[1][0] < -0.998) : # singularity at south pole
heading = math.atan2(mat[0][2],mat[2][2])
attitude = -math.pi/2.
bank = 0
return (heading,attitude,bank)
heading = math.atan2(-mat[2][0],mat[0][0])
bank = math.atan2(-mat[1][2],mat[1][1])
attitude = math.asin(mat[1][0])
if mat[0][0] < 0 :
if (attitude < 0.) and (math.degrees(attitude) > -90.):
attitude = -math.pi-attitude
elif (attitude > 0.) and (math.degrees(attitude) < 90.):
attitude = math.pi-attitude
return (heading,attitude,bank)
def eulerToMatrix(euler): #double heading, double attitude, double bank
"""
code from 'http://www.euclideanspace.com/maths/geometry/rotations/conversions/'.
this conversion uses NASA standard aeroplane conventions as described on page:
'http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm'
Coordinate System: right hand
Positive angle: right hand
Order of euler angles: heading first, then attitude, then bank
matrix row column ordering:
[m00 m01 m02]
[m10 m11 m12]
[m20 m21 m22]
@type euler: 3d array
@param euler: the euler angle to convert in matrice
@rtype: 4x4array
@return: the matrix computed from the euler angle
"""
# Assuming the angles are in radians.
import math
heading=euler[0]
attitude=euler[1]
bank=euler[2]
m=[[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]]
ch = math.cos(heading)
sh = math.sin(heading)
ca = math.cos(attitude)
sa = math.sin(attitude)
cb = math.cos(bank)
sb = math.sin(bank)
m[0][0] = ch * ca
m[0][1] = sh*sb - ch*sa*cb
m[0][2] = ch*sa*sb + sh*cb
m[1][0] = sa
m[1][1] = ca*cb
m[1][2] = -ca*sb
m[2][0] = -sh*ca
m[2][1] = sh*sa*cb + ch*sb
m[2][2] = -sh*sa*sb + ch*cb
return m
rotY90n = Numeric.array([[ 0., 0., 1., 0.],
[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]],'f')
def ApplyMatrix(coords,mat):
"""
Apply the 4x4 transformation matrix to the given list of 3d points
@type coords: array
@param coords: the list of point to transform.
@type mat: 4x4array
@param mat: the matrix to apply to the 3d points
@rtype: array
@return: the transformed list of 3d points
"""
#4x4matrix"
coords = Numeric.array(coords)
one = Numeric.ones( (coords.shape[0], 1), coords.dtype.char )
c = Numeric.concatenate( (coords, one), 1 )
return Numeric.dot(c, Numeric.transpose(mat))[:, :3]
def Decompose4x4(matrix):
"""
Takes a matrix in shape (16,) in OpenGL form (sequential values go
down columns) and decomposes it into its rotation (shape (16,)),
translation (shape (3,)), and scale (shape (3,))
@type matrix: 4x4array
@param matrix: the matrix to decompose
@rtype: list of array
@return: the decomposition of the matrix ie : rotation,translation,scale
"""
m = matrix
transl = Numeric.array((m[12], m[13], m[14]), 'f')
scale0 = Numeric.sqrt(m[0]*m[0]+m[4]*m[4]+m[8]*m[8])
scale1 = Numeric.sqrt(m[1]*m[1]+m[5]*m[5]+m[9]*m[9])
scale2 = Numeric.sqrt(m[2]*m[2]+m[6]*m[6]+m[10]*m[10])
scale = Numeric.array((scale0,scale1,scale2)).astype('f')
mat = Numeric.reshape(m, (4,4))
rot = Numeric.identity(4).astype('f')
rot[:3,:3] = mat[:3,:3].astype('f')
rot[:,0] = (rot[:,0]/scale0).astype('f')
rot[:,1] = (rot[:,1]/scale1).astype('f')
rot[:,2] = (rot[:,2]/scale2).astype('f')
rot.shape = (16,)
#rot1 = rot.astype('f')
return rot, transl, scale
def rotatePoint(pt,m,ax):
"""
rotate a point (x,y,z) arount an axis by alha degree.
@type pt: point
@param pt: the point to rotate
@type m: array
@param m: translation offset to apply after the rotation
@type ax: vector4D
@param ax: axise of rotation (ax[0:3]) and the angle of rotation (ax[3])
@rtype: point
@return: the new rotated point
"""
x=pt[0]
y=pt[1]
z=pt[2]
u=ax[0]
v=ax[1]
w=ax[2]
ux=u*x
uy=u*y
uz=u*z
vx=v*x
vy=v*y
vz=v*z
wx=w*x
wy=w*y
wz=w*z
sa=sin(ax[3])
ca=cos(ax[3])
pt[0]=(u*(ux+vy+wz)+(x*(v*v+w*w)-u*(vy+wz))*ca+(-wy+vz)*sa)+ m[0]
pt[1]=(v*(ux+vy+wz)+(y*(u*u+w*w)-v*(ux+wz))*ca+(wx-uz)*sa)+ m[1]
pt[2]=(w*(ux+vy+wz)+(z*(u*u+v*v)-w*(ux+vy))*ca+(-vx+uy)*sa)+ m[2]
return pt
def norm(A):
"""Return vector norm"""
return Numeric.sqrt(sum(A*A))
def dist(A,B):
"""Return distnce between point A and point B"""
return Numeric.sqrt((A[0]-B[0])**2+(A[1]-B[1])**2+(A[2]-B[2])**2)
def normsq(A):
"""Return square of vector norm"""
return abs(sum(A*A))
def normalize(A):
"""Normalize the Vector A"""
if (norm(A)==0.0) : return A
else :return A/norm(A)
def getCenter(coords):
"""
Get the center from a 3d array of coordinate x,y,z.
@type coords: liste/array
@param coords: the coordinates
@rtype: list/array
@return: the center of mass of the coordinates
"""
coords = Numeric.array(coords)#self.allAtoms.coords
center = sum(coords)/(len(coords)*1.0)
center = list(center)
for i in range(3):
center[i] = round(center[i], 4)
#print "center =", self.center
return center
def computeRadius(protein,center=None):
"""
Get the radius of gyration of a protein.
@type protein: MolKit Protein
@param protein: the molecule
@type center: list/array
@param center: the center of the molecule
@rtype: float
@return: the radius of the molecule
"""
if center == None : center = protein.getCenter()
rs = 0.
for atom in protein.allAtoms:
r = dist(center,atom._coords[0])
if r > rs:
rs = r
return rs
def convertColor(col,toint=True):
"""
This function will convert a color array [r,g,b] from range 1-255
to range 0.-1 (vice/versa)
@type col: array
@param col: the color [r,g,b]
@type toint: boolean
@param toint: way of the convertion, if true convert to 1-255, if false
convert to range 0-1
@rtype: array
@return: the converted color [0-1.,0-1.,0-1.] or [1-255,1-255,1-255]
"""
if toint and max(col)<=1.0: col = [x*255 for x in col]
elif not toint and max(col)>1.0: col = [x/255. for x in col]
return col
DGatomIds=['ASPOD1','ASPOD2','GLUOE1','GLUOE2', 'SERHG',
'THRHG1','TYROH','TYRHH',
'LYSNZ','LYSHZ1','LYSHZ2','LYSHZ3','ARGNE','ARGNH1','ARGNH2',
'ARGHH11','ARGHH12','ARGHH21','ARGHH22','ARGHE','GLNHE21',
'GLNHE22','GLNHE2',
'ASNHD2','ASNHD21', 'ASNHD22','HISHD1','HISHE2' ,
'CYSHG', 'HN']
def lookupDGFunc(atom):
assert isinstance(atom, Atom)
if atom.name in ['HN']:
atom.atomId = atom.name
else:
atom.atomId=atom.parent.type+atom.name
if atom.atomId not in DGatomIds:
atom.atomId=atom.element
return atom.atomId.upper()
def norm(A):
"Return vector norm"
return Numeric.sqrt(sum(A*A))
def dist(A,B):
return Numeric.sqrt((A[0]-B[0])**2+(A[1]-B[1])**2+(A[2]-B[2])**2)
def normsq(A):
"Return square of vector norm"
return abs(sum(A*A))
def normalize(A):
"Normalize the Vector"
if (norm(A)==0.0) : return A
else :return A/norm(A)
def changeR(txt):
from Pmv.pmvPalettes import RasmolAminoSortedKeys
from MolKit.protein import ResidueSetSelector
#problem this residue not in r_keyD
rname = txt[0:3]
rnum = txt[3:]
if rname not in RasmolAminoSortedKeys :#ResidueSetSelector.r_keyD.keys() :
# print(rname)
rname=rname.replace(" ","")
if len(rname) == 1 :
return rname+rnum
elif len(rname) == 0 :
return rname+"X"
return rname[1]+rnum
else :
rname=rname.replace(" ","")
if rname in ResidueSetSelector.r_keyD:
r1n=ResidueSetSelector.r_keyD[rname]
else :
r1n=rname
return r1n+rnum
def restoreR(txt):
from Pmv.pmvPalettes import RasmolAminoSortedKeys
from MolKit.protein import ResidueSetSelector
#problem this residue not in r_keyD
rname = txt
if rname not in ResidueSetSelector.r_keyD.values() :#ResidueSetSelector.r_keyD.keys() :
return rname
else :
for k in ResidueSetSelector.r_keyD:
if rname == ResidueSetSelector.r_keyD[k]:
return k
return rname
def patchRasmolAminoColor():
from Pmv.pmvPalettes import RasmolAmino,RasmolAminoSortedKeys
RasmolAminocorrected=RasmolAmino.copy()
for res in RasmolAminoSortedKeys:
name=res.strip()
if name in ['A', 'C', 'G', 'T', 'U']:
name = 'D'+name
RasmolAminocorrected[name]= RasmolAmino[res]
del RasmolAminocorrected[res]
return RasmolAminocorrected
#######################ENERGY CLASS & FUNCTION##########################################################
class EnergyHandler:
""" object to manage the different energies calculation between set of atoms """
def __init__(self,viewer):
self.viewer = viewer
# list the energies instance to manage
self.data = {} # keys name, values: energie classs instance
self.current_scorer = None
self.realTime = True
def add(self,atomset1,atomset2,score_type='c_ad3Score',**kw):
""" a pairs of atoms to get energies between them
should be receptor ligan
"""
# make name from molecule name of each atom set instance
n1 = atomset1.top.uniq()[0].name
n2 = atomset2.top.uniq()[0].name
n = n1+'-'+n2+'-'+score_type
if self.viewer.hasGui : self.viewer.infoBox.Set(visible=True)
# we test if energy scorer already been setup
if n in self.data:
self.current_scorer = self.data[n]
return self.data[n]
# we create a energy scorer for pairs of atoms
if score_type == 'PairWise':
nrg = PairWiseEnergyScorer(atomset1,atomset2)
elif score_type == 'Trilinterp':
nrg = TrilinterpEnergyScorer(atomset1,atomset2,stem=kw.get('stem'),atomtypes=kw.get('atomtypes'))
elif score_type == 'TrilinterpAD3':
nrg = TrilinterpEnergyScorerAD3(atomset1,atomset2,stem=kw.get('stem'),atomtypes=kw.get('atomtypes'))
elif score_type == 'PyPairWise':
nrg = PyPairWiseEnergyScorer(atomset1,atomset2)
elif score_type == 'ad3Score':
nrg = PyADCalcAD3Energies(atomset1,atomset2)
elif score_type == 'ad4Score':
nrg = PyADCalcAD4Energies(atomset1,atomset2)
elif score_type == 'c_ad3Score':
nrg = cADCalcAD3Energies(atomset1,atomset2)
elif score_type == 'c_ad4Score':
nrg = cADCalcAD4Energies(atomset1,atomset2)
self.data[n]=nrg
self.current_scorer = nrg
if self.viewer.hasGui:
self.viewer.GUI.nrg_pairs_combobox.setlist(list(self.data.keys()))
self.viewer.GUI.nrg_pairs_combobox.setentry(list(self.data.keys())[0])
return nrg
def reset(self):
""" delete all the atoms pairs """
self.current_scorer = None
if self.viewer.hasGui:
self.viewer.GUI.nrg_pairs_combobox.setlist(list(self.data.keys()))
## ATTENTION the following code do create a segmentation fault
## FIX ME AG 04/2007
## # free up allocate memory for each nengy scorer
## for scorer in self.data.values():
## scorer.free_memory()
## del(scorer)
## self.data.clear()
def compute_energies(self):
""" retrieve the score for each pairs """
sc = self.current_scorer
if sc is None: return
#if sc.mol1 in self.viewer.mol_detected.keys() and sc.mol2 in self.viewer.mol_detected.keys():
score,estat,hbond,vdw,ds = sc.doit()
from Pmv.moleculeViewer import EditAtomsEvent
#editAtom event ? just to check ?
#event = EditAtomsEvent('coords', sc.mol2.allAtoms)
#self.viewer.dispatchEvent(event)
if self.viewer.hasGui:
self.viewer.infoBox.update_entry(score=score,estat=estat,hbond=hbond,
vdw=vdw,ds=ds)
return True
def save_conformations(self):
for nrg in list(self.data.values()):
nrg.saveCoords()
cAD=True
try:
from cAutoDock import scorer as c_scorer
from memoryobject import memobject
except:
cAD = False
memobject = None
c_scorer = None
class EnergyScorer:
""" Base class for energie scorer """
def __init__(self,atomset1,atomset2,func=None):
self.atomset1 =atomset1
self.atomset2 =atomset2
# save molecule instance of parent molecule
self.mol1 = self.atomset1.top.uniq()[0]
self.mol2 = self.atomset2.top.uniq()[0]
# dictionnary to save the state of each molecule when the
# energie is calculated, will allow to retrieve the conformation
# use for the energie calculation
# keys are score,values is a list a 2 set of coords (mol1,mol2)
self.confcoords = {}
self.ms = ms = MolecularSystem()
self.cutoff = 1.0
self.score = 0.0
def doit(self):
self.update_coords()
score,estat,hbond,vdw,ds= self.get_score()
self.score = score
self.saveCoords(score)
self.atomset1.setConformation(0)
self.atomset2.setConformation(0)
return (score,estat,hbond,vdw,ds)
def update_coords(self):
""" methods to update the coordinate of the atoms set """
pass
def get_score(self):
""" method to get the score """
score = estat = hbond = vdw = ds = 1000.
return (score,estat,hbond,vdw,ds)
def saveCoords(self,score):
"""methods to store each conformation coordinate.
the score is use as the key of a dictionnary to store the different conformation.
save the coords of the molecules to be use later to write out
a pdb file
We only save up 2 ten conformations per molecule. When 10 is reach we delete the one with the
highest energie
"""
score_int= int(score*100)
# check number of conf save
if len(list(self.confcoords.keys())) >= 50:
# find highest energies
val =max(self.confcoords.keys())
del(self.confcoords[val])
# add new conformation
coords = [self.atomset1.coords[:],self.atomset2.coords[:]]
self.confcoords[score_int] = coords
def writeCoords(self,score=None,filename1=None,filename2=None,
sort=True, transformed=False,
pdbRec=['ATOM', 'HETATM', 'CONECT'],
bondOrigin='all', ssOrigin=None):
""" write the coords of the molecules in pdb file
pdb is file will have the molecule name follow by number of conformation
"""
writer = PdbWriter()
if score is None:
score = min( self.confcoords.keys())
if float(score) not in self.confcoords: return
c1 = self.confcoords[score][0]
c2 = self.confcoords[score][1]
if filename1 is None:
filename1 = self.mol1.name + '_1.pdb'
prev_conf = self.setCoords(self.atomset1,c1)
writer.write(filename1, self.atomset1, sort=sort, records=pdbRec,
bondOrigin=bondOrigin, ssOrigin=ssOrigin)
self.atomset1.setConformation(prev_conf)
if filename2 is None:
filename2 = self.mol2.name + '_1.pdb'
prev_conf = self.setCoords(self.atomset2,c2)
writer.write(filename2, self.atomset2, sort=sort, records=pdbRec,
bondOrigin=bondOrigin, ssOrigin=ssOrigin)
self.atomset2.setConformation(prev_conf)
def setCoords(self,atomset,coords):
""" set the coords to a molecule """
mol = atomset.top.uniq()[0]
prev_conf = atomset.conformation[0]
# number of conformations available
confNum = len(atomset[0]._coords)
if hasattr(mol, 'nrgCoordsIndex'):
# uses the same conformation to store the transformed data
atomset.updateCoords(coords,
mol.nrgCoordsIndex)
else:
# add new conformation to be written to file
atomset.addConformation(coords)
mol.nrgCoordsIndex = confNum
atomset.setConformation( mol.nrgCoordsIndex )
return prev_conf
def free_memory(self):
""" Method to free memory allocate by scorer
Should be implemented """
pass
class TrilinterpEnergyScorer(EnergyScorer):
""" Scorer using the trilinterp method, base on autogrid
"""
def __init__(self,atomset1,atomset2,stem, atomtypes):
"""
based on AD4 scoring function:
stem (string) and atomtypes list (list of string)2 specify filenames for maps
value_outside_grid is energy penalty for pts outside box
atoms_to_ignore are assigned 0.0 energy: specifically
added to avoid huge energies from atoms bonded to flexible residues
"""
EnergyScorer.__init__(self,atomset1,atomset2)
self.l = self.ms.add_entities(self.atomset2)
#eg: stem = 'hsg1', atomtypes= ['C','A','HD','N','S']
scorer = self.scorer = TrilinterpScorer(stem, atomtypes,readMaps=True)
self.scorer.set_molecular_system(self.ms)
self.prop='Trilinterp'
self.scorer.prop = self.prop
self.grid_obj = None
def set_grid_obj(self,grid_obj):
self.grid_obj = grid_obj
def update_coords(self):
""" update the coords """
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
confNum = 0
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
confNum = self.mol2.cconformationIndex
# transform ligand coord with grid.mat_transfo_inv
# put back the ligand in grid space
#print "dans update coord nrg"
#print self.mol2.allAtoms.coords
if hasattr(self.grid_obj,'mat_transfo_inv'):
M = self.grid_obj.mat_transfo_inv
vt = []
for pt in self.mol2.allAtoms.coords:
ptx = (M[0][0]*pt[0]+M[0][1]*pt[1]+M[0][2]*pt[2]+M[0][3])
pty = (M[1][0]*pt[0]+M[1][1]*pt[1]+M[1][2]*pt[2]+M[1][3])
ptz = (M[2][0]*pt[0]+M[2][1]*pt[1]+M[2][2]*pt[2]+M[2][3])
vt.append( (ptx, pty, ptz) )
self.mol2.allAtoms.updateCoords(vt,ind=confNum)
#print vt
def get_score(self):
# labels atoms
score_array,terms_dic = self.scorer.get_score_array()
self.scorer.labels_atoms_w_nrg(score_array)
self.score =score= min(Numeric.add.reduce(score_array),100.)
#self.score =score= min(self.scorer.get_score(),100.)
terms_score = terms_dic
estat = min(round(Numeric.add.reduce(terms_score[0]),2),1000.)
hbond = 0.#min(round(terms_score['m'],2),1000.)
vdw = min(round(Numeric.add.reduce(terms_score[1]),2),1000.)
ds = min(round(Numeric.add.reduce(terms_score[2]),2),1000.) #problem with ds
#ds=ds-ds
#self.score = self.score -ds
return (score,estat,hbond,vdw,ds)
class TrilinterpEnergyScorerAD3(EnergyScorer):
""" Scorer using the trilinterp method, base on autogrid
"""
def __init__(self,atomset1,atomset2,stem, atomtypes):
"""
based on AD4 scoring function:
stem (string) and atomtypes list (list of string)2 specify filenames for maps
value_outside_grid is energy penalty for pts outside box
atoms_to_ignore are assigned 0.0 energy: specifically
added to avoid huge energies from atoms bonded to flexible residues
"""
EnergyScorer.__init__(self,atomset1,atomset2)
self.l = self.ms.add_entities(self.atomset2)
#eg: stem = 'hsg1', atomtypes= ['C','A','HD','N','S']
scorer = self.scorer = TrilinterpScorer_AD3(stem, atomtypes)
self.scorer.set_molecular_system(self.ms)
self.prop = 'Trilinterp'
self.grid_obj = None
def set_grid_obj(self,grid_obj):
self.grid_obj = grid_obj
def update_coords(self):
""" update the coords """
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
confNum = 0
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
confNum = self.mol2.cconformationIndex
# transform ligand coord with grid.mat_transfo_inv
# put back the ligand in grid space
#print "dans update coord nrg"
#print self.mol2.allAtoms.coords
if hasattr(self.grid_obj,'mat_transfo_inv'):
M = self.grid_obj.mat_transfo_inv
vt = []
for pt in self.mol2.allAtoms.coords:
ptx = (M[0][0]*pt[0]+M[0][1]*pt[1]+M[0][2]*pt[2]+M[0][3])
pty = (M[1][0]*pt[0]+M[1][1]*pt[1]+M[1][2]*pt[2]+M[1][3])
ptz = (M[2][0]*pt[0]+M[2][1]*pt[1]+M[2][2]*pt[2]+M[2][3])
vt.append( (ptx, pty, ptz) )
self.mol2.allAtoms.updateCoords(vt,ind=confNum)
#print vt
def get_score(self):
score = self.scorer.get_score()
estat = 0.0
hbond = 0.0
vdw = 0.0
ds = 0.0
return (score,estat,hbond,vdw,ds)
class PairWiseEnergyScorer(EnergyScorer):
"""For each atom in one AtomSet, determine the electrostatics eneregy vs all the atoms in a second
AtomSet using the C implementation of the autodock scorer.
When using the autodock3 scorer, the receptor need to be loaded as a pdbqs file, the ligand as pdbqt.
"""
def __init__(self,atomset1,atomset2,scorer_ad_type='305'):
EnergyScorer.__init__(self,atomset1,atomset2)
self.prop = 'ad305_energy'
self.ms = ms = c_scorer.MolecularSystem()
self.receptor= self.pyMolToCAtomVect(atomset1)
self.ligand = self.pyMolToCAtomVect(atomset2)
self.r = ms.add_entities(self.receptor)
self.l = ms.add_entities(self.ligand)
ms.build_bonds( self.r )
ms.build_bonds( self.l )
# Notice: keep references to the terms !
# or they will be garbage collected.
self.scorer_ad_type = scorer_ad_type
if self.scorer_ad_type == '305':
self.ESTAT_WEIGHT_AUTODOCK = 0.1146 # electrostatics
self.HBOND_WEIGHT_AUTODOCK = 0.0656 # hydrogen bonding
self.VDW_WEIGHT_AUTODOCK = 0.1485 # van der waals
self.DESOLV_WEIGHT_AUTODOCK= 0.1711 # desolvation
## !!! Make sure that all the terms are save and not free after init is done
## use self.
self.estat = c_scorer.Electrostatics(ms)
self.hbond = c_scorer.HydrogenBonding(ms)
self.vdw = c_scorer.VanDerWaals(ms)
self.ds = c_scorer.Desolvation(ms)
self.scorer = c_scorer.WeightedMultiTerm(ms)
self.scorer.add_term(self.estat, self.ESTAT_WEIGHT_AUTODOCK)
self.scorer.add_term(self.hbond, self.HBOND_WEIGHT_AUTODOCK)
self.scorer.add_term(self.vdw, self.VDW_WEIGHT_AUTODOCK)
self.scorer.add_term(self.ds, self.DESOLV_WEIGHT_AUTODOCK)
# shared memory, used by C++ functions
self.proteinLen = len(atomset1)
self.ligLen = len(atomset2)
self.msLen = self.proteinLen + self.ligLen
self.sharedMem = memobject.allocate_shared_mem([self.msLen, 3],
'SharedMemory', memobject.FLOAT)
self.sharedMemPtr = memobject.return_share_mem_ptr('SharedMemory')[0]
#print "Shared memory allocated.."
def update_coords(self):
""" update the coordinate of atomset """
# use conformation set by dectected patterns
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
# get the coords
R_coords = self.atomset1.coords
L_coords = self.atomset2.coords
self.sharedMem[:] = Numeric.array(R_coords+L_coords, 'f')[:]
c_scorer.updateCoords(self.proteinLen, self.msLen, self.ms,self.sharedMemPtr)
def get_score(self):
""" return the score """
mini = self.ms.check_distance_cutoff(0, 1, self.cutoff)
# when number return should not do get_score ( proteins too close)
# flag = (mini==1.0 and mini==2.0)
flag = (mini == mini)
# for each of the terms and the score, we cap their max value to 100
# so if anything is greater than 100 we assign 100
# If their is bad contact score = 1000.
if flag: # if any distance < cutoff : no scoring
#self.score = min(9999999.9, 9999.9/mini)
self.score = 1000.
estat = hbond = vdw = ds = 1000.
else:
self.score = min(self.scorer.get_score(),100.)
estat = min(round(self.estat.get_score() * self.ESTAT_WEIGHT_AUTODOCK,2),1000.)
hbond = min(round(self.hbond.get_score() * self.HBOND_WEIGHT_AUTODOCK,2),1000.)
vdw = min(round(self.vdw.get_score() * self.VDW_WEIGHT_AUTODOCK,2),1000.)
ds = min(round(self.ds.get_score() * self.DESOLV_WEIGHT_AUTODOCK,2),1000.)
#print "--",estat,hbond,vdw,ds
return (self.score,estat,hbond,vdw,ds)
def pyMolToCAtomVect( self,mol):
"""convert Protein or AtomSet to AtomVector
"""
try :
from cAutoDock.scorer import AtomVector, Atom, Coords
except :
pass
className = mol.__class__.__name__
if className == 'Protein':
pyAtoms = mol.getAtoms()
elif className == 'AtomSet':
pyAtoms = mol
else:
return None
pyAtomVect = AtomVector()
for atm in pyAtoms:
a=Atom()
a.set_name(atm.name)
a.set_element(atm.autodock_element)# aromatic type 'A', vs 'C'
coords=atm.coords
a.set_coords( Coords(coords[0],coords[1],coords[2]))
a.set_charge( atm.charge)
try:
a.set_atvol( atm.AtVol)
except:
pass
try:
a.set_atsolpar( atm.AtSolPar)
except:
pass
a.set_bond_ord_rad( atm.bondOrderRadius)
a.set_charge( atm.charge)
pyAtomVect.append(a)
return pyAtomVect
def free_memory(self):
# free the shared memory
memobject.free_shared_mem("SharedMemory")
#from AutoDockTools.pyAutoDockCommands import pep_aromList
pep_aromList=[]
class PyADCalcAD3Energies(EnergyScorer):
"""For each atom in one AtomSet, determine the autodock3 energy vs all the atoms in a second
AtomSet
"""
def __init__(self,atomset1,atomset2):
""" """
EnergyScorer.__init__(self,atomset1,atomset2)
self.weight = None
self.weightLabel = None
self.scorer = AutoDock305Scorer()
self.prop = self.scorer.prop
bothAts = atomset1 + atomset2
for a in bothAts:
if a.parent.type + '_' + a.name in pep_aromList:
a.autodock_element=='A'
a.AtSolPar = .1027
elif a.autodock_element=='A':
a.AtSolPar = .1027
elif a.autodock_element=='C':
a.AtSolPar = .6844
else:
a.AtSolPar = 0.0
self.r = self.ms.add_entities(atomset1)
self.l = self.ms.add_entities(atomset2)
self.scorer.set_molecular_system(self.ms)
def update_coords(self):
""" update the coords """
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
for ind in (self.r,self.l):
# clear distance matrix
self.ms.clear_dist_mat(ind)
def get_score(self):
score = self.scorer.get_score()
terms_score = []
for t,w in self.scorer.terms:
terms_score.append(w*t.get_score())
estat = min(round(terms_score[0]),1000.)
hbond = min(round(terms_score[1]),1000.)
vdw = min(round(terms_score[2]),1000.)
ds = min(round(terms_score[3]),1000.)
# labels atoms
score_array = self.scorer.get_score_array()
self.scorer.labels_atoms_w_nrg(score_array)
return (score,estat,hbond,vdw,ds)
class PyADCalcAD4Energies(EnergyScorer):
"""For each atom in one AtomSet, determine the autodock4 energy vs all the atoms
in a second AtomSet
"""
def __init__(self,atomset1,atomset2):
""" """
EnergyScorer.__init__(self,atomset1,atomset2)
self.weight = None
self.weightLabel = None