Ejemplo n.º 1
0
def make_gradient(sel, gradient, nbins, sat, value, hs, he, ss, se, vs, ve, colorname):
    if gradient == 'bgr' or gradient == 'rainbow':
        col = []
        coldesc = []
        for j in range(nbins):
            # must append the str(sel[j]) to the color name so that it is unique
            # for the selection
            coldesc.append(colorname + str(j))
            # coldesc.append('col' + str(sel[j]) + str(j))

            # create colors using hsv scale (fractional) starting at blue(.6666667)
            # through red(0.00000) in intervals of .6666667/(nbins -1) (the "nbins-1"
            # ensures that the last color is, in fact, red (0)
            # rewrote this to use the colorsys module to convert hsv to rgb
            hsv = (hs - (hs - he) * float(j) / (nbins - 1), ss - (ss - se) * float(j) / (nbins - 1), vs - (vs - ve) * float(j) / (nbins - 1))
            # convert to rgb and append to color list
            rgb = colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2])

            col.append(rgb)
            # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
            cmd.set_color(colorname + str(j), col[j])

            # cmd.color(,resi[j])

    # return the gradient as a list of colors named by their index (i.e. col0,col1,col2,col3,...)
    return coldesc
Ejemplo n.º 2
0
def color_frags(fA, pymol_file, single_color=''):
    warm = []
    x = math.ceil((len(fA) / 8.)**(1. / 3.))
    for li in range(int(2 * x)):
        i = 1.0 - li * (1.0 - 0.4) / (2 * x - 1)
        for lj in range(int(4 * x)):
            j = lj * (1.0 - 0.0) / (4 * x - 1)
            for lk in range(int(x)):
                safe = x
                if x != 1: safe = x - 1
                k = lk * (0.25 - 0.0) / (safe)
                warm.append([i, j, k])

    for frag in range(len(fA)):
        selection = ''
        for atom in range(len(fA[frag][1:])):
            key = str(fA[frag][1 + atom])
            selection += 'rank ' + key + ' '
        #linspace through color vector
        safefA = len(fA)
        if len(fA) != 1: safefA = len(fA) - 1
        fragind = int(math.floor(frag * ((len(warm)) - 1) / safefA))
        if single_color == '': color = warm[fragind]
        else: color = single_color
        pymol_file.write('cmd.select("(' + fA[frag][0] + ')", "' + selection +
                         '")\n')
        pymol_file.write('cmd.set_color("A_' + fA[frag][0] + '", ' +
                         str(color) + ')\n')
        pymol_file.write('cmd.color("A_' + fA[frag][0] + '","(' + fA[frag][0] +
                         ')")\n')
        if pymol:
            cmd.select("(" + fA[frag][0] + ")", selection)
            cmd.set_color("A_" + fA[frag][0], color)
            cmd.color("A_" + fA[frag][0], "(" + fA[frag][0] + ")")
Ejemplo n.º 3
0
def color_destab(posfile, binding=False):
    #re_pos = re.compile('([A-Z])\s+([0-9]+)\s+[a-zA-Z]+\s+([0-9]+)\s+([0-9]+)')
    re_pos = re.compile('([A-Z])\s+([0-9]+)\s+([0-9]+)')
    cols = [('destab%i' % i, [float(i) / 20, 0, 0]) for i in range(20)]
    print cols
    for name, col in cols:
        cmd.set_color(name, col)
    cmd.color('gray', 'all')
    for match in re_pos.finditer(open(posfile).read()):
        #chain,pos,ndestab,nbind = match.groups()
        chain, pos, ndestab = match.groups()
        which_n = ndestab
        if binding: which_n = nbind
        print chain, pos, which_n
        print cols[int(which_n)]
        cmd.color(cols[int(which_n)][0], 'c. %s and i. %s' % (chain, pos))
    # the following only works if DNASelections has alreay been run/called
    cmd.hide('everything')
    cmd.show('ribbon', 'notDNA')
    cmd.set('ribbon_sampling', 5)
    cmd.show('lines', 'notDNA')
    cmd.set('ray_trace_mode', 0)
    cmd.create('dnao', 'DNA')
    cmd.hide('labels')
    cmd.hide('everything', 'dnao')
    cmd.hide('everything', 'DNA')
    cmd.show('surface', 'dnao')
    cmd.show('spheres', 'r. hoh w. 4 of DNA')
    cmd.color('marine', 'r. hoh')
Ejemplo n.º 4
0
def add_color(col2, butt):
# checking if the button was already hit
# if so, toggling the selection off

  button_list.append(butt)

  if button_list.count(butt) > 1:

    button_list.remove(butt)
    button_list.remove(butt)	
    cmd.util.cbag ('all')

  elif butt != button_list[0]:
    button_list.remove(button_list[0])
    cmd.util.cbag ('all')
    curSel = col2

  else:
    cmd.util.cbag ('all')
    curSel = col2

# colouring selection with specified colour scheme
  cmd.set_color('siff', curSel )
  cmd.color('siff', InteractionButton[InteractionName.index(butt)]+'_'+butt )
  butt=[]
def set_colors(replace=False):
    '''Add the color blind-friendly colors to PyMOL.'''
    # Track the added colors
    added_colors = []

    for color, properties in CB_COLORS.items():
        # RGB tuple shortcut
        rgb = properties['rgb']

        # Get the primary and alternate color names into a single list
        names = [color]
        if properties['alt']:
            names.extend(properties['alt'])

        # Set the colors
        for name in names:
            # Set the cb_color
            cb_name = 'cb_{}'.format(name)
            cmd.set_color(cb_name, rgb)

            # Optionally replace built-in colors
            if replace:
                cmd.set_color(name, rgb)
                spacer = (20 - len(name)) * ' '
                added_colors.append('    {}{}{}'.format(name, spacer, cb_name))
            else:
                added_colors.append('    {}'.format(cb_name))

    # Notify user of newly available colors
    print('\nColor blind-friendly colors are now available:')
    print('\n'.join(added_colors))
    print('')
Ejemplo n.º 6
0
    def updateColor(self):
        if self.ss_asgn_prog is None:
            err_msg = 'Run DSSP or Stride to assign secondary structures first!'
            print('ERROR: %s' % (err_msg,))
            tkMessageBox.showinfo(title='ERROR', message=err_msg)
        else:
            print('Update color for %s' % (self.pymol_sel.get()), end=' ')
            print('using secondary structure assignment by %s' % (self.ss_asgn_prog,))

            if self.ss_asgn_prog == 'DSSP':
                SSE_list = self.DSSP_SSE_list
            elif self.ss_asgn_prog == 'Stride':
                SSE_list = self.STRIDE_SSE_list

            for sse in SSE_list:  # give color names
                cmd.set_color('%s_color' % (sse,), self.SSE_col_RGB[sse])
            for sse in SSE_list:  # color each SSE
                for sel_obj in self.sel_obj_list:
                    if self.SSE_sel_dict[sel_obj][sse] is not None:
                        cmd.color('%s_color' % (sse,), self.SSE_sel_dict[sel_obj][sse])
                        print('color', self.SSE_sel_dict[sel_obj][sse], ',', self.SSE_col_RGB[sse])
                    else:
                        print('No residues with SSE \'%s\' to color.' % (sse,))

        return
Ejemplo n.º 7
0
def genColor(color="wolfgang.v1", reverse="OFF", colorDict=colorDict, dpi=300, ray=1, N=256):
	
	"""
	color	:	Color ramp to be used for value mapping.
	reverse	:	Reverse color ramp for value mapping.
	maxCut	:	Maximum value (cutoff) allowed for redefined value range.
	minCut	:	Minimum value (cutoff) allowed for redefined value range.
	dpi		:	PyMol resolution; dots per inch.
	ray		:	PyMol rendering mode.
	N		:	Color ramp size.
	"""
	
	# Load color map. Note that colors come inverted:
	colorMix = list(colorDict[color])
	if reverse == "OFF":
		colorMix.reverse()
	colorMap = mpl.colors.LinearSegmentedColormap.from_list(colorMix, colors=colorMix, N=N)
	color256 = colorMap(numpy.arange(N))
	
	print
	print "ColorMap:", color
	print "Colors:", len(color256)
	print
	
	# color residues:
	k = 1
	for i in color256:
		colorName = color + "." + str(k)
		r, g, b, f = color256[k]
		cmd.set_color(colorName, str([r, g, b]))
Ejemplo n.º 8
0
def fade_color( sele = "all", fade_extent = 0.7, by_chain = True ):
  """
  Fade out RGB color values associated with a selection.
  The by_chain variable assumes that chains are uniform color, to
    allow speedy color setting based on chain, rather than based on
    residue (which can take a long time!)
  """
  pymol.stored.colors = []
  cmd.iterate( sele, "stored.colors.append( (chain, resi, name, color))")
  res_colors = {}
  stored_colors = pymol.stored.colors;

  cols = []
  colorname = ''
  chain = ''
  prev_chain = ''
  for chain, resi, name, color in stored_colors:
    if name == 'CA' or name == 'P': # c-alpha atom
      if by_chain and chain != prev_chain and len( colorname ) > 0:
        cmd.color( colorname, 'chain %s and %s' % (prev_chain,sele) )
      color_tuple = cmd.get_color_tuple(color)
      cols = [];
      for i in range(3):
        cols.append( fade_extent  + ( 1.0  - fade_extent ) * float(color_tuple[ i ]) )
      colorname = 'temp_chain%s' % chain
      cmd.set_color( colorname, cols )
      if not by_chain: cmd.color( colorname, 'resi %s and chain %s and %s' % (resi,chain,sele) )
      prev_chain = chain

  if by_chain: cmd.color( colorname, 'chain %s and %s' % (chain,sele) )
Ejemplo n.º 9
0
 def update_pymod_color_dict_with_list(self,
                                       color_list,
                                       update_in_pymol=False):
     for color_name in color_list:
         if update_in_pymol:
             cmd.set_color(color_name, color_name)
         self.all_colors_dict_tkinter.update({color_name: color_name})
Ejemplo n.º 10
0
Archivo: rpc.py Proyecto: jandom/rdkit
def rpcLabel(pos, labelText, id='lab1', color=(1, 1, 1)):
  """ create a text label
 
    Arguments:
      pos: a 3 tuple with the position of the label
      text: a string with the label
      color: a 3 tuple with the color of the label. (1,1,1) is white
      id: (OPTIONAL) the name of the object to be created
 
    NOTE:
      at the moment this is, how you say, a hack
 
  """
  x, y, z = pos
  text = """
Atom
 
  1  0  0  0  0  0  0  0  0  0999 V2000
% 10.4f% 10.4f%10.4f C   0  0  0  0  0  0  0  0  0  0  0  0
M  END""" % (x, y, z)
  cmd.read_molstr(text, id)
  cmd.label("%s" % (id), '"%s"' % labelText)
  cmd.hide("nonbonded", id)
  cmd.set_color("%s-color" % id, color)
  cmd.color("%s-color" % id, id)
  return 1
Ejemplo n.º 11
0
def pymol_color_atoms_by_elem(elem_colors=CPK_COLORS):
    """Color atoms by element in PyMOL"""
    logging.info("Coloring atoms.")
    for elem, rgb in elem_colors.items():
        color_name = elem + "_color"
        cmd.set_color(color_name, list(rgb))
        cmd.color(color_name, "e. {}".format(elem))
Ejemplo n.º 12
0
def color_destab(posfile,binding=False):
	#re_pos = re.compile('([A-Z])\s+([0-9]+)\s+[a-zA-Z]+\s+([0-9]+)\s+([0-9]+)')
	re_pos = re.compile('([A-Z])\s+([0-9]+)\s+([0-9]+)')
	cols = [ ('destab%i' %i, [float(i)/20,0,0]) for i in range(20) ]
	print cols
	for name,col in cols: cmd.set_color(name,col)
	cmd.color('gray','all')
	for match in re_pos.finditer( open(posfile).read() ):
		#chain,pos,ndestab,nbind = match.groups()
		chain,pos,ndestab = match.groups()
		which_n = ndestab
		if binding: which_n = nbind
		print chain, pos, which_n
		print cols[int(which_n)]
		cmd.color( cols[int(which_n)][0], 'c. %s and i. %s' %(chain,pos) )
	# the following only works if DNASelections has alreay been run/called
	cmd.hide('everything')
	cmd.show('ribbon','notDNA')
	cmd.set('ribbon_sampling',5)
	cmd.show('lines','notDNA')
	cmd.set('ray_trace_mode',0)
	cmd.create('dnao','DNA')
	cmd.hide('labels')
	cmd.hide('everything','dnao')
	cmd.hide('everything','DNA')
	cmd.show('surface','dnao')
	cmd.show('spheres','r. hoh w. 4 of DNA')
	cmd.color('marine','r. hoh')
Ejemplo n.º 13
0
def make_gradient(sel,gradient,nbins,sat,value,hs,he,ss,se,vs,ve,colorname):
  if gradient == 'bgr' or gradient == 'rainbow':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # must append the str(sel[j]) to the color name so that it is unique 
      # for the selection
      coldesc.append(colorname + str(j))
      # coldesc.append('col' + str(sel[j]) + str(j))
 
      # create colors using hsv scale (fractional) starting at blue(.6666667) 
      # through red(0.00000) in intervals of .6666667/(nbins -1) (the "nbins-1" 
      # ensures that the last color is, in fact, red (0)
      # rewrote this to use the colorsys module to convert hsv to rgb
      hsv = (hs - (hs-he) * float(j) / (nbins-1), ss-(ss-se)*float(j)/(nbins-1), vs-(vs-ve)*float(j)/(nbins-1) )
      #convert to rgb and append to color list
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])
 
      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      cmd.set_color(colorname + str(j),col[j])
 
      #cmd.color(,resi[j])
 
  # return the gradient as a list of colors named by their index (i.e. col0,col1,col2,col3,...)
  return coldesc
Ejemplo n.º 14
0
def _cartoon(selection='all'):
    """
    Draw `selection` in a cartoon style.

    """

    cmd.show('spheres', selection)
    cmd.set('sphere_scale', 0.23, selection)

    cmd.hide('sticks', selection)
    cmd.show('lines', selection)
    cmd.set('line_as_cylinders', 1)
    cmd.set('line_radius', 0.08)
    cmd.set('line_use_shader', 1)
    cmd.set('valence_mode', 0, selection)
    cmd.set('valence_size', 0.14, selection)

    cmd.set('ray_trace_mode', 3)
    cmd.set('ray_trace_color', 'black')

    cmd.set_color('lgray', [0.6, 0.6, 0.6])
    cmd.color('lgray', 'elem C')

    cmd.orient(selection)
    cmd.zoom(selection, 3, complete=1)
Ejemplo n.º 15
0
 	def sele2Color(self, sele):
 		globalShader = self.optionMenu_shader.getvalue()

		newShader =  self.seleShaderDict[sele]
		if newShader != globalShader: # should be different from global shader, otherwise do nothing
			newColorInc = ShaderFactory.seleSlot[newShader]


			stored.idcolor_list = set() 
			cmd.iterate(sele, 'stored.idcolor_list.add(int(color))')

			if(len(stored.idcolor_list)>1):
				self.selectionConsole.set('Warning: Selection [%s] contains more than one color.' % sele)

			color = stored.idcolor_list.pop()
			rgb_color = cmd.get_color_tuple(color)

			if rgb_color[2] >= 0.990:
				color_id = '%s %s %s' % (str(rgb_color[0])[0:5].ljust(5, '0'), str(rgb_color[1])[0:5].ljust(5, '0'), str(rgb_color[2]-newColorInc)[0:5])
			else:
				color_id = '%s %s %s' % (str(rgb_color[0])[0:5].ljust(5, '0'), str(rgb_color[1])[0:5].ljust(5, '0'), str(rgb_color[2]+newColorInc)[0:5])

			# color_id from all the sele:shader dictionary
			# determine color_id:shader pair
			if color_id not in self.spColorShaderDict:
				self.spColorShaderDict[color_id] = [newShader, sele]

			# apply new color to atom set
			newRGB = color_id.split(' ')
			newColor = [float(newRGB[0]), float(newRGB[1]), float(newRGB[2])]
			cmd.set_color(color_id, newColor)
			cmd.color(color_id, sele)			

			print 'apply shader [%s] to selection [%s].' % (newShader, sele)			
Ejemplo n.º 16
0
 def update_pymod_color_dict_with_dict(self,
                                       color_dict,
                                       update_in_pymol=True):
     for color_name in list(color_dict.keys()):
         if update_in_pymol:
             cmd.set_color(color_name, color_dict[color_name])
         self.all_colors_dict_tkinter.update(
             {color_name: pmdt.convert_rgb_to_hex(color_dict[color_name])})
Ejemplo n.º 17
0
def heatmap(scores):
    colors = make_colors(scores)
    df = pd.read_csv(scores)
    nscores = normalize(df['score'])
    for i, j in zip(colors.keys(), nscores):
        cmd.set_color(f'c{i}', colors[i].tolist())
        cmd.show('sticks', f'(sidechain, resi {i})')
        cmd.color(f'c{i}', f'resi {i}')
Ejemplo n.º 18
0
 def paintChain(self, chainID, **kw):
     colormapname = kw.get('colormapname', self.colormapname) 
     Norm = self.norms[kw.get('norm', 'global')]
     cmap = ScalarMappable(Norm, get_cmap(colormapname))
     for resnum,value in self.chains[chainID].iteritems(): 
         colorname = "chain{}res{}".format(chainID, resnum)
         cmd.set_color(colorname, cmap.to_rgba(value)[:-1])
         cmd.color(colorname, "chain {} and resi {}".format(chainID, resnum))
def color_resi():
    # change absolute path here
    df = pd.read_csv("CgDODAa1_col_out.tsv", header=0, sep="\t")
    rgbList = [[x, y, z] for x, y, z in zip(df['r'], df['g'], df['b'])]
    colDict = dict([x, y] for x, y in zip(df['pos'], rgbList))
    for k, v in colDict.items():
        colorName = "mycol" + str(k)
        cmd.set_color(colorName, v)
        cmd.color(selection="(resi " + str(k) + ")", color=colorName)
Ejemplo n.º 20
0
 def add_new_color(self, new_color_rgb, new_color_hex):
     """
     Adds a new color to PyMod/PyMOL.
     """
     new_color_name = "custom_color_%s" % self.custom_colors_index
     self.all_colors_dict_tkinter[new_color_name] = new_color_hex
     cmd.set_color(new_color_name, new_color_rgb)
     self.custom_colors_index += 1
     return new_color_name
Ejemplo n.º 21
0
def color_obj(rainbow=0):

        """
        stolen from :)
AUTHOR
        Gareth Stockwell

USAGE
        color_obj(rainbow=0)

        This function colours each object currently in the PyMOL heirarchy
        with a different colour.  Colours used are either the 22 named
        colours used by PyMOL (in which case the 23rd object, if it exists,
        gets the same colour as the first), or are the colours of the rainbow

        """

        # Process arguments
        rainbow = int(rainbow)

        # Get names of all PyMOL objects
        obj_list = cmd.get_names('objects')

        if rainbow:

           print("\nColouring objects as rainbow\n")

           nobj = len(obj_list)

           # Create colours starting at blue(240) to red(0), using intervals
           # of 240/(nobj-1)
           for j in range(nobj):
              hsv = (240-j*240/(nobj-1), 1, 1)
              # Convert to RGB
              rgb = hsv_to_rgb(hsv)
              # Define the new colour
              cmd.set_color("col" + str(j), rgb)
              print(obj_list[j], rgb)
              # Colour the object
              cmd.color("col" + str(j), obj_list[j])

        else:
           # List of available colours
           colours = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan',    \
           'salmon', 'lime', 'pink', 'slate', 'magenta', 'orange', 'marine', \
           'olive', 'purple', 'teal', 'forest', 'firebrick', 'chocolate',    \
           'wheat', 'white', 'grey' ]
           ncolours = len(colours)

           # Loop over objects
           i = 0
           for obj in obj_list:
              print("  ", obj, colours[i])
              cmd.color(colours[i], obj)
              i = i+1
              if(i == ncolours):
                 i = 0
Ejemplo n.º 22
0
def set_acv_style(donor_name,
                  acceptor_name,
                  donor_site,
                  acceptor_site,
                  labels,
                  volume_type="AV",
                  transparency=False):
    """
    Set a default style for the ACV clouds

    Parameters
    ----------
    donor_name, acceptor_name : str
        names of the donor and acceptor ACV
    donor_site : str
        reference identifier for the donor labeling position
    acceptor_site : str
        reference identifier for the acceptor labeling position
    labels : dict
        dye, linker and setup parameters for the accessible volume calculation
    volume_type : {'AV', 'CV'}
        entire accessible volume or contact volume
    transparency : bool
        make volume transparent
    """
    cmd.set_color("donor_green", [108, 179, 129])
    cmd.set_color("acceptor_red", [194, 84, 73])
    if volume_type == "CV":
        contour_level = "contour_level_CV"
        donor_sele = "{} and resn CV".format(donor_name)
        acceptor_sele = "{} and resn CV".format(acceptor_name)
        donor_name = donor_name + "_CV"
        acceptor_name = acceptor_name + "_CV"
    else:
        contour_level = "contour_level_AV"
        donor_sele = donor_name
        acceptor_sele = acceptor_name
    smooth_map_from_xyz(
        donor_name,
        donor_sele,
        labels["Position"][donor_site][contour_level],
        labels["Position"][donor_site]["grid_spacing"],
        labels["Position"][donor_site]["state"],
    )
    smooth_map_from_xyz(
        acceptor_name,
        acceptor_sele,
        labels["Position"][acceptor_site][contour_level],
        labels["Position"][acceptor_site]["grid_spacing"],
        labels["Position"][acceptor_site]["state"],
    )
    cmd.color("donor_green", donor_name + "_isosurf")
    cmd.color("acceptor_red", acceptor_name + "_isosurf")
    if transparency:
        cmd.set("transparency", 0.4, donor_name + "_isosurf")
        cmd.set("transparency", 0.4, acceptor_name + "_isosurf")
Ejemplo n.º 23
0
def _handle_atom_color(c, at):
    return
    ck = tuple((int(255. * x) for x in c))
    if ck not in colors:
        name = "rmf" + str(len(colors))
        print "color", name, c, ck
        cmd.set_color(name, list(c))
        colors[ck] = name
        at.color = name
    else:
        at.color = colors[ck]
Ejemplo n.º 24
0
 	def sele2Color_deprecated(self):
 		globalShader = self.optionMenu_shader.getvalue()

 		# (color:shader) dictionary
 		# be used in shaderFactory.SCString()
 		#self.spColorShaderDict = {}
 		# get all the selection name
		sess = cmd.get_session()['names']
		for i in sess:
			if type(i) is ListType:
				# for each selection in the scene
				# also should exist in seleShaderDict
				if i[0] in self.seleShaderDict:
					newShader =  self.seleShaderDict[i[0]]
					if newShader != globalShader: # should be different from global shader, otherwise do nothing
						newColorInc = ShaderFactory.seleSlot[newShader]
						# pymol api routine
						# get the color for all the atoms in current selection
						stored.idcolor_list = []
						cmd.iterate(i[0], 'stored.idcolor_list.append((ID, int(color)))')

						# for a set of atoms have the same new color
						# apply color all at once for better performance
						# cmd.color is slow
						# example result: (color_index: [atom ids])
						# {25: [2, 3, 6], 6: [1], 9: [4, 5]}
						colorSetDict = {}
						for (atom_id, color) in stored.idcolor_list:
							colorSetDict.setdefault(color, []).append(str(atom_id))
						#print repr(colorSetDict)

						# for each color
						#for (atom_id, color) in stored.idcolor_list:
						for color in colorSetDict:
							atom_set = colorSetDict[color]
							rgb_color = cmd.get_color_tuple(color)
							#newColorInc = 0.001
							if rgb_color[2] >= 0.990:
								color_id = '%s %s %s' % (str(rgb_color[0])[0:5].ljust(5, '0'), str(rgb_color[1])[0:5].ljust(5, '0'), str(rgb_color[2]-newColorInc)[0:5])
							else:
								color_id = '%s %s %s' % (str(rgb_color[0])[0:5].ljust(5, '0'), str(rgb_color[1])[0:5].ljust(5, '0'), str(rgb_color[2]+newColorInc)[0:5])
							#print atom_id, color, color_id, repr(rgb_color)

							# color_id from all the sele:shader dictionary
							# determine color_id:shader pair
							if color_id not in self.spColorShaderDict:
								self.spColorShaderDict[color_id] = [newShader, i[0]]

							# apply new color to atom set
							newRGB = color_id.split(' ')
							newColor = [float(newRGB[0]), float(newRGB[1]), float(newRGB[2])]
							cmd.set_color(color_id, newColor)
							cmd.color(color_id, ('ID %s' % '+'.join(atom_set)))
						print 'apply shader [%s] to selection [%s].' % (newShader, i[0])
def color_residues(filename,
                   color_by='propensity',
                   power=1,
                   gradient="bwr",
                   scale=None):

    power = float(power)

    f = open(filename, "r")
    reader = csv.reader(f)

    residues = []

    header = reader.next()
    column = [i for i, col in enumerate(header) if col == color_by]

    if len(column) == 0:
        raise ValueError('No %s column found.  Check your input file' %
                         (color_by))
    elif len(column) > 1:
        raise ValueError('More than one %s column' % (color_by))
    else:
        column = column[0]

    for line in reader:
        residues.append(
            (line[0], line[1],
             float(line[column])))  #changed from line[1] and line[2]
    f.close()
    num_residues = len(residues)

    scores = [float(residue[2]) for residue in residues]
    if scale:
        min_value = scale[0]
        max_value = scale[1]
    else:
        max_value = max(scores)
        min_value = min(scores)

    if gradient == 'bwr':
        for residue in residues:
            res_num, chain, score = residue

            scaled_score = (score - min_value) / (max_value - min_value)

            curve1 = round((2**power) * (scaled_score**power), 5)
            curve2 = round((2**power) * ((1 - scaled_score)**power), 5)

            rgb = [min(1, curve1), min(curve1, curve2), min(curve2, 1)]

            cmd.set_color('r_color' + res_num + chain, rgb)
            cmd.color('r_color' + res_num + chain,
                      'resi ' + res_num + ' AND chain ' + chain)
            print 'colored residue' + res_num + ' chain ' + chain
Ejemplo n.º 26
0
def color_selections(selections):
    cl = len(selections)
    hsv_range = [(float(i + 1) * 1.0 / float(cl), 0.5, 0.5) for i in range(cl)]
    # *x means the same as in
    # rgb_range = map(lambda x: hsv_to_rgb(x[0], x[1], x[2]), hsv_range)
    rgb_range = map(lambda x: hsv_to_rgb(*x), hsv_range)
    colornames = []
    for [selection, color] in zip(selections, rgb_range):
        cmd.set_color(selection, color)
        colornames.append(selection)
        cmd.color(colornames[-1], selection)
    return colornames
Ejemplo n.º 27
0
    def testSetColor(self):
        self._testSpectrum_setup()
        cmd.color('red')
        self.assertImageHasColor('red')

        # redefine existing name, [0-1] float range
        cmd.set_color('red', [0., 0., 1.])
        cmd.recolor()
        self.assertImageHasColor('blue')

        # add new name, [0-1] float range
        cmd.set_color('thomas', [0., 1., 0.])
        cmd.color('thomas')
        self.assertImageHasColor('green')

        # redefine existing (custom) name, [0-255] int range
        cmd.set_color('thomas', [0x00, 0x80, 0x80])
        cmd.recolor()
        self.assertImageHasColor('0x008080')

        # add new very long name, [0-255] int range
        longname = 'some' + 'very' * 10 + 'longcolorname'
        cmd.set_color(longname, [0xFF, 0xFF, 0x00])
        cmd.color(longname)
        self.assertImageHasColor('yellow')
def color_bonds(filename,
                color_by='pp',
                name='bond',
                power=1,
                gradient="bwr",
                scale=None):

    power = float(power)

    bonds = []

    f = open(filename, "r")
    reader = csv.reader(f)

    header = reader.next()

    column = [i for i, col in enumerate(header) if col == color_by]
    if len(column) > 1:
        raise ValueError('More than one {0} column'.format(color_by))
    else:
        column = column[0]

    for line in reader:
        bonds.append([line[0], float(line[column])])
    f.close()

    num_bonds = len(bonds)

    scores = [bond[1] for bond in bonds]
    if scale:
        score_min = float(scale[0])
        score_max = float(scale[1])
    else:
        score_max = max(scores)
        score_min = min(scores)

    for bond in bonds:
        id_ = bond[0]
        score = bond[1]

        scaled_score = (score - score_min) / (score_max - score_min)

        curve1 = round((2**power) * (scaled_score**power), 5)
        curve2 = round((2**power) * ((1 - scaled_score)**power), 5)

        rgb = [min(1, curve1), min(curve1, curve2), min(curve2, 1)]

        cmd.set_color('b_color' + name + id_, rgb)
        cmd.color('b_color' + name + id_, name + id_)
Ejemplo n.º 29
0
 def make_gradient(self, name, init, end, steps):
     i0 = 0
     # look for free space !!!
     #while is_color("%s%d"%(name,i0)): i0+=1
     iS=range(i0,i0+steps)
     cS=[]
     # start creating colors
     for i in range(steps):
         g=[]
         for j in range(len(init)):
             g.append(init[j]+float(end[j]-init[j])/steps*i)
         c = "%s%d"%(name,iS[i])
         cS.append(c)
         cmd.set_color(c, g)
     return cS
Ejemplo n.º 30
0
 def make_gradient(self, name, init, end, steps):
     i0 = 0
     # look for free space !!!
     #while is_color("%s%d"%(name,i0)): i0+=1
     iS = range(i0, i0 + steps)
     cS = []
     # start creating colors
     for i in range(steps):
         g = []
         for j in range(len(init)):
             g.append(init[j] + float(end[j] - init[j]) / steps * i)
         c = "%s%d" % (name, iS[i])
         cS.append(c)
         cmd.set_color(c, g)
     return cS
Ejemplo n.º 31
0
def bgcolor_switch(tag):
    if tag == 'Black':
        cmd.bg_color('black')
    elif tag == 'White':
        cmd.bg_color('white')
    elif tag == 'Grey':
        cmd.bg_color('grey')
    elif tag == 'Other':
        color = askcolor(title = "Background Color Chooser")
        clr = str(color[1])
        newcolor = 'newcolor%s' % glb.incnewcolor()
        if clr != None:
            cmd.set_color(newcolor,
                ([int(n, 16) for n in (clr[1:3], clr[3:5], clr[5:7])]))
            cmd.bg_color(newcolor)
Ejemplo n.º 32
0
def stucture_attribution(pdb_id, attributions_path, pdb_path, flag=False):
    '''
    '''
    data = np.load(attributions_path)
    attributions = data['data']
    kernels = data['kernels']
    labels = data['labels']
    offsets = data['offsets']
    ind = np.where(labels == pdb_id)
    #attribution = attributions[ind][0][:,-1]
    if flag:
        a_ = data["all_"][0]
        a_[a_ <= 0] = 0.0
        attribution = data['all_'][0] + data['all_'][1]
        attribution[attribution <= 0] = 0.0
        attribution = a_ * attribution
    else:
        a_ = data["all_"][1]
        a_[a_ <= 0] = 0.0
        attribution = data['all_'][0] + data['all_'][1]
        attribution[attribution <= 0] = 0.0
        attribution = a_ * attribution

    # Load PDB
    cmd.load(pdb_path + pdb_id[:-2] + '.pdb')
    cmd.split_chains(pdb_id[:-2])
    for name in cmd.get_names('objects', 0, '(all)'):
        if not name.endswith(pdb_id[-1].upper()) and name.startswith(
                pdb_id[:4]):
            cmd.delete(name)
        else:
            zero_residues(name)
    cmd.reset()

    cmd.color('white', pdb_id)
    for i, _ in enumerate(attribution):
        #if flag: _ = _ *-1
        cmd.select('toBecolored',
                   pdb_id + ' and res ' + str(i + offsets[ind][0]))
        cmd.set_color('saliency' + str(i) + pdb_id, list(cmap(norm(_)))[:3])
        #else: cmd.set_color('saliency'+str(i)+pdb_id, list(cmap2(norm(_)))[:3])
        cmd.color('saliency' + str(i) + pdb_id, 'toBecolored')

    cmd.select('selected', pdb_id)
    #cmd.show('mesh', 'selected')
    #cmd.show('sticks', 'selected')
    cmd.deselect()
Ejemplo n.º 33
0
def paint_vars_f(vars_file, show_var_labels=False):
    import pandas as pd
    ## Should labels be colored the same way as atoms?
    match_label_color = False
    cmd.bg_color("white")
    cmd.set("depth_cue", 0)
    cmd.set("ray_trace_fog", 0)
    cmd.show_as("cartoon", "all")
    cmd.set("transparency", 0.5, "all")
    #cmd.show("surface", "not chain F")
    cmd.show("surface", "all")
    #chain_colors = ("gray40", "gray60", "gray80")
    chain_colors = ("palecyan", "wheat", "paleyellow")
    for chain, col in zip("DEF", chain_colors):
        sel = "chain {}".format(chain)
        color_sel(col, sel, set_label_color=match_label_color)
        cmd.set("cartoon_color", col, sel)
    cmd.select("epi", "resi 62-69+196-212")
    cmd.select("F2", "resi 22-109")
    cmd.select("F1", "resi 160-516")
    cmd.select("near_epi", "byres epi expand 10")
    color_sel("tv_green", "epi", set_label_color=match_label_color)  #"smudge"
    cmd.set("transparency", 0.3, "epi")

    vars_all = pd.read_csv(vars_file, dialect="excel-tab")
    for item in vars_all.itertuples():
        res_sel = "resi {}".format(item.pos)
        cmd.alter(res_sel, "b={}".format(item.freq))
        rgb = (item.red, item.green, item.blue)
        rgb_str = "_".join([str(_) for _ in rgb])
        color_name = "var_freq_{}".format(rgb_str)
        cmd.set_color(color_name, rgb)
        color_sel(color_name, res_sel, set_label_color=match_label_color)
    vars_sel = "resi " + "+".join(vars_all.pos.astype(str))
    cmd.select("vars", vars_sel)
    #cmd.show_as("spheres","vars")
    #color_sel("red","vars",set_label_color=match_label_color)
    #cmd.spectrum("b","blue_red","vars",
    #             minimum=min(freq_all),
    #             maximum=max(freq_all),
    #             byres=1)
    if show_var_labels:
        set_labels()
        cmd.label("vars and name cb and near_epi and (chain F or epi)",
                  "'%s'%(resi,)")
    show_spheres("vars")
    show_spheres("vars and epi", spikes=True)
Ejemplo n.º 34
0
def rpcLabel(pos,labelText,id='lab1',color=(1,1,1)):
  """ create a text label
 
    Arguments:
      pos: a 3 tuple with the position of the label
      text: a string with the label
      color: a 3 tuple with the color of the label. (1,1,1) is white
      id: (OPTIONAL) the name of the object to be created
 
    NOTE:
      at the moment this is, how you say, a hack
 
  """
  cmd.pseudoatom(id, label=repr(labelText), elem='C', pos=pos)
  cmd.set_color("%s-color"%id,color)
  cmd.color("%s-color"%id,id)
  return 1
Ejemplo n.º 35
0
def color_by_rgb( filename, selection = "all" ):
  """
  Read in a text file with rows like:

  125 0.1 0.1 0.1
  126 0.5 0.2 0.2

  and color specified residue numbers by RGB values.

  """
  lines = open( filename ).readlines()
  print "Applying RGB values from: " , filename
  for line in lines:
    cols = string.split( line )
    j = cols[0]
    colorname = string.split(filename)[0] + str(j)
    cmd.set_color( colorname, (float(cols[1]),float(cols[2]),float(cols[3])) )
    #print colorname
    cmd.color( colorname, 'resi %s and %s' % (cols[0],selection) )
Ejemplo n.º 36
0
    def get_colors(self, nbins, sat=1.0, value=1.0):
        import colorsys

        self.col = []
        self.coldesc = []
        for j in range(nbins):
            self.coldesc.append("col" + str(j))
            # create colors in a gradient from red through magenta to blue
            rgb = [min(1.0, float(j) * 2 / (nbins - 1)), 0.0, min(1.0, float(nbins - j - 1) * 2 / (nbins - 1))]

            # convert rgb to hsv,  modify saturation and value and convert back to rgb
            hsv = list(colorsys.rgb_to_hsv(rgb[0], rgb[1], rgb[2]))
            hsv[1] *= sat
            hsv[2] *= value

            # hsv = (colorsys.TWO_THIRD - colorsys.TWO_THIRD * float(j) / (nbins-1), sat, value)
            # convert to rgb and append to color list
            rgb = colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2])
            self.col.append(rgb)

            cmd.set_color(self.coldesc[j], self.col[j])
Ejemplo n.º 37
0
def color_rbw(rainbow=0):
        """
        similar to color_obj() but this time colors every obect as rainbow
        """
        rainbow = int(rainbow)

        # Get names of all PyMOL objects
        obj_list = cmd.get_names('objects')

        if rainbow:

           print("\nColouring objects as rainbow\n")

           nobj = len(obj_list)

           # Create colours starting at blue(240) to red(0), using intervals
           # of 240/(nobj-1)
           for j in range(nobj):
              hsv = (240-j*240/(nobj-1), 1, 1)
              # Convert to RGB
              rgb = hsv_to_rgb(hsv)
              # Define the new colour
              cmd.set_color("col" + str(j), rgb)
              print(obj_list[j], rgb)
              # Colour the object
              cmd.color("col" + str(j), obj_list[j])
        else:
           colours = ['rainbow']
           ncolours = len(colours)

           # Loop over objects
           i = 0
           for obj in obj_list:
              print("  ", obj, colours[i])
              cmd.spectrum('count', colours[i], obj)
#              cmd.color(colours[i], obj)
              i = i+1
              if(i == ncolours):
                 i = 0
Ejemplo n.º 38
0
    def SetPartitionColor(self, Sel):
        
        try:
            mycolors = {'colors': []}
            cmd.iterate( Sel, 'colors.append(color)', space=mycolors)

            for color in mycolors['colors']:
                one = list( cmd.get_color_tuple(color) )
                break

            for i in range(0,3):
                if one[i] <= 0.80:
                    one[i] += 0.20
                else:
                    one[i] -= 0.20
            
            cmd.set_color(self.PartitionColor, one)
            partition_rgb = General.one_to_rgb(one)
            
        except:
            return tuple()

        return tuple(partition_rgb)
Ejemplo n.º 39
0
def show(sel, file,min=-1,max=1):
    f = open(file)
    header = f.readline()
    #read in atom term data
    statesdata = []
    data = []
    pregex = re.compile('<(.*),(.*),(.*)>')
    for line in f:        
        d = line.split()
        if len(d) > 3 and d[0] != "atomid":
            pos = d[2]
            m = pregex.match(pos)
            energy = sum(float(e) for e in d[3:])
            data.append({'pos':map(float,m.groups()), 'energy': energy})
        elif line.count("END"):
            #reset for next molecule
            statesdata.append(data);
            data = [];
    
    #now get atom data from pymol
    n_states = cmd.count_states(sel)
    if(n_states != len(statesdata)):
        print "Inconsistent number of states/molecules";
        return;
    
    for i in xrange(1,n_states+1):
        energies = MolPosLookup(statesdata[i-1])
        model = cmd.get_model(sel,i)
        for a in model.atom:
            e = energies.energyForPos(a.coord)
            if e is None:
                print "Missing",i,a.coord
            else:
                color = gwr(e,min,max,0)
                cmd.set_color("smina_color%d" % a.index,color)
                cmd.color("smina_color%d" %a.index,"%s and index %d" % (sel,a.index))
Ejemplo n.º 40
0
def color_sel(tag):
    if tag == 'Red':
        cmd.color('red', glb.SELE)
    elif tag == 'Green':
        cmd.color('green', glb.SELE)
    elif tag == 'Orange':
        cmd.color('orange', glb.SELE)
    elif tag == 'Yellow':
        cmd.color('yellow', glb.SELE)
    elif tag == 'Blue':
        cmd.color('blue', glb.SELE)
    elif tag == 'Violet':
        cmd.color('violet', glb.SELE)
    elif tag == 'CPK':
        glb.procolor(selection=glb.SELE, show_selection='sticks',
            color_selection='cpk', show_all=None)
    elif tag == 'Other':
        color = askcolor(title = "Selection Color Chooser")
        clr = str(color[1])
        newcolor = 'newcolor%s' % glb.incnewcolor()
        if clr != None:
            cmd.set_color(newcolor,
                ([int(n, 16) for n in (clr[1:3], clr[3:5], clr[5:7])]))
            cmd.color(newcolor, glb.SELE)
Ejemplo n.º 41
0
 def create_FMN_colors(self):
     cmd.set_color("FMN001", [0.00, 0.00, 1.00])
     cmd.set_color("FMN002", [0.04, 0.02, 0.96])
     cmd.set_color("FMN003", [0.08, 0.05, 0.92])
     cmd.set_color("FMN004", [0.12, 0.08, 0.87])
     cmd.set_color("FMN005", [0.16, 0.10, 0.84])
     cmd.set_color("FMN006", [0.20, 0.13, 0.79])
     cmd.set_color("FMN007", [0.24, 0.16, 0.75])
     cmd.set_color("FMN008", [0.28, 0.18, 0.71])
     cmd.set_color("FMN009", [0.33, 0.21, 0.67])
     cmd.set_color("FMN010", [0.36, 0.24, 0.63])
     cmd.set_color("FMN011", [0.41, 0.26, 0.59])
     cmd.set_color("FMN012", [0.45, 0.29, 0.55])
     cmd.set_color("FMN013", [0.49, 0.31, 0.51])
     cmd.set_color("FMN014", [0.53, 0.34, 0.47])
     cmd.set_color("FMN015", [0.57, 0.37, 0.43])
     cmd.set_color("FMN016", [0.61, 0.40, 0.38])
     cmd.set_color("FMN017", [0.65, 0.42, 0.35])
     cmd.set_color("FMN018", [0.69, 0.45, 0.31])
     cmd.set_color("FMN019", [0.73, 0.47, 0.26])
     cmd.set_color("FMN020", [0.77, 0.50, 0.22])
     cmd.set_color("FMN021", [0.82, 0.53, 0.18])
     cmd.set_color("FMN022", [0.85, 0.55, 0.14])
     cmd.set_color("FMN023", [0.89, 0.58, 0.10])
     cmd.set_color("FMN024", [0.94, 0.60, 0.06])
     cmd.set_color("FMN025", [0.98, 0.63, 0.02])
     cmd.set_color("FMN026", [1.00, 0.63, 0.00])
     cmd.set_color("FMN027", [1.00, 0.60, 0.00])
     cmd.set_color("FMN028", [1.00, 0.58, 0.00])
     cmd.set_color("FMN029", [1.00, 0.55, 0.00])
     cmd.set_color("FMN030", [1.00, 0.53, 0.00])
     cmd.set_color("FMN031", [1.00, 0.50, 0.00])
     cmd.set_color("FMN032", [1.00, 0.47, 0.00])
     cmd.set_color("FMN033", [1.00, 0.45, 0.00])
     cmd.set_color("FMN034", [1.00, 0.42, 0.00])
     cmd.set_color("FMN035", [1.00, 0.40, 0.00])
     cmd.set_color("FMN036", [1.00, 0.37, 0.00])
     cmd.set_color("FMN037", [1.00, 0.34, 0.00])
     cmd.set_color("FMN038", [1.00, 0.31, 0.00])
     cmd.set_color("FMN039", [1.00, 0.29, 0.00])
     cmd.set_color("FMN040", [1.00, 0.26, 0.00])
     cmd.set_color("FMN041", [1.00, 0.24, 0.00])
     cmd.set_color("FMN042", [1.00, 0.21, 0.00])
     cmd.set_color("FMN043", [1.00, 0.18, 0.00])
     cmd.set_color("FMN044", [1.00, 0.16, 0.00])
     cmd.set_color("FMN045", [1.00, 0.13, 0.00])
     cmd.set_color("FMN046", [1.00, 0.10, 0.00])
     cmd.set_color("FMN047", [1.00, 0.08, 0.00])
     cmd.set_color("FMN048", [1.00, 0.05, 0.00])
     cmd.set_color("FMN049", [1.00, 0.02, 0.00])
     cmd.set_color("FMN050", [1.00, 0.00, 0.00])
# The RGB percentage values given on that page are less precise than the 0-255
# values, so the 0-255 values are converted here (e.g. 230/255 = 0.902).
cb_colors = (
    ("black", (0.000, 0.000, 0.000),                   # (  0,   0,   0)
            ()),
    ("orange", (0.902, 0.624, 0.000),                   # (230, 159,   0)
     ()),
    ("sky_blue", (0.337, 0.706, 0.914),                   # ( 86, 180, 233)
     ("skyblue", "light_blue", "lightblue")),
    ("bluish_green", (0.000, 0.620, 0.451),                   # (  0, 158, 115)
     ("bluishgreen", "green")),
    ("yellow", (0.941, 0.894, 0.259),                   # (240, 228,  66)
     ()),
    ("blue", (0.000, 0.447, 0.698),                   # (  0, 114, 178)
     ()),
    ("vermillion", (0.835, 0.369, 0.000),                   # (213,  94,   0)
     ("red", "red_orange", "redorange")),
    ("reddish_purple", (0.800, 0.475, 0.655),                   # (204, 121, 167)
     ("reddishpurple", "rose", "violet", "magenta")),
)

for c in cb_colors:
    # main name
    cmd.set_color("cb_%s" % c[0], c[1])
    print "Set color: cb_%s" % c[0]

    # alternate names
    for alt in c[2]:
        cmd.set_color("cb_%s" % alt, c[1])
        print "           cb_%s" % alt
Ejemplo n.º 43
0
def color_as(col, str):
        hsv = (col, 1, 1)
        rgb = hsv_to_rgb(hsv)
        cmd.set_color("color"+str, rgb)
        cmd.color("color"+str, str)
        cmd.disable(str)
Ejemplo n.º 44
0
def make_gradient(sel,gradient,nbins,sat,value,user_rgb,debug=0):
  if gradient == 'bgr' or gradient == 'rainbow':
    gradient = 'bgr'
    col=[]
    coldesc=[]
    for j in range(nbins):
      # must append the str(sel[j]) to the color name so that it is unique
      # for the selection
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # coldesc.append('col' + str(sel[j]) + str(j))

      # create colors using hsv scale (fractional) starting at blue(.6666667)
      # through red(0.00000) in intervals of .6666667/(nbins -1) (the "nbins-1"
      # ensures that the last color is, in fact, red (0)
      # rewrote this to use the colorsys module to convert hsv to rgb
      hsv = (colorsys.TWO_THIRD - colorsys.TWO_THIRD * float(j) / (nbins-1), sat, value)
      #convert to rgb and append to color list
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      #cmd.set_color("col" + gradient + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])
      #print col[j],"defined as ", "col"+str(j)

  elif gradient == 'user':
    # --------------------------------------------
    #  Modified color ramp by Mark Wall 2007.07.20
    # --------------------------------------------
    # assign 3-color ramp values (rgb 0-255)
    # could easily assign RGB color values between 0.0 and 1.0 below
    # !!! Black must be at least 1,0,0 or div by zero error !!!
    #
    #r1, g1, b1 = 255, 255, 225   # low   white
    #r1, g1, b1 = 170, 170, 170   # low   gray
    user_rgb = re.compile('[\[\](){}]').sub('',user_rgb)
    user_rgb_fract = 0
    try:
      r1,g1,b1, r2,g2,b2, r3,g3,b3 = map(int,user_rgb.split(','))
    except ValueError:
      r1,g1,b1, r2,g2,b2, r3,g3,b3 = map(float,user_rgb.split(','))
      user_rgb_fract = 1

    print 'user_rgb', r1,g1,b1, r2,g2,b2, r3,g3,b3

#    r1, g1, b1 = 50, 50, 195     # low   med blue
#    r2, g2, b2 = 245, 245, 20    # mid   yellow
#    r3, g3, b3 = 255, 20, 20     # high  red
    #
    #r1, g1, b1 = 255, 20, 20     # low   red
    #r2, g2, b2 = 150, 150, 20    # mid   yellow
    #r3, g3, b3 = 20, 20, 195     # high   med blue
    #
    #r1, g1, b1 = 1, 0, 0         # low   black
    #r2, g2, b2 = 155, 155, 155   # mid  gray
    #r3, g3, b3 = 255, 255, 255   # high  white
    #
    #r1, g1, b1 = 0, 50, 200      # low  blue
    #r2, g2, b2 = 1, 0, 0         # mid   black
    #r3, g3, b3 = 255, 255, 20    # high  yellow
    #
    #r1, g1, b1 = 0, 0, 1         # low   black
    #r2, g2, b2 = 200, 0, 0       # mid  red
    #r3, g3, b3 = 255, 255, 0     # high  yellow
    #
    #r1, g1, b1 = 180, 170, 170   # low   gray
    #r2, g2, b2 = 250, 90, 40     # mid  orange
    #r3, g3, b3 = 255, 255, 0     # high  yellow
    #
    #r1, g1, b1 = 235, 255, 255   # low   white
    #r2, g2, b2 = 55, 255, 255    # mid   cyan
    #r3, g3, b3 = 0, 0, 180       # high  blue
    #
    # change color values to fractions
    #
    if max(r1,g1,b1,r2,g2,b2,r3,g3,b3) > 1:
      r1, g1, b1 = float(r1)/255.0, float(g1)/255.0, float(b1)/255.0
      r2, g2, b2 = float(r2)/255.0, float(g2)/255.0, float(b2)/255.0
      r3, g3, b3 = float(r3)/255.0, float(g3)/255.0, float(b3)/255.0

    col=[]
    coldesc=[]
#    print "r1,g1,b1, r2,g2,b2, r3,g3,b3", r1,g1,b1, r2,g2,b2, r3,g3,b3
    for j in range(nbins/2):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from low to mid
      rgb = [r1*((float(nbins)-float(j)*2.0)/float(nbins))+r2*(float(j)*2.0/float(nbins)), \
             g1*((float(nbins)-float(j)*2.0)/float(nbins))+g2*(float(j)*2.0/float(nbins)), \
             b1*((float(nbins)-float(j)*2.0)/float(nbins))+b2*(float(j)*2.0/float(nbins))]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])
      print j,"rgb: %4.3f %4.3f %4.3f"% rgb

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

    for j in range(nbins/2,nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from mid to high
      rgb = [r2*((float(nbins)-((float(j+1)-float(nbins)/2.0)*2.0))/float(nbins))+r3*(((float(j+1)-float(nbins)/2.0)*2.0)/float(nbins)), \
             g2*((float(nbins)-((float(j+1)-float(nbins)/2.0)*2.0))/float(nbins))+g3*(((float(j+1)-float(nbins)/2.0)*2.0)/float(nbins)), \
             b2*((float(nbins)-((float(j+1)-float(nbins)/2.0)*2.0))/float(nbins))+b3*(((float(j+1)-float(nbins)/2.0)*2.0)/float(nbins))]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])
      print j,"rgb: %4.3f %4.3f %4.3f"% rgb

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'rgb' or gradient == 'reverserainbow':
    gradient = 'rgb'
    col=[]
    coldesc=[]
    for j in range(nbins):
      # must append the str(sel[j]) to the color name so that it is unique
      # for the selection
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))

      # create colors using hsv scale (fractional) starting at red(.00000)
      # through blue(0.66667) in intervals of .6666667/(nbins -1) (the "nbins-1"
      # ensures that the last color is, in fact, red (0)
      # rewrote this to use the colorsys module to convert hsv to rgb
      hsv = (colorsys.TWO_THIRD * float(j) / (nbins-1), sat, value)
      #convert to rgb and append to color list
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'bmr':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from blue through magenta to red
      rgb = [min(1.0, float(j)*2/(nbins-1)), 0.0, min(1.0, float(nbins-j-1)*2/(nbins-1))]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'rmb':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from red through magenta to blue
      rgb = [min(1.0, float(nbins-j-1)*2/(nbins-1)), 0.0, min(1.0, float(j)*2/(nbins-1))]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'rw':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from red through white
      rgb = [1.0, float(j)/(nbins-1), float(j)/(nbins-1)]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'wr':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from white through red
      rgb = [1.0, float(nbins-j-1)/(nbins-1), float(nbins-j-1)/(nbins-1)]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'ry':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from red through white
      rgb = [1.0, float(j)/(nbins-1), 0]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'yr':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from white through red
      rgb = [1.0, float(nbins-j-1)/(nbins-1), 0]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'gw':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from green through white
      rgb = [float(j)/(nbins-1), 1.0, float(j)/(nbins-1)]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'wg':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from white through green
      rgb = [float(nbins-j-1)/(nbins-1), 1.0, float(nbins-j-1)/(nbins-1)]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'bw':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from blue through white
      rgb = [float(j)/(nbins-1), float(j)/(nbins-1), 1.0 ]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'wb':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from blue through white
      rgb = [float(nbins-j-1)/(nbins-1), float(nbins-j-1)/(nbins-1), 1.0 ]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'wr':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from white through blue
      rgb = [float(nbins-j-1)/(nbins-1), float(nbins-j-1)/(nbins-1), 1.0]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'gy':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from green through yellow
      rgb = [float(j)/(nbins-1), 1.0, 0.]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'yg':
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from green through yellow
      rgb = [float(nbins-j-1)/(nbins-1), 1.0, 0.]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'bwr':
    col=[]
    coldesc=[]
    for j in range(nbins/2):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from blue to white
      rgb = [min(1.0, float(j)*2/(nbins-1)), min(1.0,float(j)*2/(nbins-1)), min(1.0, float(nbins-j-1)*2/(nbins-1))]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

    for j in range(nbins/2,nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from white to red
      rgb = [min(1.0, float(j)*2/(nbins-1)), min(1.0,float(nbins-j-1)*2/(nbins-1)), min(1.0, float(nbins-j-1)*2/(nbins-1))]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'rwb':
    col=[]
    coldesc=[]
    for j in range(nbins/2):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient from red to white
      rgb = [min(1.0, float(nbins-j-1)*2/(nbins-1)), min(1.0,float(j)*2/(nbins-1)), min(1.0, float(j)*2/(nbins-1))]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

    for j in range(nbins/2,nbins):
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # coldesc.append('col' + str(sel[j]) + str(j)))
      # create colors in a gradient from white to blue
      rgb = [min(1.0, float(nbins-j-1)*2/(nbins-1)), min(1.0,float(nbins-j-1)*2/(nbins-1)), min(1.0, float(j)*2/(nbins-1))]

      # convert rgb to hsv,  modify saturation and value and convert back to rgb
      hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
      hsv[1] = hsv[1]*sat
      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'gray' or gradient == 'grey':
# if it is "gray" then sat must be 0!
    sat = 0.0
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient of grays from "sat" to "value"

      hsv = [0, 0, sat + (value-sat)*float(j)/(nbins-1)]
#      hsv[1] = hsv[1]*sat
#      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

  elif gradient == 'reversegray' or gradient == 'reversegrey':
# if it is "gray" then sat must be 0!
    sat = 0.0
    col=[]
    coldesc=[]
    for j in range(nbins):
      # coldesc.append('col' + str(sel[j]) + str(j))
      coldesc.append('col' + gradient + str(j) + str(sel[j]))
      # create colors in a gradient of grays from "sat" to "value"

      hsv = [0, 0, value - (value-sat)*float(j)/(nbins-1)]
#      hsv[1] = hsv[1]*sat
#      hsv[2] = hsv[2]*value
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      # cmd.set_color("col" + str(sel[j]) + str(j),col[j])
      if debug:
        print "Colour RGB triplet [ %6.4f, %6.4f, %6.4f ] is defined as %s" % (col[j][0],col[j][1],col[j][2],"col"+str(j)+str(sel[j]))
      cmd.set_color("col" + gradient + str(j) + str(sel[j]),col[j])

#  if debug:
#    for j in range(nbins):
#      print "colour #:",j,"colour RGB triplet: ",col[j]

  #print coldesc
# return the gradient as a list of colors named by their gradient & index (i.e. colbw0,colbw1,colbw2,...)
  return coldesc
Ejemplo n.º 45
0
# Copyright (c) 2004 Robert L. Campbell
import colorsys,sys
from pymol import cmd


cmd.set_color('lightblue', [0.6, 0.8, 1.0])
def color_by_attype(selection="all",
        hydrophobic='white',
        positive='blue',
        negative='red',
        polar_n='lightblue',
        polar_o='salmon',
        sulfur='yellow'):

  """

  usage: color_by_attype <selection>, <optional overrides of default colors>

  e.g. color_by_attype protein and chain A, hydrophobic=white

  Atom types:            Default colours:
    hydrophobic            white
    polar_n                lightblue
    polar_o                salmon
    positive               blue
    negative               red
    sulfur                 yellow
  """
# used a list to maintain order!
  at_list = ['positive','negative','polar_o','polar_n','sulfur']
Ejemplo n.º 46
0
def color_chains(rainbow=0):
 
        """
 
AUTHOR 

        Kevin Houlihan
        adapted from a script by Gareth Stockwell
 
USAGE
 
        color_chains(rainbow=0)
 
        This function colours each object currently in the PyMOL heirarchy
        with a different colour.  Colours used are either the 22 named
        colours used by PyMOL (in which case the 23rd object, if it exists,
        gets the same colour as the first), or are the colours of the rainbow
 
SEE ALSO
 
        util.color_objs()
        """
 
        # Process arguments
        rainbow = int(rainbow)
 
        # Get names of all PyMOL objects
        # obj_list = cmd.get_names('objects')
	# don't color selections, alignments, measurements, etc.
	obj_list = cmd.get_names_of_type("object:molecule")
	chain_list = []
	for obj in obj_list:
		for ch in cmd.get_chains(obj):
			# there seems to be a bug in pymol, some CA don't get colored
			#sele = obj + " and c. " + ch + " and (e. C or name CA)"
			#sele = obj + " and c. " + ch + " and e. C"
			sele = obj + " and c. " + ch
			chain_list.append(sele)
 
        if rainbow:
 
           #print "\nColouring objects as rainbow\n"
 
           nobj = len(obj_list)
	   nchain = len(chain_list)
 
           # Create colours starting at blue(240) to red(0), using intervals
           # of 240/(nobj-1)
           for j in range(nchain):
              # hsv = (240-j*240/(nobj-1), 1, 1)
	      # disparate colors for adjacent objects in sequence, colors heterodimers nicely
	      hsv = (240 - ( (120*(j - j%2))/(nchain-1) + 120*(j%2) ), 1, 1)
              # Convert to RGB
              rgb = hsv_to_rgb(hsv)
              # Define the new colour
              cmd.set_color("col" + str(j), rgb)
              #print chain_list[j], rgb
              # Colour the object
              cmd.color("col" + str(j), chain_list[j])
	      util.cnc(chain_list[j])
 
        else:
 
           #print "\nColouring objects using PyMOL defined colours\n"
 
           # List of available colours
	   # standard pymol colors, I like these better
	   # color sets listed at http://www.pymolwiki.org/index.php/Color_Values
	   mainset1_colours = ['carbon', 'cyan', 'lightmagenta', 'yellow', 'salmon', 'hydrogen', 'slate', 'orange']
	   mainset2_colours = ['lime', 'deepteal', 'hotpink', 'yelloworange', 'violetpurple', 'grey70', 'marine', 'olive']
	   mainset3_colours = ['smudge', 'teal', 'dirtyviolet', 'wheat', 'deepsalmon', 'lightpink', 'aquamarine', 'paleyellow']
           mainset4_colours = ['limegreen', 'skyblue', 'warmpink', 'limon', 'violet', 'bluewhite', 'greencyan', 'sand']
	   mainset5_colours = ['forest', 'lightteal', 'darksalmon', 'splitpea', 'raspberry', 'grey50', 'deepblue', 'brown']
	   #colours = mainset1_colours + mainset4_colours
	   colours = mainset1_colours + mainset2_colours + mainset3_colours + mainset4_colours + mainset5_colours
	   # colors in original script
           extra_colours = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan',    \
           'salmon', 'lime', 'pink', 'slate', 'magenta', 'orange', 'marine', \
           'olive', 'purple', 'teal', 'forest', 'firebrick', 'chocolate',    \
           'wheat', 'white', 'grey' ]
           ncolours = len(colours)
 
           # Loop over objects
           i = 0
           for ch in chain_list:
              #print "  ", obj, ch, colours[i]
              cmd.color(colours[i], ch)
	      util.cnc(ch)
              i += 1
	      i %= ncolours
Ejemplo n.º 47
0
#Rudimentary summation of the two sequences
h_seq = holo.unaligned_edge_weights_by_seq
a_seq = apo.unaligned_edge_weights_by_seq
seq_scores = [i + j for i, j in zip(h_seq, a_seq)]

#Modify these to use different colors, use valid PyMOL named colors
start_color= 'yelloworange'
end_color = 'density'

#seq_offset = 12  # The first residue number of the sequence

def get_color_rgb(color):
    try:
        return cmd.get_color_tuple(color)
    except:
        print('Could not find a reference for that color')
        return None

start_rgb = get_color_rgb(start_color)
end_rgb = get_color_rgb(end_color)
diffs = [end_rgb[i] - start_rgb[i] for i in xrange(3)]
min_score = min(seq_scores)
diff_score = max(seq_scores) - min_score
for i in xrange(len(seq_scores)):
    cmd.select('heatmap', 'chain a and resi {0}'.format(i))
    norm_score = (seq_scores[i] - min_score) / diff_score
    temp_color = [start_rgb[j] + norm_score * diffs[j] for j in xrange(3)]
    color_name = 'heat_col{0}'.format(i)
    cmd.set_color(color_name, temp_color)
    cmd.color(color_name, 'heatmap')
Ejemplo n.º 48
0
def color_obj(rainbow=0,cnc=1):
    """
AUTHOR

        Gareth Stockwell
        
        Modified by Spencer Bliven

USAGE

        color_obj(rainbow=0, cnc=0)

ARGUMENTS

        rainbow = integer: 0 to use the 22 named colors, or 1 to generate
        a rainbow based on the number of objects currently

        cnc = integer: 0 to color all atoms by object, 1 to color non-carbon
        atoms according to their element.

NOTES
        This function colours each object currently in the PyMOL heirarchy
        with a different colour.  Colours used are either the 22 named
        colours used by PyMOL (in which case the 23rd object, if it exists,
        gets the same colour as the first), or are the colours of the rainbow

        If cnc is set, color non-carbon atoms by their element
SEE ALSO

        util.color_objs()
    """

    # Process arguments
    rainbow = int(rainbow)
    cnc = int(cnc)

    # Get names of all PyMOL objects
    obj_list = cmd.get_names('objects')

    if rainbow:

        print "\nColouring objects as rainbow\n"

        nobj = len(obj_list)

        # Create colours starting at blue(240) to red(0), using intervals
        # of 240/(nobj-1)
        for j in range(nobj):
            hsv = (240-j*240/(nobj-1), 1, 1)
            # Convert to RGB
            rgb = hsv_to_rgb(hsv)
            # Define the new colour
            cmd.set_color("col" + str(j), rgb)
            print obj_list[j], rgb
            # Colour the object
            cmd.color("col" + str(j), obj_list[j])

    else:

        print "\nColouring objects using PyMOL defined colours\n"

        # List of available colours
        colours = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan',    \
        'salmon', 'lime', 'pink', 'slate', 'magenta', 'orange', 'marine', \
        'olive', 'purple', 'teal', 'forest', 'firebrick', 'chocolate',    \
        'wheat', 'white', 'grey' ]
        ncolours = len(colours)

        # Loop over objects
        i = 0
        for obj in obj_list:
            print "  ", obj, colours[i]
            cmd.color(colours[i], obj)
            i = i+1
            if(i == ncolours):
                i = 0
    if cnc:
        #color non-carbons appropriately
        util.cnc()