Exemple #1
0
def colorBB():

    red = getColorByName('red')
    yellow = getColorByName('yellow')

    # return a list of opened molecules
    for mol in openModels.list(modelTypes=[Molecule]):
        mol.color = red  # change model color to be red
        atoms = mol.atoms
        for atom in atoms:
            if atom.name == 'CA':
                atom.color = yellow
Exemple #2
0
def getRGBcolor_byName(sCol):
	from chimera import colorTable
	try:
		c = colorTable.getColorByName(sCol)
		return c.rgba()[:3]
	except KeyError:
		return None
	def fillInUI(self, parent):
		self.info = [
			("Helix", HELIX_COLOR, 'isHelix'),
			("Strand", SHEET_COLOR, 'isSheet'),
			("Other", OTHER_COLOR, None)
		]
		header = Tkinter.Frame(parent)
		header.grid(row=0, column=0, sticky="nsew")
		parent.rowconfigure(0, weight=1)
		for i in range(len(self.info)):
			parent.columnconfigure(i, weight=1)

		from chimera.widgets import MoleculeScrolledListBox
		self.molListBox = MoleculeScrolledListBox(header,
				selectioncommand=lambda: self.configure(
				models=self.molListBox.getvalue()),
				listbox_selectmode="extended",
				labelpos="nw", label_text="Models")
		self.molListBox.grid(row=0, column=0,
					rowspan=len(self.info), sticky="nsew")
		for i in range(3):
			header.rowconfigure(i, weight=1)
		header.columnconfigure(0, weight=1)

		self.colorRibVar = Tkinter.IntVar(parent)
		self.colorRibVar.set(True)
		self.colorAtomVar = Tkinter.IntVar(parent)
		self.colorAtomVar.set(False)
		self.colorSurfVar = Tkinter.IntVar(parent)
		self.colorSurfVar.set(False)
		varFrame = Tkinter.Frame(parent)
		varFrame.grid(row=1, column=0)
		for i, info in enumerate([(self.colorRibVar, "Color ribbons"),
				(self.colorAtomVar, "Color atoms"),
				(self.colorSurfVar, "Color surfaces")]):
			var, text = info
			but = Tkinter.Checkbutton(varFrame, variable=var,
								text=text)
			but.grid(row=i, column=0, sticky='w')

		self.wells = []
		self.actVars = []
		from CGLtk.color.ColorWell import ColorWell
		from chimera.colorTable import getColorByName
		for row, ssInfo in enumerate(self.info):
			ssType, prefName, attrName = ssInfo
			rgba = prefs[prefName]
			if isinstance(rgba, basestring):
				rgba = getColorByName(rgba).rgba()
			well = ColorWell(header, color=rgba,
							noneOkay=True)
			self.wells.append(well)
			well.grid(row=row, column=2)

			actVar = Tkinter.IntVar(parent)
			actVar.set(True)
			self.actVars.append(actVar)
			Tkinter.Checkbutton(header, variable=actVar,
						text=ssType).grid(row=row,
						column=1, sticky='w')
Exemple #4
0
 def _rgba(self, colorInfo):
     if colorInfo is None:
         colorInfo = self['newcolor']
     if isinstance(colorInfo, basestring):
         from chimera.colorTable import getColorByName
         colorInfo = getColorByName(colorInfo)
     if hasattr(colorInfo, 'rgba'):
         if callable(colorInfo.rgba):
             return colorInfo.rgba()
         return colorInfo.rgba
     return colorInfo
	def _rgba(self, colorInfo):
		if colorInfo is None:
			colorInfo = self['newcolor']
		if isinstance(colorInfo, basestring):
			from chimera.colorTable import getColorByName
			colorInfo = getColorByName(colorInfo)
		if hasattr(colorInfo, 'rgba'):
			if callable(colorInfo.rgba):
				return colorInfo.rgba()
			return colorInfo.rgba
		return colorInfo
Exemple #6
0
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]
Exemple #7
0
def draw_bond_orders(molecule, error_spring=True):
    pbg = getPseudoBondGroup('Bond order errors', associateWith=[molecule])
    pbg.lineWidth, pbg.lineType, pbg.color = 2, 1, getColorByName('red')

    def draw_spring(bond):
        pbg = getPseudoBondGroup('Bond order errors')
        pb = pbg.newPseudoBond(*bond.atoms)
        pb.drawMode = 2
        pb.radius = bond.radius + 0.1

    for bond in molecule.bonds:
        order = getattr(bond, 'order', None)
        if not order:
            print('! Invalid order for bond', bond)
            if error_spring:
                draw_spring(bond)
            continue
        if not hasattr(bond, '_oldradius'):
            bond._oldradius = bond.radius
        bond.radius = bond._oldradius * order * 0.5

    return pbg
Exemple #8
0
def color_path_regions(markers, reg_path, seq_start):
    '''
    TODO: This Chimera code has not been ported to ChimeraX.
    '''
    f = open(reg_path)
    lines = f.readlines()
    f.close()

    c3 = [line.split('\t')[:3] for line in lines]
    from chimera.colorTable import getColorByName
    regions = [(int(i1), int(i2), getColorByName(cname).rgba())
               for i1, i2, cname in c3]

    color = {}
    for i1, i2, rgba in regions:
        for i in range(i1, i2 + 1):
            color[i] = rgba

    for m in markers:
        i = seq_start + m.residue.number - 1
        if i in color:
            m.set_rgba(color[i])
Exemple #9
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

"""
Show a residue with different color

Tasks
=====
1. Obtain selected residues from interface as Python objects
2. Force display of such residues
3. Color those atoms in red
"""
import chimera

# 1
from chimera import runCommand as rc
rc("sel ligand zr < 5")
selected_residues = chimera.selection.currentResidues()

# 2
for residue in selected_residues:
    for atom in residue.atoms:
        atom.display = 1

# 3
from chimera.colorTable import getColorByName
red = getColorByName('red')
for residue in selected_residues:
    for atom in residue.atoms:
        atom.color = red
Exemple #10
0
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 __init__(self):
                ### Volume name
                self.volumepath = os.environ.get('CHIMVOL')
                print self.volumepath
                if self.volumepath is None:
                        sys.exit(1)
                self.rundir = os.path.dirname(self.volumepath)
                self.chimlog = os.path.join(self.rundir, "apChimSnapshot.log")

                self.writeMessageToLog("\n\n")
                self.writeMessageToLog("======================")
                self.writeMessageToLog("Running apChimSnapshot")
                self.writeMessageToLog("======================")
                self.writeMessageToLog("\n")

                ### Temporary volume, low pass filtered
                self.tmpfilepath = os.environ.get('CHIMTEMPVOL')
                if self.tmpfilepath is None:
                        self.tmpfilepath = self.volumepath
                ### PDB structure
                self.pdbfilepath = os.environ.get('CHIMPDBFILE')
                ### High resolution rendering
                voxellimit = os.environ.get('CHIMVOXELLIMIT')
                if voxellimit is not None and bool(voxellimit) is True:
                        self.voxellimit = True
                else:
                        self.voxellimit = False
                ### Symmetry
                self.symmetry = os.environ.get('CHIMSYM')
                if self.symmetry is None:
                        self.symmetry = 'c1'
                else:
                        self.symmetry = self.symmetry.lower()
                ### Zoom factor
                self.zoom = os.environ.get('CHIMZOOM')
                if self.zoom is None:
                        self.zoom = 1.0
                else:
                        self.zoom = float(self.zoom)
                ### Contour factor
                self.contour = os.environ.get('CHIMCONTOUR')
                if self.contour is not None:
                        self.contour = float(self.contour)
                ### Image type
                self.type = os.environ.get('CHIMTYPE')
                if self.type is None or self.type not in ('snapshot', 'animate'):
                        self.type = 'snapshot'
                ### Color array
                colors = os.environ.get('CHIMCOLORS')
                if colors is not None and "," in colors:
                        self.colors = colors.split(",")
                else:
                        self.colors = None
                ### Silhouette
                silhouette = os.environ.get('CHIMSILHOUETTE')
                if silhouette is not None and bool(silhouette) is True:
                        chimera.viewer.showSilhouette = True
                        chimera.viewer.silhouetteWidth = 3.0
                        self.writeMessageToLog("using chimera silhouette")
                else:
                        chimera.viewer.showSilhouette = False
                        self.writeMessageToLog("skipping chimera silhouette")
                ### Background
                if os.environ.get('CHIMBACK') is None:
                        white = getColorByName('white')
                        chimera.viewer.background = white
                else:
                        backcolor = os.environ.get('CHIMBACK').strip()
                        color = getColorByName(backcolor)
                        chimera.viewer.background = color
                ### image format
                self.imgformat = os.environ.get('CHIMIMGFORMAT')
                if self.imgformat is None:
                        self.imgformat = "PNG"
                ### image size
                imgsize = os.environ.get('CHIMIMGSIZE')
                if imgsize is not None:
                        imgsize = int(imgsize)
                        self.imgsize = (imgsize, imgsize)
                elif self.type == 'animate':
                        self.imgsize = (512,512)
                else:
                        self.imgsize = (1024,1024)
                ### file format
                self.fileformat = os.environ.get('CHIMFILEFORMAT')
                if self.fileformat is None:
                        self.fileformat = "mrc"
                ### write to log
                self.writeMessageToLog("Chimera version: %s"%(chimera.version.version))
                self.writeMessageToLog("Environmental data: ")
                for var in os.environ.keys():
                        if var[:4] == "CHIM":
                                if os.environ.get(var) is not None:
                                        self.writeMessageToLog("export %s=%s"%(var, os.environ.get(var)))               
Exemple #12
0
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 _setColor(color=color, g=g):
     from chimera.colorTable import getColorByName
     g.color = getColorByName(color)
     g.lineType = chimera.Dash
	try:
		info = typeInfo[a.idatmType]
	except KeyError:
		return False
	return info.substituents < info.geometry

from chimera.colorTable import getColorByName
from prefs import defaults, CLASH_THRESHOLD, HBOND_ALLOWANCE, BOND_SEPARATION, \
	IGNORE_INTRA_RES, ACTION_SELECT, ACTION_COLOR, CLASH_COLOR, \
	NONCLASH_COLOR, ACTION_PSEUDOBONDS, PB_COLOR, PB_WIDTH, ACTION_ATTR, \
	ACTION_REPLYLOG
defColors = {}
for color in [CLASH_COLOR, NONCLASH_COLOR, PB_COLOR]:
	val = defaults[color]
	if val is not None:
		val = getColorByName(val)
	defColors[color] = val
_continuousID = None
def cmdDetectClash(testAtoms, overlapCutoff=defaults[CLASH_THRESHOLD],
		hbondAllowance=defaults[HBOND_ALLOWANCE], test="others",
		setAttrs=defaults[ACTION_ATTR], selectClashes=
		defaults[ACTION_SELECT], colorClashes=defaults[ACTION_COLOR],
		clashColor=defColors[CLASH_COLOR], nonclashColor=
		defColors[NONCLASH_COLOR], makePseudobonds=
		defaults[ACTION_PSEUDOBONDS], pbColor=defColors[PB_COLOR],
		lineWidth=defaults[PB_WIDTH], bondSeparation=
		defaults[BOND_SEPARATION], saveFile=None, namingStyle=None,
		ignoreIntraRes=defaults[IGNORE_INTRA_RES], interSubmodel=False,
		log=defaults[ACTION_REPLYLOG], summary=True,
		continuous=False):
	global _continuousID
Exemple #15
0
import chimera

opened = chimera.openModels.open('3fx2', type="PDB")
mol = opened[0]

mol.display = True

from chimera.colorTable import getColorByName
red = getColorByName('red')

mol.color = red

blue = getColorByName('blue')
yellow = getColorByName('yellow')

ATOMS = mol.atoms
for at in ATOMS:
	at.drawMode = chimera.Atom.Ball
	if at.name == 'CA':
		at.color = yellow
	else:
		at.color = blue

BONDS = mol.bonds
for b in BONDS:
	b.display = chimera.Bond.Smart
	b.drawMode = chimera.Bond.Stick
	b.halfbond = True

RESIDUES = mol.residues
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
#    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#    the 'color' attribute represents the model-level color.
#    This color can be controlled by the midas command 'modelcolor'.
#    The 'color' assigned to a newly opened model is determined by a configurable preference (see discussion above).
#    Programmatically, the model 
#    color can be changed by simply assigning a 'MaterialColor' to 'molecule.color'. Molecules also have a
#    'display' attribute, where a value of 'True' corresponds to being displayed, and a value of 'False'
#     means the molecule is not displayed.
#     So to make sure the molecule is shown (it is by default when first opened):
mol.display = True

#     To color the molecule red,
#     get a reference to Chimera's notion of the color red (returns a 'MaterialColor' object)
from chimera.colorTable import getColorByName
red = getColorByName('red')

#     and assign it to 'mol.color'. 
mol.color = red
#     Note that the model will appear red at this point because all the atoms/bonds/residues
#     'color' attributes are set to 'None'

#    Atom Display Properties
#    ~~~~~~~~~~~~~~~~~~~~~~~
#
#    Each atom in a molecule has its own individual color,
#    accessible by the 'color' attribute. Upon opening a molecule, each atom's 'color' is set to 'None'; 
#    it can be changed by assigning a new 'MaterialColor' to 'atom.color'.
#    So, if we wanted to color all the alpha-carbon atoms blue, and all the rest yellow,
#    get references to the colors:
blue    = getColorByName('blue')
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
		def _setColor(color=color, g=g):
			from chimera.colorTable import getColorByName
			g.color = getColorByName(color)
			g.lineType = chimera.Dash
Exemple #20
0
        info = typeInfo[a.idatmType]
    except KeyError:
        return False
    return info.substituents < info.geometry


from chimera.colorTable import getColorByName
from prefs import defaults, CLASH_THRESHOLD, HBOND_ALLOWANCE, BOND_SEPARATION, \
 IGNORE_INTRA_RES, ACTION_SELECT, ACTION_COLOR, CLASH_COLOR, \
 NONCLASH_COLOR, ACTION_PSEUDOBONDS, PB_COLOR, PB_WIDTH, ACTION_ATTR, \
 ACTION_REPLYLOG
defColors = {}
for color in [CLASH_COLOR, NONCLASH_COLOR, PB_COLOR]:
    val = defaults[color]
    if val is not None:
        val = getColorByName(val)
    defColors[color] = val
_continuousID = None


def cmdDetectClash(testAtoms,
                   overlapCutoff=defaults[CLASH_THRESHOLD],
                   hbondAllowance=defaults[HBOND_ALLOWANCE],
                   test="others",
                   setAttrs=defaults[ACTION_ATTR],
                   selectClashes=defaults[ACTION_SELECT],
                   colorClashes=defaults[ACTION_COLOR],
                   clashColor=defColors[CLASH_COLOR],
                   nonclashColor=defColors[NONCLASH_COLOR],
                   makePseudobonds=defaults[ACTION_PSEUDOBONDS],
                   pbColor=defColors[PB_COLOR],