def select_atoms_outside_map(): from chimera.replyobj import status, info from VolumeViewer import active_volume dr = active_volume() if dr is None: status('No density map opened.') return if dr.surface_model() == None or not dr.surface_model().display: status('No surface shown for map.') return levels = dr.surface_levels if len(levels) == 0: status('No surface shown for map.') return contour_level = min(levels) from chimera import selection atoms = selection.currentAtoms() aolist = atoms_outside_map(atoms, dr, contour_level) msg = ('%d of %d selected atoms outside %s at level %.5g' % (len(aolist), len(atoms), dr.name, contour_level)) status(msg) info(msg + '\n') selection.setCurrent(aolist)
def unselAtoms(): from chimera.selection import currentAtoms selAtoms = currentAtoms(asDict=True) unsel = [] for m in chimera.openModels.list(modelTypes=[chimera.Molecule]): unsel.extend(filter(lambda a: a not in selAtoms, m.atoms)) return unsel
def _finishDockPrep(self): timestamp("end _getParameters") from chimera import selection selectedAtoms = set(selection.currentAtoms()) addSelected = [] numAdded = 0 for m in self.mols: for a in m.atoms: if a in self.originalAtoms: continue numAdded += 1 # This atom was added. If it was added to # a selected atom, then we add this atom # into the current selection as well. for b in a.bonds: oa = a.bonds[0].otherAtom(a) if oa in selectedAtoms: addSelected.append(a) break del self.originalAtoms if addSelected: selection.addCurrent(addSelected) #from chimera import replyobj #replyobj.info("%d atoms added, %d selected\n" # % (numAdded, len(addSelected))) self._finishInit()
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 ShowEllipsoids(self, *args): if self.showAxesVar.get(): axisFactor = self.axisFactorOpt.get() else: axisFactor = None if self.showEllipsesVar.get(): ellipseFactor = self.ellipseFactorOpt.get() else: ellipseFactor = None kw = { 'color': self.ellipsoidColorOpt.get(), 'smoothing': int(self.smoothing.getvalue()), 'scale': float(self.scaling.getvalue()), 'showEllipsoid': self.showEllipsoidVar.get(), 'transparency': self.transparencyOpt.get(), 'axisFactor': axisFactor, 'axisColor': self.axisColorOpt.get(), 'axisThickness': self.axisThicknessOpt.get(), 'ellipseFactor': ellipseFactor, 'ellipseColor': self.ellipseColorOpt.get(), 'ellipseThickness': self.ellipseThicknessOpt.get() } if self.selRestrictVar.get(): from chimera.selection import currentAtoms selAtoms = currentAtoms() if selAtoms: kw['targets'] = selAtoms from Aniso import aniso from Midas import MidasError try: aniso(**kw) except MidasError: from chimera import UserError raise UserError("No atoms chosen had anisotropic" " information")
def _atomsDistanceCB(self): atoms = selection.currentAtoms() if not atoms: self.status("No atoms selected", color="red") return items = self.table.selected() if not items: self.status("No objects chosen", color="red") return for item in items: points = [] dists = item.pointDistances([a.xformCoord() for a in atoms]) if len(dists) == 1: self.status("Distance from %s to %s: %.1f\n" % (atoms[0], item, dists[0]), log=True) continue import numpy dists = numpy.array(dists) imin = dists.argmin() imax = dists.argmax() self.status("Distance from %d atoms to %s: " "min: %.1f (%s), mean: %.1f, max: %.1f (%s)\n" % (len(atoms), item, dists[imin], atoms[imin], dists.mean(), dists[imax], atoms[imax]), log=True)
def align_backbones_using_selected_atoms(): # Find atom pairs from chimera import selection a1, a2 = backbone_atom_pairs(selection.currentAtoms()) if a1 == None: return # Compute alignment from chimera import match xform, rmsd = match.matchAtoms(a1, a2) # Apply transformation m1 = a1[0].molecule m2 = a2[0].molecule xf = m1.openState.xform xf.multiply(xform) xf2 = m2.openState.xform m2.openState.xform = xf # Report atom count, rmsd, and angle xf2.invert() xf.multiply(xf2) axis, angle = xf.getRotation() from chimera import replyobj replyobj.status('RMSD between %d atom pairs is %.3f angstroms, rotation angle = %.2f degrees\n' % (len(a1), rmsd, angle), log = True)
def align_molecule(): # TODO: Not ported. from chimera import selection atoms = selection.currentAtoms(ordered=True) mols = set([a.molecule for a in atoms]) if len(mols) != 1: return mol = mols.pop() molxf = mol.openState.xform from Molecule import atom_positions axyz = atom_positions(atoms, molxf) from numpy import roll, float32, float64 from Matrix import xform_matrix, xform_points from chimera.match import matchPositions xflist = [] for mset in cage_marker_sets(): for p in polygons(mset): if p.n == len(atoms): c = p.center() vxyz = [p.vertex_xyz(m) for m in p.vertices] exyz = (0.5 * (vxyz + roll(vxyz, 1, axis=0))).astype(float32) xform_points(exyz, mset.transform(), molxf) xf, rms = matchPositions(exyz.astype(float64), axyz.astype(float64)) xflist.append(xf) molxf.multiply(xflist[0]) mol.openState.xform = molxf import MultiScale mm = MultiScale.multiscale_manager() tflist = [xform_matrix(xf) for xf in xflist] mm.molecule_multimer(mol, tflist)
def Apply(self): from chimera import UserError if self.replaceExisting.get(): axisManager.removeAxes(axisManager.axes) kw = {} kw['color'] = self.colorOpt.get() if self.fixedRadiusVar.get(): kw['radius'] = prefs[AXIS_RADIUS] = self.radiusOpt.get() kw['massWeighting'] = self.massWeighting.get() \ and self.modeVar.get() == self.MODE_SELECTION kw['helicalCorrection'] = self.helixCorrection.get() \ and not kw['massWeighting'] if kw['helicalCorrection']: replyobj.info("Creating axes with helical correction\n") elif kw['massWeighting']: replyobj.info("Creating axes with mass weighting\n") else: replyobj.info("Creating axes\n") if self.modeVar.get() == self.MODE_HELICES: mols = self.molList.getvalue() if not mols: self.enter() raise UserError("No molecules chosen") created = 0 for m in mols: createHelices(m, **kw) else: selAtoms = selection.currentAtoms() if len(selAtoms) < 3: self.enter() raise UserError("Need to select at least three" " atoms to define an axis") axisManager.createAxis(self.axisNameVar.get().strip(), selAtoms, **kw)
def align_backbones_using_selected_atoms(): # Find atom pairs from chimera import selection a1, a2 = backbone_atom_pairs(selection.currentAtoms()) if a1 == None: return # Compute alignment from chimera import match xform, rmsd = match.matchAtoms(a1, a2) # Apply transformation m1 = a1[0].molecule m2 = a2[0].molecule xf = m1.openState.xform xf.multiply(xform) xf2 = m2.openState.xform m2.openState.xform = xf # Report atom count, rmsd, and angle xf2.invert() xf.multiply(xf2) axis, angle = xf.getRotation() from chimera import replyobj replyobj.status( 'RMSD between %d atom pairs is %.3f angstroms, rotation angle = %.2f degrees\n' % (len(a1), rmsd, angle), log=True)
def move_selected_atoms_to_maximum(max_steps=2000, ijk_step_size_min=0.01, ijk_step_size_max=0.5, optimize_translation=True, optimize_rotation=True, move_whole_molecules=True, request_stop_cb=None): from . import active_volume volume = active_volume() if volume == None or volume.model_transform() == None: if request_stop_cb: request_stop_cb('No volume data set.') return {} from chimera import selection atoms = selection.currentAtoms() if len(atoms) == 0: if request_stop_cb: request_stop_cb('No atoms selected.') return {} stats = move_atoms_to_maximum(atoms, volume, max_steps, ijk_step_size_min, ijk_step_size_max, optimize_translation, optimize_rotation, move_whole_molecules, request_stop_cb) return stats
def move_selected_atoms_to_maximum(max_steps = 100, ijk_step_size_min = 0.01, ijk_step_size_max = 0.5, optimize_translation = True, optimize_rotation = True, move_whole_molecules = True, request_stop_cb = None): from VolumeViewer import active_volume volume = active_volume() if volume == None or volume.model_transform() == None: if request_stop_cb: request_stop_cb('No volume data set.') return {} from chimera import selection atoms = selection.currentAtoms() if len(atoms) == 0: if request_stop_cb: request_stop_cb('No atoms selected.') return {} stats = move_atoms_to_maximum(atoms, volume, max_steps, ijk_step_size_min, ijk_step_size_max, optimize_translation, optimize_rotation, move_whole_molecules, request_stop_cb) return stats
def record_movable_objects(self, event): mode = self.mode if mode == self.MOVE_SELECTION: from chimera import selection atoms = selection.currentAtoms() chains = selected_multiscale_chains() spieces = selected_surface_pieces() self.movable_groups = objects_grouped_by_model( atoms, chains, spieces) elif mode in (self.MOVE_MOLECULE, self.MOVE_CHAIN, self.MOVE_SECONDARY_STRUCTURE): from chimera import viewer, Atom, Residue # TODO: Appears to be a bug where picking 1a0m ribbon gives # lists of many erroneous residues. It is caused by LensViewer # pick(x,y) doing drag pick using previously set x,y! Not clear # why since there is separate dragPick(x,y) method. viewer.delta(event.x, event.y) # Sets lastx, lasty objects = viewer.pick(event.x, event.y) atoms = [a for a in objects if isinstance(a, Atom)] residues = [r for r in objects if isinstance(r, Residue)] if mode == self.MOVE_MOLECULE: catoms = extend_to_molecules(atoms, residues) mschains = multiscale_chain_pieces(objects, full_molecules=True) elif mode == self.MOVE_CHAIN: catoms = extend_to_chains(atoms, residues) mschains = multiscale_chain_pieces(objects) elif mode == self.MOVE_SECONDARY_STRUCTURE: catoms = extend_to_secondary_structure(atoms, residues) mschains = [] self.movable_groups = objects_grouped_by_model(catoms, mschains) else: self.movable_groups = []
def selected_markers(self): atoms = selection.currentAtoms() markers = [] for a in atoms: if self.atom_to_marker.has_key(a): markers.append(self.atom_to_marker[a]) return markers
def _createDistance(self): """'Create distance' callback""" selAtoms = selection.currentAtoms() if len(selAtoms) != 2: replyobj.error("Exactly two atoms must be selected " "in graphics window\n") return addDistance(*tuple(selAtoms))
def HideEllipsoids(self): kw = {} if self.selRestrictVar.get(): from chimera.selection import currentAtoms selAtoms = currentAtoms() if selAtoms: kw['targets'] = selAtoms from Aniso import unaniso unaniso(**kw)
def selected_markers(self): from chimera.selection import currentAtoms atoms = currentAtoms() markers = [] for a in atoms: if self.atom_to_marker.has_key(a): markers.append(self.atom_to_marker[a]) return markers
def show_surface(): 'Show MSMS molecular surface' from chimera.selection import currentAtoms from Surface import selected_surface_pieces, show_surfaces if len(currentAtoms()) > 0 or len(selected_surface_pieces()) == 0: # If actions.showSurface() with no atoms selected and a SurfacePiece is # selected then it shows a warning dialog. Suppress that. from chimera import actions actions.showSurface() # MSMSModel surfaces show_surfaces(selected_surface_pieces()) # SurfaceModel surfaces
def selected_and_unselected_atom_sets(displayed_only): # Get selected atoms. from chimera import selection atoms = selection.currentAtoms() # Group atoms by multiscale chain piece or non-multiscale molecule. ca_sel, ma_sel = group_atoms(atoms) # Get multiscale chains with selected surfaces. cp_sel = selected_multiscale_chains() # When chain atoms and surface are both selected ignore surface selection. cp_sel = filter(lambda cp: not cp in ca_sel, cp_sel) # Separate out unloaded selected chains. cpul_sel = filter(lambda cp: not cp.lan_chain.is_loaded(), cp_sel) # Merge loaded selected chains into table of atoms grouped by chain. cpl_sel = filter(lambda cp: cp.lan_chain.is_loaded(), cp_sel) for cp in cpl_sel: catoms = cp.lan_chain.atoms() ca_sel[cp] = catoms atoms.extend(catoms) # Get unselected atoms unsel_atoms = subtract_lists(all_atoms(), atoms) ca_unsel, ma_unsel = group_atoms(unsel_atoms) # Get unselected multiscale chains. cp_unsel = subtract_lists(all_multiscale_chains(), cp_sel) # Don't include chains with selected atoms. cp_unsel = filter(lambda cp: not cp in ca_sel, cp_unsel) # Separate out unloaded unselected chains. cpul_unsel = filter(lambda cp: not cp in ca_unsel, cp_unsel) # Eliminate undisplayed atoms and chains. if displayed_only: cpul_sel = filter(lambda cp: cp.surface_shown(), cpul_sel) cpul_unsel = filter(lambda cp: cp.surface_shown(), cpul_unsel) for table in (ca_sel, ca_unsel, ma_sel, ma_unsel): remove_undisplayed_table_atoms(table) # Make selected and unselected atom sets for non-multiscale models, # loaded multiscale chains, and unloaded multiscale chains. asets_sel = (map(molecule_atom_set, ma_sel.items()) + map(chain_atom_subset, ca_sel.items()) + chain_atom_sets(cpul_sel)) asets_unsel = (map(molecule_atom_set, ma_unsel.items()) + map(chain_atom_subset, ca_unsel.items()) + chain_atom_sets(cpul_unsel)) return asets_sel, asets_unsel
def molecular_weight(): 'Report molecular weight of selected atoms' from chimera import selection, replyobj w = sum([a.element.mass for a in selection.currentAtoms()]) if w >= 1.0e6: s = '%.4g MDa' % (w * 1.0e-6) elif w >= 1.0e3: s = '%.4g KDa' % (w * 1.0e-3) else: s = '%.4g Daltons' % (w * 1.0e-3) replyobj.status('Molecular weight ' + s)
def _itemsSelectAtoms(self, items, add=False): atoms = set() for item in items: atoms.update(item.atoms) if self.geomSelAtomsVar.get(): if add: selection.addCurrent(atoms) else: selection.setCurrent(atoms) elif set(atoms) == set(selection.currentAtoms()): selection.removeCurrent(atoms)
def move_atoms_to_maxima(): from chimera.selection import currentAtoms atoms = currentAtoms() if len(atoms) == 0: from chimera.replyobj import status status('No atoms selected.') return for a in atoms: move_atom_to_maximum(a)
def setFixed(self, which): from chimera import selection if which == "none" or selection.currentEmpty(): for ma in self.universe.atomList(): ma.fixed = False elif which == "selected": import chimera for ma in self.universe.atomList(): ma.fixed = False for a in selection.currentAtoms(): if a.molecule in self.mols: ma = self.atomMap[a] ma.fixed = True else: import chimera for ma in self.universe.atomList(): ma.fixed = True for a in selection.currentAtoms(): if a.molecule in self.mols: ma = self.atomMap[a] ma.fixed = False
def fit_atoms(self): m = self.object_menu.getvalue() if m == 'selected atoms': from chimera import selection atoms = selection.currentAtoms() return atoms from chimera import Molecule if isinstance(m, Molecule): return m.atoms return []
def chosen_atoms(self): m = self.molecule_menu.getvalue() from chimera import Molecule, openModels, selection if isinstance(m, Molecule): return [m], False elif m == 'selected atoms': mlist = list(set([a.molecule for a in selection.currentAtoms()])) return mlist, True elif m == 'all molecules': mlist = openModels.list(modelTypes=[Molecule]) return mlist, False return [], False
def chosen_atoms(self): m = self.molecule_menu.getvalue() from chimera import Molecule, openModels, selection if isinstance(m, Molecule): return [m], False elif m == 'selected atoms': mlist = list(set([a.molecule for a in selection.currentAtoms()])) return mlist, True elif m == 'all molecules': mlist = openModels.list(modelTypes = [Molecule]) return mlist, False return [], False
def selection_surface_distance(): from chimera import selection alist = selection.currentAtoms() if len(alist) == 0: from chimera.replyobj import status status('No atoms or markers selected') return from chimera import openModels from _surface import SurfaceModel smlist = openModels.list(modelTypes = [SurfaceModel]) write_surface_distances(alist, smlist)
def fit_atoms(self): m = self.object_menu.getvalue() if m == 'selected atoms': from chimera import selection atoms = selection.currentAtoms() return atoms from VolumeViewer import Volume from chimera import Molecule if isinstance(m, Molecule): return m.atoms return []
def select_connected(): 'Select atoms and bonds connected to currently selected atoms and bnods' from chimera import selection, Atom atoms_and_bonds = selection.currentAtoms() + selection.currentBonds() reached = set(atoms_and_bonds) i = 0 while i < len(atoms_and_bonds): ab = atoms_and_bonds[i] if isinstance(ab, Atom): n = ([b for b in ab.bonds if not b in reached] + [a for a in ab.neighbors if not a in reached]) else: n = [a for a in ab.atoms if not a in reached] atoms_and_bonds.extend(n) reached.update(set(n)) i += 1 selection.setCurrent(atoms_and_bonds)
def _selChanged(self, trigName, myData, trigData): ats = selection.currentAtoms() if len(ats) != 1: return entry = self.cmd.component('entry') text = entry.get() pre = True for i in range(len(text)): c = text[i] if c == '+' and pre and (i == len(text) - 1 or text[i + 1].isspace()): break pre = c.isspace() else: return entry.delete(i) entry.insert(i, ats[0].oslIdent())
def _getMolecules(self, assignsel, usesel, restrict): if assignsel or usesel: sel = selection.currentMolecules() if usesel: for r in selection.currentResidues(): restrict[r] = True for a in selection.currentAtoms(): restrict[a] = True for m in sel: restrict[m] = True if assignsel: molecules = sel else: molecules = [] if not molecules: molecules = chimera.openModels.list( modelTypes=[chimera.Molecule]) return molecules
def bounding_map(pad = 5.0): from chimera.selection import currentAtoms atoms = currentAtoms() if len(atoms) == 0: from chimera.replyobj import status status('No atoms selected') return from volumedialog import active_volume v = active_volume() if v is None: from chimera.replyobj import status status('No volume shown in volume dialog') return from volume import map_covering_atoms bv = map_covering_atoms(atoms, pad, v) bv.show() v.show(show = False)
def bounding_map(pad=5.0): from chimera.selection import currentAtoms atoms = currentAtoms() if len(atoms) == 0: from chimera.replyobj import status status('No atoms selected') return from volumedialog import active_volume v = active_volume() if v is None: from chimera.replyobj import status status('No volume shown in volume dialog') return from volume import map_covering_atoms bv = map_covering_atoms(atoms, pad, v) bv.show() v.show(show=False)
def Apply(self): from chimera import UserError if self.replaceExistingOpt.get(): planeManager.removePlanes(planeManager.planes) kw = { 'color': self.colorOpt.get(), 'thickness': self.thicknessOpt.get() } prefs[PLANE_THICKNESS] = kw['thickness'] if self.autoRadiusOpt.get(): kw['radiusOffset'] = self.radOffsetOpt.get() else: kw['radius'] = self.radiusOpt.get() replyobj.info("Creating plane\n") selAtoms = selection.currentAtoms() if len(selAtoms) < 3: self.enter() raise UserError("Need to select at least three" " atoms to define a plane") planeManager.createPlane(self.nameOpt.get().strip(), selAtoms, **kw)
def illustrate_backbone_alignment(): # Find atom pairs from chimera import selection a1, a2 = backbone_atom_pairs(selection.currentAtoms()) if a1 == None: return # Compute alignment from chimera import match xform, rmsd = match.matchAtoms(a1, a2) # Find aligning transformation to apply to molecule 2 object coordinates m1 = a1[0].molecule m2 = a2[0].molecule xf = m1.openState.xform xf.multiply(xform) # New m2 transform to align. inv_xf2 = m2.openState.xform inv_xf2.invert() xf.premultiply(inv_xf2) # xform in m2 object coordinates # Make schematic illustrating rotation # alpha = .5 from_rgba = list(m2.color.rgba()) # from_rgba[3] = alpha to_rgba = list(m1.color.rgba()) # to_rgba[3] = alpha sm = transform_schematic(xf, center_of_atoms(a2), from_rgba, to_rgba) if sm: sm.name = 'Transform from %s to %s' % (m2.name, m1.name) from chimera import openModels openModels.add([sm], sameAs=m2) # Report atom count, rmsd, and angle axis, angle = xf.getRotation() from chimera import replyobj replyobj.status( 'RMSD between %d atom pairs is %.3f angstroms, rotation angle = %.2f degrees\n' % (len(a1), rmsd, angle), log=True)
def illustrate_backbone_alignment(): # Find atom pairs from chimera import selection a1, a2 = backbone_atom_pairs(selection.currentAtoms()) if a1 == None: return # Compute alignment from chimera import match xform, rmsd = match.matchAtoms(a1, a2) # Find aligning transformation to apply to molecule 2 object coordinates m1 = a1[0].molecule m2 = a2[0].molecule xf = m1.openState.xform xf.multiply(xform) # New m2 transform to align. inv_xf2 = m2.openState.xform inv_xf2.invert() xf.premultiply(inv_xf2) # xform in m2 object coordinates # Make schematic illustrating rotation # alpha = .5 from_rgba = list(m2.color.rgba()) # from_rgba[3] = alpha to_rgba = list(m1.color.rgba()) # to_rgba[3] = alpha sm = transform_schematic(xf, center_of_atoms(a2), from_rgba, to_rgba) if sm: sm.name = 'Transform from %s to %s' % (m2.name, m1.name) from chimera import openModels openModels.add([sm], sameAs = m2) # Report atom count, rmsd, and angle axis, angle = xf.getRotation() from chimera import replyobj replyobj.status('RMSD between %d atom pairs is %.3f angstroms, rotation angle = %.2f degrees\n' % (len(a1), rmsd, angle), log = True)
def zone_cb(self, event = None): self.message('') surface = self.chosen_surface() if surface == None: self.message('Select a surface') return radius = self.radius_from_gui() if radius == None: return from chimera import selection atoms = selection.currentAtoms() bonds = selection.currentBonds() from SurfaceZone import path_points, surface_zone points = path_points(atoms, bonds, surface.openState.xform.inverse()) if len(points) > 0: surface_zone(surface, points, radius, auto_update = True) else: self.message('No atoms are selected')
def zone_cb(self, event=None): self.message('') surface = self.chosen_surface() if surface == None: self.message('Select a surface') return radius = self.radius_from_gui() if radius == None: return from chimera import selection atoms = selection.currentAtoms() bonds = selection.currentBonds() from SurfaceZone import path_points, surface_zone points = path_points(atoms, bonds, surface.openState.xform.inverse()) if len(points) > 0: surface_zone(surface, points, radius, auto_update=True) else: self.message('No atoms are selected')
def color_zone_cb(self, event = None): self.message('') surface = self.chosen_surface() if surface == None: self.message('Select a surface') return radius = self.radius_from_gui() if radius == None: return xform_to_surface = surface.openState.xform.inverse() from chimera import selection atoms = selection.currentAtoms() bonds = selection.currentBonds() from ColorZone import points_and_colors, color_zone points, colors = points_and_colors(atoms, bonds, xform_to_surface) if len(points) > 0: color_zone(surface, points, colors, radius, auto_update = True) else: self.message('No atoms are selected')
def selAtoms(noneReturnsAll=True, implied=False, create=False): atoms = selection.currentAtoms() extendSelection(atoms, 'atoms', noneReturnsAll, implied, create) return atoms
def _any_selected(self): from chimera import selection, Molecule, MSMSModel, PseudoBondGroup text = "" numAtoms = len(selection.currentAtoms()) if numAtoms: text = "%d atom" % numAtoms if numAtoms > 1: text += "s" numBonds = len(selection.currentBonds()) if numBonds: if text: text += ", " text += "%d bond" % numBonds if numBonds > 1: text += "s" numEdges = len(selection.currentEdges()) if numEdges != numBonds: if text: text += ", " numPBonds = numEdges - numBonds text += "%d pbond" % numPBonds if numPBonds > 1: text += "s" graphs = selection.currentGraphs() numSurfs = numObjs = 0 for g in graphs: if isinstance(g, (Molecule, PseudoBondGroup)): continue if isinstance(g, MSMSModel) or "surf" in g.__class__.__name__.lower(): numSurfs += 1 else: numObjs += 1 if numSurfs: if text: text += ", " text += "%d surf" % numSurfs if numSurfs > 1: text += "s" if numObjs: if text: text += ", " text += "%d obj" % numObjs if numObjs > 1: text += "s" import help if not text: help.register(self.selections_button, balloon="no selection") show_message("selection cleared", blankAfter=5) return False else: help.register(self.selections_button, balloon=text) if self.first_selection: self.first_selection = False show_message(text, followWith="up-arrow to increase selection " "(atoms->residues->chains etc.)") else: show_message(text) return True
rc("color NIH_blue") export_scene("surf") rc("color white") # output Coulombic coloring surface 3D print if <25000 atoms if numAtoms < 25000: description = "coulombicsurf" rc("addcharge std") rc("coulombic atoms #0 -10 red 0 white 10 blue #1") export_scene("surf-coulombic") # output Kyte-Doolittle coloring surface 3D print (only works on amino acids) # check for protein (only works on amino acids) rc("select protein") if len(selection.currentAtoms()) > 0: rc("~select") rc("color magenta #0") rc("rangecolor kdHydrophobicity min 0.16,0.67,0.87 max 1.00,0.45,0.00 mid white novalue magenta #0") #Need to loop from 1 to numSubmodels and put into scolor #1 for surfs in range(1, numSubmodelsP): try: rc("scolor #" + str(surfs) + " zone #0 range 6.0") except: try: rc("scolor #0." + str(surfs) + " zone #0 range 6.0") except: pass export_scene("surf-hydropathy") # output colored by chain surface 3D print
def lists(level="atom", mode="any", attribute=None): import chimera from chimera import replyobj, selection mode = findBestMatch(mode, ["any", "all"]) level = findBestMatch(level, ["atom", "residue", "chain", "molecule"]) if level == "atom": if attribute is None: attribute = "idatmType" _reportAtoms(selection.currentAtoms(), attribute) elif level == "residue": if mode == "any": residues = selection.currentResidues() else: rMap = {} for a in selection.currentAtoms(): l = rMap.setdefault(a.residue, []) l.append(a) residues = [] for r, aList in rMap.iteritems(): if len(r.atoms) == len(aList): residues.append(r) if attribute is None: attribute = "type" _reportResidues(residues, attribute) elif level == "chain": if mode == "any": chains = selection.currentChains() else: rcMap = {} cached = set([]) cMap = {} for r in selection.currentResidues(): if r.molecule not in cached: cached.add(r.molecule) for seq in r.molecule.sequences(): for res in seq.residues: rcMap[res] = seq try: seq = rcMap[r] except KeyError: pass else: l = cMap.setdefault(seq, []) l.append(r) chains = [] for seq, rList in cMap.iteritems(): if len(seq) == len(rList): chains.append(seq) if attribute is None: attribute = "chain" _reportChains(chains, attribute) elif level == "molecule": if mode == "any": molecules = selection.currentMolecules() else: mMap = {} for a in selection.currentAtoms(): l = mMap.setdefault(a.molecule, []) l.append(a) molecules = [] for m, aList in mMap.iteritems(): if len(m.atoms) == len(aList): molecules.append(m) if attribute is None: attribute = "name" _reportModels(molecules, attribute) else: raise chimera.UserError("\"%s\": unknown listselection level" % level)
def createHBonds(models=None, intramodel=True, intermodel=True, relax=True, distSlop=recDistSlop, angleSlop=recAngleSlop, twoColors=False, selRestrict=None, lineWidth=1.0, saveFile=None, batch=False, interSubmodel=False, makePseudobonds=True, retainCurrent=False, reveal=False, namingStyle=None, log=False, cacheDA=None, color=(0.0, 0.8, 0.9, 1.0), slopColor=(0.95, 0.5, 0.0, 1.0)): """Wrapper to be called by gui and command line. Use findHBonds for other programming applications. """ inColors = (color, slopColor) outColors = [] for c in inColors: if isinstance(c, basestring): from chimera.colorTable import getColorByName try: outColors.append(getColorByName(c)) except KeyError: raise "No known color named '%s'" % c elif isinstance(c, tuple): oc = chimera.MaterialColor() oc.ambientDiffuse = c[:3] if len(c) > 3: oc.opacity = c[-1] outColors.append(oc) else: outColors.append(c) bondColor, slopColor = outColors donors = acceptors = None if selRestrict is not None: selAtoms = currentAtoms(asDict=True) if not selAtoms: if batch: return raise UserError("No atoms in selection.") if (not intermodel or selRestrict == "both") and models is None: # intramodel only or both ends in selection models = currentMolecules() if selRestrict == "both": # both ends in selection donors = acceptors = selAtoms if models is None: models = chimera.openModels.list(modelTypes=[chimera.Molecule]) if not relax: distSlop = angleSlop = 0.0 if cacheDA == None: # cache trajectories by default cacheDA = len(models) == 1 and len(models[0].coordSets) > 1 hbonds = findHBonds(models, intermodel=intermodel, intramodel=intramodel, distSlop=distSlop, angleSlop=angleSlop, donors=donors, acceptors=acceptors, interSubmodel=interSubmodel, cacheDA=cacheDA) if selRestrict and donors == None: hbonds = _filterBySel(hbonds, selAtoms, selRestrict) outputInfo = (intermodel, intramodel, relax, distSlop, angleSlop, models, hbonds) if log: import sys # provide a separator from other output print>>sys.stdout, "" _fileOutput(sys.stdout, outputInfo, namingStyle) if saveFile == '-': from MolInfoDialog import SaveMolInfoDialog SaveMolInfoDialog(outputInfo, _fileOutput, initialfile="hbond.info", title="Choose H-Bond Save File", historyID="H-bond info") elif saveFile is not None: _fileOutput(saveFile, outputInfo, namingStyle) replyobj.status("%d hydrogen bonds found\n" % len(hbonds), log=1, blankAfter=120) if not makePseudobonds: return if twoColors: # color relaxed constraints differently precise = findHBonds(models, intermodel=intermodel, intramodel=intramodel, donors=donors, acceptors=acceptors, interSubmodel=interSubmodel, cacheDA=cacheDA) if selRestrict and donors == None: precise = _filterBySel(precise, selAtoms, selRestrict) # give another opportunity to read the result... replyobj.status("%d hydrogen bonds found\n" % len(hbonds), blankAfter=120) from chimera.misc import getPseudoBondGroup pbg = getPseudoBondGroup("hydrogen bonds", issueHint=True) if not retainCurrent: pbg.deleteAll() pbg.lineWidth = lineWidth for don, acc in hbonds: if don.associated(acc, "hydrogen bonds"): continue pb = pbg.newPseudoBond(don, acc) if twoColors: if (don, acc) in precise: color = bondColor else: color = slopColor else: color = bondColor pb.color = color if reveal: for end in [don, acc]: if end.display: continue for ea in end.residue.oslChildren(): ea.display = True