-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathepmvAdaptor.py
4347 lines (4098 loc) · 197 KB
/
epmvAdaptor.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/epmvAdaptor.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>.
"""
"""
The ePMV Adaptor Module
The ePMV Adaptor Module
=======================
This module provides the function to start ePMV, the function that handle the molecule loading, and
the Adaptor base class.
"""
# fixFile "/local/ludo/Desktop/blender-2.49b/MGLToolsPckgs/ePMV/blender/v24/blenderAdaptor.py",
# line 301, in updateMolAtomCoordLines KeyError: 'hsg1:A_line'
import sys, os
import platform
import DejaVu
DejaVu.enableVertexArray = False
from Pmv.mvCommand import MVCommand
from Pmv.moleculeViewer import MoleculeViewer
from Pmv.moleculeViewer import DeleteGeomsEvent, AddGeomsEvent, EditGeomsEvent
from Pmv.moleculeViewer import DeleteAtomsEvent, EditAtomsEvent
from Pmv.deleteCommands import BeforeDeleteMoleculesEvent, AfterDeleteAtomsEvent
from Pmv.displayCommands import BindGeomToMolecularFragment
from Pmv.trajectoryCommands import PlayTrajectoryCommand
from Pmv.pmvPalettes import AtomElements
from Pmv.pmvPalettes import DavidGoodsell, DavidGoodsellSortedKeys
from Pmv.pmvPalettes import RasmolAmino, RasmolAminoSortedKeys
from Pmv.pmvPalettes import Shapely
from Pmv.pmvPalettes import SecondaryStructureType
from MolKit.protein import ResidueSetSelector, Chain, Protein, Residue, ChainSet
from MolKit.molecule import Atom, AtomSet
from mglutil.util.recentFiles import RecentFiles
import numpy
import numpy.oldnumeric as Numeric # backward compatibility
import math
import ePMV
from ePMV import comput_util as util
from ePMV.installer import Installer
from ePMV.lightGridCommands import addGridCommand
from ePMV.lightGridCommands import readAnyGrid
from ePMV.lightGridCommands import IsocontourCommand
# TODO:
# add computation (trajectory reading,energy,imd,pyrosetta?,amber)
# check if work with server/client mode...
# color utility from pyubi
from upy import colors as col
def is_os_64bit():
return platform.machine().endswith('64')
arch = "32bit"
if platform.architecture()[0] == '64bit':
if platform.machine().endswith('64'): # sys.maxint == 9223372036854775807:
arch = "64bit"
# retrieve architecture os
class loadMoleculeInHost(MVCommand):
"""
Command call everytime a molecule is read in PMV. Here is define whats happen
in the hostApp when a molecule is add in PMV.ie creating hierarchy, empty
parent optional pointCloud object, camera, light, etc...
"""
def __init__(self, epmv):
"""
constructor of the command.
@type epmv: epmvAdaptor
@param epmv: the embeded PMV object which consist in the adaptor, the molecular
viewer and the helper.
"""
MVCommand.__init__(self)
self.mv = epmv.mv
self.epmv = epmv
def checkDependencies(self, vf):
from bhtree import bhtreelib
def doit(self, mol, **kw):
"""
actual function of the command.
@type mol: MolKit molecule
@param mol: the molecule loaded in PMV
@type kw: dictionary
@param kw: the dictionary of optional keywords arguments
"""
# sys.stderr.write('loadMolecule in host\n')
print (".............loadMolecule..................")
chname = ['Z', 'Y', 'X', 'W', 'V', 'U', 'T']
molname = mol.name # mol.replace("'","")
# setup some variable
self.mv.molDispl[molname] = {}
for k in ["bead", "cpk", "bs", "ss", "loft", "arm", "spline", "surf",
"cms", "meta", "points", "lines", "cgeom"]:
self.mv.molDispl[molname][k] = False
self.mv.molDispl[molname]["col"] = None
if molname not in list(self.mv.MolSelection.keys()):
self.mv.MolSelection[molname] = {}
if molname not in list(self.mv.selections.keys()):
self.mv.selections[molname] = {}
if molname not in list(self.mv.iMolData.keys()):
self.mv.iMolData[molname] = []
sc = self.epmv._getCurrentScene()
# mol=os.path.splitext(os.path.basename(mol))[0]
# sys.stderr.write('%s\n'%molname)
if self.epmv.duplicatemol: # molecule already loaded,so the name is overwrite by pmv, add _ind
# print self.epmv.duplicatedMols.keys()
if mol in list(self.epmv.duplicatedMols.keys()):
self.epmv.duplicatedMols[molname] += 1
else:
self.epmv.duplicatedMols[molname] = 1
molname = molname + "_" + str(self.epmv.duplicatedMols[molname])
molname = molname.replace(".", "_")
# sys.stderr.write('%s\n'%mol)
# print self.mv.Mols.name
P = mol = self.mv.getMolFromName(molname)
if mol == None:
# print "WARNING RMN MODEL OR ELSE, THERE IS SERVERAL MODEL IN THE
# FILE\nWE LOAD ONLY LOAD THE 1st\n",self.Mols.name
P = mol = self.mv.getMolFromName(molname + "_model1")
mol.name = molname
# mol=mol.replace("_","")
print('read %s\n' % mol)
# mol.name = mol.name.replace("_","")
if self.epmv.build_bonds:
import MolKit
MolKit.bonds_threshold = self.epmv.bonds_threshold
# if ciff and have bon information, use it.
if not hasattr(mol, "mmCIF_dict"):
self.mv.buildBondsByDistance(mol, log=0)
# self.mv.computeSESAndSASArea(mol,log=0)
# sys.stderr.write("center")
center = mol.getCenter()
# sys.stderr.write(center)
# if centering is need we will translate to center
centerO = None
if self.epmv.center_mol: # and not self.epmv.parseBioMT:
matrix = numpy.identity(4, 'f')
matrix[3, :3] = numpy.array(center) * -1
# print matrix
vt = util.transformedCoordinatesWithMatrice(mol, matrix.transpose())
mol.allAtoms.updateCoords(numpy.array(vt).tolist(), ind=0)
# mol.allAtoms.setConformation(0)
center = mol.getCenter()
# print center
else:
# create an empty at center
centerO = self.epmv._newEmpty(mol.name + "_center", location=center) # center)
if self.epmv.host == 'chimera':
model = self.epmv.helper.readMol(mol.parser.filename)
mol.ch_model = model
mol.geomContainer.masterGeom.obj = model
return
if self.epmv.useModeller:
# print "ok add a conf"
# add a conformation for modeller
mol.allAtoms.addConformation(mol.allAtoms.coords[:])
iConf = len(mol.allAtoms[0]._coords) - 1
from ePMV.extension.Modeller.pmvAction import pmvAction
mol.pmvaction = pmvAction(1, 1, 1000, iconf=iConf, pmvModel=mol,
mv=self.epmv.mv, epmv=self.epmv)
mol.allAtoms.setConformation(0)
# skip,first,last
else:
if self.epmv.removeWater:
self.mv.deleteWater(mol)
# create an empty/null object as the parent of all geom, and build the
# molecule hierarchy as empty for each Chain
master = self.epmv._newEmpty(mol.name, location=[0., 0., 0.]) # center)
mol.geomContainer.masterGeom.obj = master
self.epmv._addObjectToScene(sc, master)
if not self.epmv.center_mol and centerO is not None:
self.epmv._addObjectToScene(sc, centerO, parent=master)
mol.geomContainer.masterGeom.chains_obj = {}
mol.geomContainer.masterGeom.res_obj = {}
# if self.epmv.doCloud:
# cloud = self.epmv._PointCloudObject(mol.name+"_cloud",
# vertices=mol.allAtoms.coords,
# parent=master)
ch_colors = self.mv.colorByChains.palette.lookup(mol.chains)
for i, ch in enumerate(mol.chains):
sys.stderr.write(str(i) + "\n")
# how to fix this problem...?
if self.epmv.host == 'maya':
if ch.name == " " or ch.name == "":
# this dont work with stride....name of chain dont stay for ss
ch.name = chname[i]
ch_center = [0., 0., 0.] # util.getCenter(ch.residues.atoms.coords)
chobj = self.epmv._newEmpty(ch.full_name(), location=ch_center) # ,parentCenter=center)
mol.geomContainer.masterGeom.chains_obj[ch.name] = self.epmv._getObjectName(chobj)
self.epmv._addObjectToScene(sc, chobj, parent=master, centerRoot=True)
parent = chobj
# make the chain material
ch.material = self.epmv.helper.addMaterial(ch.full_name() + "_mat", ch_colors[i])
ch.material = ch.full_name() + "_mat"
# if self.epmv.doCloud:
# print "ok docloud",ch.full_name()+"_cloud"
# cloud = self.epmv._PointCloudObject(ch.full_name()+"_cloud",
# vertices=ch.residues.atoms.coords,
# parent=chobj)
# self.epmv._addObjectToScene(sc,cloud,parent=chobj)
# if self.useTree == 'perRes' :
# for res in ch.residues :
# res_obj = util.makeResHierarchy(res,parent,useIK='+str(self.useIK)+')
# mol.geomContainer.masterGeom.res_obj[res.name]=util.getObjectName(res_obj)
# elif self.useTree == 'perAtom' :
# for res in ch.residues :
# parent = util.makeAtomHierarchy(res,parent,useIK='+str(self.useIK)+')
# else :
chobjcpk = self.epmv._newEmpty(ch.full_name() + "_cpk", location=ch_center)
mol.geomContainer.masterGeom.chains_obj[ch.name + "_cpk"] = self.epmv._getObjectName(chobjcpk)
self.epmv._addObjectToScene(sc, chobjcpk, parent=chobj, centerRoot=True)
chobjballs = self.epmv._newEmpty(ch.full_name() + "_bs", location=ch_center)
mol.geomContainer.masterGeom.chains_obj[ch.name + "_balls"] = self.epmv._getObjectName(chobjballs)
self.epmv._addObjectToScene(sc, chobjballs, parent=chobj, centerRoot=True)
chobjss = self.epmv._newEmpty(ch.full_name() + "_ss", location=ch_center)
mol.geomContainer.masterGeom.chains_obj[ch.name + "_ss"] = self.epmv._getObjectName(chobjss)
self.epmv._addObjectToScene(sc, chobjss, parent=chobj, centerRoot=True)
# if mol.parser.hasSsDataInFile():
# mod = "From File"
# else:
# mod = "From Pross"
# self.mv.computeSecondaryStructure(
# mol, molModes={'%s'%mol.name:mod}, topCommand=0)
# self.mv.extrudeSecondaryStructure(sel, topCommand=0, log=0, display=0)
self.epmv.testNumberOfAtoms(mol)
self.mv.assignAtomsRadii(str(molname), united=0, log=0, overwrite=1)
self.epmv._addMolecule(mol.name)
radius = util.computeRadius(P, center)
# sys.stderr.write(str(radius))
focal = 2. * math.atan((radius * 1.03) / 100.) * (180.0 / 3.14159265358979323846)
# sys.stderr.write(str(focal))
center = center[0], center[1], (center[2] + focal * 2.0)
# if mol.parser.hasSsDataInFile():
# mod = "From File"
# else:
# mod = "From Pross"
# self.mv.computeSecondaryStructure(
# mol, molModes={'%s'%mol.name:mod}, topCommand=0)
# print center
if self.epmv.doCamera:
self.epmv._addCameraToScene("cam_" + mol.name, "ortho", focal, center, sc)
if self.epmv.doLight:
self.epmv._addLampToScene("lamp_" + mol.name, 'Area', (1., 1., 1.), 15., 0.8, 1.5, False, center, sc)
self.epmv._addLampToScene("sun_" + mol.name, 'Sun', (1., 1., 1.), 15., 0.8, 1.5, False, center, sc)
# parseBioMT: problem of centering....we should just center the big thing at the end
# if self.epmv.parseBioMT:
# #need to get the information from the parser and create the instance/null parent etc.
# #problem for maya and blender....
# #only for PDB actually
# #by default we can create the trnasformation node and then apply later the geometry...?
def onAddObjectToViewer(self, obj):
self.doitWrapper(*(obj,))
def __call__(self, mol, **kw):
self.doitWrapper(*(mol,), **kw)
class epmvAdaptor(object):
"""
The ePMV Adaptor object
=======================
The base class for embedding pmv in a hostApplication
define the hostAppli helper function to apply according Pmv event.
Each hostApp adaptor herited from this class.
"""
lastUsed = {}
listeKeywords = {}
listeKeywords["dsAtLoad"] = ["secondary structure", "beadRibbon", "clouds",
"line", "MSMS", "CMS", "None"]
keywords = {"useLog": None,
"bicyl": {"name": "Split bonds (slower)", "value": True, "type": "checkbox"},
# one or two cylinder to display a bond stick
"center_mol": {"name": "Center molecule to origin", "value": True, "type": "checkbox"},
"center_grid": {"name": "Center Grid", "value": True, "type": "checkbox"},
"build_bonds": {"name": "Build bonds by distance, with", "value": True, "type": "checkbox"},
"bonds_threshold": {"name": "bonds distance cutoff", "value": 1.1, "type": "inputFloat",
"mini": 0., "maxi": 10., "label": "Minimum bond distance [A]:"},
"joins": None,
"uniq_ss": {"name": "Single colorizable mesh for Ribbon and Beaded Ribbon", "value": False,
"type": "checkbox"},
"colorProxyObject": None,
"only": None,
"updateSS": None,
"updateColor": {"name": "Update color automatically for multi-state models", "value": True,
"type": "checkbox"},
"use_instances": {"name": "Build instances for atoms and bonds", "value": True, "type": "checkbox"},
"duplicatemol": None,
"useTree": None, # None#'perRes' #or perAtom
"useIK": None,
"use_progressBar": {"name": "Progress bar", "value": False, "type": "checkbox"},
# "doCloud":{"name":"Render points","value":True,"type":"checkbox"}, now in the represnetation
"doCamera": {"name": "PMV camera", "value": False, "type": "checkbox"},
"removeWater": {"name": "Remove water", "value": True, "type": "checkbox"},
"dsAtLoad": {"name": "Loading display",
"label": "Default representation:",
"value": listeKeywords["dsAtLoad"],
"type": "pullMenu"},
"join_ss": {"name": "Connect Ribbon geometry", "value": False, "type": "checkbox"},
"force_pross": {"name": "Force PROSS (override pdb file SS)", "value": False, "type": "checkbox"},
"doLight": {"name": "PMV light", "value": False, "type": "checkbox"},
"useModeller": {"name": "Use Modeller", "value": False, "type": "checkbox"},
"usePymol": {"name": "Use PyMOL", "value": False, "type": "checkbox"},
# "parseBioMT":{"name":"Use PyMol","value":False,"type":"checkbox"},
"synchro_realtime": {"name": "Viewport changes modify PDB data (Synchro realtime)", "value": False,
"type": "checkbox"},
"synchro_timeline": {"name": "Synchronize Data Player to host animation timeline with:",
"value": False, "type": "checkbox"},
"synchro_ratio": [{"name": "data steps for every", "value": 1, "type": "inputInt",
"mini": 0, "maxi": 2000},
{"name": "host animation frames", "value": 1, "type": "inputInt",
"mini": 0, "maxi": 2000}],
"forceFetch": {"name": "Override cache version when [Fetch]ing new molecule",
"value": False, "type": "checkbox"},
"minmaxCMSgrid": [{"name": "mini cms gridstep", "value": 0, "type": "inputInt",
"mini": 0, "maxi": 2000},
{"name": "maxi cms gridstep", "value": 100, "type": "inputInt",
"mini": 0, "maxi": 2000}],
}
# need keyword order
def setupMV(self):
print ("setupMV", sys.version_info, sys.version_info < (3, 0))
self.mv.addCommand(BindGeomToMolecularFragment(), 'bindGeomToMolecularFragment', None)
self.mv.browseCommands('trajectoryCommands', commands=['openTrajectory'], log=0, package='Pmv')
self.mv.addCommand(PlayTrajectoryCommand(), 'playTrajectory', None)
self.mv.addCommand(addGridCommand(), 'addGrid', None)
self.mv.addCommand(readAnyGrid(), 'readAny', None)
self.mv.addCommand(IsocontourCommand(), 'isoC', None)
if sys.version_info < (3, 0):
self.mv.browseCommands('colorCommands', package='ePMV.pmv_dev', topCommand=0)
# self.mv.browseCommands('trajectoryCommands',commands=['openTrajectory'],log=0,package='Pmv')
# self.mv.browseCommands('trajectoryCommands',commands=['openTrajectory'],log=0,package='Pmv')
# define the listener
if self.host is not None:
self.mv.registerListener(DeleteGeomsEvent, self.updateGeom)
self.mv.registerListener(AddGeomsEvent, self.updateGeom)
self.mv.registerListener(EditGeomsEvent, self.updateGeom)
self.mv.registerListener(AfterDeleteAtomsEvent, self.updateModel)
self.mv.registerListener(BeforeDeleteMoleculesEvent, self.updateModel)
self.mv.addCommand(loadMoleculeInHost(self), '_loadMol', None)
# self.mv.embedInto(self.host,debug=0)
self.mv.embeded = True
# compatibility with PMV
self.mv.Grid3DReadAny = self.mv.readAny
# mv.browseCommands('superimposeCommandsNew', package='Pmv', topCommand=0)
self.mv.userpref['Read molecules as']['value'] = 'conformations'
self.mv.setUserPreference(('Read molecules as', 'conformations',), log=0)
self.mv.setUserPreference(('Number of Undo', '0',), redraw=0, log=1)
self.mv.setUserPreference(('Save Perspective on Exit', 'no',), log=0)
self.mv.setUserPreference(('Transformation Logging', 'no',), log=0)
# should add some user preferece and be able to save it
# recentFiles Folder
rcFile = self.mv.rcFolder
if rcFile:
rcFile += os.sep + 'Pmv' + os.sep + "recent.pkl"
self.mv.recentFiles = RecentFiles(self.mv, None, filePath=rcFile, index=0)
else:
print("no rcFolder??")
# this create mv.hostapp which handle server/client and log event system
# NOTE : need to test it in the latest version
# if not self.useLog :
# self.mv.hostApp.driver.useEvent = True
self.mv.iTraj = {}
self.funcColor = [self.mv.colorByAtomType,
self.mv.colorAtomsUsingDG,
self.mv.colorByResidueType,
self.mv.colorResiduesUsingShapely,
self.mv.colorBySecondaryStructure,
self.mv.colorByChains,
self.mv.colorByDomains,
self.mv.color,
self.mv.colorByProperty]
self.fTypeToFc = {"ByAtom": 0, "AtomsU": 1, "ByResi": 2, "Residu": 3,
"BySeco": 4, "ByChai": 5, "ByDoma": 6, "": 7,
"ByPropN": 8, "ByPropT": 9, "ByPropS": 10}
self.mv.host = self.host
self.mv.selectionLevel = Atom
# mv.hostApp.driver.bicyl = self.bicyl
def __init__(self, mv=None, host="", useLog=False, debug=0, gui=False, **kw):
"""
Constructor of the adaptor. Register the listener for PMV events and setup
defaults options. If no molecular viewer are provided, start a fresh pmv
session.
@type mv: MolecularViewer
@param mv: a previous pmv cession gui-less
@type host: string
@param host: name of the host application
@type useLog: boolean
@param useLog: use Command Log event instead of Geom event (deprecated)
@type debug: int
@param debug: debug mode, print verbose
"""
self.mv = mv
self.host = host
self.soft = host
self.rep = "epmv"
if not hasattr(self, "helper"):
self.helper = None
# self.Set(reset=True,useLog=useLog,**kw)
if self.mv == None:
self.mv = self.start(debug=debug)
self.mv.helper = self.helper
self.setupMV()
self.addADTCommands()
if not hasattr(self.mv, 'molDispl'): self.mv.molDispl = {}
if not hasattr(self.mv, 'MolSelection'): self.mv.MolSelection = {}
if not hasattr(self.mv, 'selections'): self.mv.selections = {}
if not hasattr(self.mv, 'iMolData'): self.mv.iMolData = {}
# options with default values
self.duplicatedMols = {}
self.env = None
self.inst = None
self.gui = None
self.GUI = None
self.timer = False
self.mglroot = ""
self.setupInst()
self.ResidueSelector = ResidueSetSelector()
self.ssk = ['Heli', 'Shee', 'Coil', 'Turn', 'Stra']
self.ResidueSelector = ResidueSetSelector()
self.AtmRadi = {"A": 1.54, "M": 1.54, "N": "1.7", "C": "1.74", "CA": "1.74",
"O": "1.39", "S": "1.85", "H": "1.2", "P": "1.04"}
self.lookupDGFunc = util.lookupDGFunc
self.max_atoms = 10000
self.usefullname = False
self.molDictionary = {}
self.hmol = 0
self.control_mmaya = False
self.MAX_LENGTH_NAME = 20
self.current_selection = None
# if self.host.find("blender") != -1 :
# self.MAX_LENGTH_NAME = 5#this for blender..you may change it for other host...
def setupInst(self):
# print "mglroot ",self.mglroot
if not self.mglroot:
import Pmv
dirP = Pmv.__path__[0]
os.chdir(dirP) # pmv
os.chdir(".." + os.sep) # MGLToolsPckgs
os.chdir(".." + os.sep) # mgltools
self.mglroot = os.path.abspath(os.curdir)
# print "mglrootx ",self.mglroot
if self.inst is None:
self.inst = Installer(mgl=self.mglroot)
else:
self.inst.setMGL(mgl=self.mglroot)
def initOption(self):
"""
Initialise the defaults options for ePMV, e.g. keywords.
"""
# we should use userpref from the ViewerFramework and mglutil.userpref class
# saved in '/local/ludo/.mgltools/1.5.6rc3/.settings'
for key in self.keywords:
if self.keywords[key] is not None and key != "synchro_ratio" and key != "minmaxCMSgrid":
if self.keywords[key]["type"] == "pullMenu":
val = self.listeKeywords[key][0]
setattr(self, key, val)
else:
setattr(self, key, self.keywords[key]["value"])
self.dsAtLoad = "secondary structure" # default
self.useLog = False
self.joins = False
self.colorProxyObject = False
self.only = False
self.updateSS = False
# self.use_instances=True
self.duplicatemol = False
self.useTree = 'default' # None#'perRes' #or perAtom
self.useIK = False
self.useModeller = False # do we use modeller
self.usePymol = False
self._modeller = False # is modeller present
self.synchro_ratio = [self.keywords["synchro_ratio"][0]["value"],
self.keywords["synchro_ratio"][0]["value"]] # every 1 step for every 1 frame
self._AF = False
self._AR = False
self._pymol = False
self._prody = False
self.doCamera = False
self.synchronize()
def Set(self, reset=False, **kw):
"""
Set ePmv options provides by the keywords arguments.
e.g. epmv.Set(bicyl=True)
@type reset: bool
@param reset: reset to default values all options
@type kw: dic
@param kw: list of options and their values.
"""
if reset:
self.initOption()
for k in kw:
if k in list(self.keywords.keys()):
if self.keywords[k] is not None and k != "synchro_ratio" and k != "minmaxCMSgrid":
setattr(self, k, kw[k])
self.keywords[k]["value"] = kw[k]
val = kw.pop('joins', None)
if val is not None:
self.joins = val
val = kw.pop('colorProxyObject', None)
if val is not None:
self.colorProxyObject = val
val = kw.pop('only', None)
if val is not None:
self.only = val
val = kw.pop('updateSS', None)
if val is not None:
self.updateSS = val
val = kw.pop('use_instances', None)
if val is not None:
self.use_instances = val
val = kw.pop('duplicatemol', None)
if val is not None:
self.duplicatemol = val
val = kw.pop('useTree', None)
if val is not None:
self.useTree = val
val = kw.pop('useIK', None)
if val is not None:
self.useIK = val
val = kw.pop('useModeller', None)
if val is not None:
self.useModeller = val
val = kw.pop('usePymol', None)
if val is not None:
self.usePymol = val
val = kw.pop('synchro_ratio', None)
if val is not None:
self.synchro_ratio = val
# should be a an array [1,1]
val = kw.pop('usefullname', None)
if val is not None:
self.usefullname = val
def start(self, debug=0):
"""
Initialise a PMV guiless session. Load specific command to PMV such as
trajectory, or grid commands which are not automatically load in the
guiless session.
@type debug: int
@param debug: debug mode, print verbose
@rtype: MolecularViewer
@return: a PMV object session.
"""
customizer = ePMV.__path__[0] + os.sep + "epmvrc.py"
# print "customizer ",customizer
# replace _pmvrc ?
mv = MoleculeViewer(logMode='overwrite', customizer=customizer,
master=None, title='pmv', withShell=0,
verbose=False, gui=False)
return mv
def synchronize(self):
pass
def addADTCommands(self):
"""
Add to PMV some usefull ADT commands, and setup the conformation player.
readDLG
showDLGstates
"""
from AutoDockTools.autoanalyzeCommands import ADGetDLG, StatesPlayerWidget, ShowAutoDockStates
# from AutoDockTools.autoanalyzeCommands import ADShowBindingSite
self.mv.addCommand(ADGetDLG(), 'readDLG', None)
# self.mv.addCommand(StatesPlayerWidget(),'playerDLG',None)
self.mv.addCommand(ShowAutoDockStates(), 'showDLGstates', None)
self.mv.userpref['Player GUI'] = {}
self.mv.userpref['Player GUI']['value'] = 'Player'
# general util function
def createMesh(self, name, g, proxyCol=False, parent=None):
"""
General function to create mesh from DejaVu.Geom.
@type name: string
@param name: name of the host application
@type g: DejaVu.Geom
@param g: the DejaVu geometry to convert in hostApp mesh
@type proxyCol: boolean
@param proxyCol: if need special object when host didnt support color by vertex (ie C4D)
@type parent: hostApp object
@param parent: the parent for the hostApp mesh
"""
vertices = None
faces = None
if not hasattr(g, "getVertices"):
# this os probably a extEl then just get vertices and faces
vertices = g.vertices
faces = g.faces
else:
vertices = g.getVertices()
faces = g.getFaces()
obj = self._createsNmesh(name, vertices, None, faces,
proxyCol=proxyCol)
# print "_createsNmesh",obj
self._addObjToGeom(obj, g)
print ("mesh created", name, g, g.mesh, g.obj)
self._addObjectToScene(self._getCurrentScene(), obj[0], parent=parent)
return obj
def getChainParentName(self, selection, mol):
"""
Return the hostApp object masterParent at the chain level for a
given MolKit selection.
@type selection: MolKit.AtomSet
@param selection: the current selection
@type mol: MolKit.Protein
@param mol: the selection's parent molecule
@rtype: hostApp object
@return: the masterparent object at the chain level or None
"""
parent = None
import time
t1 = time.time()
if len(selection) != len(mol.allAtoms):
# if self.host.find("t") != -1 :
if isinstance(selection, AtomSet):
chain = selection[0].parent.parent
else:
print (type(selection))
return None
# else :
# chain=selection.findParentsOfType(Chain)[0]#way too slow
parent = mol.geomContainer.masterGeom.chains_obj[chain.name]
parent = self._getObject(parent)
print (time.time() - t1)
return parent
def compareSel(self, currentSel, molSelDic):
"""
Comapre the currentSel to the selection dictionary, return selname if retrieved.
@type currentSel: MolKit.AtomSet
@param currentSel: the current selection
@type molSelDic: dictionary
@param molSelDic: the dictionary of saved selection
@rtype: string
@return: the name of the selection in the dictionary if retrieved.
"""
for selname in list(molSelDic.keys()):
if currentSel[-1] == ';': currentSel = currentSel[0:-1]
if currentSel == molSelDic[selname][3]: return selname
if currentSel == molSelDic[selname]: return selname
return None
def getMolName(self, val, forupdate=False):
# print "get ",val
selname = ""
mname = val
# print self.mv.iMol.keys()
if mname in list(self.mv.selections.keys()):
selname = mname
# print str(val),mname,selname
else: # it is the selecetionname
for name in list(self.mv.selections.keys()):
for sname in list(self.mv.selections[name].keys()):
if mname == sname:
selname = sname
mname = name
# print mname
mol = self.mv.getMolFromName(mname)
# print mol.name
if forupdate:
return selname, mol # ?
return mname, mol
def sortName(self, array):
stringselection = ""
for element in array:
if ":" in element:
stringselection += element + ";"
else:
return element
return stringselection
def toStringSel(self, array):
stringselection = ""
# print array
for sel in array:
for elem in sel:
# print elem,str(elem)
stringselection += str(elem) + ":"
stringselection = stringselection[:-1] + ";"
# print stringselection
return stringselection
def getSelectionLevel(self, mol, selString):
# fix...problem if multiple chain...
# R=mol.chains[0].residues
if mol == None:
sel = ''
else:
sel = mol.name
selection = selString
if selection == '' or selection == "" or len(selection) == 0:
sel = mol.name
elif selection.upper() == 'BACKBONE':
sel = mol.name + ":::N,CA,C"
elif selection.upper() == 'SIDECHAIN':
sel = mol.name + ":::sidechain"
elif selection.upper() in list(AtomElements.keys()):
sel = mol.name + ':::' + selection
elif selection.upper() in list(RasmolAmino.keys()):
sel = mol.name + '::' + self.ResidueSelector.r_keyD[selection] + ':'
elif selection.lower() in list(ResidueSetSelector.residueList.keys()):
sel = mol.name + '::' + selection + ':'
elif selection.split(':')[0] == mol.name:
sel = selection
elif selection.split(' ')[0].lower() == "chain":
sel = mol.name + ':' + selection.split(' ')[1] + '::'
elif selection == 'picked' and self.gui is not None:
# need to get the current object selected in the doc
# and parse their name to recognize the atom selection...do we define a picking level ? and some phantom object to be picked?
CurrSel = self.helper.getCurrentSelection()
astr = []
for o in CurrSel:
# print o,self.parseObjectName(o)
astr.append(self.parseObjectName(o, res=True))
# ned to go from 3letter to 2letter
sel = self.toStringSel(astr)
# print("parsed selection ",sel)
# print("from ",astr)
# should be #B_MOL:CHAIN:RESIDUE:ATOMS
# thus atoms =
# sel=mol.name astr[3]
elif selection[:5] == "(Mol:":
if mol == None:
sel = ''
else:
sel = mol.name
else:
sel = selection
selection = self.mv.select(str(sel), negate=False, only=True, xor=False,
log=0, intersect=False)
if not isinstance(selection, Atom): selection = selection.findType(Atom)
print("ok sel", str(sel), selString, len(selection), selection) # ,selection
return sel, selection
def getSelectionCommand(self, selection, mol):
"""
From the given currentSel and its parent molecule, return the selection name
in the selection dictionary.
@type selection: MolKit.AtomSet
@param selection: the current selection
@type mol: MolKit.Protein
@param mol: the selection's parent molecule
@rtype: string
@return: the name of the selection in the dictionary if retrieved.
"""
parent = None
if hasattr(self.mv, "selections"):
parent = self.compareSel('+selection+', self.mv.selections[mol.name])
return parent
def updateModel(self, event):
"""
This is the callback function called everytime
a PMV command affect the molecule data, ie deleteAtomSet.
@type event: VFevent
@param event: the current event, ie DeleteAtomsEvent
"""
if isinstance(event, AfterDeleteAtomsEvent): # DeleteAtomsEvent):
action = 'deleteAt'
# when atom are deleted we have to redo the current representation and
# selection
atom_set = event.objects
# mol = atom_set[0].getParentOfType(Protein)
# need helperFunction to delete Objects
for i, atms in enumerate(atom_set):
nameo = "S" + "_" + atms.full_name()
o = self._getObject(nameo)
if o is not None:
# print nameo
self.helper.deleteObject(o)
# and the ball/stick
nameo = "B" + "_" + atms.full_name()
o = self._getObject(nameo)
if o is not None:
# print nameo
self.helper.deleteObject(o)
# and the bonds...and other geom?
mol = atom_set[0].top # getParentOfType(Protein)
self.mv.buildBondsByDistance(mol, log=0)
elif isinstance(event, BeforeDeleteMoleculesEvent):
action = 'deletMol'
# print action,dir(event)
mols = event.arg
for mol in mols:
# print "delete",mol.name
self.delMolDic(mol.name)
self.delGeomMol(mol)
if self.gui is not None:
# need to update molmenu
self.gui.resetPMenu(self.gui.COMB_BOX["mol"])
self.gui.restoreMolMenu()
# the main function, call every time an a geom event is dispatch
def updateGeom(self, event):
"""
This the main core of ePMV, this is the callback function called everytime
a PMV command affect a geometry.
@type event: VFevent
@param event: the current event, ie EditGeomsEvent
"""
if isinstance(event, AddGeomsEvent):
action = 'add'
elif isinstance(event, DeleteGeomsEvent):
action = 'delete'
elif isinstance(event, EditGeomsEvent):
action = 'edit'
else:
import warnings
warnings.warn('Bad event %s for epmvAdaptor.updateGeom' % event)
return
nodes, options = event.objects
if event.arg == 'iso':
self._isoSurface(nodes, options)
return
mol, atms = self.mv.getNodesByMolecule(nodes, Atom)
#################GEOMS EVENT############################################
if event.arg == 'lines' and action == 'edit':
self._editLines(mol, atms)
elif event.arg == 'cpk' and action == 'edit' and not self.useLog:
self._editCPK(mol, atms, options)
elif event.arg == 'bs' and action == 'edit' and not self.useLog:
self._editBS(mol, atms, options)
elif event.arg == 'trace' and action == 'edit' and not self.useLog:
print("displayTrace not supported Yet")
# displayTrace should use a linear spline extruded like _ribbon command
elif event.arg[0:4] == 'msms' and action == 'edit' and not self.useLog:
# there is 2 different msms event : compute msms_c and display msms_ds
if event.arg == "msms_c": # ok compute
self._computeMSMS(mol, atms, options)
elif event.arg == "msms_ds": # ok display
self._displayMSMS(mol, atms, options)
elif event.arg[:2] == 'SS' and action == 'edit' and not self.useLog:
# if event.arg == "SSextrude":
# self._SecondaryStructure(mol,atms,options,extrude=True)
if event.arg == "SSdisplay":
self._SecondaryStructure(mol, atms, options)
if event.arg == "SSdisplayU":
self._SecondaryStructure(mol, atms, options, uniq=True)
# the bead riibbon ?
# ('bead', [nodes,[params,redraw]],setOn=setOn, setOff=setOff)
elif event.arg == 'bead' and action == 'edit':
self._beadedRibbons(mol, atms, options[0])
elif event.arg == 'beadU' and action == 'edit':
self._beadedRibbons(mol, atms, options[0], uniq=True)
# self.beadedRibbons("1crn", redraw=0, log=1)
#################COLOR EVENT############################################
elif event.arg[0:5] == "color": # color Commands
# in this case liste of geoms correspond to the first options
# and the type of function is the last options
self._color(mol, atms, options)
elif event.arg == 'struts' and action == 'edit':
self._struts(mol, atms, options[0]) # nodes, params
def delMolDic(self, mname):
if mname in self.mv.selections:
del self.mv.selections[mname]
if mname in self.mv.iMolData:
del self.mv.iMolData[mname]
if mname in self.mv.molDispl:
del self.mv.molDispl[mname]
if mname in self.mv.MolSelection:
del self.mv.MolSelection[mname]
# print self.mv.selections
def delGeomMol(self, mol):
master = mol.geomContainer.masterGeom.obj
self.helper.deleteChildrens(master)
for g in mol.geomContainer.geoms:
if hasattr(g, 'obj'):
del g.obj
if hasattr(g, 'mesh'):
del g.mesh
def _addMolecule(self, molname):
"""
Initialise a molecule. ie prepare the specific dictionary for this molecule.
@type molname: str
@param molname: the molecule name
"""
if molname not in list(self.mv.molDispl.keys()):
self.mv.molDispl[molname] = {}
for k in ["cpk", "bs", "ss", "bead", "loft", "arm", "spline",
"surf", "cms", "meta", "points", "lines", "cgeom"]:
self.mv.molDispl[molname][k] = False
self.mv.molDispl[molname]["col"] = None
if molname not in list(self.mv.MolSelection.keys()):
self.mv.MolSelection[molname] = {}
if molname not in list(self.mv.selections.keys()):
self.mv.selections[molname] = {}
if molname not in list(self.mv.iMolData.keys()):
self.mv.iMolData[molname] = []
molinDic = False
for k in self.molDictionary:
if molname == self.molDictionary[k][0]:
molinDic = True
if not molinDic:
self.molDictionary[self.hmol] = [molname, self.mv.Mols.name.index(molname)]
self.hmol += 1
def _deleteMolecule(self, mol):
if mol.name in self.mv.Mols.name:
# need to first delete the geom and the associates dictionary
# note the mesh are still in the memory ....
self.delMolDic(mol.name)
try:
self.delGeomMol(mol)
except:
print("oups")
# then delete the mol
self.mv.deleteMol(mol, log=0)
# del cam and light
# need to update self.molDictionary[molname]
self.molDictionary = {}
for i, mol in enumerate(self.mv.Mols):
mindice, mvindice = self.getIndiceMol(mol.name)
self.molDictionary[mindice] = [mol.name, self.mv.Mols.name.index(mol.name)]
def _toggleUpdateSphere(self, atms, display, needRedo, i, N, prefix, opts=None):
"""
Handle the visibility and the update (pos) of each atom's Sphere geometry.
i and N arg are used for progress bar purpose.
@type atms: MolKit.Atom
@param atms: the atom to handle
@type display: boolean
@param display: visibility option
@type needRedo: boolean