def _evaluate(f, models): if f[0] is SIMPLE: ks = knownSelection(f[1], models) if ks is not None: if ks == 1: sel = selection.copyCurrent() elif isinstance(ks, basestring): sel = selection.OSLSelection(ks, models) else: sel = ks else: sel = selection.OSLSelection(f[1], models) elif f[0] is ZONE: sel = zone(_evaluate(f[1], chimera.openModels.list()), f[2], f[3], f[4], models) elif f[0] is UNION: left = _evaluate(f[1], models) right = _evaluate(f[2], models) sel = selection.ItemizedSelection() sel.merge(selection.REPLACE, left) sel.merge(selection.EXTEND, right) elif f[0] is INTERSECT: left = _evaluate(f[1], models) right = _evaluate(f[2], left.graphs()) sel = selection.ItemizedSelection() sel.merge(selection.REPLACE, left) sel.merge(selection.INTERSECT, right) elif f[0] is COMPLEMENT: sel = selection.ItemizedSelection() sel.add(models) operand = _evaluate(f[1], models) sel.merge(selection.REMOVE, operand) else: raise ValueError, 'Unknown specifier function: %s' % str(f[0]) return sel
def analysisAtoms(movie, useSel, ignoreBulk, ignoreHyds): mol = movie.model.Molecule() if useSel: selAtoms = selection.currentAtoms() if selAtoms: # reduce to just ours sel1 = selection.ItemizedSelection() sel1.add(selAtoms) sel2 = selection.ItemizedSelection() sel2.add(mol.atoms) sel1.merge(selection.INTERSECT, sel2) atoms = sel1.atoms() if not atoms: raise UserError("No selected atoms in" " trajectory!") else: atoms = mol.atoms else: atoms = mol.atoms if ignoreBulk: bulkSel = selection.OSLSelection("@/surfaceCategory=" "solvent or surfaceCategory=ions") atomSel = selection.ItemizedSelection() atomSel.add(atoms) atomSel.merge(selection.REMOVE, bulkSel) atoms = atomSel.atoms() if not atoms: raise UserError("No atoms remaining after ignoring" " solvent/ions") if ignoreHyds: atoms = [a for a in atoms if a.element.number != 1] if not atoms: raise UserError("No atoms remaining after ignoring" " hydrogens") return atoms
def _getSourceModel(self, atoms): sel = selection.ItemizedSelection() sel.add(atoms) mols = sel.molecules() if len(mols) == 1: return mols[0] return None
def apply(self, vFunc=None, eFunc=None): sel = selection.ItemizedSelection() sels = [] # used as a stack when selections get composited funcGlobals = { "__doc__": None, "__name__": "CodeItemizedSelection", "__builtins__": __builtins__ } if self.models is None: sm = chimera.openModels.list() else: sm = self.models funcLocals = { "models": sm, "molecules": filter(lambda m, M=Molecule: isinstance(m, M), sm), "sel": sel, "sels": sels, "selection": selection } try: exec self.codeObj in funcGlobals, funcLocals except: from chimera import replyobj replyobj.error(" CodeItemizedSelection failed\n") s = apply(traceback.format_exception, sys.exc_info()) replyobj.message(string.join(s, '')) sel.apply(vFunc, eFunc)
def focus(): disped = [x for x in selAtoms() + selBonds() if x.shown()] ribbons = [ x for x in selResidues() if x.ribbonDisplay and x.hasRibbon() and x.molecule.display ] disped.extend(ribbons) disped.extend([ p for p in selectedSurfacePieces() if p.display and p.model.display and p.triangleCount > 0 ]) if not disped: from chimera import replyobj replyobj.error( "No target atoms/bonds/ribbons/surfaces currently shown\n") return sel = selection.ItemizedSelection() sel.add(disped) sel.addImplied(edges=False) from Midas import window, cofr window(sel) from chimera import openModels as om if selection.currentEmpty(): from chimera import viewing, viewer om.cofrMethod = viewing.defaultCofrMethod viewer.clipping = False else: om.cofrMethod = om.CenterOfView
def selectionFromText(self, enumText, models=None): if enumText[0] in OSL_START_CHAR and '\n' not in enumText: sel = selection.ItemizedSelection() sel.merge(selection.REPLACE, selection.OSLSelection(enumText)) sel.addImplied(vertices=0) return sel else: return CodeItemizedSelection(enumText, models=models)
def restoreSelections(curSelIds, savedSels): selection.setCurrent(map(idLookup, curSelIds)) for selInfo in savedSels: selName, ids = selInfo sel = selection.ItemizedSelection() sel.add(map(idLookup, ids)) chimera.selection.saveSel(selName, sel)
def restoreSelections(curSelOsls, savedSels): selection.setCurrent(weedOSLlist(curSelOsls)) for selInfo in savedSels: selName, osls = selInfo sel = selection.ItemizedSelection() sel.add(weedOSLlist(osls)) chimera.selection.saveSel(selName, sel)
def selBackbone(op=None): # Define a regular expression for matching the names of protein backbone # atoms (we do not include the carbonyl oxygens because they tend to # clutter up the graphics display without adding much information). MAINCHAIN = re.compile("^(N|CA|C)$", re.I) # The 'list' method of chimera.openModels will return a list of # currently open models, and takes several optional keyword arguments # to restrict this list to models matching certain criteria. # When called with no arguments, this method will # return a list of all visible models, essentially models that # were created by the user. Internally managed ('hidden') models, # such as the distance monitor pseudobondgroup, do not show up in this # list. A list of hidden models can be obtained by setting the # optional keyword argument 'hidden' to True. # The 'all' argument (True/False) can be used to return a list of all open models # (including both hidden and visible). Other optional arguments include: # 'id' and 'subid', which restrict the returned list to models with the given # id and subid, respectively, while 'modelTypes' (a list of model types, # i.e. '[chimera.Molecule]') will restrict the returned list to models # of a particular type. bbAtoms = [] for m in chimera.openModels.list(modelTypes=[chimera.Molecule]): for a in m.atoms: if MAINCHAIN.match(a.name): bbAtoms.append(a) # Create a selection instance that we can use to hold the protein # backbone atoms. We could have added the atoms one by one to the # selection while we were in the above loop, but it is more efficient # to add items in bulk to selections if possible. backboneSel = selection.ItemizedSelection() backboneSel.add(bbAtoms) # Add the connecting bonds to the selection. The 'addImplied' method # of Selection adds bonds if both bond endpoint atoms are in the # selection, and adds atoms if any of the atom's bonds are in the # selection. We use that method here to add the connecting bonds. backboneSel.addImplied() # Change the selection in the main Chimera window in the manner # indicated by this function's 'op' keyword argument. If op is # 'None', then use whatever method is indicated by the 'Selection Mode' # item in Chimera's Select menu. Otherwise, op should # be one of: 'selection.REPLACE', 'selection.INTERSECT', # 'selection.EXTEND' or 'selection.REMOVE'. # - 'REPLACE' causes the Chimera selection to be replaced with # 'backboneSel'. # - 'INTERSECT' causes the Chimera selecion to be intersected # with 'backboneSel'. # - 'EXTEND' causes 'backboneSel' to be appended to the Chimera # selection. # - 'REMOVE' causes 'backboneSel' to be unselected in the # Chimera window. if op is None: chimera.tkgui.selectionOperation(backboneSel) else: selection.mergeCurrent(op, backboneSel)
def zoomModel(self, model): self.manipulateModel(model) sel = selection.ItemizedSelection() for m in self.refModels: if m.openState.active: sel.add(m.atoms) for m in self.altModels: if m.openState.active: sel.add(m.atoms) Midas.window(sel)
def setPivot(): atoms = selAtoms(noneReturnsAll=False) plist = selectedSurfacePieces(noneReturnsAll=False) sel = selection.ItemizedSelection() sel.add(atoms) sel.add(plist) from Midas import cofr, uncofr if len(sel) > 0: cofr(sel) else: uncofr()
def _zoneResidue(orig, floor, ceiling, modelList): coordList = _getCoordList(orig) if not coordList: return orig if floor is None: fSq = None fbbox = None else: fSq = floor * floor valid, fbbox = chimera.find_minimum_bounding_sphere(coordList) if valid: fbbox.radius += floor else: fbbox = None if ceiling is None: cSq = None cbbox = None else: cSq = ceiling * ceiling valid, cbbox = chimera.find_minimum_bounding_sphere(coordList) if valid: cbbox.radius += ceiling else: cbbox = None zone = selection.ItemizedSelection() for m in modelList: try: residueList = m.residues except AttributeError: continue for r in residueList: atomList = r.oslChildren() keep = ceiling is None for a in atomList: try: c = a.xformCoord() except AttributeError: continue if cbbox and not cbbox.inside(c): continue isIn = _inZone(c, coordList, fSq, cSq, fbbox) if isIn < 0: keep = 0 break elif isIn > 0: keep = 1 if keep: zone.add(atomList) if floor is None: zone.merge(selection.EXTEND, orig) return zone
def select_atoms_and_chains(atoms, cplist): # Don't select chains where atoms are selected. rlist = list(set([a.residue for a in atoms])) import MultiScale ac = set(MultiScale.containing_chain_pieces(cplist, rlist)) splist = [cp.surface_piece for cp in cplist if not cp in ac and cp.surface_piece != None] from chimera import selection sel = selection.ItemizedSelection() sel.add(atoms + splist) sel.addImplied(vertices = False, edges = True) # Select bonds selection.setCurrent(sel)
def prune(self): from chimera import selection molecule = self.molecules.getvalue() import ModUtil pairs, residues = ModUtil.convertSelection( selection._currentSelection, minLen=4, molecule=molecule, keepHet=self.hetatms.get(), keepNA=self.nucleic.get(), turnsOnly=self.turnsOnly.get()) sel = selection.ItemizedSelection() sel.add(residues) sel.addImplied() selection.mergeCurrent(selection.INTERSECT, sel) return pairs, residues
def localFit(input_map_path,input_pdb_path): chimera.openModels.open(input_map_path) chimera.openModels.open(input_pdb_path) import FitMap from chimera import selection from FitMap import fitcmd mapid = chimera.openModels.list(id = 0)[0] pdbid = chimera.openModels.list(id = 1)[0] s1 = selection.ItemizedSelection([pdbid]) fit_list=FitMap.fitcmd.fitmap(s1,mapid,search=30 ,listFits = False,resolution=20) for fit in fit_list: va = fit.correlation() print va return fit_list
def _zoneAtom(orig, floor, ceiling, modelList): coordList = _getCoordList(orig) if not coordList: return orig if floor is None: fSq = None fbbox = None else: fSq = floor * floor valid, fbbox = chimera.find_minimum_bounding_sphere(coordList) if valid: fbbox.radius += floor else: fbbox = None if ceiling is None: cSq = None cbbox = None else: cSq = ceiling * ceiling valid, cbbox = chimera.find_minimum_bounding_sphere(coordList) if valid: cbbox.radius += ceiling else: cbbox = None zone = selection.ItemizedSelection() for m in modelList: try: atomList = m.atoms except AttributeError: continue for a in atomList: try: c = a.xformCoord() except AttributeError: continue if cbbox and not cbbox.inside(c): continue if _inZone(c, coordList, fSq, cSq, fbbox) > 0: zone.add(a) if floor is None: zone.merge(selection.EXTEND, orig) return zone
def path_length(operation, path, group='all'): from chimera import selection if isinstance(path, selection.OSLSelection): # OSLSelection never includes bonds. Use bonds between selected atoms. atoms = path.contents()[0] path = selection.ItemizedSelection(atoms) path.addImplied() bonds = path.bonds() if len(bonds) == 0: raise CommandError('No bonds specified') if group == 'all': groups = [bonds] elif group == 'models': groups = bonds_per_molecule(bonds) elif group == 'connected': groups = connected_bonds(bonds) else: raise CommandError('Group must be "all", "models", or "connected"') lines = [] totlen = 0 import PathLength for g in groups: length = PathLength.path_length(g) totlen += length lines.append('%s ... %s path, %d segments, length = %.5g' % (g[0].atoms[0].oslIdent(), g[-1].atoms[1].oslIdent(), len(g), length)) avelen = totlen / len(groups) t = '\n'.join(lines) + '\n' s = lines[0] if len(lines) == 1 else '%d paths, average length = %.5g' % ( len(groups), avelen) from chimera import replyobj replyobj.info(t) replyobj.status(s)
def _menuCB(self, cmdText, br): # callback from angle pull-down menu if cmdText == "Revert": br.set(0) elif cmdText == "Deactivate": br.bond.label = "" br.destroy() elif cmdText == "Select": selectables = [] selectables.extend(br.atoms) selectables.append(br.bond) if self.angleTitle.get() == "Torsion": near, far = self.dihedEndAtoms(br) selectables.extend([near, far]) selectables.append(br.atoms[0].bondsMap[near]) selectables.append(br.atoms[1].bondsMap[far]) from chimera.tkgui import selectionOperation sel = selection.ItemizedSelection() sel.add(selectables) selectionOperation(sel) elif cmdText == "Reverse": br.anchorSide = br.bond.otherAtom(br.anchorSide)
global _selInfos, selLevel sel, info = _selInfos[selLevel] if _countsFromSel(sel) == info: return chimera.triggers.deleteHandler("selection changed", _selChangeHandler) chimera.triggers.deleteHandler("Atom", _atomChangeHandler) _selInfos = _selInfos[:SELATOM] selLevel = SELATOM def _addModelHandler(*args): # adding a model invalidates the 'all' selection global _topValid _topValid = False def _infoFromSel(sel): return (sel, _countsFromSel(sel)) def _countsFromSel(sel): mols = sel.molecules() sortable = [(m.oslIdent(), m) for m in mols] from chimera.misc import oslModelCmp sortable.sort(oslModelCmp) return [len(s[1].atoms) for s in sortable] _selInfos = [_infoFromSel(selection.ItemizedSelection())] _selAllHandler = None
def _nextSel(): sel = selection.ItemizedSelection() sel.add(selection.currentBarrenGraphs()) if selLevel == SELRES: items = [] addResidues = {} for r in selection.currentResidues(): addResidues[r] = 1 selPseudoBonds = filter( lambda e, PB=chimera.PseudoBond: isinstance(e, PB), selection.currentEdges()) # for currently selected chain-trace pseudobonds # act as if they select their residues for ct in filter( lambda e: isinstance(e.pseudoBondGroup, chimera.ChainTrace), selPseudoBonds): addResidues[ct.atoms[0].residue] = 1 addResidues[ct.atoms[1].residue] = 1 for r in addResidues.keys(): items.extend(r.atoms) sel.add(items) sel.addImplied(vertices=0) sel.add(selPseudoBonds) # add chain trace pseudobonds that should be selected sel.add(selChainTrace(sel)) elif selLevel == SELCHAIN: chainIDs = {} for a in selection.currentAtoms(): chainID = a.residue.id.chainId try: chainIDs[a.molecule][chainID] = 1 except KeyError: chainIDs[a.molecule] = {chainID: 1} items = [] for m, ids in chainIDs.items(): for a in m.atoms: if not ids.has_key(a.residue.id.chainId): continue items.append(a) items.extend(a.bonds) pbgs = {} for pb in filter(lambda b, PB=chimera.PseudoBond: isinstance(b, PB), selection.currentEdges()): pbgs[pb.pseudoBondGroup] = 1 for pbg in pbgs.keys(): if isinstance(pbg, chimera.ChainTrace): continue items.extend(pbg.pseudoBonds) sel.add(items) sel.add(selChainTrace(sel)) elif selLevel == SELSUBMODEL: items = [] for m in selection.currentMolecules(): items.extend(m.atoms) items.extend(m.bonds) items.extend( filter(lambda e, PB=chimera.PseudoBond: isinstance(e, PB), selection.currentEdges())) sel.add(items) sel.add(selChainTrace(sel)) elif selLevel == SELMODEL: molDict = {} for m in selection.currentMolecules(): osl = m.oslIdent() if '.' in osl: molDict[osl[:osl.index('.')]] = 1 else: molDict[m] = 1 items = [] for mosl in molDict.keys(): if isinstance(mosl, basestring): for m in selection.OSLSelection(mosl).molecules(): items.extend(m.atoms) items.extend(m.bonds) else: items.extend(mosl.atoms) items.extend(mosl.bonds) items.extend( filter(lambda e, PB=chimera.PseudoBond: isinstance(e, PB), selection.currentEdges())) sel.add(items) sel.add(selChainTrace(sel)) elif selLevel == SELALL: global _topValid _topValid = True items = [] if selection.currentMolecules(): for m in chimera.openModels.list(): if hasattr(m, 'atoms'): items.extend(m.atoms) items.extend(m.bonds) for e in selection.currentEdges(): if isinstance(e, chimera.PseudoBond): pbsSelected = True break else: pbsSelected = False if pbsSelected: mgr = chimera.PseudoBondMgr.mgr() for grp in mgr.pseudoBondGroups: items.extend(grp.pseudoBonds) sel.add(items) sel.add(selChainTrace(sel)) global _selAllHandler if _selAllHandler is not None: _selAllHandler = \ chimera.openModels.addAddHandler( _addModelHandler, None) else: raise ValueError, "Bad selection level" # Handle selected surface pieces from Surface import selected_surface_pieces plist = selected_surface_pieces() mlist = set([p.model for p in plist]) if selLevel == SELALL and len(mlist) > 0: from _surface import SurfaceModel mlist = chimera.openModels.list(modelTypes=[SurfaceModel]) sel.add(mlist) return sel