def __init__(self, target=None, # Tk container name = 'Embedded camera', debug = 0, ): self.debug = debug if self.debug: print "EmbeddedMolViewer __init__> ", target self.target = target self.PMV_win = Toplevel() self.PMV_win.withdraw() VFGUI.hasDnD2 = False print "\n==========================================" print " Initializing PMV..." self.mv = MoleculeViewer(logMode = 'overwrite', master=self.PMV_win, # customizer='custom_pmvrc', title='[embedded viewer]', withShell=False, verbose=False, gui = True, guiVisible=1) self.VIEWER = self.mv.GUI.VIEWER self.GUI = self.mv.GUI self.VIEWER.cameras[0].suspendRedraw = 1 # stop updating the main Pmv camera self._pmv_visible = False self.cameras = {} # 'name' {'obj' : pmv_obj, 'structures': [mol1_obj, mol2_obj, ....], } self.cameras['pmv'] = { 'obj' :self.VIEWER.cameras[0], 'structures' : [], } self.cameraslist = ['pmv'] # name0, name1, name2 # keep the order in which cameras are added self.target = target print " [ DONE ]" print "==========================================\n" self.initStyles() if self.target: self.addCamera(target = self.targer, name=name)
def setUp(self): from Pmv.moleculeViewer import MoleculeViewer self.mv = MoleculeViewer(customizer='./.empty', logMode='overwrite', withShell=0) self.mv.loadCommand('fileCommands', 'readMolecule', 'Pmv') self.mv.loadCommand('deleteCommands', 'deleteMol', 'Pmv') self.mv.loadCommand("bondsCommands", "buildBondsByDistance", "Pmv") self.mv.setOnAddObjectCommands( ['buildBondsByDistance', 'displayLines'], log=0) self.mv.loadModule("interactiveCommands", 'Pmv') # Don't want to trap exceptions and errors... # the user pref is set to 1 by # default self.mv.setUserPreference(('trapExceptions', '0'), log=0) self.mv.setUserPreference(('warningMsgFormat', 'printed'), log=0) self.mv.loadModule('displayCommands', 'Pmv')
def setUp(self): from Pmv.moleculeViewer import MoleculeViewer self.mv = MoleculeViewer(customizer = './.empty', logMode = 'overwrite', withShell=0) self.mv.loadCommand('fileCommands', 'readMolecule', 'Pmv') self.mv.loadCommand('deleteCommands','deleteMol', 'Pmv') self.mv.loadCommand("bondsCommands", "buildBondsByDistance", "Pmv") self.mv.setOnAddObjectCommands(['buildBondsByDistance', 'displayLines'], log=0) self.mv.loadModule("interactiveCommands", 'Pmv') # Don't want to trap exceptions and errors... # the user pref is set to 1 by # default self.mv.setUserPreference(('trapExceptions', '0'), log = 0) self.mv.setUserPreference(('warningMsgFormat', 'printed'), log = 0) self.mv.loadModule('displayCommands', 'Pmv')
## if hasattr(atom, 'segID'): ## atom.segID = a[1].segID ## atom.hetatm = 0 ## atom.alternate = [] ## atom.element = 'H' ## atom.number = -1 ## atom.occupancy = 1.0 ## atom.conformation = 0 ## atom.temperatureFactor = 0.0 ## atom.babel_atomic_number = a[2] ## atom.babel_type = a[3] ## atom.babel_organic=1 ## bond = Bond( a[1], atom ) from Pmv.moleculeViewer import MoleculeViewer mv = MoleculeViewer() mv.addMolecule(mol) mol.bondsflag = 1 mv.lines(mol) v = [] l = [] g = mv.Mols[0].geomContainer.geoms['lines'] vc = len(g.vertexSet) scale = [0, 1, -1, 2, -2, 3, -3, 4, -4] add = -1 ## for b in bonds: ## if b.bondOrder>1: ## b.bondOrder = 5 ## break
import math from Pmv.moleculeViewer import MoleculeViewer from ViewerFramework.VF import LogEvent from pdb_c4d import * #from Pmv.displayCommands import BindGeomToMolecularFragment from ViewerFramework.clientsCommands import Pmv_client from c4d import plugins from c4d import documents import c4d scene = doc = documents.get_active_document() self = MoleculeViewer(logMode = 'overwrite', customizer=None, master=None,title='toto', withShell= 0,verbose=False, gui = False) self.abclogfiles=open('abclog','w') self.pmvstderr=open('pmvstderr','w') sys.stderr=self.pmvstderr self.addCommand(Pmv_client(), 'client', None) #self.addCommand(BindGeomToMolecularFragment(), 'bindGeomToMolecularFragment', None) self.client.setDriver('c4d') self.registerListener(LogEvent, self.client.handleLogEvent) self.armObj = None self.browseCommands('fileCommands', package="Pmv", topCommand=0) com=True cpk=False coarse=False sym=False
def startMoleculeViewer(): global mv from Pmv.moleculeViewer import MoleculeViewer mv = MoleculeViewer(customizer='./.empty', logMode='overwrite', withShell=0) mv.setUserPreference(('trapExceptions', '0'), log=0) mv.setUserPreference(('warningMsgFormat', 'printed'), log=0) mv.loadCommand('fileCommands', 'readMolecule', 'Pmv') mv.loadCommand('deleteCommands', 'deleteMol', 'Pmv') mv.loadCommand("bondsCommands", "buildBondsByDistance", "Pmv") mv.setOnAddObjectCommands(['buildBondsByDistance', 'displayLines'], log=0) mv.loadModule("interactiveCommands", 'Pmv') mv.loadModule('secondaryStructureCommands', 'Pmv')
def runADT(*argv, **kw): """The main function for running AutoDockTools """ import sys if type(argv) is tuple: if len(argv) == 0: argv = None elif len(argv) == 1: argv = argv[0] if type(argv) is not list: argv = [argv] else: argv = list(argv) if kw.has_key("ownInterpreter"): ownInterpreter = kw["ownInterpreter"] else: if argv is None: argv = ['AutoDockTools/bin/runADT.py', '-i'] ownInterpreter = False elif argv[0].endswith('runADT.py') is False: argv.insert(0, '-i') argv.insert(0, 'AutoDockTools/bin/runADT.py') ownInterpreter = False else: ownInterpreter = True optlist, args = getopt.getopt(argv[1:], 'haipsd:c:v:', [ 'update', 'help', 'again', 'overwriteLog', 'uniqueLog', 'noLog', 'noGUI', 'die', 'customizer=', 'interactive', 'dmode=', 'cmode=', 'noSplash', 'vision', 'python' ]) help_msg = """usage: pmv <options> -h or --help : print this message -a or --again : play back lastlog file --overwriteLog : overwrite log file --uniqueLog : create a log file with a unique name --noLog : turn off logging --noGUI : start PMV without the Graphical User Interface -s or --noSplash : turn off Splash Screen --die : do not start GUI event loop --customizer file : run the user specified file --lib packageName : add a libraries of commands -p or --ipython : create an ipython shell instead of a python shell -v r or --vision run : run vision networks on the command line -v o or --vision once : run vision networks and exit PMV --update [nightly|tested|clear] : update MGLTools if no arguments are given Update Manager GUI is provided 'nightly': download and install Nightly Builds 'tested' : download and install tested Nightly Builds 'clear' : clear/uninstall all the updates -d or --dmode modes : specify a display mode modes can be any a combination of display mode 'cpk' : cpk 'lines': lines 'ss' : secondary structure ribbon 'sb' : sticks and balls 'lic' : licorice 'ms' : molecular surface 'ca' : C-alpha trace 'bt' : backbone trace 'sp' : CA-spline 'sssb' : secondary structure for proteins, sticks and balls for other residues with bonds lines for other residues without bonds -c or --cmode modes : specify a display mode color scheme: 'ca' : color by atom 'cr' : color by residue (RASMOL scheme) 'cc' : color by chain 'cm' : color by molecule 'cdg': color using David Goodsell's scheme 'cs' : color residues using Shapely scheme 'css': color by secondary structure element example: display protein as ribbon, non protein as sticks and balls and color by atom type adt -i --dmode sssb --cmode cr myprot.pdb adt -i -m sssb -c cr myprot.pdb """ customizer = None logmode = 'overwrite' libraries = [] again = 0 interactive = 0 ipython = False die = 0 gui = True noSplash = False dmode = cmode = None dmodes = [ 'cpk', 'lines', 'ss', 'sb', 'lic', 'ms', 'ca', 'bt', 'sp', 'sssb' ] cmodes = ['ca', 'cr', 'cc', 'cm', 'cdg', 'cs', 'css'] visionarg = None for opt in optlist: if opt[0] in ('-h', '--help'): print help_msg sys.exit() elif opt[0] in ('-a', '--again'): again = 1 os.system("mv mvAll.log.py .tmp.py") elif opt[0] == '--overwriteLog': logmode = 'overwrite' elif opt[0] == '--uniqueLog': logmode = 'unique' elif opt[0] == '--noLog': logmode = 'no' elif opt[0] == '--noGUI': gui = False elif opt[0] == '--die': die = 1 elif opt[0] in ('-s', '--noSplash'): noSplash = True elif opt[0] == '--customizer': customFile = opt[1] elif opt[0] == '--lib': libraries.append(opt[1]) elif opt[0] in ('-i', '--interactive'): interactive = 1 elif opt[0] in ('-p', '--python'): ipython = True elif opt[0] in ('-d', '--dmode'): assert min([mo in dmodes for mo in opt[1].split('|')]) == True dmode = opt[1] elif opt[0] in ('-c', '--cmode'): assert min([mo in cmodes for mo in opt[1].split('|')]) == True cmode = opt[1] elif opt[0] == '--update': try: from Support.update import Update except ImportError: print "Support package is needed to get updates" break update = Update() if 'nightly' in args: update.latest = 'nightly' update.getUpdates() elif 'tested' in args: update.latest = 'tested' update.getUpdates() elif 'clear' in args: print "Removing all updates" update.clearUpdates() else: waitTk = update.gui() update.master.wait_variable(waitTk) elif opt[0] in ('-v', '--vision'): if opt[1] in ('o', 'once'): visionarg = 'once' elif opt[1] in ('r', 'run'): visionarg = 'run' else: print "unknown option %s %s" % tuple(opt) print help_msg sys.exit(1) #import sys text = 'Python executable : ' + sys.executable + '\n' if kw.has_key('AdtScriptPath'): text += 'ADT script : ' + kw['AdtScriptPath'] + '\n' text += 'MGLTool packages ' + '\n' from Support.path import path_text, release_path from Support.version import __version__ from mglutil import __revision__ version = __version__ text += path_text text += version + ': ' + release_path path_data = text print 'Run ADT from ', __path__[0] # if MGLPYTHONPATH environment variable exists - insert the specified path # into sys.path #if os.environ.has_key("MGLPYTHONPATH"): # if sys.platform == "win32": # mglPath = split(os.environ["MGLPYTHONPATH"], ";") # else: # mglPath = split(os.environ["MGLPYTHONPATH"], ":") # mglPath.reverse() # for p in mglPath: # sys.path.insert(0, os.path.abspath(p)) try: ################################################################## # Splash Screen ################################################################## import Pmv image_dir = os.path.join(Pmv.__path__[0], 'Icons', 'Images') copyright = """(c) 1999-2011 Molecular Graphics Laboratory, The Scripps Research Institute ALL RIGHTS RESERVED """ authors = """Authors: Michel F. Sanner, Ruth Huey, Sargis Dallakyan, Chris Carrillo, Kevin Chan, Sophie Coon, Alex Gillet, Sowjanya Karnati, William (Lindy) Lindstrom, Garrett M. Morris, Brian Norledge, Anna Omelchenko, Daniel Stoffler, Vincenzo Tschinke, Guillaume Vareille, Yong Zhao""" icon = os.path.join(Pmv.__path__[0], 'Icons', '64x64', 'adt.png') third_party = """Fast Isocontouring, Volume Rendering -- Chandrait Bajaj, UT Austin Adaptive Poisson Bolzman Solver (APBS) -- Nathan Baker Wash. Univ. St Louis GL extrusion Library (GLE) -- Linas Vepstas Secondary Structure Assignment (Stride) -- Patrick Argos EMBL Mesh Decimation (QSlim 2.0) -- Micheal Garland, Univeristy of Illinois Tiled Rendering (TR 1.3) -- Brian Paul GLF font rendering library -- Roman Podobedov PyMedia video encoder/decoder -- http://pymedia.org""" title = "AutoDockTools" #create a root and hide it try: from TkinterDnD2 import TkinterDnD root = TkinterDnD.Tk() except ImportError: from Tkinter import Tk root = Tk() root.withdraw() from mglutil.splashregister.splashscreen import SplashScreen from mglutil.splashregister.about import About about = About(image_dir=image_dir, third_party=third_party, path_data=path_data, title=title, version=version, revision=__revision__, copyright=copyright, authors=authors, icon=icon) if gui: splash = SplashScreen(about, noSplash=noSplash) from Pmv.moleculeViewer import MoleculeViewer mv = MoleculeViewer(logMode=logmode, customizer=customizer, master=root, title=title, withShell=not interactive, verbose=False, gui=gui) mv.browseCommands('autotors41Commands', commands=None, package='AutoDockTools') mv.browseCommands('autoflex41Commands', commands=None, package='AutoDockTools') mv.browseCommands('autogpf41Commands', commands=None, package='AutoDockTools') mv.browseCommands('autodpf41Commands', commands=None, package='AutoDockTools') mv.browseCommands('autostart41Commands', commands=None, package='AutoDockTools') mv.browseCommands('autoanalyze41Commands', commands=None, package='AutoDockTools') #mv.GUI.currentADTBar = 'AutoTools42Bar' #setADTmode("AD4.0", mv) setADTmode("AD4.2", mv) mv.browseCommands('selectionCommands', package='Pmv') mv.browseCommands('AutoLigandCommand', package='AutoDockTools', topCommand=0) mv.GUI.naturalSize() mv.customize('_adtrc') mv.help_about = about if gui: font = mv.GUI.ROOT.option_get('font', '*') mv.GUI.ROOT.option_add('*font', font) try: import Vision mv.browseCommands('visionCommands', commands=('vision', ), topCommand=0) mv.browseCommands('coarseMolSurfaceCommands', topCommand=0) if hasattr(mv, 'vision') and mv.vision.ed is None: mv.vision(log=0) else: # we address the global variable in vision Vision.ed = mv.vision.ed except ImportError: pass #show the application after it built if gui: splash.finish() root.deiconify() globals().update(locals()) if gui: mv.GUI.VIEWER.suspendRedraw = True cwd = os.getcwd() #mv._cwd differs from cwd when 'Startup Directory' userpref is set os.chdir(mv._cwd) if dmode is not None or cmode is not None: # save current list of commands run when a molecule is loaded addCmds = mv.getOnAddObjectCmd() # remove them if dmode is not None: for c in addCmds: mv.removeOnAddObjectCmd(c[0]) # set the mode setdmode(dmode, mv) if cmode is not None: # set the mode setcmode(cmode, mv) for a in args: if a[0] == '-': # skip all command line options continue elif (a[-10:] == '_pmvnet.py') or (a[-7:] == '_net.py'): # Vision networks mv.browseCommands('visionCommands', commands=('vision', )) if mv.vision.ed is None: mv.vision() mv.vision.ed.loadNetwork(a) if visionarg == 'run' or visionarg == 'once': mv.vision.ed.softrunCurrentNet_cb() elif a[-3:] == '.py': # command script print 'sourcing', a mv.source(a) elif a[-4:] in ['.pdb', '.pqr', 'pdbq', 'mol2', '.cif', '.gro' ] or a[-5:] == 'pdbqs' or a[-5:] == 'pdbqt': mv.readMolecule(a) elif a in ['clear', 'tested', 'nighlty']: pass else: print 'WARNING: unable to process %s command line argument' % a if again: mv.source(".tmp.py") if dmode is not None or cmode is not None: # get current list of commands run when a molecule is loaded cmds = mv.getOnAddObjectCmd() # remove them for c in cmds: mv.removeOnAddObjectCmd(c[0]) # restore original list of commands for c in addCmds: apply(mv.addOnAddObjectCmd, c) if gui: mv.GUI.VIEWER.suspendRedraw = False os.chdir(cwd) if visionarg != 'once': if ownInterpreter is True: mod = __import__('__main__') mod.__dict__.update({'self': mv}) if interactive: sys.stdin = sys.__stdin__ sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ if ipython is True: try: # create IPython shell from IPython.Shell import _select_shell sh = _select_shell([])(argv=[], user_ns=mod.__dict__) sh.mainloop() except: import code try: # hack to really exit code.interact code.interact( 'AutoDockTools Interactive Shell', local=mod.__dict__) except: pass else: import code try: # hack to really exit code.interact code.interact('AutoDockTools Interactive Shell', local=mod.__dict__) except: pass elif not die: #mv.GUI.pyshell.interp.locals = globals() if gui: mv.GUI.pyshell.interp.locals = mod.__dict__ mv.GUI.ROOT.mainloop() mod.__dict__.pop('self') else: ed.master.mainloop() except: import traceback traceback.print_exc() raw_input("hit enter to continue") import sys sys.exit(1)
def startMoleculeViewer(): global mv from Pmv.moleculeViewer import MoleculeViewer mv = MoleculeViewer(customizer = './.empty', logMode = 'overwrite') mv.setUserPreference(('trapExceptions', '0'), log = 0) mv.setUserPreference(('warningMsgFormat', 'printed'), log = 0) mv.loadCommand('fileCommands', 'readMolecule', 'Pmv') mv.loadCommand('deleteCommands','deleteMol', 'Pmv') mv.loadCommand("bondsCommands", "buildBondsByDistance", "Pmv") mv.setOnAddObjectCommands(['buildBondsByDistance','displayLines'], log=0) mv.loadModule("interactiveCommands", 'Pmv') mv.loadModule('secondaryStructureCommands', 'Pmv')
def runADT(*argv, **kw): """The main function for running AutoDockTools """ import sys if type(argv) is tuple: if len(argv) == 0: argv = None elif len(argv) == 1: argv = argv[0] if type(argv) is not list: argv = [argv] else: argv = list(argv) if kw.has_key("ownInterpreter"): ownInterpreter = kw["ownInterpreter"] else: if argv is None: argv = ['AutoDockTools/bin/runADT.py', '-i'] ownInterpreter = False elif argv[0].endswith('runADT.py') is False: argv.insert(0,'-i') argv.insert(0,'AutoDockTools/bin/runADT.py') ownInterpreter = False else: ownInterpreter = True optlist, args = getopt.getopt(argv[1:], 'haipsd:c:v:', [ 'update', 'help', 'again', 'overwriteLog', 'uniqueLog', 'noLog', 'noGUI', 'die', 'customizer=', 'interactive', 'dmode=', 'cmode=', 'noSplash', 'vision', 'python'] ) help_msg = """usage: pmv <options> -h or --help : print this message -a or --again : play back lastlog file --overwriteLog : overwrite log file --uniqueLog : create a log file with a unique name --noLog : turn off logging --noGUI : start PMV without the Graphical User Interface -s or --noSplash : turn off Splash Screen --die : do not start GUI event loop --customizer file : run the user specified file --lib packageName : add a libraries of commands -p or --ipython : create an ipython shell instead of a python shell -v r or --vision run : run vision networks on the command line -v o or --vision once : run vision networks and exit PMV --update [nightly|tested|clear] : update MGLTools if no arguments are given Update Manager GUI is provided 'nightly': download and install Nightly Builds 'tested' : download and install tested Nightly Builds 'clear' : clear/uninstall all the updates -d or --dmode modes : specify a display mode modes can be any a combination of display mode 'cpk' : cpk 'lines': lines 'ss' : secondary structure ribbon 'sb' : sticks and balls 'lic' : licorice 'ms' : molecular surface 'ca' : C-alpha trace 'bt' : backbone trace 'sp' : CA-spline 'sssb' : secondary structure for proteins, sticks and balls for other residues with bonds lines for other residues without bonds -c or --cmode modes : specify a display mode color scheme: 'ca' : color by atom 'cr' : color by residue (RASMOL scheme) 'cc' : color by chain 'cm' : color by molecule 'cdg': color using David Goodsell's scheme 'cs' : color residues using Shapely scheme 'css': color by secondary structure element example: display protein as ribbon, non protein as sticks and balls and color by atom type adt -i --dmode sssb --cmode cr myprot.pdb adt -i -m sssb -c cr myprot.pdb """ customizer = None logmode = 'overwrite' libraries = [] again = 0 interactive = 0 ipython = False die=0 gui = True noSplash = False dmode = cmode = None dmodes = ['cpk', 'lines', 'ss', 'sb', 'lic', 'ms', 'ca', 'bt', 'sp', 'sssb' ] cmodes = ['ca', 'cr', 'cc', 'cm', 'cdg', 'cs', 'css'] visionarg = None for opt in optlist: if opt[ 0] in ('-h', '--help'): print help_msg sys.exit() elif opt[ 0] in ('-a', '--again'): again = 1 os.system("mv mvAll.log.py .tmp.py") elif opt[ 0] =='--overwriteLog': logmode = 'overwrite' elif opt[ 0] =='--uniqueLog': logmode = 'unique' elif opt[ 0] =='--noLog': logmode = 'no' elif opt[ 0] =='--noGUI': gui = False elif opt[ 0] =='--die': die = 1 elif opt[ 0] in ('-s', '--noSplash'): noSplash = True elif opt[ 0] == '--customizer': customFile = opt[1] elif opt[ 0] == '--lib': libraries.append(opt[1]) elif opt[ 0] in ('-i', '--interactive'): interactive = 1 elif opt[ 0] in ('-p', '--python'): ipython = True elif opt[ 0] in ('-d', '--dmode'): assert min([mo in dmodes for mo in opt[1].split('|')])==True dmode = opt[1] elif opt[ 0] in ('-c', '--cmode'): assert min([mo in cmodes for mo in opt[1].split('|')])==True cmode = opt[1] elif opt[0] == '--update': try: from Support.update import Update except ImportError: print "Support package is needed to get updates" break update = Update() if 'nightly' in args: update.latest = 'nightly' update.getUpdates() elif 'tested' in args: update.latest = 'tested' update.getUpdates() elif 'clear' in args: print "Removing all updates" update.clearUpdates() else: waitTk = update.gui() update.master.wait_variable(waitTk) elif opt[ 0] in ('-v', '--vision'): if opt[1] in ('o', 'once'): visionarg = 'once' elif opt[1] in ('r', 'run'): visionarg = 'run' else: print "unknown option %s %s"%tuple(opt) print help_msg sys.exit(1) #import sys text = 'Python executable : '+ sys.executable +'\n' if kw.has_key('AdtScriptPath'): text += 'ADT script : '+ kw['AdtScriptPath'] +'\n' text += 'MGLTool packages '+'\n' from Support.path import path_text, release_path from Support.version import __version__ from mglutil import __revision__ version = __version__ text += path_text text += version+': '+release_path path_data = text print 'Run ADT from ', __path__[0] # if MGLPYTHONPATH environment variable exists - insert the specified path # into sys.path #if os.environ.has_key("MGLPYTHONPATH"): # if sys.platform == "win32": # mglPath = split(os.environ["MGLPYTHONPATH"], ";") # else: # mglPath = split(os.environ["MGLPYTHONPATH"], ":") # mglPath.reverse() # for p in mglPath: # sys.path.insert(0, os.path.abspath(p)) try: ################################################################## # Splash Screen ################################################################## import Pmv image_dir = os.path.join( Pmv.__path__[0],'Icons','Images') copyright = """(c) 1999-2010 Molecular Graphics Laboratory, The Scripps Research Institute ALL RIGHTS RESERVED """ authors = """Authors: Michel F. Sanner, Ruth Huey, Sargis Dallakyan, Chris Carrillo, Kevin Chan, Sophie Coon, Alex Gillet, Sowjanya Karnati, William (Lindy) Lindstrom, Garrett M. Morris, Brian Norledge, Anna Omelchenko, Daniel Stoffler, Vincenzo Tschinke, Guillaume Vareille, Yong Zhao""" icon = os.path.join(Pmv.__path__[0],'Icons','64x64','adt.png') third_party = """Fast Isocontouring, Volume Rendering -- Chandrait Bajaj, UT Austin Adaptive Poisson Bolzman Solver (APBS) -- Nathan Baker Wash. Univ. St Louis GL extrusion Library (GLE) -- Linas Vepstas Secondary Structure Assignment (Stride) -- Patrick Argos EMBL Mesh Decimation (QSlim 2.0) -- Micheal Garland, Univeristy of Illinois Tiled Rendering (TR 1.3) -- Brian Paul GLF font rendering library -- Roman Podobedov PyMedia video encoder/decoder -- http://pymedia.org""" title="AutoDockTools" #create a root and hide it try: from TkinterDnD2 import TkinterDnD root = TkinterDnD.Tk() except ImportError: from Tkinter import Tk root = Tk() root.withdraw() from mglutil.splashregister.splashscreen import SplashScreen from mglutil.splashregister.about import About about = About(image_dir=image_dir, third_party=third_party, path_data=path_data, title=title, version=version, revision=__revision__, copyright=copyright, authors=authors, icon=icon) if gui: splash = SplashScreen(about, noSplash=noSplash) from Pmv.moleculeViewer import MoleculeViewer mv = MoleculeViewer( logMode=logmode, customizer=customizer, master=root, title=title, withShell= not interactive, verbose=False, gui=gui) mv.browseCommands('autotors41Commands', commands = None, package = 'AutoDockTools') mv.browseCommands('autoflex41Commands', commands = None, package = 'AutoDockTools') mv.browseCommands('autogpf41Commands', commands = None, package = 'AutoDockTools') mv.browseCommands('autodpf41Commands', commands = None, package = 'AutoDockTools') mv.browseCommands('autostart41Commands', commands = None, package = 'AutoDockTools') mv.browseCommands('autoanalyze41Commands', commands = None, package = 'AutoDockTools') #mv.GUI.currentADTBar = 'AutoTools42Bar' #setADTmode("AD4.0", mv) setADTmode("AD4.2", mv) mv.browseCommands('selectionCommands', package='Pmv') mv.browseCommands('AutoLigandCommand', package='AutoDockTools', topCommand=0) mv.GUI.naturalSize() mv.customize('_adtrc') mv.help_about = about if gui: font = mv.GUI.ROOT.option_get('font', '*') mv.GUI.ROOT.option_add('*font', font) try: import Vision mv.browseCommands('visionCommands', commands=('vision',), topCommand=0) mv.browseCommands('coarseMolSurfaceCommands', topCommand=0) if hasattr(mv,'vision') and mv.vision.ed is None: mv.vision(log=0) else: # we address the global variable in vision Vision.ed = mv.vision.ed except ImportError: pass #show the application after it built if gui: splash.finish() root.deiconify() globals().update(locals()) if gui: mv.GUI.VIEWER.suspendRedraw = True cwd = os.getcwd() #mv._cwd differs from cwd when 'Startup Directory' userpref is set os.chdir(mv._cwd) if dmode is not None or cmode is not None: # save current list of commands run when a molecule is loaded addCmds = mv.getOnAddObjectCmd() # remove them if dmode is not None: for c in addCmds: mv.removeOnAddObjectCmd(c[0]) # set the mode setdmode(dmode, mv) if cmode is not None: # set the mode setcmode(cmode, mv) for a in args: if a[0]=='-':# skip all command line options continue elif (a[-10:]=='_pmvnet.py') or (a[-7:]=='_net.py'): # Vision networks mv.browseCommands('visionCommands', commands=('vision',) ) if mv.vision.ed is None: mv.vision() mv.vision.ed.loadNetwork(a) if visionarg == 'run' or visionarg == 'once': mv.vision.ed.softrunCurrentNet_cb() elif a[-3:]=='.py': # command script print 'sourcing', a mv.source(a) elif a[-4:] in ['.pdb', '.pqr', 'pdbq', 'mol2', '.cif', '.gro'] or a[-5:]=='pdbqs' or a[-5:]=='pdbqt': mv.readMolecule(a) elif a in ['clear', 'tested', 'nighlty']: pass else: print 'WARNING: unable to process %s command line argument'%a if again: mv.source(".tmp.py") if dmode is not None or cmode is not None: # get current list of commands run when a molecule is loaded cmds = mv.getOnAddObjectCmd() # remove them for c in cmds: mv.removeOnAddObjectCmd(c[0]) # restore original list of commands for c in addCmds: apply( mv.addOnAddObjectCmd, c ) if gui: mv.GUI.VIEWER.suspendRedraw = False os.chdir(cwd) if visionarg != 'once': if ownInterpreter is True: mod = __import__('__main__') mod.__dict__.update({'self':mv}) if interactive: sys.stdin = sys.__stdin__ sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ if ipython is True: try: # create IPython shell from IPython.Shell import _select_shell sh = _select_shell([])(argv=[], user_ns=mod.__dict__) sh.mainloop() except: import code try: # hack to really exit code.interact code.interact( 'AutoDockTools Interactive Shell', local=mod.__dict__) except: pass else: import code try: # hack to really exit code.interact code.interact( 'AutoDockTools Interactive Shell', local=mod.__dict__) except: pass elif not die: #mv.GUI.pyshell.interp.locals = globals() if gui: mv.GUI.pyshell.interp.locals = mod.__dict__ mv.GUI.ROOT.mainloop() mod.__dict__.pop('self') else: ed.master.mainloop() except: import traceback traceback.print_exc() raw_input("hit enter to continue") import sys sys.exit(1)
## if hasattr(atom, 'segID'): ## atom.segID = a[1].segID ## atom.hetatm = 0 ## atom.alternate = [] ## atom.element = 'H' ## atom.number = -1 ## atom.occupancy = 1.0 ## atom.conformation = 0 ## atom.temperatureFactor = 0.0 ## atom.babel_atomic_number = a[2] ## atom.babel_type = a[3] ## atom.babel_organic=1 ## bond = Bond( a[1], atom ) from Pmv.moleculeViewer import MoleculeViewer mv = MoleculeViewer() mv.addMolecule(mol) mol.bondsflag = 1 mv.lines( mol ) v = [] l = [] g = mv.Mols[0].geomContainer.geoms['lines'] vc = len(g.vertexSet) scale = [0, 1, -1, 2, -2, 3, -3, 4, -4] add = -1 ## for b in bonds: ## if b.bondOrder>1: ## b.bondOrder = 5 ## break
class EmbeddedMolViewer: def __init__(self, target=None, # Tk container name = 'Embedded camera', debug = 0, ): self.debug = debug if self.debug: print "EmbeddedMolViewer __init__> ", target self.target = target self.PMV_win = Toplevel() self.PMV_win.withdraw() VFGUI.hasDnD2 = False print "\n==========================================" print " Initializing PMV..." self.mv = MoleculeViewer(logMode = 'overwrite', master=self.PMV_win, # customizer='custom_pmvrc', title='[embedded viewer]', withShell=False, verbose=False, gui = True, guiVisible=1) self.VIEWER = self.mv.GUI.VIEWER self.GUI = self.mv.GUI self.VIEWER.cameras[0].suspendRedraw = 1 # stop updating the main Pmv camera self._pmv_visible = False self.cameras = {} # 'name' {'obj' : pmv_obj, 'structures': [mol1_obj, mol2_obj, ....], } self.cameras['pmv'] = { 'obj' :self.VIEWER.cameras[0], 'structures' : [], } self.cameraslist = ['pmv'] # name0, name1, name2 # keep the order in which cameras are added self.target = target print " [ DONE ]" print "==========================================\n" self.initStyles() if self.target: self.addCamera(target = self.targer, name=name) def initStyles(self): """ initialize styles dictionary """ #color_cb = CallbackFunction(self.mv.colorByAtomType, (['lines', 'balls', 'sticks'], log=0) ) #self.styles ={ 'default' : [ color_cb ] } # XXX WHAT TO DO? pass def togglepmv(self, event=None): """ toggle between visible and hidden pmv""" if self._pmv_visible: self._hidePmv() else: self._showPmv() def _showPmv(self, event=None): """ stop all cams and restore the underlying pmv session """ if self.debug: print "_showPmv> called" print "ACTIVE CAMS", self.activeCams() self._pmv_suspended_cams = self.activeCams() self.activateCam(['pmv'], only=1, mols=True) self._pmv_visible = True self.mv.GUI.ROOT.deiconify() def _hidePmv(self, event=None): """ stop Pmv camera, minimize Pmv and restore previously disabled cams """ self.VIEWER.cameras[0].suspendRedraw = 1 # stop updating the main Pmv camera self._pmv_visible = False self.mv.GUI.ROOT.withdraw() self.activateCam(self._pmv_suspended_cams, only=1, mols=True) def addCamera(self,target,name = '', depth=True, bgcolor=(0., 0., 0.)): """ add a new camera 'name' bound to 'target'""" if self.debug: print "adding another camera" if name in self.cameraslist: print "Camera [%s] already exist!", name return cam_obj = self.VIEWER.AddCamera(master=target) # the next ones will be added) if depth: cam_obj.fog.Set(enabled=1) cam_obj.backgroundColor = ( bgcolor + (1.0,) ) cam_obj.Redraw() self.cameraslist.append(name) self.cameras[name] = { 'obj':cam_obj, 'structures' : [] } return cam_obj def delCamera(self, idx=None, name=None, mols=True): """ delete camera by index or by name; by default all molecules loaded in a given camera are loaded """ if self.debug: print "delcamera", idx, name if idx == None and name == None: print "delete camera by name or by idx!" return if idx == 0 or len(self.VIEWER.cameras) == 1: print "cowardly refusing to delete the main Pmv camera...(returning)" return self.VIEWER.DeleteCamera(idx) name = self.cameraslist.pop(idx) if mols: for s in self.cameras[name]['structures']: self.mv.deleteMol(s) # delete all objects from this camera self.nukeCamMols(name) # delete camera del self.cameras[name] def activeCams(self): """ return list of active cameras""" active = [] #active = [ name for name in self.cameras.keys() if self.cameras[name]['obj'].suspendRedraw == 0 ] for c in self.cameras.keys(): if not self.cameras[c]['obj'].suspendRedraw: active.append(c) return active def cams(self): """ return the list of all camera names""" return self.cameras.keys() def cameraByName(self, name): #, attribute='obj'): """ retrieve camera object by name None, if camera doesn't exist """ cam = self.cameras.get(name, None) if not cam == None: return cam['obj'] else: return None def cameraStructures(self, name): """ return all mols loaded in this camera""" return self.cameras[name]['structures'] def activateCam(self, namelist=[], only=1, mols=True): """ activate redraw on selected camera and disabling (by default) other cameras """ # - reactivate this camera if self.debug: print "activatecam> namelist", namelist for c in self.cameras.keys(): if c in namelist: for s in self.cameras[c]['structures']: # XXX ASK MICHEL if isinstance(s, Molecule): s = s.geomContainer.geoms['master'] s.Set(visible=True) #,redraw=False) self.cameras[c]['obj'].Redraw() self.cameras[c]['obj'].suspendRedraw = 0 elif only: self.cameras[c]['obj'].suspendRedraw = 1 # hide molecules loaded in this camera for s in self.cameras[c]['structures']: if isinstance(s, Molecule): s = s.geomContainer.geoms['master'] s.Set(visible=False) #,redraw=False) def deactivateCam(self, namelist=[]): """ disable redraw update in cameras""" self.VIEWER.redrawLock.acquire() if len(namelist) == 0: namelist = self.cameras.keys() for c in namelist: self.cameras[c]['obj'].suspendRedraw = 1 self.VIEWER.redrawLock.release() def loadMolWithStyle(self, molfile, style='default'): """ load molecules with representation style """ mol = self.mv.readMolecule(molfile, modelsAs='conformations') return mol def loadInCamera(self, molfile, camera, style='default'): """ load molecule in selected camera and apply optional repr.style """ mol = self.loadMolWithStyle(molfile, style=style)[0] self.cameras[camera]['structures'].append(mol) return mol def deleteInCamera(self, molobj, camera): """ delete an object from a camera""" m = """ ####################################### ### ### ### PROBLEMATIC DELETION! ASK MICHEL ### ISSUE WITH DELETING FILES ### ### #######################################""" #print m #print "LIST OF STRUCTURES", self.cameras[camera]['structures'] self.mv.deleteMol(molobj) self.cameras[camera]['structures'] = [ x for x in self.cameras[camera]['structures'] if not x == molobj ] return idx = self.cameras[camera]['structures'].index(molobj) d = self.cameras[camera]['structures'].pop(idx) try: self.mv.deleteMol(d) except: print "TRYING TO DELETE MOLECULE %s RAISED ERROR!" % d def nukeCamMols(self, camera): """ delete all molecules from a cam""" for m in self.cameras[camera]['structures']: self.mv.deleteMol(m) self.cameras[camera]['structures'] = [] def centerView(self, item=None): """ center the view on specified target if target is None, reset the view on all mols """ root = self.VIEWER.rootObject if item == None: item = root self.VIEWER.toggleTransformRootOnly(False) self.VIEWER.SetCurrentObject(item) #self.VIEWER.Reset_cb() self.VIEWER.Normalize_cb() self.VIEWER.toggleTransformRootOnly(True) self.VIEWER.Center_cb() self.VIEWER.SetCurrentObject(root)
def setUp(self): global mv if mv is None: from Pmv.moleculeViewer import MoleculeViewer mv = MoleculeViewer(customizer='./.empty', logMode='no', withShell=False, verbose=False) mv.browseCommands('fileCommands', package="Pmv", topCommand=0) mv.browseCommands('bondsCommands', package='Pmv', topCommand=0) mv.browseCommands('colorCommands', package='Pmv', topCommand=0) mv.browseCommands('deleteCommands', package='Pmv', topCommand=0) mv.browseCommands('displayCommands', commands=[ 'displaySticksAndBalls', 'undisplaySticksAndBalls', 'displayCPK', 'undisplayCPK', 'displayLines', 'undisplayLines', 'displayBackboneTrace', 'undisplayBackboneTrace', 'DisplayBoundGeom' ], package='Pmv', topCommand=0) mv.setOnAddObjectCommands( ['buildBondsByDistance', 'displayLines', 'colorByAtomType'], topCommand=0) #mv.loadModule("interactiveCommands", 'Pmv') mv.loadCommand("visionCommands", "vision", "Pmv") # Don't want to trap exceptions and errors... the user pref is set to 1 by # default #mv.setUserPreference(('trapExceptions', '0'), log = 0) mv.setUserPreference(('warningMsgFormat', 'printed'), log=0) self.mv = mv