def guiCallback(self): if len(self.vf.Mols) == 0: return self.chooser = MoleculeChooser(self.vf, mode='extended', title='Choose Molecules to delete') self.undoableVar = Tkinter.IntVar() self.undoableVar.set(1) self.chooser.ipf.append({ 'name': 'Undo', 'widgetType': Tkinter.Checkbutton, 'wcfg': { 'text': ' Undoable Delete', 'variable': self.undoableVar }, 'gridcfg': { 'sticky': Tkinter.E + Tkinter.W } }) self.chooser.ipf.append({ 'name': 'Delete Button', 'widgetType': Tkinter.Button, 'text': 'Delete Molecule', 'wcfg': { 'bd': 6 }, 'gridcfg': { 'sticky': Tkinter.E + Tkinter.W }, 'command': self.deleteMolecule_cb }) self.form = self.chooser.go(modal=0, blocking=0)
def ClosestAtom(): """ask for 2 molecules, compute for each atom the distance to the closest atom in the other molecule. After execution, each atom has a new attribute 'closest' holding the distance""" # it would be better to ask for the attribute's name also from Pmv.guiTools import MoleculeChooser p = MoleculeChooser(self, 'extended', 'Choose 2 molecules') mols = p.go(modal=1) mol1Atoms = mols[0].allAtoms mol2Atoms = mols[1].allAtoms def distanceToClosestPoint(point, setOfPoints): """computes the shortest distance between point and setOfPoints""" diff = Numeric.array(point) - Numeric.array(setOfPoints) diff = diff * diff len = Numeric.sqrt(Numeric.sum(diff, 1)) return min(len) for a in mol1Atoms: a.closest = distanceToClosestPoint(a.coords, mol2Atoms.coords) for a in mol2Atoms: a.closest = distanceToClosestPoint(a.coords, mol1Atoms.coords)
def ClosestAtom(): """ask for 2 molecules, compute for each atom the distance to the closest atom in the other molecule. After execution, each atom has a new attribute 'closest' holding the distance""" # it would be better to ask for the attribute's name also from Pmv.guiTools import MoleculeChooser p = MoleculeChooser(self, 'extended', 'Choose 2 molecules') mols = p.go(modal=1) mol1Atoms = mols[0].allAtoms mol2Atoms = mols[1].allAtoms def distanceToClosestPoint(point, setOfPoints): """computes the shortest distance between point and setOfPoints""" diff = Numeric.array(point) - Numeric.array(setOfPoints) diff = diff*diff len = Numeric.sqrt(Numeric.sum(diff,1)) return min(len) for a in mol1Atoms: a.closest = distanceToClosestPoint( a.coords, mol2Atoms.coords) for a in mol2Atoms: a.closest = distanceToClosestPoint( a.coords, mol1Atoms.coords)
def sesExposurePercent(): """Compute the percentage of solvent exposed surface for each amino acide. After running this macro, each residue has the 2 following members: ses_area: total surface area for this residue ses_ratio: percentage of residue surface exposed to solvent The ratio is the percentage of SES area exposed to the solvent in each residue, where 100 is the surface of that particular residue when all other atoms are ignored """ import mslib import numpy.oldnumeric as Numeric from Pmv.guiTools import MoleculeChooser mol = MoleculeChooser(self).go(modal=0, blocking=1) allrads = mol.defaultRadii() allResidues = mol.chains.residues allAtoms = mol.allAtoms # compute the surface srf = mslib.MSMS(coords=allAtoms.coords, radii=allrads) srf.compute() srf.compute_ses_area() # get surface areas per atom import swig ses_areas = [] for i in xrange(srf.nbat): atm = srf.get_atm(i) ses_areas.append(swig.getdoublearray(atm.ses_area, (1,))[0]) # get surface areas to each atom allAtoms.ses_area = ses_areas # sum up ses areas over resdiues for r in allResidues: r.ses_area = Numeric.sum(r.atoms.ses_area) # compute the surface for each residue independantly # compute the % of ses srfList = [] for r in allResidues: coords = r.atoms.coords rad = map(lambda x: x.radius, r.atoms) m = mslib.MSMS(coords=coords, radii=rad) m.compute() m.compute_ses_area() srfList.append(m) if r.ses_area > 0.0: r.ses_ratio = (r.ses_area * 100) / m.sesr.fst.a_ses_area else: r.ses_ratio = 0.0
def sesExposurePercent(): """Compute the percentage of solvent exposed surface for each amino acide. After running this macro, each residue has the 2 following members: ses_area: total surface area for this residue ses_ratio: percentage of residue surface exposed to solvent The ratio is the percentage of SES area exposed to the solvent in each residue, where 100 is the surface of that particular residue when all other atoms are ignored """ import mslib import numpy.oldnumeric as Numeric from Pmv.guiTools import MoleculeChooser mol = MoleculeChooser(self).go(modal=0, blocking=1) allrads = mol.defaultRadii() allResidues = mol.chains.residues allAtoms = mol.allAtoms # compute the surface srf = mslib.MSMS(coords=allAtoms.coords, radii=allrads) srf.compute() srf.compute_ses_area() # get surface areas per atom ses_areas = [] for i in xrange(srf.nbat): atm = srf.get_atm(i) ses_areas.append(atm.get_ses_area(0)) # get surface areas to each atom allAtoms.ses_area = ses_areas # sum up ses areas over resdiues for r in allResidues: r.ses_area = Numeric.sum(r.atoms.ses_area) # compute the surface for each residue independantly # compute the % of ses srfList = [] for r in allResidues: coords = r.atoms.coords rad = map(lambda x: x.radius, r.atoms) m = mslib.MSMS(coords=coords, radii=rad) m.compute() m.compute_ses_area() srfList.append(m) if r.ses_area > 0.0: r.ses_ratio = (r.ses_area * 100) / m.sesr.fst.a_ses_area else: r.ses_ratio = 0.0
def guiCallback(self): if len(self.vf.Mols) == 0: return self.chooser = MoleculeChooser(self.vf,mode = 'extended', title='Choose Molecules to delete' ) self.chooser.ipf.append({'name':'Delete Button', 'widgetType':Tkinter.Button, 'text':'Delete Molecule', 'wcfg':{'bd':6}, 'gridcfg':{'sticky':Tkinter.E+Tkinter.W}, 'command': self.deleteMolecule_cb}) self.form = self.chooser.go(modal=0, blocking=0)
def selectObject(): """Bind trackball to a user specified object. Only geometries related to this object move, scaling is disabled""" from Pmv.guiTools import MoleculeChooser mol = MoleculeChooser(self).go(modal=0, blocking=1) vi = self.GUI.VIEWER vi.TransformRootOnly(yesno=0) obj = mol.geomContainer.geoms['master'] vi.SetCurrentObject(obj) vi.BindTrackballToObject(obj) vi.currentTransfMode = 'Object'
def setMobSequence(self): molName = MoleculeChooser(self.vf).go().name self.vf.alnEditor.master.lift() if molName not in self.vf.alignment.seqNames: return #recolor the previous reference sequence, if it exists if hasattr(self,'mobMolName'): uniqtag = self.mobMolName+'_name' item = self.vf.alnEditor.canvas.find_withtag(uniqtag) color = self.vf.alnEditor.colors['default'] self.vf.alnEditor.canvas.itemconfig(item,fill=color) uniqtag = molName+'_name' self.vf.alnEditor.colors['special'][uniqtag]='green' item = self.vf.alnEditor.canvas.find_withtag(uniqtag) self.vf.alnEditor.canvas.itemconfig(item,fill='green') self.mobMolName = molName
def getSequence(self,mol=None): if not mol: mol = MoleculeChooser(self.vf).go() if not mol: return self.vf.alnEditor.master.lift() #for extracting sequence(s) from molecules chains = mol.children seqList = [] numbers = [] for chain in chains: seqList = seqList+chain.children.type+['-','|','-'] for residue in chain.children: numbers.append(chain.name + residue.type + residue.number) molSequence = Sequence(sequence=seqList,numbers=numbers,name=mol.name) seqName = mol.name if seqName in self.vf.alignment.seqNames: # if sequence with this molecule name is already in the alignment, # only need to update the numbers sequence = self.vf.alignment.sequences[seqName] sequence.applyNumbers(numbers) return self.vf.alignment.addSequence(molSequence) self.vf.alnEditor.redraw()
def guiCallback(self): if not hasattr(self.vf, "SL"): self.warningMsg( "This command requires 'SLCommands' module. Load the module.") return file = self.vf.askFileOpen(types=[('BSPT file', '*.bsp')], title="Read .bsp") if file: root = Tkinter.Toplevel() root.withdraw() from SimpleDialog import SimpleDialog ans = SimpleDialog(root, text="Bind object to molecule?", buttons=["Yes", "No", "Cancel"], default=0, title="new data dialog").go() root.destroy() mol = None if ans == 0: from Pmv.guiTools import MoleculeChooser ans = MoleculeChooser(self.vf).go() if ans: mol = ans.name apply(self.doitWrapper, (file, mol), {})
class DeleteMolecule(MVCommand): """Command to delete a molecule from the MoleculeViewer \nPackage : Pmv \nModule : deleteCommands \nClass : DeleteMolecule \nCommand : deleteMolecule \nSynopsis:\n None<---deleteMol(nodes, **kw) \nRequired Arguments:\n nodes --- TreeNodeSet holding the current selection It resets the undo stack automatically.\n """ def onAddCmdToViewer(self): self.vf._deletedLevels = [] if not self.vf.commands.has_key('select'): self.vf.loadCommand("selectionCommands", "select", "Pmv", topCommand=0) if not self.vf.commands.has_key('clearSelection'): self.vf.loadCommand("selectionCommands", "clearSelection", "Pmv", topCommand=0) def onAddObjectToViewer(self, obj): if hasattr(self, 'chooser')\ and self.chooser is not None \ and self.form.root.winfo_exists(): w = self.chooser.form.descr.entryByName['Molecule']['widget'] molParser = obj.parser molStr = molParser.getMoleculeInformation() w.add((obj.name, molStr)) def deleteMolecule_cb(self): """called each time the 'Delete Molecule' button is pressed""" mols = self.chooser.getMolSet() if mols is not None and len(mols): if self.vf.undoCmdStack == []: self.doitWrapper(mols, redraw=0) else: text = """WARNING: This command cannot be undone. if you choose to continue the undo list will be reset. The hide Button will make the molecule disappear without resetting the Undo list. Do you want to continue?""" if not hasattr(self, 'idf'): self.idf = InputFormDescr(title="WARNING") self.idf.append({'widgetType':Tkinter.Label, 'wcfg':{'text':text}, 'gridcfg':{'columnspan':3,'sticky':'w'}}) self.idf.append({'name': 'Continue Button', 'widgetType':Tkinter.Button, 'wcfg':{'text':'CONTINUE', 'command':self.continue_cb}, 'gridcfg':{'sticky':'we'}}) self.idf.append({'name': 'Cancel Button', 'widgetType':Tkinter.Button, 'wcfg':{'text':'CANCEL', 'command':self.cancel_cb}, 'gridcfg':{'row':-1,'sticky':'we'}}) self.idf.append({'name': 'Hide Button', 'widgetType':Tkinter.Button, 'wcfg':{'text':'HIDE', 'command':self.hide_cb}, 'gridcfg':{'row':-1,'sticky':'we'}}) form = self.vf.getUserInput(self.idf, okcancel=0) self.form.root.protocol('WM_DELETE_WINDOW',self.cancel_cb) def hide_cb(self): if hasattr(self, 'chooser'): if self.chooser.ipf.form is not None: mols = self.chooser.getMolSet() self.vf.showMolecules(mols.name, negate=1, topCommand=0) self.chooser.done_cb() self.idf.form.destroy() def continue_cb(self): if hasattr(self, 'chooser'): if self.chooser.ipf.form is not None: mols = self.chooser.getMolSet() self.vf.resetUndo(topCommand=0) self.doitWrapper(mols, redraw=0) self.idf.form.destroy() def cancel_cb(self): self.idf.form.destroy() def guiCallback(self): if len(self.vf.Mols) == 0: return self.chooser = MoleculeChooser(self.vf,mode = 'extended', title='Choose Molecules to delete' ) self.chooser.ipf.append({'name':'Delete Button', 'widgetType':Tkinter.Button, 'text':'Delete Molecule', 'wcfg':{'bd':6}, 'gridcfg':{'sticky':Tkinter.E+Tkinter.W}, 'command': self.deleteMolecule_cb}) self.form = self.chooser.go(modal=0, blocking=0) def deleteMol(self, mol): """ Function to delete all the references to each elements of a molecule and then these elements and the molecule to free the memory space.""" # Call the removeObject function for all the command having an # onRemoveMol function self.vf.removeObject(mol) # Maybe do that in moleculeViewer ??? # also need to clean up selector.selection: nodes = self.vf.getSelection() mol.__class__._numberOfDeletedNodes = 0 node = mol while len(node.children): node = node.children # Initialize the variable _numberOfDeletedNodes at 0 node[0].__class__._numberOfDeletedNodes = 0 sslevels = [Coil, Helix, Strand, Turn] # Initialize the variable _numberOfDeletedNodes for each secondary # structure to 0. for sl in sslevels: # Initialize the variable _numberOfDeletedNodes at 0 sl._numberOfDeletedNodes = 0 # but only change selection if there is any if nodes is not None and len(nodes)>0: setClass = nodes.__class__ thisMolNodes = setClass(nodes.get(lambda x, mol=mol: x.top==mol)) #only change selection if this molecule has any nodes in it if len(thisMolNodes)>0: nodes = nodes-thisMolNodes self.vf.clearSelection(topCommand=0) if nodes is not None: self.vf.select(nodes) #self.vf.selector.select(nodes) if hasattr(self, 'chooser') and self.form.root.winfo_exists(): # update the listChooser lc = self.chooser.ipf.entryByName['Molecule']['widget'] lc.remove(mol.name) #lc.clearComments() #check for any possible reference in self.vf.GUI.VIEWER.lastPick if self.vf.hasGui and self.vf.GUI.VIEWER.lastPick: for key in self.vf.GUI.VIEWER.lastPick.hits.keys(): if hasattr(key,'mol'): if mol==key.mol: del self.vf.GUI.VIEWER.lastPick.hits[key] # Remove the atoms of the molecule you are deleting from the # the AtomSet self.vf.allAtoms self.vf.allAtoms = self.vf.allAtoms - mol.allAtoms # Delete all the reference to the atoms you want to delete if hasattr(mol.allAtoms, 'bonds'): bnds = mol.allAtoms.bonds[0] for b in bnds: b.__dict__.clear() del(b) mol.allAtoms.__dict__.clear() del mol.allAtoms if self.vf.hasGui and hasattr(mol, 'geomContainer'): for g in mol.geomContainer.geoms.values(): if hasattr(g, 'mol'): delattr(g, 'mol') mol.geomContainer.geoms.clear() mol.geomContainer.atoms.clear() delattr(mol.geomContainer, 'mol') del mol.geomContainer if hasattr(mol, 'atmNum'): mol.atmNum.clear() del mol.atmNum if hasattr(mol, 'childByName'): mol.childByName.clear() del mol.childByName if hasattr(mol, 'parser') and hasattr(mol.parser, 'mol'): delattr(mol.parser,'mol') del mol.parser # delete molecule from Vision, if Vision is running if self.vf.visionAPI: self.vf.visionAPI.remove(mol) if len(mol.children): deletedLevels = mol.deleteSubTree() else: deletedLevels = [] # then delete all the refences to the molecule del mol.top # Then delete the molecule deletedLevels.insert(0, mol.__class__) mol.__dict__.clear() del mol self.vf._deletedLevels = deletedLevels if len(self.vf.Mols) == 0 and hasattr(self, 'chooser') \ and self.form.root.winfo_exists(): self.chooser.done_cb() def getFreeMemoryInformation(self): """Store how many TreeNodes have been actually free'ed during the last delete operation in a dictionary""" memoryInformation = {} #print 'self.vf._deletedLevels=', self.vf._deletedLevels for d in self.vf._deletedLevels: #print 'checking ', d, ' for deletedNodes' memoryInformation[d.__name__] = d._numberOfDeletedNodes sslevels = [Coil, Helix, Strand, Turn] ## geomslevels = [IndexedPolylines, IndexedPolygons] # Have to loop on the known secondarystructure because our # Data structure doesn't support multiple children and parents. for sl in sslevels: if sl._numberOfDeletedNodes!=0: memoryInformation[sl.__name__] = sl._numberOfDeletedNodes ## for sg in geomslevels: ## if sl._numberOfDeletedNodes!=0: ## memoryInformation[sl.__name__] = sl._numberOfDeletedNodes return memoryInformation def doit(self, nodes): #if called with no selection, just return molecules, nodeSets = self.vf.getNodesByMolecule(nodes) for mol in molecules: self.deleteMol(mol) def __call__(self, nodes, **kw): """None <- deleteMol(nodes, **kw) \nnodes: TreeNodeSet holding the current selection. \nIt resets the undo stack automatically. """ if type(nodes) is types.StringType: self.nodeLogString = "'"+nodes+"'" self.vf.resetUndo(topCommand=0) apply ( self.doitWrapper, (nodes,), kw )
class DeleteMolecule(MVCommand): """Command to delete a molecule from the MoleculeViewer \nPackage : Pmv \nModule : deleteCommands \nClass : DeleteMolecule \nCommand : deleteMolecule \nSynopsis:\n None<---deleteMol(nodes, **kw) \nRequired Arguments:\n nodes --- TreeNodeSet holding the current selection It resets the undo stack automatically.\n """ def onAddCmdToViewer(self): self.vf._deletedLevels = [] if not self.vf.commands.has_key('select'): self.vf.loadCommand("selectionCommands", "select", "Pmv", topCommand=0) if not self.vf.commands.has_key('clearSelection'): self.vf.loadCommand("selectionCommands", "clearSelection", "Pmv", topCommand=0) def onAddObjectToViewer(self, obj): if hasattr(self, 'chooser')\ and self.chooser is not None \ and self.form.root.winfo_exists(): w = self.chooser.form.descr.entryByName['Molecule']['widget'] molParser = obj.parser molStr = molParser.getMoleculeInformation() w.add((obj.name, molStr)) def deleteMolecule_cb(self): """called each time the 'Delete Molecule' button is pressed""" mols = self.chooser.getMolSet() if mols is not None and len(mols): if self.vf.undoCmdStack == []: undoable = self.undoableVar.get() for mol in mols: self.doitWrapper(mol, redraw=0, undoable=undoable) else: self.continue_cb() def hide_cb(self): if hasattr(self, 'chooser'): if self.chooser.ipf.form is not None: mols = self.chooser.getMolSet() self.vf.showMolecules(mols.name, negate=1, topCommand=0) self.chooser.done_cb() self.idf.form.destroy() def continue_cb(self): if hasattr(self, 'chooser'): if self.chooser.ipf.form is not None: mols = self.chooser.getMolSet() undoable = self.undoableVar.get() if not undoable: self.vf.resetUndo(topCommand=0) for mol in mols: self.doitWrapper(mol, redraw=0, undoable=undoable) #self.idf.form.destroy() def cancel_cb(self): self.idf.form.destroy() def guiCallback(self): if len(self.vf.Mols) == 0: return self.chooser = MoleculeChooser(self.vf, mode='extended', title='Choose Molecules to delete') self.undoableVar = Tkinter.IntVar() self.undoableVar.set(1) self.chooser.ipf.append({ 'name': 'Undo', 'widgetType': Tkinter.Checkbutton, 'wcfg': { 'text': ' Undoable Delete', 'variable': self.undoableVar }, 'gridcfg': { 'sticky': Tkinter.E + Tkinter.W } }) self.chooser.ipf.append({ 'name': 'Delete Button', 'widgetType': Tkinter.Button, 'text': 'Delete Molecule', 'wcfg': { 'bd': 6 }, 'gridcfg': { 'sticky': Tkinter.E + Tkinter.W }, 'command': self.deleteMolecule_cb }) self.form = self.chooser.go(modal=0, blocking=0) def deleteMol(self, mol, undoable=False): """ Function to delete all the references to each elements of a molecule and then these elements and the molecule to free the memory space.""" # Call the removeObject function for all the command having an # onRemoveMol function self.vf.removeObject(mol, undoable=undoable) # Maybe do that in moleculeViewer ??? # also need to clean up selector.selection: nodes = self.vf.getSelection() mol.__class__._numberOfDeletedNodes = 0 node = mol while len(node.children): node = node.children # Initialize the variable _numberOfDeletedNodes at 0 node[0].__class__._numberOfDeletedNodes = 0 sslevels = [Coil, Helix, Strand, Turn] # Initialize the variable _numberOfDeletedNodes for each secondary # structure to 0. for sl in sslevels: # Initialize the variable _numberOfDeletedNodes at 0 sl._numberOfDeletedNodes = 0 # but only change selection if there is any if nodes is not None and len(nodes) > 0: setClass = nodes.__class__ thisMolNodes = setClass(nodes.get(lambda x, mol=mol: x.top == mol)) #only change selection if this molecule has any nodes in it if len(thisMolNodes) > 0: nodes = nodes - thisMolNodes self.vf.clearSelection(topCommand=0) if nodes is not None: self.vf.select(nodes) #self.vf.selector.select(nodes) if hasattr(self, 'chooser') and self.form.root.winfo_exists(): # update the listChooser lc = self.chooser.ipf.entryByName['Molecule']['widget'] lc.remove(mol.name) #lc.clearComments() #check for any possible reference in self.vf.GUI.VIEWER.lastPick if self.vf.hasGui and self.vf.GUI.VIEWER.lastPick: for key in self.vf.GUI.VIEWER.lastPick.hits.keys(): if hasattr(key, 'mol'): if mol == key.mol: del self.vf.GUI.VIEWER.lastPick.hits[key] # Remove the atoms of the molecule you are deleting from the # the AtomSet self.vf.allAtoms self.vf.allAtoms = self.vf.allAtoms - mol.allAtoms if not undoable: # Delete all the reference to the atoms you want to delete if hasattr(mol.allAtoms, 'bonds'): bnds = mol.allAtoms.bonds[0] for b in bnds: b.__dict__.clear() del (b) mol.allAtoms.__dict__.clear() del mol.allAtoms if self.vf.hasGui and hasattr(mol, 'geomContainer'): for g in mol.geomContainer.geoms.values(): if hasattr(g, 'mol'): delattr(g, 'mol') mol.geomContainer.geoms.clear() mol.geomContainer.atoms.clear() delattr(mol.geomContainer, 'mol') del mol.geomContainer if hasattr(mol, 'atmNum'): mol.atmNum.clear() del mol.atmNum if hasattr(mol, 'childByName'): mol.childByName.clear() del mol.childByName if hasattr(mol, 'parser') and hasattr(mol.parser, 'mol'): delattr(mol.parser, 'mol') del mol.parser # delete molecule from Vision, if Vision is running if self.vf.visionAPI: self.vf.visionAPI.remove(mol) if not undoable: if len(mol.children): deletedLevels = mol.deleteSubTree() else: deletedLevels = [] # then delete all the refences to the molecule del mol.top # Then delete the molecule deletedLevels.insert(0, mol.__class__) mol.__dict__.clear() del mol self.vf._deletedLevels = deletedLevels if len(self.vf.Mols) == 0 and hasattr(self, 'chooser') \ and self.form.root.winfo_exists(): self.chooser.done_cb() def getFreeMemoryInformation(self): """Store how many TreeNodes have been actually free'ed during the last delete operation in a dictionary""" memoryInformation = {} #print 'self.vf._deletedLevels=', self.vf._deletedLevels for d in self.vf._deletedLevels: #print 'checking ', d, ' for deletedNodes' memoryInformation[d.__name__] = d._numberOfDeletedNodes sslevels = [Coil, Helix, Strand, Turn] ## geomslevels = [IndexedPolylines, IndexedPolygons] # Have to loop on the known secondarystructure because our # Data structure doesn't support multiple children and parents. for sl in sslevels: if sl._numberOfDeletedNodes != 0: memoryInformation[sl.__name__] = sl._numberOfDeletedNodes ## for sg in geomslevels: ## if sl._numberOfDeletedNodes!=0: ## memoryInformation[sl.__name__] = sl._numberOfDeletedNodes return memoryInformation def doit(self, nodes, undoable=False): #if called with no selection, just return molecules, nodeSets = self.vf.getNodesByMolecule(nodes) event = BeforeDeleteMoleculesEvent(molecules) self.vf.dispatchEvent(event) for mol in molecules: self.deleteMol(mol, undoable) if self.vf.hasGui: self.vf.GUI.VIEWER.SetCurrentObject(self.vf.GUI.VIEWER.rootObject) if not undoable: self.vf.resetUndo(topCommand=0) def __call__(self, nodes, undoable=False, **kw): """None <- deleteMol(nodes, **kw) \nnodes: TreeNodeSet holding the current selection. """ if type(nodes) is types.StringType: self.nodeLogString = "'" + nodes + "'" kw['undoable'] = undoable self.doitWrapper(*(nodes, ), **kw) def setupUndoBefore(self, molecule, undoable=False): if undoable: if type(molecule) is types.StringType: molecules, nodeSets = self.vf.getNodesByMolecule(molecule) if not len(molecules): return molecule = molecules[0] molecule.code = self.vf.getStateCodeForMolecule(molecule) self.addUndoCall([molecule], {}, self.name) def undo(self): """Undo for DeleteMolecule: We use self.vf.getStateCodeForMolecule from setupUndoBefore to restore the state of the molecule. """ mol = self.undoStack.pop() mol = mol[0][0] self.vf.addMolecule(mol) exec(mol.code, {'self': self.vf})
def doSetOperation(self, name1, name2, opname, res_name, bindToMol): """ Performs Bspt set operations. """ ex = 0.5 expon = 1.0 bspt_set1 = None bspt_set2 = None if name1 in self.setdict.keys(): #check if we need to recompute the Bspt for the object if self.recomputeBSPT1.get(): if hasattr(self.obj_dict[name1]['obj'], "SLnewobj"): # this object had been created by SL : # do not recompute bspt_set1 = self.setdict[name1] else: #remove the computed Bspt from self.setdict # remove a copy of the object from # self.obj_dict so that the function could use # updated arrays of vertices and faces. del (self.setdict[name1]) if self.obj_dict[name1].has_key('copy_obj'): del (self.obj_dict[name1]['copy_obj']) else: bspt_set1 = self.setdict[name1] if not geometrylib.Size_of_Set(bspt_set1): bspt_set1 = None if not bspt_set1: if self.obj_dict[name1].has_key('copy_obj'): object1 = self.obj_dict[name1]['copy_obj'] else: ## if isinstance(self.obj_dict[name1]['obj'], GleObject): ## object1 = self.obj_dict[name1]['obj'] ## else: object1 = self.obj_dict[name1]['obj'].asIndexedPolygons( run=1, removeDupVerts=0) self.obj_dict[name1]['copy_obj'] = object1 v1 = object1.vertexSet.vertices.array #print "object1: ", object1 ## if isinstance(object1, GleObject): ## f1 = self.triangulate_strips(object1.faceSet.faces.array) ## else: f1 = object1.faceSet.faces.array #print "obj1, verts: ", len(v1), "faces: ", len(f1) brep_set1 = sl.buildBrepSet(v1, f1) t1 = time() bspt_set1 = sl.Brep_To_Bspt(brep_set1, expense=ex, exponent=expon) t2 = time() print "time to build bspt_set1(%s) is %.5f " % (name1, (t2 - t1)) if name2 in self.setdict.keys(): if self.recomputeBSPT2.get(): if hasattr(self.obj_dict[name2]['obj'], "SLnewobj"): bspt_set2 = self.setdict[name2] else: del (self.setdict[name2]) if self.obj_dict[name2].has_key('copy_obj'): del (self.obj_dict[name2]['copy_obj']) else: bspt_set2 = self.setdict[name2] if not geometrylib.Size_of_Set(bspt_set2): bspt_set2 = None if not bspt_set2: if self.obj_dict[name2].has_key('copy_obj'): object2 = self.obj_dict[name2]['copy_obj'] else: object2 = self.obj_dict[name2]['obj'].asIndexedPolygons( run=1, removeDupVerts=0) self.obj_dict[name2]['copy_obj'] = object2 #print "object2: ", object2 v2 = object2.vertexSet.vertices.array ## if isinstance(object2, GleObject): ## f2 = self.triangulate_strips(object2.faceSet.faces.array) ## else: f2 = object2.faceSet.faces.array brep_set2 = sl.buildBrepSet(v2, f2) t1 = time() bspt_set2 = sl.Brep_To_Bspt(brep_set2, expense=ex, exponent=expon) t2 = time() print "time to build bspt_set2(%s) is %.5f " % (name2, (t2 - t1)) rset = sl.operateBsptSets(bspt_set1, bspt_set2, opname, expense=ex, copy="duplicate") brep_set = sl.convert_to_Brep(rset, expense=ex, duplicate=1) verts, faces, vnorms, fnorms = sl.getBoundaries(brep_set, has_vnormals=0, has_fnormals=1) vs, fs, vns, fns = sl.indexedFromArr(verts, faces, fnorms=fnorms) #sl.discardSet(brep_set) #brep_set = None if find(res_name, "_"): #name should not contain "_" res_name = replace(res_name, "_", "-") ## if vs: ## length = map( len, fs) ## mlength = max(length) ## for i in range(len(fs)): ## d = mlength-len(fs[i]) ## if d: ## for j in range(d): ## fs[i].append(-1) vi = self.vf.GUI.VIEWER mol = None res_fullname = 'root|' + res_name if bindToMol: from Pmv.guiTools import MoleculeChooser mol = MoleculeChooser(self.vf).go() if mol: #mol_geom = self.vf.Mols.NodesFromName( molname )[0].geomContainer.masterGeom mol_geom = mol.geomContainer.masterGeom res_fullname = mol_geom.fullName + '|' + res_name #find if an object with the same name already exists: obj_fullnames = self.obj_dict.keys() objnames = map(lambda x: split(x, '|')[-1], obj_fullnames) overwrite = False if res_name in objnames: ind = objnames.index(res_name) if res_fullname in obj_fullnames: ipg = self.obj_dict[res_fullname]['obj'] if hasattr(ipg, "SLnewobj"): # the object is a result # of SL operation if ipg.SLnewobj: overwrite = True # will overwrite the object's # vertices and faces arrays ## if not overwrite: ## ipg = self.obj_dict[ obj_fullnames[ind] ]['obj'] ## if isinstance(ipg, IndexedPolygons): ## #ask the user : ## root = Tkinter.Toplevel() ## root.withdraw() ## from SimpleDialog import SimpleDialog ## ans = SimpleDialog(root, text="Object %s exists. Overwrite it?"% (obj_fullnames[ind],), ## buttons=["Yes", "No"], ## default=0, ## title="overwrite dialog").go() ## root.destroy() ## if ans == 0: ## overwrite = True if overwrite: ipg.Set(vertices=vs, faces=fs, fnormals=fns, freshape=True, tagModified=False) if mol: cl_atoms = self.vf.bindGeomToMolecularFragment(ipg, mol.name, log=0) #addToViewer=False, log=0) if cl_atoms: #self.vf.bindGeomToMolecule.data[res_name]['fns']=fns self.vf.bindGeomToMolecularFragment.data[ ipg.fullName]['fns'] = fns else: ipg = IndexedPolygons( res_name, vertices=vs, faces=fs, #fnormals=fns, #materials=col2, visible=1, inheritMaterial=0, protected=True, ) if self.vf.userpref['Sharp Color Boundaries for MSMS'][ 'value'] == 'blur': ipg.Set( inheritSharpColorBoundaries=False, sharpColorBoundaries=False, ) if mol: cl_atoms = self.vf.bindGeomToMolecularFragment(ipg, mol.name, log=0) if cl_atoms: #self.vf.bindGeomToMolecule.data[res_name]['fns']=fns self.vf.bindGeomToMolecularFragment.data[ ipg.fullName]['fns'] = fns else: vi.AddObject(ipg) else: vi.AddObject(ipg) ipg.Set(frontPolyMode=GL.GL_FILL, shading=GL.GL_FLAT) ipg.Set(fnormals=fns, tagModified=False) self.setdict[ipg.fullName] = rset ipg.SLnewobj = True print "size of bspt_set1:", geometrylib.Size_of_Set(bspt_set1) print "size of bspt_set2:", geometrylib.Size_of_Set(bspt_set2) print "size of rset:", geometrylib.Size_of_Set(rset) else: print "Number of vertices of the resultant object is 0." if name1 not in self.setdict.keys(): self.setdict[name1] = bspt_set1 if name2 not in self.setdict.keys(): self.setdict[name2] = bspt_set2