コード例 #1
0
def ss(mol, startaa=1, visual="Y"):
    """
	Replaces B-factors with TALOS predicted secondary structure elements

	mol = any object selection (within one single object though)
	startaa = number of first amino acid in 'new B-factors' file (default=1)
	visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y)

	example: ss 1LVM, startaa=4
	"""
    source = 'predSS.tab'
    ss_dict = {'L': 0, 'H': 2, 'E': 1, 'X': 0}
    ss_only = []
    with open(source) as ss_file:
        for lines in ss_file:
            searcher = re.search('^\d+', lines.strip())
            if searcher != None:
                if int(lines.strip().split()[0]) < int(startaa):
                    continue
                ss_only.append(ss_dict[lines.strip().split()[8]])
    obj = cmd.get_object_list(mol)[0]
    cmd.alter(mol, "b=-1.0")
    counter = int(startaa)
    bfacts = []
    for line in ss_only:
        bfact = float(line)
        bfacts.append(bfact)
        cmd.alter("%s and resi %s and n. CA" % (mol, counter), "b=%s" % bfact)
        counter = counter + 1
    if visual == "Y":
        cmd.cartoon("automatic", mol)
        cmd.spectrum("b", "grey blue red", "%s and n. CA " % mol)
        cmd.recolor()
コード例 #2
0
def drab(nlim=-2.0, plim=2.0):
    #zero the indexes
    #zero_residues("all", 1, 1)
    #Read the values in
    fileName = cmd.get_names()[0]
    print fileName
    fileName = fileName + ".dat"
    cmd.alter("all", "b=0.0")
    #file = open(fileName, 'r')
    #table = [row.strip().split('\t') for row in file]
    bVals = []
    #print table
    for line in file(fileName):
        line = line.strip().split()
        if (line[0][0] != "#"):
            selection = "resi %s" % line[0]
            #Normalize the values
            bval = (float(line[1]) - nlim) / (plim - nlim)
            #print bval
            cmd.alter(selection, "b=%f" % bval)
            print(selection, "b=%f" % bval)
            bVals.append([selection, bval])
    cmd.hide("all")
    cmd.show("cartoon")
    cmd.spectrum("b", "blue_white_red", "all", "0.0", "1.0", "1")
    cmd.ramp_new("rawFac_ramp",
                 cmd.get_names()[0], [nlim, plim],
                 color="[blue, white, red ]")
    cmd.recolor()
コード例 #3
0
ファイル: loadBfacts.py プロジェクト: nguyenvanessa/src
def loadBfacts(mol, startaa=1, source="newBfactors.txt", visual="Y"):
    """
	Replaces B-factors with a list of values contained in a plain txt file
	
	usage: loadBfacts mol, [startaa, [source, [visual]]]
 
	mol = any object selection (within one single object though)
	startaa = number of first amino acid in 'new B-factors' file (default=1)
	source = name of the file containing new B-factor values (default=newBfactors.txt)
	visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y)
 
	example: loadBfacts 1LVM and chain A
	"""
    obj = cmd.get_object_list(mol)[0]
    cmd.alter(mol, "b=-1.0")
    inFile = open(source, 'r')
    counter = int(startaa)
    bfacts = []
    for line in inFile.readlines():
        bfact = float(line)
        bfacts.append(bfact)
        cmd.alter("%s and resi %s and n. CA" % (mol, counter), "b=%s" % bfact)
        counter = counter + 1
    if visual == "Y":
        cmd.show_as("cartoon", mol)
        cmd.cartoon("putty", mol)
        cmd.set("cartoon_putty_scale_min", min(bfacts), obj)
        cmd.set("cartoon_putty_scale_max", max(bfacts), obj)
        cmd.set("cartoon_putty_transform", 0, obj)
        cmd.set("cartoon_putty_radius", 0.2, obj)
        cmd.spectrum("b", "rainbow", "%s and n. CA " % mol)
        cmd.ramp_new("count", obj, [min(bfacts), max(bfacts)], "rainbow")
        cmd.recolor()
コード例 #4
0
ファイル: viewing.py プロジェクト: schrodinger/pymol-testing
    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')
コード例 #5
0
def loadBfacts (mol,startaa=1,source="/Users/student/Box Sync/PUBS/Pymol-practice.txt", visual="Y"):
	"""
	Replaces B-factors with a list of values contained in a plain txt file
 
	usage: loadBfacts mol, [startaa, [source, [visual]]]
 
	mol = any object selection (within one single object though)
	startaa = number of first amino acid in 'new B-factors' file (default=1)
	source = name of the file containing new B-factor values (default=newBfactors.txt)
	visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y)
 
	example: loadBfacts 1LVM and chain A
	"""
	obj=cmd.get_object_list(mol)[0]
	cmd.alter(mol,"b=-1.0")
	inFile = open(source, 'r')
	counter=int(startaa)
	bfacts=[]
	for line in inFile.readlines():	
		bfact=float(line)
		bfacts.append(bfact)
		cmd.alter("%s and resi %s and n. CA"%(mol,counter), "b=%s"%bfact)
		counter=counter+1
	if visual=="Y":
		cmd.show_as("cartoon",mol)
		cmd.cartoon("putty", mol)
		cmd.set("cartoon_putty_scale_min", min(bfacts),obj)
		cmd.set("cartoon_putty_scale_max", max(bfacts),obj)
		cmd.set("cartoon_putty_transform", 0,obj)
		cmd.set("cartoon_putty_radius", 0.2,obj)
		cmd.spectrum("b","rainbow", "%s and n. CA " %mol)
		cmd.ramp_new("count", obj, [min(bfacts), max(bfacts)], "rainbow")
		cmd.recolor()
コード例 #6
0
def loadFitnessFactors (mol,startaa=1,source="/Users/student/Box Sync/PUBS/Pymol-practice.txt", visual="Y"):
        # adapted from http://www.pymolwiki.org/index.php/Load_new_B-factors
        """
        Replaces B-factors with a list of fitness factor values contained in a plain txt file
 
        usage: loadFitnessFactors mol, [startaa, [source, [visual]]]
 
        mol = any object selection (within one single object though)
        startaa = number of first amino acid in 'new Fitness-factors' file (default=1)
        source = name of the file containing new Fitness-factor values (default=newFitnessFactors.txt)
        visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y)
 
        example: loadFitnessFactors 1LVM and chain A
        """
        obj=cmd.get_object_list(mol)[0]
        cmd.alter(mol,"b=-1.0")
        inFile = open(source, 'r')
        counter=int(startaa)
        fitnessFacts=[]
        for line in inFile.readlines():
                fitnessFact=float(line)
                fitnessFacts.append(fitnessFact)
                cmd.alter("%s and resi %s and n. CA"%(mol,counter), "b=%s"%fitnessFact)
                counter=counter+1
        if visual=="Y":
                cmd.show_as("cartoon",mol)
                cmd.cartoon("putty", mol)
#                cmd.set("cartoon_putty_scale_min", min(fitnessFacts),obj)
#                cmd.set("cartoon_putty_scale_max", max(fitnessFacts),obj)
                cmd.set("cartoon_putty_transform", 0,obj)
                cmd.set("cartoon_putty_radius", 0.2,obj)
                cmd.spectrum("b","red_white_blue", "%s and n. CA " %mol)
                cmd.ramp_new("count", obj, [min(fitnessFacts), (min(fitnessFacts)+max(fitnessFacts))/2, max(fitnessFacts)], color = ["blue", "white", "red"])
                cmd.recolor()
コード例 #7
0
ファイル: viewing.py プロジェクト: av-hub/pymol-testing
    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')
コード例 #8
0
def nicecolor(method, selection='all'):
    """
DESCRIPTION

    color a selection with unique colors based on atom properties exposed by iterate

USAGE

    nicecolor method [, selection]

ARGUMENTS

    method = property that will be used as a method for coloring (e.g.: "resi")
    selection = selection to act upon
    """
    stored.tmp_dict = {}
    stored.r_choice = random.choice
    cmd.iterate(
        selection,
        f'stored.tmp_dict[{method}] = stored.r_choice(stored.nice_colors)')
    cmd.alter(selection, f'color = stored.tmp_dict[{method}]')
    cmd.sync()
    del stored.tmp_dict
    cmd.recolor()
    cmd.sync()
コード例 #9
0
ファイル: rmsf2prop.py プロジェクト: raruiz61/ProyectoHPC
def spectrumproperty(propname, color_list, selection='(all)', minimum=None, maximum=None, quiet=1):
    '''
DESCRIPTION

    Define a color spectrum with as many color-stops as you like (at least 2).

ARGUMENTS

    propname = string: property name which has a float value.

    color_list = string: Space separated list of colors

    ... all other arguments like with `spectrum` command
    '''
    quiet = int(quiet)
    colors = color_list.split()
    if len(colors) < 2:
        print 'failed! please provide at least 2 colors'
        return

    colvec = [cmd.get_color_tuple(i) for i in colors]
    parts = len(colvec) - 1

    value_list = []
    cmd.iterate(selection, 'value_list.append(properties[propname])', space=locals())

    if len(value_list) == 0:
        print 'empty selection'
        return

    if minimum is None:
        minimum = min(value_list)
    if maximum is None:
        maximum = max(value_list)
    minimum, maximum = float(minimum), float(maximum)
    val_range = (maximum - minimum) * (1 + 1e-6)

    if not quiet:
        print ' Spectrum: range (%.5f to %.5f)' % (minimum, maximum)

    if maximum == minimum:
        print 'no spectrum possible, only equal values'
        return

    rgb = lambda i, p, j: int(255 * (colvec[i+1][j] * p + colvec[i][j] * (1.0 - p)))

    col_list = []
    for value in value_list:
        p = (value - minimum) / val_range * parts
        i = int(p)
        p -= i
        col_list.append(0x40000000 +
                rgb(i, p, 0) * 0x10000 +
                rgb(i, p, 1) * 0x100 +
                rgb(i, p, 2))

    cmd.alter(selection, 'color = col_iter.next()', space={'col_iter': iter(col_list)})
    cmd.recolor()
コード例 #10
0
def loadFitnessFactors(
        mol,
        startaa=1,
        source="/Users/student/Box Sync/PUBS/Pymol-practice.txt",
        visual="Y"):
    # adapted from http://www.pymolwiki.org/index.php/Load_new_B-factors
    """
        Replaces B-factors with a list of fitness factor values contained in a plain txt file
 
        usage: loadFitnessFactors mol, [startaa, [source, [visual]]]
 
        mol = any object selection (within one single object though)
        startaa = number of first amino acid in 'new Fitness-factors' file (default=1)
        source = name of the file containing new Fitness-factor values (default=newFitnessFactors.txt)
        visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y)
 
        example: loadFitnessFactors 1LVM and chain A
        """
    obj = cmd.get_object_list(mol)[0]
    cmd.alter(mol, "b=-1.0")
    inFile = open(source, 'r')
    counter = int(startaa)
    fitnessFacts = []
    for line in inFile.readlines():
        fitnessFact = float(line)
        fitnessFacts.append(fitnessFact)
        cmd.alter("%s and resi %s and n. CA" % (mol, counter),
                  "b=%s" % fitnessFact)
        counter = counter + 1
    if visual == "Y":
        cmd.show_as("cartoon", mol)
        cmd.cartoon("putty", mol)
        #                cmd.set("cartoon_putty_scale_min", min(fitnessFacts),obj)
        #                cmd.set("cartoon_putty_scale_max", max(fitnessFacts),obj)
        cmd.set("cartoon_putty_transform", 0, obj)
        cmd.set("cartoon_putty_radius", 0.2, obj)
        cmd.spectrum("b", "red_white_blue", "%s and n. CA " % mol)
        cmd.ramp_new("count",
                     obj, [
                         min(fitnessFacts),
                         (min(fitnessFacts) + max(fitnessFacts)) / 2,
                         max(fitnessFacts)
                     ],
                     color=["blue", "white", "red"])
        cmd.recolor()
コード例 #11
0
def loadBfacts(mol, startaa=1, visual="Y"):
    obj = cmd.get_object_list(mol)[0]
    cmd.alter(mol, "b=-1.0")
    counter = int(startaa)
    bfacts = []
    for item in List1:
        bfact = float(item * 10)
        bfacts.append(bfact)
        cmd.alter("%s and resi %s and n. CA" % (mol, counter), "b=%s" % bfact)
        counter = counter + 1
    if visual == "Y":
        cmd.show_as("cartoon", mol)
        # cmd.cartoon("putty", mol)
        cmd.set("cartoon_putty_scale_min", min(bfacts), obj)
        cmd.set("cartoon_putty_scale_max", max(bfacts), obj)
        cmd.set("cartoon_putty_transform", 0, obj)
        cmd.set("cartoon_putty_radius", 0.2, obj)
        cmd.spectrum("b", "blue_white_red", "%s and n. CA " % mol)
        cmd.ramp_new("count", obj, [min(bfacts), max(bfacts)],
                     ['blue', 'white', 'red'])
        cmd.recolor()
コード例 #12
0
def color_shift2(start="cterm",end="cterm2",divide=100):
    stored.start_colors=[]
    cmd.iterate("%s and name ca and chain A" % start,"stored.start_colors.append(color)")
    stored.end_colors=[]
    cmd.iterate("%s and name ca and chain A" % end,"stored.end_colors.append(color)")    
    start_color_indice=cmd.get_color_tuple(stored.start_colors[0])
    end_color_indice=cmd.get_color_tuple(stored.end_colors[0])
    graduate_color_indice=(np.array(end_color_indice)-np.array(start_color_indice))/float(divide)
    i=0
    while i<=divide:
        cmd.refresh()
        cmd.recolor()
        cmd.set_color("temp%s" %i,list(np.array(start_color_indice)+graduate_color_indice*i))
        #cmd.color("temp%s" % i,"%s and name ca and chain A and not (e;N,O)" % start)
        cmd.color("temp%s" % i,"start%s2_end%s_%s and chain A and not (e;N,O)" % (start,end,i))
        #cmd.set("sphere_color","temp%s" % i,"start%s2_end%s_%s and  elem C" % (start,end,i))
        cmd.set("stick_color","red","start%s2_end%s_%s and elem O" % (start,end,i))  
        cmd.set("stick_color","blue","start%s2_end%s_%s and elem N" % (start,end,i))         
        cmd.set("cartoon_color","red","start%s2_end%s_%s and chain C" % (start,end,i))
        cmd.set("cartoon_color","tv_blue","start%s2_end%s_%s and chain B" % (start,end,i))
        i+=1
コード例 #13
0
def s2(mol, startaa=1, visual="Y"):
    """
	Replaces B-factors with TALOS predicted RCI S2 values
	Thickness and color are determined by S2 values with thicker values being more dynamic

	mol = any object selection (within one single object though)
	startaa = number of first amino acid in 'new B-factors' file (default=1)
	visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y)

	example: ss 1LVM, startaa=4
	"""
    source = 'predS2.tab'
    s2_only = []
    with open(source) as s2_file:
        for lines in s2_file:
            searcher = re.search('\d+\.\d{3}', lines)
            if searcher != None:
                if int(lines.strip().split()[0]) < int(startaa):
                    continue
                s2_only.append(searcher.group(0))
    obj = cmd.get_object_list(mol)[0]
    cmd.alter(mol, "b=-1.0")
    counter = int(startaa)
    bfacts = []
    for line in s2_only:
        bfact = ((1 / (float(line))) - float(line)) / 1.5
        bfacts.append(bfact)
        cmd.alter("%s and resi %s and n. CA" % (mol, counter), "b=%s" % bfact)
        counter = counter + 1
    if visual == "Y":
        cmd.show_as("cartoon", mol)
        cmd.cartoon("putty", mol)
        cmd.set("cartoon_putty_scale_min", min(bfacts), obj)
        cmd.set("cartoon_putty_scale_max", max(bfacts), obj)
        cmd.set("cartoon_putty_transform", 7, obj)
        cmd.set("cartoon_putty_radius", max(bfacts), obj)
        cmd.spectrum("b", "white red", "%s and n. CA " % mol)
        cmd.ramp_new("color_bar", obj, [min(bfacts), max(bfacts)],
                     ["white", "red"])
        cmd.recolor()
コード例 #14
0
def complexb(mol, startaa=1, visual="Y"):
    """
    Replaces B-factors with a list of values contained in a plain txt file and colours the structure accordingly if in visual mode.

    usage: complexb mol, [startaa, [visual]]]

    mol = any object selection (within one single object though)
    startaa = number of first amino acid in 'new B-factors' file (default=1)
    source = name of the file containing new B-factor values (default=newBfactors.txt)
    visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y)

    example: complexb 1LVM
    """

    for subchains in cmd.get_chains(mol):
        source = "bfactors_%s_%s.txt" % (mol, subchains)
        obj = cmd.get_object_list(mol)[0]
        cmd.alter("%s and chain %s" % (mol, subchains), "b=-1.0")
        infile = open(source, 'r')
        counter = int(startaa)
        bfacts = []

        for line in infile.readlines():
            bfact = float(line)
            print(bfact)
            bfacts.append(bfact)
            # the counter method will break for skips encoded in fasta header
            # file. Needs fixing.
            cmd.alter(
                "%s and chain %s and resi %s" % (mol, subchains, counter),
                "b=%s" % bfact)
            counter = counter + 1

        if visual == "Y":
            cmd.cartoon("tube", mol)
            cmd.spectrum("b", "rainbow", "%s" % mol, 1, 3)
            # print(b)
            cmd.ramp_new("count", obj, [1, 3], "rainbow")
            cmd.recolor()
コード例 #15
0
def color_shift(start="Apo2",end="cterm2",divide=100):
    stored.start_colors=[]
    cmd.iterate("%s and name ca and chain A" % start,"stored.start_colors.append(color)")
    stored.end_colors=[]
    cmd.iterate("%s and name ca and chain A" % end,"stored.end_colors.append(color)")    
    print stored.start_colors[0],stored.end_colors[0]
    print cmd.get_color_tuple(stored.start_colors[0]),cmd.get_color_tuple(stored.end_colors[0])
    start_color_indice=cmd.get_color_tuple(stored.start_colors[0])
    end_color_indice=cmd.get_color_tuple(stored.end_colors[0])
    print "start ,end" 
    print  start_color_indice,end_color_indice
    print np.array(end_color_indice)-np.array(start_color_indice)
    #print (np.array(end_color_indice)-np.array(start_color_indice))/float(divide)
    graduate_color_indice=(np.array(end_color_indice)-np.array(start_color_indice))/float(divide)
    i=1
    while i<divide:
        i+=1
        #print list(np.array(start_color_indice)+graduate_color_indice*i)
        time.sleep(0.1)
        cmd.refresh()
        cmd.recolor()
        cmd.set_color("temp%s" %i,list(np.array(start_color_indice)+graduate_color_indice*i))
        cmd.color("temp%s" % i,"%s and name ca and chain A" % start)
コード例 #16
0
ファイル: electrostatics.py プロジェクト: speleo3/pymol-psico
def volume_esp(name, map, stops=[0.1, 1.0], neg='red', pos='blue',
        opacity=0.2, quiet=1):
    '''
DESCRIPTION

    Create a volume object from a map object with default coloring
    for electrostatic potential (similar to positive and negative
    isosurface).

ARGUMENTS

    name = string: name for the new volume object

    map = string: name of the map object to use

    stops = list of floats: 2 or 3 values in standard deviations for creating
    the volume ramp {default: [0.1, 1.0]}

    neg = string: color for negative volume {default: red}

    pos = string: color for positive volume {default: blue}

    opacity = float: maximum opacity in volume ramp {default: 0.2}

SEE ALSO

    volume
    '''
    from .setting import set_temporary

    opacity, quiet = float(opacity), int(quiet)

    if isinstance(stops, str):
        stops = cmd.safe_list_eval(stops)

    try:
        from pymol.colorramping import ColorRamp
    except ImportError:
        print(' Warning: volume_esp is deprecated')
        stdevD = cmd.get_volume_histogram(map, 0)[3]
        stops = [s * stdevD for s in stops]
        ramp = [
            -stops[1], neg, opacity,
            -stops[0], neg, 0.0,
            stops[0], pos, 0.0,
            stops[1], pos, opacity,
        ]
        if len(stops) == 3:
            ramp = [-stops[2], neg, opacity] + ramp + [stops[2], pos, opacity]
        cmd.volume(name, map, ramp, quiet=quiet)
        return

    c_neg = cmd.get_color_tuple(neg)
    c_pos = cmd.get_color_tuple(pos)

    c_pos_0 = c_pos + (0.0,)
    c_pos_1 = c_pos + (opacity,)
    c_neg_0 = c_neg + (0.0,)
    c_neg_1 = c_neg + (opacity,)

    if len(stops) == 2:
        cstops = [(c_neg_1, -999), (c_neg_1, -stops[1]), (c_neg_0, -stops[0]),
                (c_pos_0, stops[0]), (c_pos_1, stops[1]), (c_pos_1, 999)]
    elif len(stops) == 3:
        cstops = [(c_neg_0, -999), (c_neg_0, -stops[2]), (c_neg_1, -stops[1]),
                (c_neg_0, -stops[0]), (c_pos_0, stops[0]), (c_pos_1, stops[1]),
                (c_pos_0, stops[2]), (c_pos_0, 999)]
    else:
        print(' Error: need 2 or 3 stops')
        raise CmdException

    cmd.volume(name, map, quiet=quiet)

    # get_volume_histogram returns zeros without refresh
    with set_temporary(suspend_updates='off'):
        cmd.refresh()

    minD, maxD, meanD, stdevD = cmd.get_volume_histogram(name)[:4]

    v_ramp = []
    c_ramp = ColorRamp(360)
    for c, s in cstops:
        i = int(360 * ((s * stdevD) - minD) / (maxD - minD))
        i = min(max(i, 0), 359)
        v_ramp.append(i)
        v_ramp.extend(c)
        c_ramp.addColor(i, c)

    cmd.set_volume_ramp(name, v_ramp)
    cmd.volume_color(name, c_ramp.getRamp())
    cmd.recolor(name)
コード例 #17
0
    'VAL': 4,
    'GLY': 4,
}

def check_best(x, y, z):
    if y>stored.best_y: 
        stored.best_x = x
        stored.best_y = y 
        stored.best_z = z

stored.check_best = check_best

stored.best_x = float('-inf')
stored.best_y = float('-inf')
stored.best_z = float('-inf')

if (argv[3] == 'c'):
    cmd.fetch(argv[2])
else:
    cmd.load(argv[2])

cmd.show_as('surface', cmd.get_object_list('all')[0])
cmd.alter('all', 'color=stored.classification_dict.get(resn, 0)')
cmd.recolor()
cmd.save(argv[1]+".wrl", cmd.get_object_list('all')[0])

cmd.iterate_state(0, cmd.get_object_list('all')[0], "stored.check_best(x, y+vdw, z,)")

file = open('.protein', 'w')
file.write('{0}\n{1}\n{2}'.format(stored.best_x, stored.best_y, stored.best_z))
file.close()
コード例 #18
0
def bfactorRamp(mol,
                color1="blue",
                color2="red",
                color3="yellow",
                cartoon="off",
                cartoon_putty="off",
                invcolor="grey40",
                style="off",
                fancy="off"):
    '''
DESCRIPTION
    
    Version: bfactorRamp_v1.1
    Author : Erik Breslmayr; April 2020
    
    - bfactorRamp colors the molecule of choise in regard of bfactors provided in the pdb file and adds a color legend starting from the lowest to the highest bfactor. 
    - Additionally some styling features are included, for nicer visualization
    
    Usage: bfactorRamp mol, color1, color2, color3, cartoon=on or off, cartoon_putty=on or off, invcolor=color, style=on or off, fancy=on or off
    
    mol = any object selection (within one single object!)
    color1,2,3 (optional) = three colors, first for lowest, second for middle and third for highest bfactors
    cartoon (optional) = on or off -> enbales cartoon representation
    cartoon_putty (optional) = on or off -> enbales cartoon_putty representation
    invcolor (optional) = add color, which should represent not selected atoms
    style (optional) = styles the cartoon representation in regard of helix oval length and width
    fancy = changes to fancy helices representaton
    
    Defaults:
    - spectrum colors: blue, red, yellow
    - cartoon:         off
    - cartoon_putty:   off
    - invcolor:        grey40 
    - style:           off
    - fancy:           off
    
    Examples: 
    > bfactorRamp objectName -> uses all defaults
    > bfactorRamp objectName, red, green, grey -> changes the colors for the spectrum
    > bfactorRamp objectName, cartoon=on -> turns cartoon representation on
    > bfactorRamp objectName, cartoon=on -> turns cartoon_putty representation on
    > bfactorRamp objectName, invcolor=green -> changes the color of the not selected region to green
    > bfactorRamp objectName, style=on -> changes helices style and not selected region will be transparent
    > bfactorRamp objectName, fancy=on -> changes helices style to fancy and not selected region will be transparent
    '''
    obj = cmd.get_object_list(mol)[0]
    range = cmd.spectrum("b", "%s %s %s" % (color1, color2, color3), mol)
    cmd.select("invSele", "!%s" % (mol))
    cmd.color(invcolor, "invSele")
    cmd.ramp_new("ramp",
                 obj,
                 range,
                 color=["%s" % (color1),
                        "%s" % (color2),
                        "%s" % (color3)])
    #reset styles
    cmd.set("cartoon_transparency", 0, "enabled")
    cmd.set("cartoon_oval_length", 1.2, obj)
    cmd.set("cartoon_oval_width", 0.25, obj)
    cmd.set("cartoon_fancy_helices", 0, obj)
    cmd.set("cartoon_highlight_color", -1, obj)

    if cartoon == "on":
        cmd.show_as("cartoon", mol)
        cmd.dss(obj, 1)
        cmd.recolor()
    if cartoon_putty == "on":
        cmd.show_as("cartoon", mol)
        cmd.cartoon("putty", mol)
        cmd.recolor()
    if style == "on":
        cmd.set("cartoon_transparency", 0.5, "invSele")
        cmd.set("cartoon_oval_length", 0.8, obj)
        cmd.set("cartoon_oval_width", 0.2, obj)
    if fancy == "on":
        cmd.set("cartoon_transparency", 0.5, "invSele")
        cmd.set("cartoon_highlight_color", invcolor, obj)
        cmd.set("cartoon_fancy_helices", 1, obj)

    #Output for screen
    print("for help type: help bfactorRamp")
    print("")
    print("Minimum bfactor: %s | Maximum bfactor: %s" % (range[0], range[1]))
    print("")
    print("Following settings were taken:")
    print("- mol           : %s" % (obj))
    print("- color1,2,3    : %s, %s, %s" % (color1, color2, color3))
    print("- cartoon       : %s" % (cartoon))
    print("- cartoon_putty : %s" % (cartoon_putty))
    print("- invcolor      : %s" % (invcolor))
    print("- style         : %s" % (style))
    print("- fancy         : %s" % (fancy))

    return (color1, color2, color3)
コード例 #19
0
def volume_esp(name,
               map,
               stops=[0.1, 1.0],
               neg='red',
               pos='blue',
               opacity=0.2,
               quiet=1):
    '''
DESCRIPTION

    Create a volume object from a map object with default coloring
    for electrostatic potential (similar to positive and negative
    isosurface).

ARGUMENTS

    name = string: name for the new volume object

    map = string: name of the map object to use

    stops = list of floats: 2 or 3 values in standard deviations for creating
    the volume ramp {default: [0.1, 1.0]}

    neg = string: color for negative volume {default: red}

    pos = string: color for positive volume {default: blue}

    opacity = float: maximum opacity in volume ramp {default: 0.2}

SEE ALSO

    volume
    '''
    from .setting import set_temporary

    opacity, quiet = float(opacity), int(quiet)

    if isinstance(stops, str):
        stops = cmd.safe_list_eval(stops)

    try:
        from pymol.colorramping import ColorRamp
    except ImportError:
        print(' Warning: volume_esp is deprecated')
        stdevD = cmd.get_volume_histogram(map, 0)[3]
        stops = [s * stdevD for s in stops]
        ramp = [
            -stops[1],
            neg,
            opacity,
            -stops[0],
            neg,
            0.0,
            stops[0],
            pos,
            0.0,
            stops[1],
            pos,
            opacity,
        ]
        if len(stops) == 3:
            ramp = [-stops[2], neg, opacity] + ramp + [stops[2], pos, opacity]
        cmd.volume(name, map, ramp, quiet=quiet)
        return

    c_neg = cmd.get_color_tuple(neg)
    c_pos = cmd.get_color_tuple(pos)

    c_pos_0 = c_pos + (0.0, )
    c_pos_1 = c_pos + (opacity, )
    c_neg_0 = c_neg + (0.0, )
    c_neg_1 = c_neg + (opacity, )

    if len(stops) == 2:
        cstops = [(c_neg_1, -999), (c_neg_1, -stops[1]), (c_neg_0, -stops[0]),
                  (c_pos_0, stops[0]), (c_pos_1, stops[1]), (c_pos_1, 999)]
    elif len(stops) == 3:
        cstops = [(c_neg_0, -999), (c_neg_0, -stops[2]), (c_neg_1, -stops[1]),
                  (c_neg_0, -stops[0]), (c_pos_0, stops[0]),
                  (c_pos_1, stops[1]), (c_pos_0, stops[2]), (c_pos_0, 999)]
    else:
        print(' Error: need 2 or 3 stops')
        raise CmdException

    cmd.volume(name, map, quiet=quiet)

    # get_volume_histogram returns zeros without refresh
    with set_temporary(suspend_updates='off'):
        cmd.refresh()

    minD, maxD, meanD, stdevD = cmd.get_volume_histogram(name)[:4]

    v_ramp = []
    c_ramp = ColorRamp(360)
    for c, s in cstops:
        i = int(360 * ((s * stdevD) - minD) / (maxD - minD))
        i = min(max(i, 0), 359)
        v_ramp.append(i)
        v_ramp.extend(c)
        c_ramp.addColor(i, c)

    cmd.set_volume_ramp(name, v_ramp)
    cmd.volume_color(name, c_ramp.getRamp())
    cmd.recolor(name)
コード例 #20
0
def rmsdCA(refMol, tgtMol, puttyview="Y", bfactorca="CA"):
    """
    Written up by Yufeng Tong 2020-01-29
    Inspired by rmsdByRes Zhenting Gao on 7/28/2016
    and by loadBfacts from PyMOLWiki

    USAGE

      rmsdCA refMol, tgtMol, puttyview="Y", bfactorca="CA"

      Calculate the RMSD of Calpha and backbone for each residue pairs from
        two chains of proteins with same residue numbers and close
        conformations for the two structures. The two proteins can be 
        mutants. Only residue numbers but not identity are matched.
      It will generate a putty representation of the target molecule by 
        default. You can specify whether to use the RMSD of Calpha or Backbone
        for the coloring of the putty display.
      I think it's not neccessary to calculate RMSD of the whole residue.
      A CSV file is saved of the calculated RMSD of Calpha and backbone atoms.
      A PDB file is saved with BFactor replaced by the RMSD.

    Workflow
      Read reference and target pdb files
      1. Select two objects for comparison
      2. Align two structures
      3. rmsdByRes refMol, tgtMol
    
    TODO:
      1. Save output files to the folder pdb files are loaded.
      2. Handle missing residues.
    """

    # Create temporary objects, exclude alternative conformation B
    cmd.delete("tgt_gzt rmsdPuttyScale")
    cmd.create("ref_gzt", refMol + " and polymer and not alt B")
    cmd.alter("ref_gzt", "chain='A'")
    cmd.alter("ref_gzt", "segi=''")
    cmd.create("tgt_gzt", tgtMol + " and polymer and not alt B")
    cmd.alter("tgt_gzt", "chain='A'")
    cmd.alter("tgt_gzt", "segi=''")
    cmd.alter("tgt_gzt", "b=-1.0")

    # parameters
    outputText = ""
    csvHeadline = ("refMol,refRes,refResID,target,residueName,residueId,"
                   "rmsdResCa,rmsdResBackbone\n")
    outputFile = 'rmsd%s_%s.csv' % (bfactorca, tgtMol)
    outputpdb = 'rmsdBFactor%s_%s.pdb' % (bfactorca, tgtMol)
    bfactors = []

    # select alpha carbon of selected residues in reference structure
    calpha_ref = cmd.get_model("ref_gzt and name CA")
    calpha_tgt = cmd.get_model("tgt_gzt and name CA")

    # build an index dict of {resi : index}
    ref_dict = {int(v.resi): k for k, v in enumerate(calpha_ref.atom)}
    tgt_dict = {int(v.resi): k for k, v in enumerate(calpha_tgt.atom)}

    # loop through residues in the target molecule and calculate per residue RMSDs.
    for k in sorted(ref_dict):
        if k in tgt_dict:
            ref_atom = calpha_ref.atom[ref_dict[k]]
            tgt_atom = calpha_tgt.atom[tgt_dict[k]]
            rmsdResCA = cmd.rms_cur(
                "ref_gzt and n. ca and i. " + ref_atom.resi,
                "tgt_gzt and n. ca and i. " + tgt_atom.resi,
                matchmaker=-1)
            rmsdResBb = cmd.rms_cur(
                "ref_gzt and n. ca+n+c+o and i. " + ref_atom.resi,
                "tgt_gzt and n. ca+n+c+o and i. " + tgt_atom.resi,
                matchmaker=-1)
            if bfactorca == "bb":
                bfactor = rmsdResBb
            else:
                bfactor = rmsdResCA
            cmd.alter("%s and i. %s" % ("tgt_gzt", tgt_atom.resi),
                      "b=%s" % bfactor)
            bfactors.append(bfactor)

            outputText += "%s,%s,%s,%s,%s,%s,%.3f,%.3f\n" % (
                refMol, ref_atom.resn, ref_atom.resi, tgtMol, tgt_atom.resn,
                tgt_atom.resi, rmsdResCA, rmsdResBb)

    print(outputText)
    max_b, min_b = max(bfactors), min(bfactors)
    print("RMSD: max:%.3f; min:%.3f" % (max_b, min_b))

    if puttyview == "Y":
        cmd.show_as("cartoon", "tgt_gzt")
        cmd.cartoon("putty", "tgt_gzt")
        cmd.set("cartoon_putty_scale_min", min_b, "tgt_gzt")
        cmd.set("cartoon_putty_scale_max", max_b, "tgt_gzt")
        cmd.set("cartoon_putty_transform", 0, "tgt_gzt")
        cmd.spectrum("b", "rainbow", "tgt_gzt and n. CA")
        cmd.ramp_new("rmsdPuttyScale", "tgt_gzt", [min_b, max_b], "rainbow")
        cmd.recolor()

# Destroy temporary objects
    cmd.delete("ref_gzt")

    # Save data into csv and pdb
    f = open(outputFile, 'w+')
    f.write(csvHeadline)
    f.write(outputText)
    f.close()
    cmd.save(outputpdb, "tgt_gzt")

    print("Results are saved in %s and %s " % (outputFile, outputpdb))