Package Pmv :: Module trajectoryCommands
[hide private]
[frames] | no frames]

Source Code for Module Pmv.trajectoryCommands

   1  # 
   2  # $Header: /opt/cvs/python/packages/share1.5/Pmv/trajectoryCommands.py,v 1.10 2007/07/02 22:27:05 annao Exp $ 
   3  # 
   4  # $Id: trajectoryCommands.py,v 1.10 2007/07/02 22:27:05 annao Exp $ 
   5  # 
   6   
   7   
   8  # implements classes to read and play GROMACS trajectory files 
   9  import warnings 
  10  import os 
  11  from MolKit.trajParser import trrParser, xtcParser 
  12  import Pmw, Tkinter 
  13  import Numeric 
  14  from opengltk.OpenGL import GL 
  15  import time 
  16   
17 -class Trajectory:
18 """class to store GROMACS trajectory file data""" 19
20 - def __init__ (self, file, mol = None):
21 22 self.file = file 23 self.parser = self.getParser(file) 24 self.nbAtoms = None 25 self.nbSteps = None 26 self.coords = [] 27 self.velocities = {} 28 self.nbFrames = None 29 self.forces = {} 30 self.energies = {} 31 self.mol = mol 32 self.player = None
33 34 35
36 - def getParser(self, file):
37 """determine which parser to use""" 38 39 fext = os.path.splitext(file)[-1] 40 if fext == ".trr": 41 return trrParser(file) 42 elif fext == ".xtc": 43 return xtcParser(file) 44 else: 45 print "ERROR: unsupported trajectory file format %s"%fext 46 return None
47 48 49
50 - def readTrajectory(self):
51 """parse trajectory file""" 52 self.parser.read() 53 self.coords = self.parser.coords 54 self.nbAtoms = len(self.coords[0]) 55 self.nbFrames = len(self.coords) 56 self.velocities = self.parser.velocities 57 self.forces = self.parser.forces
58 59 60 61 62 from mglutil.gui.BasicWidgets.Tk.player import Player 63 from ViewerFramework.VF import EditAtomsEvent 64 65 from mglutil.util.callback import CallBackFunction 66 from mglutil.gui.InputForm.Tk.gui import InputFormDescr, InputForm, evalString 67 from mglutil.util.callback import CallbackManager 68 from mglutil.gui.BasicWidgets.Tk.thumbwheel import ThumbWheel 69 from mglutil.util.packageFilePath import findFilePath 70 import tkMessageBox 71 from MolKit.pdbParser import PdbParser, PdbqParser, PdbqtParser 72 from MolKit.groParser import groParser 73 74 from string import find 75
76 -class TrajPlayer(Player):
77 """ a GUI to play a trajectory. The class constructor takes a Trajectory object and 78 a correspoonding molecule as arguments.""" 79
80 - def __init__(self, mol, traj, vf, titleStr=None, sequenceList=None, 81 idList = None, delta=0, form2=1, 82 ask=1, **kw):
83 84 self.mol = mol 85 self.traj = traj 86 self.startFrame = 0 87 self.ask = ask 88 mol.allAtoms.addConformation(mol.allAtoms.coords[:]) 89 self.coordSlot = len(mol.allAtoms[0]._coords) - 1 90 self.update(sequenceList, idList) 91 kw['master'] = vf.GUI.ROOT 92 kw['endFrame'] = self.endFrame 93 kw['maxFrame'] = self.endFrame 94 kw['form2'] = form2 95 kw['titleStr'] = titleStr 96 self.vf = vf 97 apply(Player.__init__, (self,), kw) 98 try: 99 self.form.ifd.entryByName['setanimB']['widget'].grid_forget() 100 #print 'withdrew SetAnim button' 101 self.form.autoSize() 102 except: 103 pass
104
105 - def update(self, sequenceList=None, idList=None):
106 if not sequenceList: 107 self.sequenceList = range(len(self.traj.coords)) 108 #self.sequenceList = self.traj.coords.keys() 109 else : 110 self.sequenceList = sequenceList 111 lenSeq = len(self.sequenceList) 112 self.maxFrame = lenSeq 113 self.endFrame = lenSeq 114 if self.startFrame>lenSeq: 115 self.startFrame = 0 116 117 if hasattr(self, 'playModeForm'): 118 e = self.playModeForm.descr.entryByName 119 endTW = e['endFrameTW']['widget'] 120 #print 'setting endTW to ', self.endFrame 121 endTW.max = self.endFrame 122 endTW.set(self.endFrame) 123 startTW = e['startFrameTW']['widget'] 124 startTW.set(self.startFrame) 125 if not idList: 126 #insert 0 for original state 127 idL = range(0, len(self.sequenceList) + 1) 128 self.idList = map(str, idL) 129 else: 130 self.idList = map(str, idList) 131 #print "self.idList", self.idList 132 133 if hasattr(self, 'form'): 134 if hasattr(self.form, 'ent2'): 135 newLen = max(map(len, self.idList)) 136 if newLen>3: 137 #print 'update:updating ent2 width' 138 self.form.ent2.config(width=newLen) 139 self.form.ent2.delete(0,'end') 140 #could use startFrame if it is valid here: 141 if self.startFrame<=len(self.sequenceList) and self.startFrame>0: 142 next_val = str(self.idList[self.startFrame]) 143 self.form.ent2.insert(0, next_val) 144 self.currentFrameIndex = self.startFrame 145 self.applyState(self.startFrame-1) 146 else: 147 #print "restarting from frame =", self.idList[0] 148 #print self.startFrame, ": index out of range for ", sequenceList, "; resetting startFrame to 0" 149 self.form.ent2.insert(0, str(self.idList[0])) 150 #this calls applyState with reset flag 151 self.applyState(-1)
152 153
154 - def applyState(self, ind):
155 """None<-applyState(ind)""" 156 mol = self.mol 157 # -1 is key for go back to original 158 if int(ind)==-1: 159 mol.allAtoms.setConformation(0) 160 conf = None 161 else: 162 163 #in this case want to get new coords 164 #coords = self.traj.coords["frame%d"%ind] 165 coords = self.traj.coords[ind] 166 coordsarr = (Numeric.array(coords)*10).astype("f") 167 allAtoms = self.mol.allAtoms 168 allAtoms.updateCoords(coordsarr[:], self.coordSlot) 169 170 if not self.vf.hasGui: return 171 event = EditAtomsEvent('coords', mol.allAtoms) 172 self.vf.dispatchEvent(event) 173 #modEvent = ModificationEvent('edit','coords', mol.allAtoms) 174 #mol.geomContainer.updateGeoms(modEvent) 175 self.vf.GUI.VIEWER.Redraw()
176 #self.showStats() 177 178 179 180 181
182 - def SetMode_cb(self, event=None):
183 #print 'SetMode' 184 #playMode options: 185 # 0 play once and stop 186 # 1 play continuously in 1 direction 187 # 2 play once in 2 directions 188 # 3 play continuously in 2 directions 189 #play framerate is frame/per second 190 if not hasattr(self, 'playModeForm'): 191 self.showPlayMode = Tkinter.IntVar() 192 self.showFrameParmWidgets = Tkinter.IntVar() 193 self.playModeVar = Tkinter.StringVar() 194 self.playModeVar.set('once and stop') 195 self.playModeList=[ 'once and stop', 196 'continuously in 1 direction', 197 'once in 2 directions', 198 'continuously in 2 directions'] 199 self.frameParmsList=[ 'framerateLabel','framerateTW','startFrameLabel', 200 'startFrameTW', 'endFrameLabel', 'endFrameTW', 201 'stepSizeLabel', 'stepSizeTW'] 202 203 #self.showListVar = Tkinter.IntVar() 204 ifd2 = InputFormDescr(title='Set Play Options') 205 ## ifd2.append({'name':'selectCB', 206 ## 'widgetType': Tkinter.Checkbutton, 207 ## 'tooltip':'show ids of current ordered conformation list', 208 ## 'wcfg':{ 'text':'Show Conf List', 209 ## #'command': self.showStatesList, 210 ## #'variable': self.showListVar, 211 ## }, 212 ## 'gridcfg':{'sticky':'ew', 'row':-1, 'column':1}}) 213 ## #'gridcfg':{'sticky':'ew'}}) 214 ifd2.append({'name':'playModeMb', 215 'widgetType': Tkinter.Menubutton, 216 'tooltip':'set play mode choice', 217 'wcfg':{ 'text':'Play Mode', 218 }, 219 'gridcfg':{'sticky':'we'}}) 220 #'gridcfg':{'sticky':'w', 'columnspan':2}}) 221 ifd2.append({'name':'adjustFrameParmsMb', 222 'widgetType': Tkinter.Checkbutton, 223 'tooltip':'opens panel to set play rate, start conf number, end conf number \nand step size for playing conf sequence', 224 'wcfg':{ 'text':'Play Parameters', 225 'command': self.showFrameParms_cb, 226 'variable': self.showFrameParmWidgets, 227 }, 228 'gridcfg':{'sticky':'w', 'row':-1, 'column':1}}) 229 ifd2.append( {'name': 'framerateLabel', 230 'widgetType':Tkinter.Label, 231 'wcfg':{'text':'frame rate:', 232 'font':('Helvetica',12,'bold')}, 233 'gridcfg':{'sticky':'w'}}) 234 ifd2.append({'name': 'framerateTW', 235 'wtype':ThumbWheel, 236 'widgetType':ThumbWheel, 237 'tooltip':'set max num of confs to be displayed per second', 238 'wcfg':{'labCfg':{'fg':'black', 'side':'left', 'text':''}, 239 'showLabel':1, 'width':100, 240 'min':0, 241 'max':100, 242 'lockBMin':1, 243 'lockBMax':0, 244 'lockBIncrement':1, 245 'value':self.framerate, 246 'oneTurn':100, 247 'type':'float', 248 'increment':.1, 249 'callback':self.setMode_cb, 250 'canvascfg':{'bg':'red'}, 251 'wheelLabcfg1':{'font':('Times',14,'bold')}, 252 'wheelLabcfg2':{'font':('Times',14,'bold')}, 253 'continuous':0, 'wheelPad':1, 'height':20}, 254 'gridcfg':{'sticky':'nesw', 'row':-1, 'column':1}}) 255 ifd2.append( {'name': 'startFrameLabel', 256 'widgetType':Tkinter.Label, 257 'wcfg':{'text':'start frame:', 258 'font':('Helvetica',12,'bold')}, 259 'gridcfg':{'sticky':'w'}}) 260 ifd2.append({'name': 'startFrameTW', 261 'wtype':ThumbWheel, 262 'widgetType':ThumbWheel, 263 'tooltip':'set number of first conf to be displayed', 264 'wcfg':{ 265 'labCfg':{ 266 'fg':'black', 267 'side':'left', 268 'text':'' 269 }, 270 'showLabel':1, 'width':100, 271 'min':0, 272 'max':self.endFrame, 273 'lockBMin':0, 274 'lockBMax':1, 275 'lockBIncrement':1, 276 'value':self.startFrame, 277 'oneTurn':10, 278 'type':'int', 279 'increment':1, 280 'callback':self.setMode_cb, 281 'canvascfg':{'bg':'green'}, 282 'wheelLabcfg1':{'font':('Times',14,'bold')}, 283 'wheelLabcfg2':{'font':('Times',14,'bold')}, 284 'continuous':0, 'wheelPad':1, 'height':20}, 285 'gridcfg':{'sticky':'ew', 'row':-1, 'column':1}}) 286 ifd2.append( {'name': 'endFrameLabel', 287 'widgetType':Tkinter.Label, 288 'wcfg':{'text':'end frame:', 289 'font':('Helvetica',12,'bold')}, 290 'gridcfg':{'sticky':'w'}}) 291 ifd2.append({'name': 'endFrameTW', 292 'wtype':ThumbWheel, 293 'widgetType':ThumbWheel, 294 'tooltip':'set number of last conf to be displayed', 295 'wcfg':{ 296 'labCfg':{ 297 'fg':'black', 298 'side':'left', 299 'text':'' 300 }, 301 'showLabel':1, 'width':100, 302 'min':self.startFrame, 303 'max':self.maxFrame, 304 'lockBMin':1, 305 'lockBMax':0, 306 'lockBIncrement':1, 307 'value':self.endFrame, 308 'oneTurn':10, 309 'type':'int', 310 'increment':1, 311 'callback':self.setMode_cb, 312 'canvascfg':{'bg':'green'}, 313 'wheelLabcfg1':{'font':('Times',14,'bold')}, 314 'wheelLabcfg2':{'font':('Times',14,'bold')}, 315 'continuous':0, 'wheelPad':1, 'height':20}, 316 'gridcfg':{'sticky':'nesw', 'row':-1, 'column':1}}) 317 ifd2.append( {'name': 'stepSizeLabel', 318 'widgetType':Tkinter.Label, 319 'wcfg':{'text':'step size:', 320 'font':('Helvetica',12,'bold')}, 321 'gridcfg':{'sticky':'w'}}) 322 ifd2.append({'name': 'stepSizeTW', 323 'wtype':ThumbWheel, 324 'widgetType':ThumbWheel, 325 'tooltip':'set step before next conf number: default is 1', 326 'wcfg':{ 327 'labCfg':{ 328 'fg':'black', 329 'side':'left', 330 'text':'' 331 }, 332 'showLabel':1, 'width':100, 333 'min':1, 334 'max':1000, 335 'lockBMin':1, 336 'lockBMax':0, 337 'lockBIncrement':1, 338 'value':self.stepSize, 339 'oneTurn':10, 340 'type':'int', 341 'increment':1, 342 'callback':self.setMode_cb, 343 'canvascfg':{'bg':'blue'}, 344 'wheelLabcfg1':{'font':('Times',14,'bold')}, 345 'wheelLabcfg2':{'font':('Times',14,'bold')}, 346 'continuous':0, 'wheelPad':1, 'height':20}, 347 'gridcfg':{'sticky':'nesw', 'row':-1, 'column':1}}) 348 ifd2.append({'name':'buildB', 349 'widgetType': Tkinter.Button, 350 'tooltip':'build a new molecule with current conf coords\nand add it to viewer', 351 'wcfg':{ 'text':'Build Current', 352 'command': self.Build_cb, 353 }, 354 'gridcfg':{'sticky':'we'}}) 355 #'gridcfg':{'sticky':'ew', 'row':-1, 'column':1}}) 356 357 ifd2.append({'name':'writeB', 358 'widgetType': Tkinter.Button, 359 'tooltip':'write a new file with current conf coords', 360 'wcfg':{ 'text':'Write Current', 361 'command': self.Write_cb, 362 }, 363 #'gridcfg':{'sticky':'we'}}) 364 'gridcfg':{'sticky':'nesw', 'row':-1, 'column':1}}) 365 366 ifd2.append({'name':'cancelB', 367 'widgetType': Tkinter.Button, 368 'wcfg':{ 369 'text': 'Close', 370 'command': self.cancelPlayMode_cb, 371 }, 372 #'gridcfg':{'sticky':'ew', 'row':-1, 'column':1}}) 373 'gridcfg':{'sticky':'ew','columnspan':2}}), 374 self.playModeForm = InputForm(self.master, self.root, 375 descr = ifd2, 376 modal = 0, blocking = 0) 377 self.framerateWidget = ifd2.entryByName['framerateTW']['widget'] 378 self.startFrameWidget = ifd2.entryByName['startFrameTW']['widget'] 379 self.endFrameWidget = ifd2.entryByName['endFrameTW']['widget'] 380 self.stepSizeWidget = ifd2.entryByName['stepSizeTW']['widget'] 381 self.frameParmCfgs = [] 382 self.frameParmWidgets = [] 383 for i in self.frameParmsList: 384 ent = ifd2.entryByName[i] 385 self.frameParmCfgs.append(ent['gridcfg']) 386 self.frameParmWidgets.append(ent['widget']) 387 self.playModeMb = ifd2.entryByName['playModeMb']['widget'] 388 self.playModeMb.bind('<ButtonPress>', self.buildPlayModeMenu, add='+') 389 self.showFrameParms_cb() 390 #self.showList = ifd2.entryByName['selectCB']['widget'] 391 else: 392 self.playModeVar.set(self.playModeList[self.playMode]) 393 self.framerateWidget.set(self.framerate) 394 self.startFrameWidget.set(self.startFrame) 395 self.endFrameWidget.set(self.endFrame) 396 self.stepSizeWidget.set(self.stepSize) 397 self.playModeForm.deiconify() 398 self.playModeForm.autoSize()
399
400 - def buildPlayModeMenu(self, event=None):
401 mB = self.playModeMb 402 keyList = self.playModeList 403 if not self.showPlayMode.get(): 404 #mB.config(bg='white') 405 if not hasattr(mB, 'menu'): 406 mB.menu = Tkinter.Menu(mB) 407 mB['menu'] = mB.menu 408 else: 409 mB.menu.delete(1, 'end') 410 for i in range(len(keyList)): 411 mB.menu.add_radiobutton(label=keyList[i], var=self.playModeVar, 412 value=keyList[i], command=self.setMode_cb) 413 self.showPlayMode.set(1) 414 else: 415 mB.menu.unpost() 416 self.showPlayMode.set(0)
417
418 - def showFrameParms_cb(self, event=None):
419 if not self.showFrameParmWidgets.get(): 420 for w in self.frameParmWidgets: 421 w.grid_forget() 422 else: 423 for i in range(len(self.frameParmWidgets)): 424 w = self.frameParmWidgets[i] 425 cfg = self.frameParmCfgs[i] 426 w.grid(cfg) 427 self.playModeForm.autoSize()
428
429 - def setMode_cb(self, event=None):
430 curVal = self.playModeVar.get() 431 #print 'setting playMode to ', curVal 432 self.playMode = self.playModeList.index(curVal) 433 #print 'setting playMode to ', curVal 434 self.framerate = round(self.framerateWidget.get(),4) 435 #print 'setting self.framerate ->', self.framerate 436 self.timestamp= 1./self.framerate 437 self.startFrame = self.startFrameWidget.get() 438 self.endFrame = self.endFrameWidget.get() 439 #print 'set endFrame to', self.endFrame 440 self.stepSize = self.stepSizeWidget.get() 441 self.playMode = self.playModeList.index(curVal) 442 #i think this restarts the player's trip memory 443 #that is, hasn't gone in any direction yet 444 self.oneDirection = 0 445 if not self.stop: 446 self.stop = 1 447 self.play(self.framerate)
448 449 450
451 - def setPlayMode_cb(self, event=None):
452 self.setMode_cb() 453 self.cancelPlayMode_cb() 454 self.oneDirection = 0
455 456
457 - def SetRMSRef_cb(self, event=None):
458 print 'in SetRMSRef_cb' 459 return
460 461
462 - def Build_cb(self, event=None):
463 #print building current 464 """None<-Build_cb(mol, event=None) 465 466 builds new molecule with current coordinates and adds it to the viewer 467 """ 468 #FIRST CHECK THAT THIS HASN'T already been built 469 #get the current counter content for name of new molecule 470 #w = self.form.ifd.entryByName['statesCounter']['widget'] 471 numStr = self.form.counter.get() 472 #numStr = w.get() 473 #remember idList has '0' always added at the beginning for input conf 474 confInd = self.idList.index(numStr) - 1 475 #CHECK THIS IS CORRECT!!! 476 conf = self.sequenceList[confInd] 477 self.buildConf(conf, numStr)
478 479
480 - def buildConf(self, conf, nameStr):
481 newname = self.mol.name + '_conf_' + nameStr 482 if newname in self.vf.Mols.name: 483 msg = newname + ' already in viewer. Not building a second copy' 484 self.vf.warningMsg(msg) 485 return 'ERROR' 486 allLines = self.mol.parser.allLines 487 newLines = [] 488 coords = self.mol.allAtoms.coords 489 natoms = len(coords) 490 ctr = 0 491 parser = self.mol.parser.__class__() 492 if isinstance(parser, groParser): 493 newLines.append(allLines[0]) 494 newLines.append(allLines[1]) 495 for l in allLines[2:natoms+2]: 496 cc = coords[ctr]/10 497 newLines.append(l[:20] +'%8.3f%8.3f%8.3f'%(cc[0],cc[1],cc[2])+ l[44:]) 498 ctr = ctr+1 499 for l in allLines[natoms+2:]: 500 newLines.append(l) 501 else: 502 for l in allLines: 503 if find(l, 'ATOM')==0 or find(l, 'HETA')==0: 504 cc = coords[ctr] 505 newLines.append(l[:30] +'%8.3f%8.3f%8.3f'%(cc[0],cc[1],cc[2])+ l[54:]) 506 ctr = ctr+1 507 else: 508 newLines.append(l) 509 510 parser.allLines = newLines 511 filename = parser.filename = self.mol.parser.filename + '_conf_' + nameStr 512 newMol = parser.parse()[0] 513 newMol.name = newname 514 newMol = self.vf.addMolecule(newMol, ask=self.ask)
515 516
517 - def Write_cb(self, event=None):
518 #print writing current 519 """None<-Write_cb(mol, event=None) 520 writes a new file with current coordinates 521 """ 522 filename = self.vf.askFileSave(types=[('pdb files','*.pdb'),('pdbq files', '*.pdbq'), 523 ('pdbqt files', '*.pdbqt'), ('.gro. files', '*.gro'), ("all", "*")], 524 title="write current conf:") 525 if filename is not None: 526 self.write_conf(filename)
527 528 529
530 - def write_conf(self, filename):
531 fptr = open(filename, 'w') 532 ctr = 0 533 liglines = self.mol.parser.allLines 534 coords = self.mol.allAtoms.coords 535 natoms = len(coords) 536 if isinstance(self.mol.parser, groParser): 537 fptr.write(liglines[0]) 538 fptr.write(liglines[1]) 539 for l in liglines[2:natoms+2]: 540 cc = coords[ctr]/10 541 fptr.write(l[:20] +'%8.3f%8.3f%8.3f'%(cc[0],cc[1],cc[2])+ l[44:]) 542 ctr +=1 543 for l in liglines[natoms+2:]: 544 fptr.write(l) 545 else: 546 for l in liglines: 547 if l.find("ATOM")!=0 and l.find("HETATM")!=0: 548 l += "\n" 549 fptr.write(l) 550 else: 551 crds = coords[ctr] 552 rec = "%s%8.3f%8.3f%8.3f%s\n"%(l[:30],crds[0], crds[1], crds[2],l[54:] ) 553 fptr.write(rec) 554 ctr += 1 555 fptr.close()
556 557 from mglutil.gui.BasicWidgets.Tk.customizedWidgets import SliderWidget 558 import Tkinter 559 560
561 -class TrajSliderWidget(SliderWidget):
562
563 - def __init__(self, master =None, **kw):
564 565 apply(SliderWidget.__init__, (self, master), kw) 566 self.draw.pack_forget() 567 self.draw.pack(side="left") 568 fnt='-*-helvetica-medium-r-narrow-*-*-120-*-*-*-*-*-*' 569 label=Tkinter.Label(self.frame, text=str(self.max), font=fnt) 570 label.pack(side='left', fill="both", expand="yes")
571 572 573
574 -class TrajPlayerCached(TrajPlayer):
575 """ This player saves display lists for each frame (when the frame is played for the first time) 576 to be used in consequent replays. """ 577
578 - def __init__(self, mol, traj, vf, titleStr=None, sequenceList=None, 579 idList = None, delta=0, form2=1, 580 ask=1, **kw):
581 kw['titleStr'] = titleStr 582 kw['sequenceList'] = sequenceList 583 kw['idList'] = idList 584 kw['delta'] = delta 585 kw['form2'] = form2 586 kw['ask'] = ask 587 TrajPlayer.__init__(self, mol, traj, vf, titleStr=titleStr, sequenceList=sequenceList, 588 idList = idList, delta=delta, form2=form2, ask=ask) 589 #add a button to clear cache 590 # add a slider to the form 591 sl = {'name': 'slider', 592 'widgetType':TrajSliderWidget, 593 'type':int, 594 'wcfg':{'label': '0', 'width':120, 'minval':0,'maxval':self.maxFrame, 'incr': 1, 595 'labelsCursorFormat':'%4d', 'sliderType':'int', 'immediate': 1, 596 'command': self.nextFrame}, 597 'gridcfg':{'sticky':'w','column':2, 'columnspan':4, } 598 } 599 cb = {'name': 'clearCache', 600 'widgetType': Tkinter.Button, 601 'text':'Clear rendering cache', 602 'tooltip':"Delete cached trajectory rendered frames to regenerate\nnew frames using currently displayed geometry", 603 'wcfg':{'bd':4}, 604 'gridcfg':{'sticky':'w', 'column':6, 'columnspan':5, 'row':-1}, 605 'command':self.clearCache_cb} 606 607 self.form.addEntry(sl) 608 self.form.addEntry(cb) 609 self.form.descr.entryByName[cb['name']] = cb 610 self.form.descr.entryByName[sl['name']] = sl 611 self.form.autoSize() 612 self.dpyLists ={}
613
614 - def nextFrame(self, id):
615 id = int(id) 616 strID = self.idList[id] 617 if self.hasCounter and self.gui: 618 self.form.ent2.delete(0,'end') 619 self.form.ent2.insert(0, str(strID)) 620 sl = self.form.descr.entryByName['slider']['widget'] 621 if int(sl.get()) != id: 622 sl.set(id, update = 0) 623 self.currentFrameIndex = int(id) 624 #self.currentFrameIndex = self.idList.index(str(id)) 625 626 self.applyState(self.currentFrameIndex-1)
627
628 - def applyState(self, ind):
629 """None<-applyState(ind)""" 630 mol = self.mol 631 viewer = self.vf.GUI.VIEWER 632 cache_list = False 633 # check if we can cache the display list for this frame 634 if self.dpyLists.has_key(ind): 635 if self.dpyLists[ind] is not None: 636 cache_list = True 637 viewer.currentCamera.dpyList = self.dpyLists[ind] 638 #viewer.dpyList = self.dpyLists[ind] 639 if not self.vf.hasGui: return 640 viewer.OneRedraw() 641 #viewer.Redraw() 642 else: 643 self.dpyLists.pop(ind) 644 if not cache_list: 645 if int(ind)==-1: # -1 is key for go back to original 646 mol.allAtoms.setConformation(0) 647 else: 648 #in this case we want to get new coords 649 coords = self.traj.coords[ind] 650 coordsarr = (Numeric.array(coords)*10).astype("f") 651 allAtoms = self.mol.allAtoms 652 allAtoms.updateCoords(coordsarr[:], self.coordSlot) 653 if not self.vf.hasGui: return 654 self.vf.GUI.VIEWER.singleDpyList = True 655 event = EditAtomsEvent('coords', mol.allAtoms) 656 self.vf.dispatchEvent(event) 657 viewer.OneRedraw() 658 #viewer.Redraw() 659 self.dpyLists[ind] = viewer.currentCamera.dpyList #viewer.dpyList 660 viewer.currentCamera.dpyList = None 661 #viewer.dpyList = None 662 self.vf.GUI.VIEWER.singleDpyList = False
663 #print "dpyList: ", ind, self.dpyLists[ind] 664 665
666 - def clearCache_cb(self):
667 #print "clearing cache: " 668 vi = self.vf.GUI.VIEWER 669 currentcontext = vi.currentCamera.tk.call(vi.currentCamera._w, 'getcurrentcontext') 670 for dl in self.dpyLists.keys(): 671 if self.dpyLists[dl]is not None: 672 if currentcontext != self.dpyLists[dl][1]: 673 print "currentcontext != self.dpyLists[%d][1]" %(dl,), currentcontext, self.dpyLists[dl][1] 674 c = vi.currentCamera 675 c.tk.call(c._w, 'makecurrent') 676 677 #import pdb; pdb.set_trace() 678 #print "glDeleteLists TrajPlayerCached", self.dpyLists[dl][0] 679 GL.glDeleteLists(self.dpyLists[dl][0], 1) 680 self.dpyLists.pop(dl)
681 682 683 684 685 from Pmv.mvCommand import MVCommand 686 from ViewerFramework.VFCommand import CommandGUI 687 from mglutil.gui.InputForm.Tk.gui import InputFormDescr 688 689
690 -class OpenTrajectoryCommand(MVCommand):
691 """ Command to open and read a trajectory file . Currently supporting Gromacs trajectories: 692 .trr and .xtc """ 693
694 - def __init__(self):
695 MVCommand.__init__(self) 696 self.trajFile = None
697
698 - def onAddCmdToViewer(self):
699 if self.vf.hasGui and not self.vf.commands.has_key("playTrajectory"): 700 self.vf.loadCommand("trajectoryCommands", "playTrajectory", "Pmv", topCommand = 0) 701 702 if not hasattr(self.vf, "Trajectories"): 703 self.vf.Trajectories = {}
704
705 - def guiCallback(self):
706 """opens a trajectory file (curenly .trr, .xtc)""" 707 708 trajFile = self.vf.askFileOpen(types=[('select trajectory filename:', '*.trr *.xtc'), 709 ("Gromacs .trr", "*.trr"), ("Gromacs .xtc", "*.xtc"), 710 ('all files','*')], 711 title = 'Trajectory File:') 712 713 if trajFile: 714 self.trajFile = trajFile 715 self.doitWrapper(trajFile)
716
717 - def doit(self, trajFile, ask=True):
718 """creates a Trajectory object, uses its parser to read the trajectory file, 719 adds created Trajectory object to self.vf.Trajectories dictionary""" 720 721 name = os.path.split(trajFile)[1] 722 trajnames = self.vf.Trajectories.keys() 723 if name in trajnames: 724 if ask: 725 from mglutil.gui.InputForm.Tk.gui import InputFormDescr 726 ifd = InputFormDescr(title = '') 727 ifd.append({'widgetType':Pmw.EntryField, 728 'name':'newtraj', 729 'required':1, 730 'wcfg':{'labelpos':'w', 731 'label_text': "Trajectory %s exists.\nEnter new name:"%(name,), 732 'validate':None}, 733 'gridcfg':{'sticky':'we'} 734 }) 735 736 vals = self.vf.getUserInput(ifd) 737 if len(vals)>0: 738 assert not vals['newtraj'] in trajnames 739 name = vals['newtraj'] 740 else: 741 return None 742 else: 743 name = name+str(len(trajnames)) 744 trj = Trajectory(trajFile) 745 if trj.parser: 746 trj.readTrajectory() 747 748 self.vf.Trajectories[name] = trj 749 if self.vf.commands.has_key("playTrajectory"): 750 if self.vf.playTrajectory.ifd: 751 cb = self.vf.playTrajectory.ifd.entryByName['trs']['widget'] 752 sl = cb.component('scrolledlist') 753 trajnames = self.vf.Trajectories.keys() 754 sl.setlist(trajnames) 755 cb.selectitem(name) 756 return name 757 else: return None
758
759 - def __call__(self, trajFile, ask=False, **kw):
760 """trajName<-openTrajectory(trajFile) 761 open aand parse a trajectory file (.trr or .xtc).""" 762 763 self.doitWrapper(trajFile, ask)
764 765 766 OpenTrajectoryGUI = CommandGUI() 767 OpenTrajectoryGUI.addMenuCommand('menuRoot', "Trajectory", "Read...") 768 #OpenTrajectoryGUI.addMenuCommand('menuRoot', 'File', 769 # 'Trajectory (Gromacs)', cascadeName='Read', index=3) 770 771 772 773
774 -class PlayTrajectoryCommand (MVCommand):
775 """This class allows the user to select/read a trajectory and a corresponding molecule. 776 It invokes TrajPlayer interface to play selected trajectory""" 777
778 - def __init__(self):
779 MVCommand.__init__(self) 780 self.trajectory = None 781 self.player = None 782 self.isDisplayed = 0 783 self.ifd =None
784
785 - def onAddCmdToViewer(self):
786 if self.vf.hasGui and not self.vf.commands.has_key("openTrajectory"): 787 self.vf.loadCommand("trajectoryCommands", "openTrajectory", "Pmv", topCommand = 0) 788 789 if not hasattr(self.vf, "trajectories"): 790 self.vf.Trajectories = {} 791 # add a menu entry for openTrajectory command to File->Read menu 792 bar = self.vf.GUI.menuBars['menuRoot'] 793 filemb = bar.menubuttons["File"] 794 readmenu = filemb.menu.children["Read"] 795 readmenu.add_command(label="Trajectory(Gromacs)", command=self.vf.openTrajectory.guiCallback)
796
797 - def onAddObjectToViewer(self, obj):
798 if self.ifd: 799 w = self.ifd.entryByName['mols']['widget'] 800 molecules = [] 801 for mol in self.vf.Mols: 802 molecules.append(mol.name) 803 w.setlist(molecules)
804
805 - def openTrajFile_cb(self):
806 """opens a trajectory file (curenly .trr, .xtc)""" 807 808 self.vf.openTrajectory.guiCallback()
809 810
811 - def getTrajectory(self, trajFile, ask=True):
812 """creates a Trajectory object, uses its parser to read the trajectory file, 813 adds created Trajectory object to self.vf.Trajectories dictionary""" 814 815 name = os.path.split(trajFile)[1] 816 trajnames = self.vf.Trajectories.keys() 817 if name in trajnames: 818 if ask: 819 from mglutil.gui.InputForm.Tk.gui import InputFormDescr 820 ifd1 = InputFormDescr(title = '') 821 ifd1.append({'widgetType':Pmw.EntryField, 822 'name':'newtraj', 823 'required':1, 824 'wcfg':{'labelpos':'w', 825 'label_text': "Trajectory %s exists.\nEnter new name:"%(name,), 826 'validate':None}, 827 'gridcfg':{'sticky':'we'} 828 }) 829 830 vals = self.vf.getUserInput(ifd1) 831 if len(vals)>0: 832 assert not vals['newtraj'] in trajnames 833 name = vals['newtraj'] 834 else: 835 return None 836 else: 837 name = name+str(len(trajnames)) 838 trj = Trajectory(trajFile) 839 if trj.parser: 840 trj.readTrajectory() 841 842 self.vf.Trajectories[name] = trj 843 if self.ifd: 844 cb = self.ifd.entryByName['trs']['widget'] 845 sl = cb.component('scrolledlist') 846 trajnames = self.vf.Trajectories.keys() 847 sl.setlist(trajnames) 848 cb.selectitem(name) 849 return name 850 else: return None
851
852 - def __call__(self, mol, trajName, **kw):
853 """None<-GetTrajectory(mol, trajName) 854 Looks for the trajectory in self.vf.Trajectories and pops up the trajectory player GUI. 855 """ 856 857 apply( self.doitWrapper, (mol, trajName), {})
858 859 860 861
862 - def buildFormDescr(self, formName):
863 if formName == "showtraj": 864 ifd = self.ifd = InputFormDescr(title = "Show trajectory") 865 trajnames = self.vf.Trajectories.keys() 866 molecules = [] 867 for i in range(len(self.vf.Mols)): 868 mol = self.vf.Mols[i] 869 molParser = mol.parser 870 molStr = molParser.getMoleculeInformation() 871 molecules.append(mol.name) 872 873 ifd.append({'widgetType':Tkinter.Label, 874 'wcfg':{'text':'Read trajectory from file:'}, 875 'gridcfg':{'sticky': 'e', 'column': 0} 876 }) 877 878 ifd.append({'name':'fileopen', 879 'widgetType':Tkinter.Button, 880 'wcfg':{'text':"...",#'Read trajectory from file', 881 #'variable': , 882 'command': self.openTrajFile_cb, 883 'width': 0, 'height': 0,}, 884 'gridcfg':{'sticky':'w', 'column':1, 'row':-1} 885 }) 886 887 ifd.append({'name': 'trs', 888 'widgetType':Pmw.ComboBox, 889 'wcfg':{'labelpos': 'n', 890 'label_text':'or select trajectory from list:', 891 'scrolledlist_items': trajnames, 892 'scrolledlist_listbox_width': 5, 893 'selectioncommand': self.getMol_cb 894 }, 895 'gridcfg':{'sticky':'we', 'column': 0, 896 'columnspan':2}, 897 }) 898 ifd.append({'name': 'mols', 899 'widgetType':Pmw.ComboBox, 900 'wcfg':{'labelpos': 'n', 901 'label_text':'Select molecule', 902 'scrolledlist_items': molecules, 903 'scrolledlist_listbox_width': 5}, 904 'gridcfg':{'sticky':'we', 'column': 2, 'row': -1, 905 'columnspan':2}, 906 }) 907 908 909 910 ifd.append({'widgetType':Tkinter.Button, 911 'wcfg': {'text': 'Play Trajectory', 912 'relief' : Tkinter.RAISED, 913 'borderwidth' : 3, 914 'command':self.playTraj}, 915 'gridcfg':{'sticky':'we', 'column':0, 'columnspan':2}, 916 }) 917 918 ifd.append({'widgetType':Tkinter.Button, 919 'wcfg':{'text': 'Dismiss', 920 'relief' : Tkinter.RAISED, 921 'borderwidth' : 3, 922 'command':self.dismiss_cb}, 923 'gridcfg':{'sticky':'we', 'row':-1, 'column':2, 'columnspan':2}, 924 }) 925 926 return ifd
927 928 929
930 - def guiCallback(self):
931 if not len(self.vf.Mols): 932 msg = 'no molecules in viewer' 933 self.vf.warningMsg(msg) 934 return 'ERROR' 935 val = self.showForm('showtraj', force = 1, modal = 0)
936 937 #val = self.showForm("showtraj", force = 1, modal = 1) 938
939 - def getMol_cb(self, trajname):
940 941 """callback of the Pmw.ComboBox (trajectory selection)""" 942 if trajname: 943 if not self.ifd.entryByName["mols"]["widget"].get(): 944 mol = self.vf.Trajectories[trajname].mol 945 if mol: 946 molwidget = self.ifd.entryByName['mols']['widget'] 947 molwidget.selectitem(mol.name)
948
949 - def playTraj(self):
950 val = self.ifd.form.checkValues() 951 mol = None 952 traj = None 953 if len(val['mols']): 954 mol = val['mols'][0] 955 if len(val['trs']): 956 traj = val['trs'][0] 957 if not mol or not traj: 958 return 959 960 self.doitWrapper(mol, traj)
961 962
963 - def dismiss_cb(self):
964 """Withdraws the GUI.""" 965 if self.cmdForms.has_key('showtraj'): 966 self.cmdForms['showtraj'].destroy() 967 self.ifd =None
968
969 - def doit (self, molname, tname):
970 # if trajFile is specified - read the trajectory from the file first 971 # if trajName specified - look for the trajectory in self.vf.Trajectories 972 #if trajFile: 973 # tname = self.getTrajectory(trajFile) 974 #elif trajName: 975 976 if tname and molname: 977 #play the trajectory 978 #print "mol" ,mol , "traj",tname 979 980 title = "Playing trajectory: %s Molecule: %s"%(tname, molname) 981 mol = self.vf.expandNodes(molname)[0] 982 traj = self.vf.Trajectories[tname] 983 if not len(traj.coords): 984 msg = "Trajectory %s has 0 frames." %(tname,) 985 if self.vf.hasGui: 986 self.vf.warningMsg(msg) 987 else: 988 print "WARNING:", msg 989 return 990 991 if len(mol.allAtoms) != len(traj.coords[0]) : 992 msg = "Number of atoms in %s molecule\nand length of coordinates in %s\n trajectory are not equal.\nChoose another molecule/trajectory."%(molname, tname) 993 if self.vf.hasGui: 994 self.vf.warningMsg(msg) 995 else: 996 print "WARNING:", msg 997 return 998 if traj.player: 999 if traj.mol != mol: 1000 traj.player.mol = mol 1001 traj.player.update() 1002 traj.player.form.root.title(title) 1003 traj.player.showGUI() 1004 else: 1005 #player = TrajPlayer(mol, traj, self.vf, form2=1, titleStr = title) 1006 player = TrajPlayerCached(mol, traj, self.vf, form2=1, titleStr = title) 1007 traj.player = player 1008 traj.mol = mol 1009 self.dismiss_cb()
1010 1011 1012 1013 1014 1015 1016 1017 PlayTrajectoryGUI = CommandGUI() 1018 PlayTrajectoryGUI.addMenuCommand('menuRoot', 'Trajectory', "Play...") 1019 1020 1021 1022 commandList = [ 1023 {'name':'openTrajectory', 'cmd':OpenTrajectoryCommand(), 'gui':OpenTrajectoryGUI}, 1024 {'name':'playTrajectory', 'cmd':PlayTrajectoryCommand(), 'gui':PlayTrajectoryGUI}, 1025 ] 1026
1027 -def initModule(vf):
1028 for dict in commandList: 1029 vf.addCommand(dict['cmd'],dict['name'],dict['gui'])
1030