def _setLightFromParams(self, params, activeName, saveName): import chimera active, diff, diffScale, spec, specScale, dir = params light = self._setActiveLight(active, activeName, saveName) light.diffuse = chimera.MaterialColor(*diff) light.diffuseScale = diffScale light.specular = chimera.MaterialColor(*spec) light.specularScale = specScale light.direction = chimera.Vector(*dir)
def Apply(self): from chimera import UserError self.clashDef.invoke() if not self.clashDef.valid(): self.enter() raise UserError("Invalid clash amount") prefs[CLASH_THRESHOLD] = float(self.clashDef.getvalue()) self.hbondAllow.invoke() if not self.hbondAllow.valid(): self.enter() raise UserError("Invalid H-bond overlap amount") prefs[HBOND_ALLOWANCE] = float(self.hbondAllow.getvalue()) prefs[CLASH_PBS] = self.pbVar.get() if prefs[CLASH_PBS]: prefs[CLASH_COLOR] = self.pbColorWell.rgba pbColor = chimera.MaterialColor(*prefs[CLASH_COLOR]) self.pbWidthEntry.invoke() if not self.pbWidthEntry.valid(): self.enter() raise UserError("Invalid pseudobond width") prefs[CLASH_WIDTH] = float(self.pbWidthEntry.getvalue()) else: pbColor = None prefs[CLASH_METHOD] = self.buttonInfo[self.computeType.index( self.computeType.getvalue())][1] prefs[CLASH_IGNORE_OTHERS] = self.ignoreOthersVar.get() self.rotDialog.addClashColumn(prefs[CLASH_THRESHOLD], prefs[HBOND_ALLOWANCE], prefs[CLASH_METHOD], prefs[CLASH_PBS], pbColor, prefs[CLASH_WIDTH], prefs[CLASH_IGNORE_OTHERS])
def Apply(self): dhb = self.drawHbondsVar.get() prefs[DRAW_HBONDS] = dhb prefs[HBOND_COLOR] = self.hbColorWell.rgba bc = chimera.MaterialColor(*prefs[HBOND_COLOR]) self.hbWidthEntry.invoke() if not self.hbWidthEntry.valid(): self.enter() raise UserError("Invalid H-bond width") lw = prefs[HBOND_WIDTH] = float(self.hbWidthEntry.getvalue()) distSlop = 0.0 angleSlop = 0.0 twoColors = False relax = self.relaxParams.relaxConstraints rc = self.relaxParams.relaxColor if relax: distSlop = self.relaxParams.relaxDist angleSlop = self.relaxParams.relaxAngle if self.relaxParams.useRelaxColor: twoColors = True prefs[RELAX_COLOR] = rc.rgba() self.groupName = "H-bonds for rotamers of %s" % ( self.rotDialog.residue) prefs[HBOND_IGNORE_OTHERS] = self.ignoreOthersVar.get() self.rotDialog.addHbondColumn(dhb, bc, lw, relax, distSlop, angleSlop, twoColors, rc, self.groupName, prefs[HBOND_IGNORE_OTHERS])
def _backgroundColorCB(option): rgba = option.get() if not rgba: color = None else: color = chimera.MaterialColor(*rgba) chimera.viewer.background = color
def create_box(self): m = chimera.Molecule() m.name = 'Subregion Selection Box' chimera.openModels.add([m], noprefs=True) chimera.addModelClosedCallback(m, self.model_closed_cb) rid = chimera.MolResId(1) r = m.newResidue('markers', rid) corners = [] for name in ('a000', 'a001', 'a010', 'a011', 'a100', 'a101', 'a110', 'a111'): a = m.newAtom(name, chimera.elements.H) r.addAtom(a) corners.append(a) green = chimera.MaterialColor(0, 1, 0, 1) for a1, a2 in ((0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7)): b = m.newBond(corners[a1], corners[a2]) b.halfbond = 0 b.drawMode = chimera.Bond.Wire b.color = green return corners
def _highlightColorCB(option): rgba = option.get() if not rgba: color = None else: color = chimera.MaterialColor(*rgba) chimera.viewer.highlightColor = color
def ColorMol ( mol ) : if not hasattr ( mol, 'chainColors' ) : from random import random mol.chainColors = {} for r in mol.residues : if not r.id.chainId in mol.chainColors : clr = chimera.MaterialColor ( random(), random(), random(), 1.0 ) mol.chainColors[r.id.chainId] = clr for r in mol.residues : rt = r.type.upper() if rt in protein3to1 or rt in nucleic3to1 or rt in nucleic1to3 : r.ribbonDisplay = True r.ribbonDrawMode = 2 r.ribbonColor = mol.chainColors[r.id.chainId] for at in r.atoms : at.display = False at.drawMode = at.EndCap if at.element.name.upper() in atomColors : at.color = atomColors[at.element.name.upper()] else : at.color = mol.chainColors[r.id.chainId] else : for at in r.atoms : at.display = True at.drawMode = at.EndCap if at.element.name.upper() in atomColors : at.color = atomColors[at.element.name.upper()] else : at.color = mol.chainColors[r.id.chainId] for b in mol.bonds : b.drawMode = b.Stick b.display = b.Smart
def matchStructureColor(atoms): # try to use ribbon color if appropriate displayedRgbas = [] undisplayedRgbas = [] for a in atoms: if a.hide: # ribbon showing r = a.residue if r.ribbonDisplay: if r.ribbonColor: rgba = r.ribbonColor.rgba() else: rgba = r.molecule.color.rgba() else: rgba = r.molecule.color.rgba() else: if a.color: rgba = a.color.rgba() else: rgba = a.molecule.color.rgba() if (a.hide and r.ribbonDisplay) or a.display: displayedRgbas.append(rgba) else: undisplayedRgbas.append(rgba) if displayedRgbas: rgbas = displayedRgbas else: rgbas = undisplayedRgbas import numpy avgRgba = numpy.mean(numpy.array(rgbas), 0) import chimera return chimera.MaterialColor(*tuple(avgRgba))
def pseudobond(atom1, atom2, group, color=None, label=None): pbg = chimera.misc.getPseudoBondGroup(group) pb = pbg.newPseudoBond(atom1, atom2) if color is not None: pb.color = chimera.MaterialColor(*color) if label is not None: pb.label = str(label) return pb
def __init__(self, f, reply_dialog, prmtop, trajectory): MovieCallbacks.__init__(self, f, reply_dialog) self.prmtop = prmtop self.trajectory = trajectory self.bondColor = chimera.MaterialColor() self.bondColor.ambientDiffuse = (0.0, 0.8, 0.9) self.bondColor.opacity = 1
def getColor(colorID): if colorID is None: return None if globals.colorMap.has_key(colorID): return globals.colorMap[colorID] name, rgba = globals.colorInfo[colorID] if name: c = chimera.Color.lookup(name) if not c: c = chimera.MaterialColor(*rgba) c.save(name) else: c.ambientDiffuse = rgba[:3] c.opacity = rgba[3] else: c = chimera.MaterialColor(*rgba) globals.colorMap[colorID] = c return c
def getColorByName(name): # can raise KeyError import chimera color = chimera.Color.lookup(name) if not color: r, g, b = colors[name] color = chimera.MaterialColor(r / 255.0, g / 255.0, b / 255.0) color.save(name) return color
def restyleXlinks(xMgrs, threshold=None): '''Restyle xlinks in provided XlinkDataMgr objects.''' good_color = chimera.MaterialColor(0, 0, 255) bad_color = chimera.MaterialColor(255, 0, 0) for xMgr in xMgrs: for b in xMgr.iterXlinkPseudoBonds(): if b is not None: b.drawMode = chimera.Bond.Stick if threshold is not None: if is_satisfied(b, threshold): b.color = good_color b.radius = 0.6 else: b.color = bad_color b.radius = 0.6 else: b.color = bad_color b.radius = 0.6
def color(self, coord): place = coord * (len(self.colors) - 1) leftIndex = int(place) if leftIndex == place: return self.colors[leftIndex] c = chimera.MaterialColor() c1, c2 = self.colors[leftIndex:leftIndex+2] f = place - leftIndex c.ambientDiffuse = tuple(map(lambda a,b: a*(1-f) + b*f, c1.ambientDiffuse, c2.ambientDiffuse)) c.opacity = c1.opacity * (1-f) + c2.opacity * f return c
def testAddDomainsSubcomplexes(self): self.g.configFrame.domainsButton.invoke() domWind = self.g.configFrame._getDomainsWindow() self.assertIsNotNone(domWind) itemList = domWind.winfo_children()[0] self.assertEqual(1, len(self.g.configFrame.config.domains)) self.assertEqual(1, len(itemList.frames)) activeItemFrame = itemList.activeItemFrame activeItemFrame.fields['name'][1].insert(0, 'testdom') activeItemFrame.fields['subunit'][3].set('A135') activeItemFrame.fields['ranges'][1].insert(0, '1-200') activeItemFrame.fields['color'][1].set(chimera.MaterialColor( 0, 255, 0)) activeItemFrame.add.invoke() self.assertEqual(2, len(self.g.configFrame.config.domains)) self.assertEqual(2, len(itemList.frames)) self.g.configFrame.subCompButton.invoke() subWind = self.g.configFrame._getSubcomplexesWindow() self.assertIsNotNone(subWind) itemList = subWind.winfo_children()[0] self.assertEqual(1, len(self.g.configFrame.config.subcomplexes)) self.assertEqual(1, len(itemList.frames)) activeItemFrame = itemList.activeItemFrame activeItemFrame.fields['name'][1].insert(0, 'new_subcomplex') activeItemFrame.fields['color'][1].set(chimera.MaterialColor( 0, 255, 0)) activeItemFrame.add.invoke() self.assertEqual(2, len(self.g.configFrame.config.subcomplexes)) self.assertEqual(2, len(itemList.frames)) newSubcomplex = self.g.configFrame.config.subcomplexes[-1] self.assertEqual(0, len(newSubcomplex.items)) subFrame = itemList.frames[-1]
def color_element(obj, level, maxLevel): #print(obj, level, maxLevel) if(not obj.doneC): wait_time = speed col = (float(level)/max(maxLevel, 1) ) #print level, obj, "coloring" set_color(obj, chimera.MaterialColor(1.0, col, col)) obj.doneC = True real_eye = ch_get_real_eye() coords = get_coords(obj) has_sobj = False sobjs = list() amp = (1.0 - (float(level)/(maxLevel + 1))) #print(grain_maker_fn) if hasattr(obj, 'sobj') and (obj.sobj != None): for sid in obj.sobj: if sid in cg.mapping_objects: has_sobj = True sobjs.append(cg.mapping_objects[sid]) if has_sobj: for sobj in sobjs: so.modify_sound_object(sobj, "gate", amp, "t_trig", 1) elif grains: real_eye = ch_get_real_eye() coords = get_coords(obj) dist, az, ele = ch_calculate_position(real_eye, coords) sobj = grain_maker_fn(obj, dist, az, ele, level, maxLevel+1) if (sobj != None): sobjs.append(sobj) if(level == 0) or not stagger: time.sleep(wait_time) else: time.sleep(wait_time * 2) if(level < maxLevel): neighbors = list() for i,r in enumerate(get_neighbors(obj)): t = threading.Thread(target=color_element, args=(r, level +1, maxLevel)) t.start() if (level == 0) and (i == 0) and stagger: time.sleep(wait_time) time.sleep(wait_time*4) for sobj in sobjs: so.modify_sound_object(sobj, "gate", 0) #print level, obj, "restoring" restore_color(obj)
def draw_interactions(interactions, startCol='FF0000', endCol='FFFF00', key=None, name="Custom pseudobonds"): """ Draw pseudobonds depicting atoms relationships. Parameters ---------- interactions : list of tuples Each tuple contains an interaction, defined, at least, by the two atoms involved. startCol : str, optional Hex code for the initial color of the pseudobond (closer to the first atom of the pair). endCol : str, optional Hex code for the final color of the pseudobond. (closer to the second atom of the pair) key : int, optional The index of an interaction tuple that represent the alpha channel in the color used to depict the interaction. name : str, optional Name of the pseudobond group created. Returns ------- chimera.pseudoBondGroup """ if not len(interactions): return pb = chimera.misc.getPseudoBondGroup(name) color = _hex_to_rgb(startCol) + [1.0] if key: max_ = max(abs(_[3]) for _ in interactions) for i in interactions: npb = pb.newPseudoBond(i[0], i[1]) if key is not None: intensity = (max_ - abs(i[key])) / (max_) opacity = 1 - 0.7 * intensity if startCol != endCol: color = _linear_color(intensity, startCol, endCol) + [opacity] else: color = _hex_to_rgb(startCol) + [opacity] npb.color = chimera.MaterialColor(*color) return pb
def settings_changed_cb(self, event=None): if not self.have_phantom(): return phantom_on = self.phantom_on.get() if not phantom_on: if self.cursor_model: chimera.openModels.close([self.cursor_model]) return phantom_range_mm = float_variable_value(self.phantom_range) box_size_mm = (phantom_range_mm, phantom_range_mm, phantom_range_mm) shape = self.cursor_shape.get() from _phantomcursor import Cursor_Model cursor_shape = { 'cross': Cursor_Model.Cross, 'jack': Cursor_Model.Jack, 'sphere': Cursor_Model.Sphere, 'volume crosshair': Cursor_Model.Cross, }[shape] cursor_size = float_variable_value(self.cursor_size) r, g, b = self.cursor_color.rgb cursor_color = chimera.MaterialColor(r, g, b) pd = self.phantom_device cm = self.cursor_model if pd == None or cm == None: pd, cm = self.make_phantom_cursor_model(box_size_mm, cursor_shape, cursor_size, cursor_color) self.phantom_device = pd self.cursor_model = cm chimera.addModelClosedCallback(cm, self.model_closed_cb) else: pd.box_size_mm = box_size_mm cm.cursor_style = cursor_shape cm.cursor_size = cursor_size cm.cursor_color = cursor_color crosshair_on = (self.cursor_shape.get() == 'volume crosshair') cm.show_crosshair = crosshair_on self.update_force_field()
def rainbowTexture(colors): key = tuple(colors) if key not in _rainbowColors: actualColors = [] for color in colors: if isinstance(color, basestring): c = getColorByName(color) elif isinstance(color, chimera.MaterialColor): c = color else: c = chimera.MaterialColor() c.ambientDiffuse = color[:3] if len(color) > 3: c.opacity = color[-1] else: c.opacity = 1.0 actualColors.append(c) _rainbowColors[key] = RainbowColors(actualColors) return _rainbowColors[key]
def testDeleteStuff(self): '''Test deletion of Subunits and Data, adding them back, setting mapping, and mapping copy from. ''' xFrame = self.g.Xlinks xFrame.displayDefault() subUnitFrame = self.g.configFrame.subUnitFrame self.assertEqual(14, len(subUnitFrame.frames)) self.assertEqual(14, len(self.g.configFrame.config.subunits)) subUnitFrame.frames[0].delete.invoke() self.assertEqual(13, len(subUnitFrame.frames)) self.assertEqual(13, len(self.g.configFrame.config.subunits)) self.assertEqual(0, len(self.g.configFrame.config.domains)) dataFrame = self.g.configFrame.dataFrame self.assertEqual(10, len(dataFrame.frames)) self.assertEqual(10, len(self.g.configFrame.config.dataItems)) dataFrame.frames[0].delete.invoke() self.assertEqual(9, len(dataFrame.frames)) self.assertEqual(9, len(self.g.configFrame.config.dataItems)) xmgr = xFrame.getXlinkDataMgrs()[0] self.assertEqual(74, len(xmgr.pbg.pseudoBonds)) #Test adding after deleting: activeItemFrame = subUnitFrame.activeItemFrame activeItemFrame.fields['name'][1].insert(0, 'A190') activeItemFrame.fields['chainIds'][1].insert(0, 'A') activeItemFrame.fields['color'][1].set(chimera.MaterialColor( 0, 255, 0)) activeItemFrame.add.invoke() self.assertEqual(14, len(self.g.configFrame.config.subunits)) self.assertEqual(170, len(xmgr.pbg.pseudoBonds)) dataFrame = self.g.configFrame.dataFrame activeItemFrame = dataFrame.activeItemFrame activeItemFrame.fields['name'][1].insert( 0, '0.05 mM X-linker, 30min at 37 C') paths = [ 'xlinks/Pol1_1_Inter.xls', 'xlinks/Pol1_1_Intra.xls', 'xlinks/Pol1_1_Loop.xls,', 'xlinks/Pol1_1_Mono.xls' ] dirname = os.path.dirname(self.xlaTestCPath) paths = [os.path.join(dirname, p) for p in paths] fileFrame = activeItemFrame.fields['fileGroup'][1] map(fileFrame.fileGroup.addFile, paths) fileFrame.resetFileMenu(paths, 0) activeItemFrame.fields['type'][3].set('xquest') activeItemFrame.add.invoke() for frame in dataFrame.frames[1:]: mapFrame = frame.fields['mapping'][1] mapFrame.mapButton.invoke() for seqName, subset in mapFrame.subsetframes.iteritems(): if 'sp|P10964|RPA1_YEAST' in seqName: subset.menus[0].var.set('A190') mapFrame.onSave() lastFrame = dataFrame.frames[-1] mapFrame = lastFrame.fields['mapping'][1] mapFrame.mapButton.invoke() mapFrame.mapVar.set('0.2 mM X-linker, 30min at 37 C') mapFrame.onSave() xFrame.displayDefault() self.assertEqual(171, len(xmgr.pbg.pseudoBonds))
def readPBinfo(fileName, category=None, clearCategory=1, lineWidth=None, drawMode=None, leftModel=None, rightModel=None, defColor=None): """read a file containing pseudobond info and display those bonds 'category' defaults to 'fileName'. 'clearCategory' controls whether the pseudobond group should be cleared of pre-existing pseudobonds before reading the file. 'lineWidth' is a floating- point number and controls the width of lines used to draw the pseudobonds. This only is relevant if 'drawMode' is Wire. 'drawMode' controls the depiction style of the pseudobonds. Possible modes are: Wire (aka chimera.Bond_Wire) -- wireframe Stick (aka chimera.Bond_Stick) -- sticks 'leftModel' and 'rightModel' control what models the endpoints of the pseudobond lie in, if none are specified in the input file. 'defColor' is the color assigned to the pseudobond group as a whole, which can be overridden by specific pseudobonds. """ foundErrors = False colorCache = {} if not category: category = fileName group = chimera.misc.getPseudoBondGroup(category) if lineWidth: group.lineWidth = lineWidth if drawMode: group.drawMode = drawMode if clearCategory: group.deleteAll() if defColor: if isinstance(defColor, basestring): c = chimera.Color.lookup(defColor) if not c: replyobj.message("Cannot find color '%s'\n" % defColor) foundErrors = True else: c = defColor group.color = c from OpenSave import osOpen bondFile = osOpen(fileName) lineNum = 0 for line in bondFile.readlines(): line = line.strip() lineNum = lineNum + 1 if not line: # blank line continue try: spec1, spec2, color = line.split(None, 2) except: label = color = None try: spec1, spec2 = line.split() except ValueError: replyobj.message("Line %d does not have at" " least two atom specifiers.") foundErrors = True continue if color: # try to distinguish between color name and label try: color, label = color.split(None, 1) except: label = None if color[0] != "#": while (label and not colors.has_key(color)): try: c, label = label.split(None, 1) except: color = " ".join([color, label]) label = None else: color = " ".join([color, c]) atom1 = _processSpec(spec1, leftModel) if not atom1: replyobj.message("Left atom spec of line %d of file doesn't" " select exactly one atom." " Skipping.\n" % lineNum) foundErrors = True continue atom2 = _processSpec(spec2, leftModel) if not atom2: replyobj.message("Right atom spec of line %d of file doesn't" " select exactly one atom." " Skipping.\n" % lineNum) foundErrors = True continue if color: if color[0] == '#': fieldLen = int((len(color) - 1) / 3) if 3 * fieldLen + 1 != len(color): replyobj.message("Bad Tk color '%s'" " on line %d of file.\n" % (color, lineNum)) foundErrors = True elif colorCache.has_key(color): color = colorCache[color] else: r = color[1:1 + fieldLen] g = color[1 + fieldLen:1 + 2 * fieldLen] b = color[1 + 2 * fieldLen:] r = int(r, 16) g = int(g, 16) b = int(b, 16) maxVal = int('f' * fieldLen, 16) maxVal = float(maxVal) c = chimera.MaterialColor(r / maxVal, g / maxVal, b / maxVal) colorCache[color] = c color = c else: try: color = getColorByName(color) except KeyError: replyobj.message("Unknown color '%s' on line %d" " of file.\n" % (color, lineNum)) foundErrors = True color = None pb = group.newPseudoBond(atom1, atom2) if color: pb.color = color if label: pb.label = label bondFile.close() if foundErrors: chimera.replyobj.error("Errors encountered while reading file.\n" "Check reply log for details.\n")
def ReadMol ( fpath, log=False ) : from random import random cif, loops = ReadCif ( fpath, log ) # descriptions by chain id: descrByEntityId = GetEntityDescr ( cif, loops ) try : atoms = loops['_atom_site']['data'] print " - %d atom records" % len(atoms) except : print " - no atoms in cif?" return None labels = loops['_atom_site']['labels'] if 0 : print "Labels:" for l in labels : print " : ", l import time start = time.time() rmap = {} nmol = chimera.Molecule() from os import path #nmol.name = path.splitext ( path.split (fpath)[1] )[0] nmol.name = path.split (fpath) [1] nmol.openedAs = [ fpath, [] ] nmol.cif = cif nmol.cifLoops = loops nmol.chainColors = {} nmol.chainDescr = {} numQ = 0 first = True for at in atoms : mp = at['asMap'] if log and first : #for label, val in mp.iteritems () : for li, label in enumerate ( labels ) : print " %d : %s : %s" % (li+1, label, mp[label]) first = False atType = mp['type_symbol'] atName = mp['label_atom_id'] rtype = mp['label_comp_id'] chainId = mp['label_asym_id'] chainEId = mp['label_entity_id'] px = mp['Cartn_x'] py = mp['Cartn_y'] pz = mp['Cartn_z'] occ = mp['occupancy'] bfactor = mp['B_iso_or_equiv'] altLoc = mp['label_alt_id'] if altLoc == "." : altLoc = '' if chainEId in descrByEntityId : nmol.chainDescr [chainId] = descrByEntityId [chainEId] resId = ResId ( mp ) if resId == None : continue ris = "%s%d" % (chainId, resId) res = None if not ris in rmap : res = nmol.newResidue ( rtype, chimera.MolResId(chainId, resId) ) rmap[ris] = res else : res = rmap[ris] clr = None if not chainId in nmol.chainColors : clr = chimera.MaterialColor ( random(), random(), random(), 1.0 ) nmol.chainColors[chainId] = clr if 0 and log : print " - chain %s" % chainId else : clr = nmol.chainColors [chainId] nat = nmol.newAtom ( atName, chimera.Element(atType) ) drawRib = rtype in protein3to1 or rtype in nucleic3to1 #aMap[at] = nat res.addAtom( nat ) nat.setCoord ( chimera.Point( float(px), float(py), float(pz) ) ) nat.altLoc = altLoc nat.occupancy = float(occ) nat.bfactor = float(bfactor) if 'Q-score' in mp : try : Q = float ( mp['Q-score'] ) nat.Q = Q numQ += 1 except : #print " - q score is", mp['Q-score'] pass end = time.time() print " - created %d atoms, %.1fs, %d q-scores" % ( len(nmol.atoms), end-start, numQ ) return nmol
def _addAttr(attrFile, models, log, raiseAttrDialog): setAttrs = {} colors = {} from CGLutil.annotatedDataFile import readDataFile control = { 'match mode': _MATCH_MODE_ANY, 'recipient': "atoms" } for rawControl, data in readDataFile(attrFile): control.update(rawControl) legalNames = ["attribute", "match mode", "recipient"] for name in control.keys(): if name not in legalNames: raise SyntaxError("Unknown name part of control" " line: '%s'\nMust be one of: %s" % ( name, ", ".join(legalNames))) if "attribute" not in control: raise SyntaxError("No attribute name specified in file") attrName = control["attribute"] if not attrName.replace("_", "").isalnum() \ or attrName[0].isdigit(): raise SyntaxError("Attribute name (%s) is bad.\n" "It must be strictly alphanumeric characters or" " underscores with no spaces and must not start" " with a digit." % control["attribute"]) colorAttr = attrName.lower().endswith("color") matchMode = control["match mode"] if matchMode not in _matchModes: raise SyntaxError("Unknown match mode (%s) specified.\n" "It must be one of: %s" % ( control["match mode"], ", ".join(_matchModes))) recipient = control["recipient"] if not hasattr(selection.ItemizedSelection, recipient): raise SyntaxError("Unknown attribute recipient (%s)" " specified.\nSuggest using atoms, residues, or" " molecules" % control["recipient"]) dataErrors = [] for lineNum, d in enumerate(data): try: selector, value = d except ValueError: dataErrors.append("Data line %d of file either" " not selector/value or not" " tab-delimited" % (lineNum+1)) continue try: sel = specifier.evalSpec(selector, models) except: import sys dataErrors.append("Mangled selector (%s) on" " data line %d: %s" % (selector, lineNum+1, sys.exc_value)) continue matches = getattr(sel, recipient)() # restrict to models; the "models" argument to evalSpec # only works if the selector is an OSL if matches and models is not None: md = set(models) level = matches[0].oslLevel() if level == selection.SelGraph: filterFunc = lambda x, md=md: x in md elif level == selection.SelEdge: filterFunc = lambda x, md=md: \ x.atoms[0].molecule in md else: filterFunc = lambda x, md=md: \ x.molecule in md matches = filter(filterFunc, matches) if not matches: if matchMode != _MATCH_MODE_ANY: dataErrors.append("Selector (%s) on" " data line %d matched nothing" % (selector, lineNum+1)) continue elif len(matches) > 1: if matchMode == _MATCH_MODE_1_TO_1: dataErrors.append("Selector (%s) on" " data line %d matched multiple" " items: %s" % (selector, lineNum+1, ", ".join(map(lambda m: m.oslIdent(), matches)))) if log: replyobj.info("Selector %s matched " % selector + ", ".join(map(misc.chimeraLabel, matches)) + "\n") if colorAttr: if value[0].isalpha(): # color name from chimera.colorTable \ import getColorByName try: value = getColorByName(value) except KeyError: dataErrors.append("Unknown" " color name on data" " line %d: '%s'" % (lineNum+1, value)) continue else: try: rgba = tuple(map(float, value.split())) except ValueError: dataErrors.append( "Unrecognizable color" " value on data line" " %d: '%s'; Must be" " either color name or" " 3 or 4 numbers" " between 0 and 1" " (RGBA)" % (lineNum+1)) continue if max(rgba) > 1.0 or min(rgba) < 0.0: dataErrors.append("Color" " component values on" " data line %d not" " in the range 0 to 1" % (lineNum+1)) continue if rgba in colors: value = colors[rgba] elif len(rgba) in [3, 4]: value = chimera.MaterialColor( *rgba) colors[rgba] = value else: dataErrors.append("Bad number" " of color components" " on data line %d; Must" " be either 3 or 4 (was" " %d)" % (lineNum+1, len(rgba))) continue else: value = convertType(value) for match in matches: setattr(match, attrName, value) if matches and not colorAttr: setAttrs[(recipient, attrName)] = value recipMapping = { "molecules": chimera.Molecule, "residues": chimera.Residue, "bonds": chimera.Bond, "atoms": chimera.Atom } from SimpleSession import registerAttribute for recipient, attrName in setAttrs: if recipient in recipMapping: registerAttribute(recipMapping[recipient], attrName) if setAttrs and not chimera.nogui and raiseAttrDialog: from ShowAttr import ShowAttrDialog, screenedAttrs from chimera import dialogs showableAttr = False reasons = [] for recipient, attrName in setAttrs.keys(): if recipient == "molecules": recipient = "models" validRecipients = ["atoms", "residues", "models"] if recipient not in validRecipients: reasons.append("%s not assigned to atoms," " residues, or models" % attrName) continue key = [chimera.Atom, chimera.Residue, chimera.Model][ validRecipients.index(recipient)] if attrName in screenedAttrs[key]: reasons.append("%s automatically screened out" " by Render By Attribute" % attrName) continue if attrName[0] == '_': reasons.append("%s considered to be a private" " variable" % attrName) continue if attrName[0].isupper(): reasons.append("%s considered to be a symbolic" " constant due to initial capital" " letter" % attrName) continue showableAttr = True break if showableAttr: if models is None: ms = chimera.openModels.list() else: ms = models if colorAttr: an = None mode = None else: an = attrName from types import StringTypes if type(setAttrs[(recipient, attrName)]) in ( bool,) + StringTypes: mode = "Select" else: mode = "Render" d = dialogs.display(ShowAttrDialog.name) d.configure(models=[m for m in ms if isinstance(m, chimera.Molecule)], attrsOf=recipient, attrName=an, mode=mode) else: replyobj.warning("No attributes usable by Render dialog" " were defined:\n" + "\n".join(reasons) + "\n") if dataErrors: raise SyntaxError, "\n".join(dataErrors) return setAttrs
try : import chimera import numpy from chimera.resCode import nucleic3to1 from chimera.resCode import protein3to1, protein1to3 protein3to1['HSD'] = protein3to1['HIS'] protein3to1['HSE'] = protein3to1['HIS'] nucleic1to3 = { 'T':'THY', 'C':'CYT', 'G':'GUA', 'A':'ADE', 'U':'URA'} nucleic3to1['GDP'] = nucleic3to1['GUA'] atomColors = {'C' : chimera.MaterialColor (0.565,0.565,0.565), 'Cbb' : chimera.MaterialColor (0.2,0.6,0.2), 'S' : chimera.MaterialColor (1.000,1.000,0.188), 'O' : chimera.MaterialColor (1.000,0.051,0.051), 'N' : chimera.MaterialColor (0.188,0.314,0.973), 'P' : chimera.MaterialColor (1.0, 0.502, 0.0), 'H' : chimera.MaterialColor (0.9,.9,.9), ' ' : chimera.MaterialColor (0.2,1,.2), "MG" : chimera.MaterialColor (0,1,0), "NA" : chimera.MaterialColor (.6,.3,.6), "CL" : chimera.MaterialColor (.2,.6,.2), "CA" : chimera.MaterialColor (.4,.4,.6), "ZN" : chimera.MaterialColor (.2,.8,.2), "MN" : chimera.MaterialColor (.4,.4,.6), "FE" : chimera.MaterialColor (.4,.4,.6), "CO" : chimera.MaterialColor (.4,.4,.6),
def wellCB(clr, cb=cb, mdl=model): if clr is not None: clr = chimera.MaterialColor(*clr) cb(mdl, clr)
def chimera_color(rgb): return chimera.MaterialColor(*rgb)
def testTutorial(self): subUnitFrame = self.g.configFrame.subUnitFrame self.assertEqual(0, len(subUnitFrame.frames)) self.assertEqual(0, len(self.g.configFrame.config.subunits)) activeItemFrame = subUnitFrame.activeItemFrame activeItemFrame.fields['name'][1].insert(0, 'Rvb1') activeItemFrame.fields['chainIds'][1].insert(0, 'A,C,E') activeItemFrame.fields['color'][1].set(chimera.MaterialColor( 0, 255, 0)) activeItemFrame.add.invoke() self.assertEqual(1, len(self.g.configFrame.config.subunits)) self.assertEqual(1, len(subUnitFrame.frames)) activeItemFrame.fields['name'][1].insert(0, 'Rvb2') activeItemFrame.fields['chainIds'][1].insert(0, 'B,D,F') activeItemFrame.fields['color'][1].set( chimera.MaterialColor(0.392, 0.584, 0.929)) activeItemFrame.add.invoke() self.assertEqual(2, len(self.g.configFrame.config.subunits)) self.assertEqual(2, len(subUnitFrame.frames)) configfilename = tempfile.mkstemp()[1] self.g.configFrame.resMngr._saveAssembly(configfilename) self.assertEqual(configfilename, xla.getRecentPaths()[0]) self.g.Subunits.table.colorAll.invoke() for chain in ['A', 'C', 'E']: color = evalSpec('#{0}:.{1}'.format(self.model.id, chain)).atoms()[0].color self.assertEqual(color, chimera.MaterialColor(0, 255, 0)) for chain in ['B', 'D', 'F']: color = evalSpec('#{0}:.{1}'.format(self.model.id, chain)).atoms()[0].color self.assertEqual(color, chimera.MaterialColor(0.392, 0.584, 0.929)) ctable = self.g.Subunits.table ctable.table.tixTable.hlist.selection_clear() ctable.table.tixTable.hlist.selection_set(0) ctable.hide.invoke() for chain in ['A', 'C', 'E']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, False) for chain in ['B', 'D', 'F']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, True) ctable.showAll.invoke() ctable.table.tixTable.hlist.selection_clear() ctable.table.tixTable.hlist.selection_set(1) ctable.hide.invoke() for chain in ['A', 'C', 'E']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, True) for chain in ['B', 'D', 'F']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, False) ctable.show.invoke() for chain in ['B', 'D', 'F']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, True) ctable.showAll.invoke() ctable.table.tixTable.hlist.selection_clear() ctable.table.tixTable.hlist.selection_set(0) ctable.showOnly.invoke() for chain in ['A', 'C', 'E']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, True) for chain in ['B', 'D', 'F']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, False) ctable.showAll.invoke() ctable.table.tixTable.hlist.selection_clear() ctable.table.tixTable.hlist.selection_set(0) chimera.selection.clearCurrent() ctable.select.invoke() self.assertListEqual( ['A', 'C', 'E'], [s.chain for s in chimera.selection.currentChains()]) chimera.selection.clearCurrent() self.assertEqual(2, len(ctable.table._sortedData())) ctable.chainVar.set(1) self.assertEqual(6, len(ctable.table._sortedData())) ctable.showAll.invoke() ctable.table.tixTable.hlist.selection_clear() ctable.table.tixTable.hlist.selection_set(0) ctable.hide.invoke() for chain in ['A']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, False) for chain in ['C', 'E']: ribbonDisplay = evalSpec('#{0}:.{1}'.format( self.model.id, chain)).residues()[0].ribbonDisplay self.assertEqual(ribbonDisplay, True) ctable.table.tixTable.hlist.selection_set(1) ctable.hide.invoke() ctable.table.tixTable.hlist.selection_set(2) ctable.hide.invoke() ctable.chainVar.set(0) self.assertEqual(False, self.g.configFrame.config.subunits[0].show) self.assertEqual(2, len(ctable.table._sortedData())) ctable.showAll.invoke() self.assertEqual(True, self.g.configFrame.config.subunits[0].show) dataFrame = self.g.configFrame.dataFrame activeItemFrame = dataFrame.activeItemFrame activeItemFrame.fields['name'][1].insert(0, 'xlinks') paths = [ 'xlinks/inter.csv', 'xlinks/intra.csv', 'xlinks/monolinks.csv' ] dirname = os.path.dirname(self.xlaTestCPath) paths = [os.path.join(dirname, p) for p in paths] fileFrame = activeItemFrame.fields['fileGroup'][1] map(fileFrame.fileGroup.addFile, paths) fileFrame.resetFileMenu(paths, 0) activeItemFrame.fields['type'][3].set('xquest') activeItemFrame.add.invoke() self.assertEqual(1, len(self.g.configFrame.config.dataItems)) self.assertEqual(1, len(dataFrame.frames)) dataMgrTab = self.g.__dict__['Data manager'] self.assertEqual(3, len(dataMgrTab.winfo_children())) xFrame = self.g.Xlinks xFrame.displayDefaultBtn.invoke() self.assertEqual(1, len(xFrame.getXlinkDataMgrs())) xmgr = xFrame.getXlinkDataMgrs()[0] self.assertEqual(216, len(xmgr.pbg.pseudoBonds)) displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(75, displayed) xFrame.ld_score_var.set(30.0) displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(57, displayed) xFrame.hideAllXlinksBtn.invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(0, displayed) xFrame.displayDefaultBtn.invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(57, displayed) xFrame.hideIntraXlinksBtn.invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(24, displayed) xFrame.displayDefaultBtn.invoke() xFrame.hideInterXlinksBtn.invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(33, displayed) xFrame.showAllXlinksBtn.invoke() xFrame.smartModeBtn.invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(162, displayed) xFrame.smartModeBtn.invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(57, displayed) xFrame.confOligBtn.invoke() xFrame.confOligWindow.winfo_children()[0].winfo_children()[0].invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(18, displayed) xFrame.confOligWindow.winfo_children()[0].winfo_children()[0].invoke() activeItemFrame.fields['name'][1].insert(0, 'sequences') paths = ['sequences.yeast.fasta'] dirname = os.path.dirname(self.xlaTestCPath) paths = [os.path.join(dirname, p) for p in paths] fileFrame = activeItemFrame.fields['fileGroup'][1] map(fileFrame.fileGroup.addFile, paths) fileFrame.resetFileMenu(paths, 0) activeItemFrame.fields['type'][3].set('sequences') activeItemFrame.add.invoke() self.assertEqual(2, len(self.g.configFrame.config.dataItems)) self.assertEqual(2, len(dataFrame.frames)) sequenceFrame = dataFrame.frames[-1] mapFrame = sequenceFrame.fields['mapping'][1] mapFrame.mapButton.invoke() for seqName, subset in mapFrame.subsetframes.iteritems(): if 'RUVB1' in seqName: subset.menus[0].var.set('Rvb1') if 'RUVB2' in seqName: subset.menus[0].var.set('Rvb2') mapFrame.onSave() self.g.configFrame.resMngr._saveAssembly( self.g.configFrame.config.file) self.assertEqual(5, len(dataMgrTab.winfo_children())) dataMgrTab.winfo_children()[2].invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(0, displayed) dataMgrTab.winfo_children()[2].invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(57, displayed) xFrame.showModifiedFrame.showModifiedMap() for chain in ['A', 'C', 'E']: color = evalSpec('#{0}:.{1}'.format(self.model.id, chain)).atoms()[0].color self.assertEqual(color, chimera.colorTable.getColorByName('light gray')) for chain in ['B', 'D', 'F']: color = evalSpec('#{0}:.{1}'.format(self.model.id, chain)).atoms()[0].color self.assertEqual(color, chimera.colorTable.getColorByName('light gray')) some_red_resi = map(str, [81, 128, 161, 174, 276]) for resi in some_red_resi: for chain in ['B', 'D', 'F']: color = evalSpec('#{0}:{2}.{1}'.format(self.model.id, chain, resi)).atoms()[0].color self.assertEqual(color, chimera.colorTable.getColorByName('red')) some_red_resi = map(str, [85, 116, 193, 210, 239, 377]) for resi in some_red_resi: for chain in ['A', 'C', 'E']: color = evalSpec('#{0}:{2}.{1}'.format(self.model.id, chain, resi)).atoms()[0].color self.assertEqual(color, chimera.colorTable.getColorByName('red')) some_yellow_resi = map(str, [15, 130, 201, 285, 438]) for resi in some_yellow_resi: for chain in ['B', 'D', 'F']: color = evalSpec('#{0}:{2}.{1}'.format(self.model.id, chain, resi)).atoms()[0].color self.assertEqual(color, chimera.colorTable.getColorByName('yellow')) some_blue_resi = map(str, [198, 331, 338, 357]) for resi in some_blue_resi: for chain in ['B', 'D', 'F']: color = evalSpec('#{0}:{2}.{1}'.format(self.model.id, chain, resi)).atoms()[0].color self.assertEqual(color, chimera.colorTable.getColorByName('blue')) xFrame.ld_score_var.set(0.0) xFrame.showModifiedFrame.showModifiedMap() some_blue_resi = map(str, [377]) for resi in some_blue_resi: for chain in ['A', 'C', 'E']: color = evalSpec('#{0}:{2}.{1}'.format(self.model.id, chain, resi)).atoms()[0].color self.assertEqual(color, chimera.colorTable.getColorByName('blue')) xFrame.ld_score_var.set(30.0) xFrame.showModifiedFrame.showModifiedMap() modelStatsTable = self.g.Xlinks.modelStatsTable modelStatsTable.xlinkToolbar.resetView() self.g.Subunits.table.colorAll.invoke() self.assertEqual(6, len(modelStatsTable.winfo_children())) csvfilename = tempfile.mkstemp()[1] with open(csvfilename, 'w') as f: modelStatsTable._exportTable(f) with open(csvfilename, 'rU') as csvfile: dialect = csv.Sniffer().sniff(csvfile.readline(), ['\t', ',']) csvfile.seek(0) reader = csv.DictReader(csvfile, dialect=dialect) self.assertListEqual([ 'All xlinks', 'Satisfied', 'Violated', 'Satisfied [%]', 'Violated [%]', 'model' ], reader.fieldnames) rows = list(reader) self.assertEqual(1, len(rows)) row = rows[0] self.assertEqual(2, int(row['Violated'])) self.assertEqual(18, int(row['All xlinks'])) self.assertEqual(16, int(row['Satisfied'])) self.assertEqual('88.9', row['Satisfied [%]']) self.assertEqual('11.1', row['Violated [%]']) self.assertEqual('yRvb12.hexamer.pdb', row['model']) modelStatsTable.modelListFrame.winfo_children()[8].invoke() detailsFrame = modelStatsTable.detailsFrame self.assertEqual(2, len(detailsFrame.winfo_children())) detailsFrame.showHistogram() xlinksSet = detailsFrame.xlinkDataMgr.getXlinksWithDistances( detailsFrame.xlinkStats) self.assertEqual(18, len(xlinksSet.data)) #TODO: test exportSelectedXlinkList detailsFrame.byCompViolatedListFrame.highlightSelBtn.invoke() self.assertEqual(6, len(chimera.selection.currentPseudobonds())) csvfilename = tempfile.mkstemp()[1] with open(csvfilename, 'w') as f: detailsFrame.byCompViolatedListFrame._exportSelectedXlinkList(f) with open(csvfilename, 'rU') as csvfile: dialect = csv.Sniffer().sniff(csvfile.readline(), ['\t', ',']) csvfile.seek(0) reader = csv.DictReader(csvfile, dialect=dialect) self.assertEqual(6, len(list(reader))) chimera.selection.clearCurrent() detailsFrame.byPairViolatedListFrame.highlightSelBtn.invoke() self.assertEqual(6, len(chimera.selection.currentPseudobonds())) csvfilename = tempfile.mkstemp()[1] with open(csvfilename, 'w') as f: detailsFrame.byCompViolatedListFrame._exportSelectedXlinkList(f) with open(csvfilename, 'rU') as csvfile: dialect = csv.Sniffer().sniff(csvfile.readline(), ['\t', ',']) csvfile.seek(0) reader = csv.DictReader(csvfile, dialect=dialect) self.assertEqual(6, len(list(reader))) chimera.selection.clearCurrent() modelStatsTable.xlinkToolbar.lengthThreshVar.set(40.0) modelStatsTable.xlinkToolbar.lengthThresholdFrameApplyBtn.invoke() modelStatsTable.updateBtn.invoke() self.assertEqual(6, len(modelStatsTable.winfo_children())) csvfilename = tempfile.mkstemp()[1] with open(csvfilename, 'w') as f: modelStatsTable._exportTable(f) with open(csvfilename, 'rU') as csvfile: dialect = csv.Sniffer().sniff(csvfile.readline(), ['\t', ',']) csvfile.seek(0) reader = csv.DictReader(csvfile, dialect=dialect) self.assertListEqual([ 'All xlinks', 'Satisfied', 'Violated', 'Satisfied [%]', 'Violated [%]', 'model' ], reader.fieldnames) rows = list(reader) self.assertEqual(1, len(rows)) row = rows[0] self.assertEqual(1, int(row['Violated'])) self.assertEqual(18, int(row['All xlinks'])) self.assertEqual(17, int(row['Satisfied'])) self.assertEqual('94.4', row['Satisfied [%]']) self.assertEqual('5.6', row['Violated [%]']) self.assertEqual('yRvb12.hexamer.pdb', row['model']) modelStatsTable.xlinkToolbar.lengthThreshVar.set(30.0) modelStatsTable.xlinkToolbar.lengthThresholdFrameApplyBtn.invoke() modelStatsTable.updateBtn.invoke() xFrame.showXlinksFromTabNameCompOptMenuFrom.var.set('Rvb1') xFrame.showXlinksFromTabNameCompOptMenuTo.var.set('Rvb2') xFrame.showXlinksFromBtn.invoke() displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(24, displayed) xFrame.ld_score_var.set(0.0) displayed = len( [pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(27, displayed) xFrame.ld_score_var.set(30.0) colorXlinkedFrame = xFrame.colorXlinkedFrame colorXlinkedFrame.compOptMenuFrom.var.set('Rvb1') colorXlinkedFrame.compOptMenuTo.var.set('Rvb2') colorXlinkedFrame.colorOptionVar.set(1) colorXlinkedFrame.colorBtn.invoke() some_test_resi = map(str, [31, 171, 174, 432, 450, 454]) for resi in some_test_resi: for chain in ['A', 'C', 'E']: color = evalSpec('#{0}:{2}.{1}'.format(self.model.id, chain, resi)).atoms()[0].color self.assertEqual(color, chimera.colorTable.getColorByName('red')) display = evalSpec('#{0}:{2}.{1}'.format( self.model.id, chain, resi)).atoms()[0].display self.assertEqual(display, True) colorXlinkedFrame.colorOptionVar.set(2) colorXlinkedFrame.colorBtn.invoke() some_test_resi = map(str, [31, 171, 174, 432, 450, 454]) for resi in some_test_resi: for chain in ['A', 'C', 'E']: color = evalSpec('#{0}:{2}.{1}'.format(self.model.id, chain, resi)).atoms()[0].color self.assertEqual(color, chimera.MaterialColor(0.392, 0.584, 0.929)) display = evalSpec('#{0}:{2}.{1}'.format( self.model.id, chain, resi)).atoms()[0].display self.assertEqual(display, True) colorXlinkedFrame.compOptMenuFrom.var.set('Rvb2') colorXlinkedFrame.compOptMenuTo.var.set('Rvb1') colorXlinkedFrame.uncolorOthersBtn.var.set(True) colorXlinkedFrame.colorOptionVar.set(2) colorXlinkedFrame.colorBtn.invoke() some_test_resi = map(str, [31, 171, 174, 432, 450, 454]) for resi in some_test_resi: for chain in ['A', 'C', 'E']: display = evalSpec('#{0}:{2}.{1}'.format( self.model.id, chain, resi)).atoms()[0].display self.assertEqual(display, False) some_test_resi = map(str, [123, 157, 198, 357, 414]) for resi in some_test_resi: for chain in ['B', 'D', 'F']: color = evalSpec('#{0}:{2}.{1}'.format(self.model.id, chain, resi)).atoms()[0].color self.assertEqual(color, chimera.MaterialColor(0, 255, 0)) display = evalSpec('#{0}:{2}.{1}'.format( self.model.id, chain, resi)).atoms()[0].display self.assertEqual(display, True)
def Apply(self): colors = {} for i, ssInfo in enumerate(self.info): ssType, prefName, attrName = ssInfo rgba = self.wells[i].rgba prefs[prefName] = rgba if not self.actVars[i].get(): continue if rgba is None: color = None else: color = chimera.MaterialColor(*rgba) colors[attrName] = color mols = self.molListBox.getvalue() # only the protein residues are relevant... protein = {} for m in mols: for r in m.residues: ratoms = r.atomsMap if 'CA' not in ratoms: continue if len(ratoms) == 1: # possible CA-only model if ratoms['CA'][0].element.number == 6: protein[r] = True continue if 'O' in ratoms \ and 'N' in ratoms \ and 'C' in ratoms: protein[r] = True atomAttrs = [] resAttrs = [] if self.colorRibVar.get(): resAttrs = ["ribbonColor"] if self.colorAtomVar.get(): atomAttrs.append("color") if self.colorSurfVar.get(): atomAttrs.append("surfaceColor") from chimera.actions import changeSurfsFromCustom changeSurfsFromCustom(mols) if atomAttrs: def colorAttrs(item, res, attrs): for attrName, color in colors.items(): if attrName is None: if not (res.isHelix or res.isSheet): break elif getattr(res, attrName): break else: return for attr in attrs: setattr(item, attr, color) for m in mols: for a in m.atoms: res = a.residue if res not in protein: continue colorAttrs(a, res, atomAttrs) if resAttrs: for m in mols: for res in m.residues: if res not in protein: continue for attrName, color in colors.items(): if attrName is None: if not (res.isHelix or res.isSheet): break elif getattr(res, attrName): break else: continue for attr in resAttrs: setattr(res, attr, color)
cur_color = None cur_style = None cur_typeface = None if (len(label.lines) > 0) and \ (len(label.lines[0]) > 0): c = label.lines[0][0] cur_color = c.rgba cur_size = c.size cur_style = c.style cur_typeface = c.fontName label.set(text) if cur_color: cur_color = chimera.MaterialColor(*cur_color) changeLabelAttrs(label, cur_size, cur_color, cur_style, cur_typeface) if color or size or style or typeface: if style: style = styleLookup(style) if typeface: typeface = typefaceLookup(typeface) changeLabelAttrs(label, size, color, style, typeface) if (xpos != None) or (ypos != None): cur_xpos, cur_ypos = label.pos if xpos == None: xpos = cur_xpos if ypos == None: ypos = cur_ypos
def _selCavityCB(self, tableSel): prefs[EXCLUDE_MOUTH] = self.excludeMouth.variable.get() from chimera.selection import ItemizedSelection, mergeCurrent, \ EXTEND, REMOVE cavitySel = ItemizedSelection() for cavity in tableSel: cavitySel.merge(EXTEND, cavity.pocketInfo["atoms"]) if prefs[EXCLUDE_MOUTH]: cavitySel.merge(REMOVE, cavity.mouthInfo["atoms"]) cavitySel.addImplied() # might be no cavities selected... cav1 = self.cavities[0] someA = (cav1.mouthInfo["atoms"].atoms() or cav1.pocketInfo["atoms"].atoms())[0] if someA.__destroyed__: return mol = someA.molecule cavitySet = set(cavitySel.atoms()) from chimera import selectionOperation doSelect = self.doSelect.variable.get() if doSelect != prefs[DO_SELECT]: #if not doSelect: # mergeCurrent(REMOVE, cavitySel) prefs[DO_SELECT] = doSelect doColor = self.doColor.variable.get() if doColor != prefs[DO_COLOR]: if not doColor and hasattr(self, '_prevColors'): for a, c, sc in self._prevColors: if a.__destroyed__: continue a.color = c a.surfaceColor = sc delattr(self, '_prevColors') prefs[DO_COLOR] = doColor if doColor: prefs[POCKET_COLOR] = self.pocketColor.rgba prefs[NONPOCKET_COLOR] = self.nonpocketColor.rgba doSurface = self.doSurface.variable.get() if doSurface != prefs[DO_SURFACE]: if not doSurface: for a in cavitySet: a.surfaceDisplay = False prefs[DO_SURFACE] = doSurface doZoom = self.doZoom.variable.get() if doZoom != prefs[DO_ZOOM]: if not doZoom: from Midas import focus, uncofr focus([mol]) uncofr() prefs[DO_ZOOM] = doZoom if doSelect: selectionOperation(cavitySel) if doColor: if prefs[POCKET_COLOR] == None: pocketColor = None else: pocketColor = chimera.MaterialColor( *prefs[POCKET_COLOR]) if prefs[NONPOCKET_COLOR] == None: nonpocketColor = None else: nonpocketColor = chimera.MaterialColor( *prefs[NONPOCKET_COLOR]) if not hasattr(self, '_prevColors'): self._prevColors = [(a, a.color, a.surfaceColor) for a in mol.atoms] for a in mol.atoms: if a in cavitySet: a.surfaceColor = a.color = pocketColor else: a.surfaceColor = a.color = nonpocketColor if doSurface: for a in mol.atoms: a.surfaceDisplay = a in cavitySet surfs = chimera.openModels.list(mol.id, mol.subid, modelTypes=[chimera.MSMSModel]) catsurfs = [s for s in surfs if s.category == "main"] if not catsurfs: from Midas import surfaceNew surfaceNew("main", models=[mol]) if doZoom and tableSel: from Midas import align, focus align(cavitySel, mol.atoms) focus(cavitySel)