Exemplo n.º 1
0
def rmsf2b(selection='all', linearscale=1.0, var='b', quiet=1):
    '''
DESCRIPTION

    Determine the root mean square fluctuation (RMSF) per atom for a
    multi-state object and assign b-factor

ARGUMENTS

    selection = string: atom selection {default: name CA}

    linearscale = float: if linearscale <= 0, then use real b-factor equation,
    else use b=(rmsf*linearscale) {default: 1.0}

SEE ALSO

    spheroid, rmsf_states.py from Robert Campbell
    '''
    _assert_package_import()
    from . import querying
    from numpy import asfarray, sqrt, pi
    linearscale = float(linearscale)
    coords = asfarray(querying.get_ensemble_coords(selection))
    n_states, n_atoms, _ = coords.shape
    if n_atoms == 0 or n_states < 2:
        print(' Error: not enough atoms or states')
        raise CmdException
    u_sq = coords.var(0).sum(1) # var over states, sum over x,y,z
    b_array = sqrt(u_sq) * linearscale if linearscale > 0.0 \
            else 8 * pi**2 * u_sq
    cmd.alter(selection, var + ' = next(b_iter)', space={'b_iter': iter(b_array), 'next': next})
    if not int(quiet):
        print(' Average RMSF: %.2f' % (sqrt(u_sq).mean()))
    return b_array
Exemplo n.º 2
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()
Exemplo n.º 3
0
    def plot(self, outfile):
        ctrl_id, case_id, snp_df_sub = self.score_on_var()
        df = pd.merge(snp_df_sub, self.snps2aa, on='id')

        #pymol.finish_launching()
        cmd.reinitialize()
        cmd.fetch(self.pdb)
        cmd.alter(self.pdb, 'b = 0.5')
        cmd.show_as('cartoon', self.pdb)
        cmd.color('white', self.pdb)

        for i, row in df.iterrows():
            resi = row['structure_position']
            chain = row['chain']
            pheno = row['es']
            selec = 'snp%s' % i
            selec_atom = 'snp_atom%s' % i
            cmd.select(selec,
                       'name ca and resi %s and chain %s' % (resi, chain))
            cmd.create(selec_atom, selec)
            cmd.set("sphere_scale", 0.8)
            cmd.show('sphere', selec_atom)
            cmd.alter(selec_atom, 'b=%s' % pheno)
            cmd.spectrum("b",
                         "blue_white_red",
                         selec_atom,
                         maximum=1.0,
                         minimum=0.0)
        cmd.bg_color("white")
        cmd.zoom()
        cmd.orient()
        cmd.save('%s.pse' % outfile)
        cmd.png('%s.png' % outfile, width=2400, height=2400, dpi=300, ray=1)
Exemplo n.º 4
0
        def hs_resize(meta_file, selection):

            if not is_sele(selection):
                raise RuntimeError(
                    "Selection \"{}\" does not exists.".format(selection))

            # Find free sele name
            temp_sele = _random_string()
            while is_sele(temp_sele):
                temp_sele = _random_string()

            states = cmd.count_states(selection=selection)

            for state in range(1, states + 1):
                stored.info = []
                cmd.iterate_state(state, selection,
                                  "stored.info.append((ID, partial_charge))")

                for id_, partial_charge in stored.info:
                    size = log(partial_charge / ref + 1)
                    print(ref)
                    print(size)

                    cmd.select(temp_sele,
                               "{} and id {}".format(selection, id_),
                               state=state)
                    cmd.set("sphere_scale", value=size, selection=temp_sele)
                    cmd.alter(temp_sele, "b={}".format(partial_charge))

            cmd.delete(temp_sele)
Exemplo n.º 5
0
 def aver(settings):
     """
     average pdb command
     :param settings:
     """
     cmd.set('orthoscopic')
     if settings.config.get('all_states', 0):
         cmd.set('all_states')
     LOG.info("Load structure file %s" % settings.args.get('pdb'))
     try:
         cmd.load(settings.args.get('pdb'))
     except CmdException:
         LOG.error("Can't load %s", settings.args.get('pdb'))
     mypdb = os.path.splitext(os.path.basename(settings.args.get('pdb')))[0]
     cmd.hide('everything', mypdb)
     cmd.show('ribbon', mypdb)
     cmd.show('spheres', '%s and name CA' % mypdb)
     cmd.alter(mypdb, 'vdw=%.2f' % settings.config.get('vdwspheres_radius'))
     cmd.rebuild(mypdb, 'spheres')
     # Fit to the first state by default (which is the best one according to
     #  aria order)
     objfit = avg_states(mypdb, object_sel=settings.args.get('sel'),
                         first=settings.config.get('first'),
                         last=settings.config.get('last'),
                         newobj=settings.config.get('newobj'),
                         fitverdict=settings.config.get('fit'),
                         verb=settings.config.get('verb'),
                         pairs=settings.config.get('pairs'),
                         writefiles=settings.config.get('writefiles'))
     cmd.cartoon('putty', objfit)
     cmd.show('cartoon', objfit)
     cmd.spectrum('b', 'blue_white_red', objfit)
Exemplo n.º 6
0
def renumber_residues(sel="polymer", start=1):
    """Renumber residues. Selection should be a single chain.
    Run from Pymol.
    See also this module for renumbering based on
    connectivity: https://pymolwiki.org/index.php/Renumber
    """
    class gen_resi_cl:
        def __init__(self, start):
            self.prev_new_resi = start
            self.prev_old_resi = None

        def __call__(self, cur_old_resi):
            if self.prev_old_resi is None:
                ret = self.prev_new_resi
            else:
                if self.prev_old_resi != cur_old_resi:
                    ret = self.prev_new_resi + 1
                else:
                    ret = self.prev_new_resi
            self.prev_old_resi = cur_old_resi
            self.prev_new_resi = ret
            print(ret, cur_old_resi)
            return ret

    space = dict(gen_resi=gen_resi_cl(start=start))
    cmd.alter(sel, "resi=gen_resi(resi)", space=space)
    cmd.rebuild()
    cmd.sort()
Exemplo n.º 7
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()
Exemplo n.º 8
0
    def reload_system(self, ln: str, smis: oechem.OEMol, old_pdb: str, is_oe_already: bool = False):
        with self.logger("reload_system") as logger:
            logger.log("Loading {} with new smiles {}".format(old_pdb, ln))
            with tempfile.TemporaryDirectory() as dirpath:
                ofs = oechem.oemolostream("{}/newlig.mol2".format(dirpath))
                oechem.OEWriteMolecule(ofs, smis)
                ofs.close()
                cmd.reinitialize()
                cmd.load(old_pdb)
                cmd.remove("not polymer")
                cmd.load("{}/newlig.mol2".format(dirpath), "UNL")
                cmd.alter("UNL", "resn='UNL'")
                cmd.alter("UNL", "chain='A'")
                self.config.pdb_file_name = self.config.tempdir() + "reloaded.pdb"
                cmd.save(self.config.pdb_file_name)
                cmd.save(self.config.tempdir() + "apo.pdb")

                with open(self.config.pdb_file_name, 'r') as f:
                    self.pdb = app.PDBFile(f)
                self.positions, self.topology = self.pdb.getPositions(), self.pdb.getTopology()

                if self.config.explicit and self.config.method == 'amber':
                    self.system, self.topology, self.positions = self.__setup_system_ex_amber(
                        pdbfile=self.config.pdb_file_name)
                elif self.config.explicit:
                    self.system, self.topology, self.positions = self.__setup_system_ex_mm()
                else:
                    self.system, self.topology, self.positions = self.__setup_system_im( pdbfile=self.config.pdb_file_name)

        return self.system
Exemplo n.º 9
0
def useOccRadii(sel="all"):
	for a in cmd.get_model(sel).atom:
		q = a.q
		if q >= 3:
			print "shrik radius"
			q <- 0.1
		cmd.alter("%s and resi %s and name %s"%(sel,a.resi,a.name),"vdw=%f"%(q))
Exemplo n.º 10
0
def alphatoall(selection='polymer', properties='b', operator='byca', quiet=1):
    '''
DESCRIPTION

    Expand any given property of the CA atoms to all atoms in the residue

    Enhanced version of http://pymolwiki.org/index.php/AlphaToAll

ARGUMENTS

    selection = string: atom selection {default: polymer}

    properties = string: space separated list of atom properties {default: b}
    '''
    properties = '(' + ','.join(properties.split()) + ')'
    space = {'props': dict()}
    cmd.iterate('%s (%s)' % (operator, selection),
                'props[model,segi,chain,resi] = ' + properties,
                space=space)
    cmd.alter(selection,
              properties + ' = props.get((model,segi,chain,resi), ' +
              properties + ')',
              space=space)
    if not int(quiet):
        print(' Modified %d residues' % (len(space['props'])))
Exemplo n.º 11
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()
Exemplo n.º 12
0
def sequential_residues(sel1, offset=1):
    """
        PURPOSE: renumbers the selected residues sequentially, regardless of gaps
        USAGE: sequential_residues protName    # first residue is 1
        USAGE: sequential_residues protName, 5 # first residue is 5
        EXAMPLE: sequential_residues *
        """
    offset = int(offset)

    # A counter from offset up
    stored.offset = int(offset) - 1
    stored.curr_res = None

    cmd.alter(
        sel1,
        """
if stored.curr_res != int(resi):
    stored.offset=stored.offset + 1
    stored.curr_res=int(resi)
    resi=stored.offset
else:
    resi=stored.offset
""",
    )
    cmd.sort()
Exemplo n.º 13
0
def color_protein(protein, df):
    #df["importance"] = np.abs(df["importance"].values)
    #df["importance"] = np.log(df["importance"].values)
    #df["importance"] = df["importance"].values/np.max(df["importance"].values)
    min_imp = min(df["importance"].values)
    max_imp = max(df["importance"].values)
    print(min_imp)
    print(max_imp)

    cmd.spectrum("b",
                 "blue red",
                 selection=protein,
                 minimum=min_imp,
                 maximum=max_imp)
    for index in df.index:
        print(df.loc[index])
        resid = int(df.loc[index]["resid"])
        net_importance = df.loc[index]["importance"]
        cmd.alter("resid %d & %s" % (resid, protein),
                  "b=%f" % (net_importance))
        cmd.show("ribbon", "resi %d" % resid)
        if net_importance > np.percentile(df["importance"].values, 95):
            cmd.show("sticks", "resi %d" % resid)
            #if "2" in protein:
            #  cmd.util.cbac("resi %d & sidechain & %s" % (resid, protein))
            #else:
            #  cmd.util.cbag("resi %d & sidechain & %s" % (resid, protein))
        print(resid)
        print(net_importance)
Exemplo n.º 14
0
def useRosettaRadii():
	cmd.alter("element C", "vdw=2.00")
	cmd.alter("element N", "vdw=1.75")
	cmd.alter("element O", "vdw=1.55")
	cmd.alter("element H", "vdw=1.00")
	cmd.alter("element P", "vdw=1.90")
	cmd.set("sphere_scale", 1.0)
Exemplo n.º 15
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()
Exemplo n.º 16
0
def zero_residues(sel1, offset=0, chains=0):
    """
        """
    offset = int(offset)

    # variable to store the offset
    stored.first = None
    # get the names of the proteins in the selection

    names = [
        '(model %s and (%s))' % (p, sel1)
        for p in cmd.get_object_list('(' + sel1 + ')')
    ]

    if int(chains):
        names = [
            '(%s and chain %s)' % (p, chain) for p in names
            for chain in cmd.get_chains(p)
        ]

    # for each name shown
    for p in names:
        # get this offset
        ok = cmd.iterate("first %s and polymer and n. CA" % p,
                         "stored.first=resv")
        # don't waste time if we don't have to
        if not ok or stored.first == offset:
            continue
        # reassign the residue numbers
        cmd.alter("%s" % p,
                  "resi=str(int(resi)-%s)" % str(int(stored.first) - offset))
        # update pymol

    cmd.rebuild()
Exemplo n.º 17
0
def corexHDXRateUpdateB(obj, infoFile, exchangeRateFile):
    """Sets the B-factor column to the HDX rate.
    infoFile is used to establish the mapping between pdb and corex numbers
        (*.info).
    exchangeRateFile gives the HDX rates (*.Exchange_Rates).
    """
    hdx = CorexExchangeRates(exchangeRateFile)
    info = CorexAtomInfo(infoFile)

    if info is None:
        print "Error parsing %s" % infoFile
        return
    if hdx is None:
        print "Error parsing %s" % exchangeRateFile
        return

    assignPDBNums(
            [atom.res for atom in info.getAtoms() if not atom.isHet],
            hdx.getResidues()
        )

    cmd.alter(obj, "b = -10")
    for res in hdx.getResidues():
        if res.pdbNum is not None and res.exchangeRate is not None:
            sel = "%s and i. %s and chain %s" % (
                    obj,  res.pdbNum, res.chain)
            cmd.alter( sel, "b = %f" % res.exchangeRate)
    cmd.sort(obj)
Exemplo n.º 18
0
def corexProtectionFactorUpdateB(obj, infoFile, pfFile):
    """Sets the B-factor column to the protection factors.
    infoFile is used to establish the mapping between pdb and corex numbers
        (*.info).
    pfFile gives the protection factors (*.Protection_Factors).
    """
    pf = CorexProtectionFactors(pfFile)
    info = CorexAtomInfo(infoFile)

    if info is None:
        print "Error parsing %s" % infoFile
        return
    if pf is None:
        print "Error parsing %s" % exchangeRateFile
        return

    assignPDBNums(
            [atom.res for atom in info.getAtoms() if not atom.isHet],
            pf.getResidues()
        )

    cmd.alter(obj, "b = -10")
    for res in pf.getResidues():
        if res.pdbNum is not None and res.modifiedProtectionFactor is not None:
            sel = "%s and i. %s and chain %s" % (
                    obj,  res.pdbNum, res.chain)
            cmd.alter( sel, "b = %f" % res.modifiedProtectionFactor)
    cmd.sort(obj)
Exemplo n.º 19
0
def test_msms_surface():
    eps = 1e-3
    cmd.reinitialize()
    cmd.fragment('ala', 'm1')
    # default
    psico.msms.msms_surface(name='surf1')
    extent = cmd.get_extent('surf1')
    assert extent[0] == approx([-2.705, -3.208, -2.413], rel=eps)
    assert extent[1] == approx([3.530, 2.907, 2.676], rel=eps)
    # global solvent_radius
    cmd.set('solvent_radius', 3.5)
    psico.msms.msms_surface(name='surf2')
    extent = cmd.get_extent('surf2')
    assert extent[0] == approx([-2.705, -3.169, -2.436], rel=eps)
    assert extent[1] == approx([3.530, 2.907, 2.676], rel=eps)
    # object-level solvent_radius
    cmd.set('solvent_radius', 2.8, 'm1')
    psico.msms.msms_surface(name='surf3')
    extent = cmd.get_extent('surf3')
    assert extent[0] == approx([-2.705, -3.161, -2.427], rel=eps)
    assert extent[1] == approx([3.530, 2.907, 2.676], rel=eps)
    # modified atom radii
    cmd.alter('m1', 'vdw = 3.0')
    psico.msms.msms_surface(name='surf4')
    extent = cmd.get_extent('surf4')
    assert extent[0] == approx([-4.605, -5.162, -4.418], rel=eps)
    assert extent[1] == approx([5.030, 4.861, 4.681], rel=eps)
Exemplo n.º 20
0
def corexDiffSAUpdateB(obj, corex1, corex2):
    """Sets the B-factor column to the difference in surface areas between
    files corex1-corex2
    """
    corex1 = CorexAtomInfo(corex1)
    if corex1 is None:
        print "Error parsing %s" % corex1
        return

    corex2 = CorexAtomInfo(corex2)
    if corex2 is None:
        print "Error parsing %s" % corex2
        return

    atoms1 = corex1.getAtoms()
    atoms2 = corex2.getAtoms()

    if len(atoms1) != len(atoms2):
        print "Error: Corex files must have identical atoms"
        #TODO line up atoms1 and atoms2 somehow
    for i in xrange(len(atoms1)):
        sel = "%s and n. %s and i. %s and chain %s" % (
                obj, atoms1[i].name, atoms1[i].res.pdbNum, atoms1[i].res.chain)
        cmd.alter( sel, "b = %f" % (atoms1[i].sa-atoms2[i].sa))
        print "b = %f" % (atoms1[i].sa-atoms2[i].sa)
    cmd.sort(obj)
Exemplo n.º 21
0
    def lsupdateview(self, lig, zone, min, max, prev, index, hlig, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.label(
            "( " + x[index] + " and (r. " + lig + " a. " + prev +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")

        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)

        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        cmd.hide("licorice", x[index] + " and r. " + hlig)
        self.togglelabells(label, index, lig, zone, hlig)
Exemplo n.º 22
0
 def wsvisualizer(self, index, lig, zone, min, max, label):
     cmd.hide("all")
     x = cmd.get_names("all")
     cmd.show("cartoon", "bo. " + x[index])
     cmd.show("sticks", x[index] + " and r. " + lig)
     cmd.color("white", x[index] + " and pol.")
     fp = open(tempfile.gettempdir() + "/temp.txt", "r")
     #tt=0
     stored.bfact = []
     for line in fp:
         stored.bfact.append(line)
         #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt))
         #tt=tt+1
     #print(tt)
     fp.close()
     cmd.alter(x[index], "b=stored.bfact.pop(0)")
     cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
     cmd.ramp_new("ramp_obj",
                  x[index],
                  range=[min, 0, max],
                  color="[blue, white, red ]")
     cmd.util.cbaw(x[index] + " and r. " + lig)
     cmd.show(
         "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
         ") ) and (not (" + x[index] +
         " and (r. SWT or r. BWT or r. SWP))) ")
     self.togglelabelws(label, index, lig, zone)
Exemplo n.º 23
0
    def testCifMissing(self):
        N = 7
        cmd.fragment('gly', 'm1')
        cmd.alter('all', '(chain, segi, resv, alt) = ("?", ".", 5, "")')

        s = cmd.get_str('cif')
        self.assertTrue("'?'" in s or '"?"' in s) # chain
        self.assertTrue("'.'" in s or '"."' in s) # segi
        self.assertTrue(' ? ' in s) # e.g. pdbx_PDB_ins_code
        self.assertTrue(' . ' in s) # e.g. label_alt_id

        cmd.delete('*')
        cmd.set('cif_keepinmemory')
        cmd.load(s, 'm2', format='cifstr')
        self.assertEqual(['?'], cmd.get_chains())
        self.assertEqual(cmd.count_atoms('segi .'), N)
        self.assertEqual(cmd.count_atoms('alt ""'), N)  # no alt
        self.assertEqual(cmd.count_atoms('resi 5'), N)  # no ins_code

        from pymol.querying import cif_get_array
        self.assertEqual(cif_get_array("m2", "_atom_site.type_symbol"), list('NCCOHHH'))
        self.assertEqual(cif_get_array("m2", "_atom_site.id", "i"),     list(range(1, N + 1)))
        self.assertEqual(cif_get_array("m2", "_atom_site.auth_asym_id"),        ['?'] * N)
        self.assertEqual(cif_get_array("m2", "_atom_site.label_asym_id"),       ['.'] * N)
        self.assertEqual(cif_get_array("m2", "_atom_site.pdbx_pdb_ins_code"),   [None] * N)
        self.assertEqual(cif_get_array("m2", "_atom_site.label_alt_id"),        [None] * N)
Exemplo n.º 24
0
    def RefreshDisplay(self):

        try:
            # Display the atoms spheres
            cmd.show('spheres', self.LigDisplay)
            cmd.refresh()

            cmd.alter(self.LigDisplay, 'vdw=0.25')
            cmd.rebuild(self.LigDisplay)
            cmd.refresh()

            util.cbag(self.LigDisplay)
            cmd.refresh()

            if self.AnchorAtom != -1:
                AtomSel = self.LigDisplay + ' & id ' + str(self.AnchorAtom)
                cmd.color('white', AtomSel)
                cmd.refresh()

                cmd.alter(AtomSel, 'vdw=0.30')
                cmd.rebuild(AtomSel)
                cmd.refresh()

        except:
            self.ErrorCode = 1

        return self.ErrorCode
Exemplo n.º 25
0
def useTempRadii(sel="all"):
	for a in cmd.get_model(sel).atom:
		bfac = a.b
		if bfac >= 3:
			print "shrik radius"
			bfac <- 0.1
		cmd.alter("%s and resi %s and name %s"%(sel,a.resi,a.name),"vdw=%f"%(bfac))
Exemplo n.º 26
0
def highlightDsspSecStruct(pdbFile, dsspBinaryPath):
    (dsspData,
     dssp2pdbResnum) = getDsspSecStructHash(runDssp(pdbFile, dsspBinaryPath))

    cmd.hide("everything")
    cmd.select("a", "all")
    cmd.alter("a", "ss=\'L\'")
    cmd.show("cartoon", "a")
    cmd.color("deepblue", "a")

    for chain in dsspData.keys():
        for pdbResNum in dsspData[chain].keys():
            print "Reading chain:" + chain + ", residue:" + pdbResNum + ", secstr:" + dsspData[
                chain][pdbResNum]["SEC_STRUCT"]
            if dsspData[chain][pdbResNum]["SEC_STRUCT"] == 'E':
                highlightResidue(chain, pdbResNum, "cartoon", "grey", 'S')
            elif dsspData[chain][pdbResNum]["SEC_STRUCT"] == 'B':
                highlightResidue(chain, pdbResNum, "cartoon", "grey90", 'S')
            elif dsspData[chain][pdbResNum]["SEC_STRUCT"] == 'H':
                highlightResidue(chain, pdbResNum, "cartoon", "tv_red", 'H')
            elif dsspData[chain][pdbResNum]["SEC_STRUCT"] == 'G':
                highlightResidue(chain, pdbResNum, "cartoon", "magenta", 'H')
            elif dsspData[chain][pdbResNum]["SEC_STRUCT"] == 'I':
                highlightResidue(chain, pdbResNum, "cartoon", "pink", 'H')
            elif dsspData[chain][pdbResNum]["SEC_STRUCT"] == 'T':
                highlightResidue(chain, pdbResNum, "cartoon", "tv_green", 'L')
            elif dsspData[chain][pdbResNum]["SEC_STRUCT"] == 'S':
                highlightResidue(chain, pdbResNum, "cartoon", "limon", 'L')
            else:
                highlightResidue(chain, pdbResNum, "cartoon", "forest", 'L')

    dsspData.clear()
Exemplo n.º 27
0
    def DisplayLigand(self):
        
        try:
            cmd.set("auto_zoom", 0)
            
            cmd.load(self.RefLigand, self.LigDisplay, state=self.State)
            cmd.refresh()
            
            # Display the atoms spheres
            cmd.show('spheres', self.LigDisplay)
            cmd.refresh()

            cmd.alter(self.LigDisplay,'vdw=0.25')
            cmd.rebuild(self.LigDisplay)
            cmd.refresh()

            util.cbag(self.LigDisplay)
            cmd.refresh()

            cmd.translate(self.Translation,self.LigDisplay)
            cmd.refresh()

            cmd.zoom(self.LigDisplay)
            cmd.refresh()
            
        except:
            self.ErrorCode = 1

        cmd.set("auto_zoom", self.auto_zoom)
        
        return self.ErrorCode
Exemplo n.º 28
0
    def updateSS(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 secondary structures for %s' % (self.pymol_sel.get()),
            print 'using secondary structure assignment by %s' % (self.ss_asgn_prog,)
            print 'SSE mapping: (H,G,I) ==> H; (E,B,b) ==> S; (T,S,-,C) ==> L'

            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:
                for sel_obj in self.sel_obj_list:
                    if self.SSE_sel_dict[sel_obj][sse] is not None:
                        cmd.alter(self.SSE_sel_dict[sel_obj][sse], 'ss=\'%s\''% (self.SSE_map[sse],))
                        print 'alter %s, ss=%s' % (self.SSE_sel_dict[sel_obj][sse], self.SSE_map[sse])
                    else:
                        print 'No residue with SSE %s to update ss.' % (sse,)

            # show cartoon for the input selection, and rebuild
            cmd.show('cartoon',self.pymol_sel.get())
            cmd.rebuild(self.pymol_sel.get()) 
            return
Exemplo n.º 29
0
def useRosettaRadii():
    cmd.alter("element C", "vdw=2.00")
    cmd.alter("element N", "vdw=1.75")
    cmd.alter("element O", "vdw=1.55")
    cmd.alter("element H", "vdw=1.00")
    cmd.alter("element P", "vdw=1.90")
    cmd.set("sphere_scale", 1.0)
Exemplo n.º 30
0
def order_atoms_in_peptide(rtpfile, selection='all'):
    """
    DESCRIPTION

    Order the atoms in the peptide according to the Gromacs .rtp database

    USAGE

    order_atoms_in_peptide rtpfile [, selection]

    ARGUMENTS

    rtpfile: either a .rtp file (Gromacs residue topology database) or a Gromacs forcefield directory

    selection: defaults to 'all'
    """
    residuetypes = list(iterate_residues(rtpfile))
    residues = {(a.resi_number, a.resn) for a in cmd.get_model(selection).atom}
    i = 0
    for resi, resn in sorted(residues, key=lambda x: x[0]):
        resn, atomnames, bondtypes = [r for r in residuetypes
                                      if r[0] == resn][0]
        for a in atomnames:
            print(i, a)
            cmd.alter(
                '({}) and (resi {}) and (resn {}) and (name {})'.format(
                    selection, resi, resn, a), 'ID={}'.format(i))
            cmd.alter(
                '({}) and (resi {}) and (resn {}) and (name {})'.format(
                    selection, resi, resn, a), 'rank={}'.format(i))
            i += 1
Exemplo n.º 31
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()
Exemplo n.º 32
0
    def updateSS(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 secondary structures for %s' % (
                self.pymol_sel.get()),
            print 'using secondary structure assignment by %s' % (
                self.ss_asgn_prog, )
            print 'SSE mapping: (H,G,I) ==> H; (E,B,b) ==> S; (T,S,-,C) ==> L'

            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:
                for sel_obj in self.sel_obj_list:
                    if self.SSE_sel_dict[sel_obj][sse] is not None:
                        cmd.alter(self.SSE_sel_dict[sel_obj][sse],
                                  'ss=\'%s\'' % (self.SSE_map[sse], ))
                        print 'alter %s, ss=%s' % (
                            self.SSE_sel_dict[sel_obj][sse], self.SSE_map[sse])
                    else:
                        print 'No residue with SSE %s to update ss.' % (sse, )

            # show cartoon for the input selection, and rebuild
            cmd.show('cartoon', self.pymol_sel.get())
            cmd.rebuild(self.pymol_sel.get())
            return
Exemplo n.º 33
0
def update_identifiers(target,
                       source,
                       identifiers='segi chain resi',
                       match='align',
                       quiet=1):
    '''
DESCRIPTION

    Transfers segi, chain, and resi identifiers from one selection to another.
    This works by mapping old to new identifiers and alters also not aligned
    atoms (works if any other atom from the same residue got aligned).
    '''
    from .fitting import matchmaker

    tmatched, smatched, tmp_names = matchmaker(target, source, match)

    key = '(' + ','.join(identifiers.split()) + ',)'
    tkeys, skeys = [], []
    cmd.iterate(tmatched, 'tkeys.append(%s)' % (key), space=locals())
    cmd.iterate(smatched, 'skeys.append(%s)' % (key), space=locals())
    t2s = dict(zip(tkeys, skeys))
    cmd.alter(target, '%s = t2s.get(%s, %s)' % (key, key, key), space=locals())

    for name in tmp_names:
        cmd.delete(name)
Exemplo n.º 34
0
    def testCifMissing(self):
        N = 7
        cmd.fragment('gly', 'm1')
        cmd.alter('all', '(chain, segi, resv, alt) = ("?", ".", 5, "")')

        s = cmd.get_str('cif')
        self.assertTrue("'?'" in s or '"?"' in s)  # chain
        self.assertTrue("'.'" in s or '"."' in s)  # segi
        self.assertTrue(' ? ' in s)  # e.g. pdbx_PDB_ins_code
        self.assertTrue(' . ' in s)  # e.g. label_alt_id

        cmd.delete('*')
        cmd.set('cif_keepinmemory')
        cmd.load(s, 'm2', format='cifstr')
        self.assertEqual(['?'], cmd.get_chains())
        self.assertEqual(cmd.count_atoms('segi .'), N)
        self.assertEqual(cmd.count_atoms('alt ""'), N)  # no alt
        self.assertEqual(cmd.count_atoms('resi 5'), N)  # no ins_code

        from pymol.querying import cif_get_array
        self.assertEqual(cif_get_array("m2", "_atom_site.type_symbol"),
                         list('NCCOHHH'))
        self.assertEqual(cif_get_array("m2", "_atom_site.id", "i"),
                         list(range(1, N + 1)))
        self.assertEqual(cif_get_array("m2", "_atom_site.auth_asym_id"),
                         ['?'] * N)
        self.assertEqual(cif_get_array("m2", "_atom_site.label_asym_id"),
                         ['.'] * N)
        self.assertEqual(cif_get_array("m2", "_atom_site.pdbx_pdb_ins_code"),
                         [None] * N)
        self.assertEqual(cif_get_array("m2", "_atom_site.label_alt_id"),
                         [None] * N)
Exemplo n.º 35
0
    def test_wildcard_sets_ranges(self):
        for i in range(10): cmd.pseudoatom('m%d' % i, chain=chr(65 + i))
        cmd.alter('m5', 'chain = "AB"')
        cmd.alter('m6', 'chain = "BA"')
        cmd.alter('m7', 'chain = "CC"')
        cmd.alter('m8', 'chain = "ZA"')
        cmd.alter('m9', 'chain = "ABA"')
        # A patterns
        self.assertEqual(1, cmd.count_atoms('chain A'))
        self.assertEqual(3, cmd.count_atoms('chain A*'))
        self.assertEqual(4, cmd.count_atoms('chain *A'))
        self.assertEqual(5, cmd.count_atoms('chain *A*'))
        self.assertEqual(1, cmd.count_atoms('chain A*A'))
        # B patterns
        self.assertEqual(2, cmd.count_atoms('chain B*'))
        self.assertEqual(2, cmd.count_atoms('chain *B'))
        self.assertEqual(4, cmd.count_atoms('chain *B*'))
        # X patterns (no matches)
        self.assertEqual(0, cmd.count_atoms('chain X*'))
        self.assertEqual(0, cmd.count_atoms('chain *X'))
        self.assertEqual(0, cmd.count_atoms('chain *X*'))
        # list with wildcards
        self.assertEqual(5, cmd.count_atoms('chain B*+A*'))
        self.assertEqual(3, cmd.count_atoms('chain B*+A*A'))
        self.assertEqual(3, cmd.count_atoms('chain B*+A*A+*X'))

        # lexicographical alpha ranges, A:C, will match AB (A <= AB <= C) but not CC (C < CC)
        # no wildcards in alpha ranges possible
        self.assertEqual(6, cmd.count_atoms('chain A:C'))
        self.assertEqual(6, cmd.count_atoms('chain A:CA'))
        self.assertEqual(7, cmd.count_atoms('chain A:CX')) # include CC
        self.assertEqual(6, cmd.count_atoms('chain A:C+Z'))
        self.assertEqual(7, cmd.count_atoms('chain A:C+Z*'))
Exemplo n.º 36
0
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()
Exemplo n.º 37
0
    def testExportStyle(self):
        cmd.fab('ACDEF', 'm1')
        cmd.hide()
        cmd.show('cartoon', 'resi 1-3')
        cmd.show('lines', 'resn CYS')
        cmd.show('sticks', 'resn ASP+PHE')
        cmd.show('spheres', 'resn GLU')
        cmd.set('stick_ball', 1, 'resn PHE')
        cmd.set('stick_ball_ratio', 1.5, 'm1')
        testlabel = 'Hello "World"'
        cmd.label('name SG', repr(testlabel))

        with testing.mktemp('.mae') as filename:
            cmd.save(filename)
            cmd.delete('*')
            cmd.load(filename, 'm2')

        g_labels = []
        cmd.iterate('name SG', 'g_labels.append(label)', space=locals())
        cmd.alter('*', 'b = 1 if s.stick_ball else 0')

        self._assertCountEqual('rep cartoon & guide', 'resi 1-3 & guide')
        self._assertCountEqual('rep lines', 'resn CYS', delta=1)
        self._assertCountEqual('rep sticks', 'resn ASP+PHE')
        self._assertCountEqual('rep spheres', 'resn GLU')
        self._assertCountEqual('b > 0.5', 'resn PHE')
        self.assertTrue(cmd.get_setting_float('stick_ball_ratio', 'm2') > 1.1)
        self.assertEqual(g_labels[0], testlabel)
Exemplo n.º 38
0
def output_PNG(this_PDB_file, OUTPUT_FOLDER_PNG, OUTPUT_FOLDER_SESSION):
  # show complex
  cmd.hide("all")
  cmd.bg_color("white")
  cmd.show("cartoon", "this_complex")
  # show protein A
  cmd.set_color("A_interface_color", [167, 244, 66]) # lightgreen
  cmd.set_color("A_C_term_color", [252, 245, 146])   # pale yellow
  cmd.color("yellow", "chain A")
  cmd.color("A_interface_color", "A_interface")
  cmd.alter("A_center_pseudoatom", "vdw=2")
  cmd.show("sphere", "A_center_pseudoatom")
  cmd.color("green", "A_center_pseudoatom")
  cmd.show("sphere", "A_N_term")
  cmd.color("yellow", "A_N_term")
  cmd.show("sphere", "A_C_term")
  cmd.color("A_C_term_color", "A_C_term")
  # show protein B
  cmd.set_color("B_interface_color", [80, 181, 244]) # medium blue
  cmd.set_color("B_C_term_color", [179, 229, 229])   # pale cyan
  cmd.color("cyan", "chain B")
  cmd.color("B_interface_color", "B_interface")
  cmd.alter("B_center_pseudoatom", "vdw=2")
  cmd.show("sphere", "B_center_pseudoatom")
  cmd.color("blue", "B_center_pseudoatom")
  cmd.show("sphere", "B_N_term")
  cmd.color("cyan", "B_N_term")
  cmd.show("sphere", "B_C_term")
  cmd.color("B_C_term_color", "B_C_term")
  # nice output
  cmd.rebuild()
  cmd.zoom("all")
  cmd.png("%s/%s.png" % (OUTPUT_FOLDER_PNG, this_PDB_file), quiet=1)
  # save session
  cmd.save("%s/%s.pse" % (OUTPUT_FOLDER_SESSION, this_PDB_file))
Exemplo n.º 39
0
def label_chains(selection):
    """
    DESCRIPTION

    Detect and label chains

    USAGE

    label_chains selection

    ARGUMENTS

    selection = name of the selection on which to operate. Atoms outside the selection
                won't be changed
    """
    chainlabels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    cmd.alter(selection, 'chain=""')
    for label in chainlabels:
        space = {'stored': []}
        cmd.iterate('({}) and (chain "")'.format(selection),
                    'stored.append(index)',
                    space=space)
        unnamedindices = space['stored']
        if not unnamedindices:
            break
        cmd.alter(
            '({}) and (bymol (({}) and index {}))'.format(
                selection, selection, unnamedindices[0]),
            'chain="{}"'.format(label))
        cmd.sort()
Exemplo n.º 40
0
    def RefreshDisplay(self):
        
        try:
            # Display the atoms spheres
            cmd.show('spheres', self.LigDisplay)
            cmd.refresh()

            cmd.alter(self.LigDisplay,'vdw=0.25')
            cmd.rebuild(self.LigDisplay)
            cmd.refresh()

            util.cbag(self.LigDisplay)
            cmd.refresh()
            
            if self.AnchorAtom != -1:
                AtomSel = self.LigDisplay + ' & id ' + str(self.AnchorAtom)
                cmd.color('white',AtomSel)
                cmd.refresh()

                cmd.alter(AtomSel ,'vdw=0.30')
                cmd.rebuild(AtomSel)
                cmd.refresh()
                        
        except:
            self.ErrorCode = 1

        return self.ErrorCode
Exemplo n.º 41
0
    def test_wildcard_sets_ranges(self):
        for i in range(10):
            cmd.pseudoatom('m%d' % i, chain=chr(65 + i))
        cmd.alter('m5', 'chain = "AB"')
        cmd.alter('m6', 'chain = "BA"')
        cmd.alter('m7', 'chain = "CC"')
        cmd.alter('m8', 'chain = "ZA"')
        cmd.alter('m9', 'chain = "ABA"')
        # A patterns
        self.assertEqual(1, cmd.count_atoms('chain A'))
        self.assertEqual(3, cmd.count_atoms('chain A*'))
        self.assertEqual(4, cmd.count_atoms('chain *A'))
        self.assertEqual(5, cmd.count_atoms('chain *A*'))
        self.assertEqual(1, cmd.count_atoms('chain A*A'))
        # B patterns
        self.assertEqual(2, cmd.count_atoms('chain B*'))
        self.assertEqual(2, cmd.count_atoms('chain *B'))
        self.assertEqual(4, cmd.count_atoms('chain *B*'))
        # X patterns (no matches)
        self.assertEqual(0, cmd.count_atoms('chain X*'))
        self.assertEqual(0, cmd.count_atoms('chain *X'))
        self.assertEqual(0, cmd.count_atoms('chain *X*'))
        # list with wildcards
        self.assertEqual(5, cmd.count_atoms('chain B*+A*'))
        self.assertEqual(3, cmd.count_atoms('chain B*+A*A'))
        self.assertEqual(3, cmd.count_atoms('chain B*+A*A+*X'))

        # lexicographical alpha ranges, A:C, will match AB (A <= AB <= C) but not CC (C < CC)
        # no wildcards in alpha ranges possible
        self.assertEqual(6, cmd.count_atoms('chain A:C'))
        self.assertEqual(6, cmd.count_atoms('chain A:CA'))
        self.assertEqual(7, cmd.count_atoms('chain A:CX'))  # include CC
        self.assertEqual(6, cmd.count_atoms('chain A:C+Z'))
        self.assertEqual(7, cmd.count_atoms('chain A:C+Z*'))
Exemplo n.º 42
0
 def test_sets_ranges(self):
     cmd.fab('ACDEFGHIKL')
     cmd.alter('resi 9', 'resi="9A"') # insertion code
     self.assertEqual(3, cmd.count_atoms('guide & resi 2-4'))
     self.assertEqual(3, cmd.count_atoms('guide & resi 2:4'))
     self.assertEqual(2, cmd.count_atoms('guide & resi 2+4'))
     self.assertEqual(4, cmd.count_atoms('guide & resi 2-4+6'))
     self.assertEqual(6, cmd.count_atoms('guide & resi 2-4+6-8'))
     self.assertEqual(0, cmd.count_atoms('guide & resi 9'))
     self.assertEqual(1, cmd.count_atoms('guide & resi 9A'))
     self.assertEqual(1, cmd.count_atoms('guide & resi 10'))
     self.assertEqual(0, cmd.count_atoms('guide & resi 10A'))
     self.assertEqual(2, cmd.count_atoms('guide & resi 9-10'))
     self.assertEqual(2, cmd.count_atoms('guide & resi 9A-10A'))
     self.assertEqual(10 + 9, cmd.count_atoms('name CA+CB'))
     self.assertEqual(10 + 9, cmd.count_atoms('name CA+CB+XYZ'))
     self.assertEqual(10, cmd.count_atoms('name C'))
     self.assertEqual(50, cmd.count_atoms('name C*'))
     self.assertEqual(10, cmd.count_atoms('name H'))
     self.assertEqual(24, cmd.count_atoms('name H*'))
     self.assertEqual(10, cmd.count_atoms('name *H'))
     self.assertEqual(74, cmd.count_atoms('name *H*'))
     self.assertEqual(20, cmd.count_atoms('name C+N'))
     self.assertEqual(23, cmd.count_atoms('name C+N*'))
     self.assertEqual(60, cmd.count_atoms('name C*+N'))
     self.assertEqual(63, cmd.count_atoms('name C*+N*'))
Exemplo n.º 43
0
 def test_sets_ranges(self):
     cmd.fab('ACDEFGHIKL')
     cmd.alter('resi 9', 'resi="9A"')  # insertion code
     self.assertEqual(3, cmd.count_atoms('guide & resi 2-4'))
     self.assertEqual(3, cmd.count_atoms('guide & resi 2:4'))
     self.assertEqual(2, cmd.count_atoms('guide & resi 2+4'))
     self.assertEqual(4, cmd.count_atoms('guide & resi 2-4+6'))
     self.assertEqual(6, cmd.count_atoms('guide & resi 2-4+6-8'))
     self.assertEqual(0, cmd.count_atoms('guide & resi 9'))
     self.assertEqual(1, cmd.count_atoms('guide & resi 9A'))
     self.assertEqual(1, cmd.count_atoms('guide & resi 10'))
     self.assertEqual(0, cmd.count_atoms('guide & resi 10A'))
     self.assertEqual(2, cmd.count_atoms('guide & resi 9-10'))
     self.assertEqual(2, cmd.count_atoms('guide & resi 9A-10A'))
     self.assertEqual(10 + 9, cmd.count_atoms('name CA+CB'))
     self.assertEqual(10 + 9, cmd.count_atoms('name CA+CB+XYZ'))
     self.assertEqual(10, cmd.count_atoms('name C'))
     self.assertEqual(50, cmd.count_atoms('name C*'))
     self.assertEqual(10, cmd.count_atoms('name H'))
     self.assertEqual(24, cmd.count_atoms('name H*'))
     self.assertEqual(10, cmd.count_atoms('name *H'))
     self.assertEqual(74, cmd.count_atoms('name *H*'))
     self.assertEqual(20, cmd.count_atoms('name C+N'))
     self.assertEqual(23, cmd.count_atoms('name C+N*'))
     self.assertEqual(60, cmd.count_atoms('name C*+N'))
     self.assertEqual(63, cmd.count_atoms('name C*+N*'))
Exemplo n.º 44
0
def number_chains(selection='all', numbers='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    """
    DESCRIPTION

    Find chains and number them consecutively

    USAGE

    number_chains [selection [, numbers]]

    ARGUMENTS

    selection = the selection in which this function operates

    numbers = list of symbols to be applied. Defaults to capital letters of the ABC
    """
    cmd.alter(selection, 'chain=""')
    chains = iter(numbers)
    foundchains = []
    logger.debug('Finding chains among {} atoms'.format(
        cmd.count_atoms(selection)))
    for idx in iterate_indices(selection):
        if get_chain(idx, selection):
            # if this atom already has a chain ID set, continue with the next atom.
            continue
        foundchains.append(next(chains))
        cmd.alter('(bymol idx {}) and ({})'.format(idx, selection),
                  'chain="{}"'.format(foundchains[-1]))
    cmd.sort(selection)
    logger.debug('Found chains: ' + ', '.join([str(c) for c in foundchains]))
    return foundchains
Exemplo n.º 45
0
def hilightPolar(sel='all'):
	N = "elem N"# and (not name N)"
	O = "elem O"# and (not name O)" # want to inlude look BB atoms...
	S = "elem S"
	sel = sel + " and " + N+" or "+O+" or "+S
	cmd.alter(sel,"vdw=0.3")
	cmd.rebuild()
	cmd.show('spheres',sel)
Exemplo n.º 46
0
def mkc2(sel, a=Vec(0, 0, 1), c=Vec(0, 0, 0)):
    cmd.delete("c1")
    cmd.delete("c2")
    cmd.create("c1", sel)
    cmd.create("c2", sel)
    rot("c2", a, 180, c)
    cmd.alter("c1", 'chain = "A"')
    cmd.alter("c2", 'chain = "B"')
Exemplo n.º 47
0
 def colorByProp(self, prop, palette="rainbow"):
     stored.propUniqVals = set()
     cmd.iterate(self.objName, "stored.propUniqVals.add(%s)" % prop)
     v = sorted(stored.propUniqVals)
     b = n.arange(1, len(v) + 1, dtype=float)  # / len(v)
     stored.b = dict(zip(v, b))
     cmd.alter(self.objName, "b=stored.b[%s]" % prop)
     cmd.spectrum("b", palette, self.objName)
Exemplo n.º 48
0
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()
Exemplo n.º 49
0
def renumber(selection='all', start=1, startsele=None, quiet=1):
    '''
DESCRIPTION

    Set residue numbering (resi) based on connectivity.

ARGUMENTS

    selection = string: atom selection to renumber {default: all}

    start = integer: counting start {default: 1}

    startsele = string: residue to start counting from {default: first in
    selection}
    '''
    start, quiet = int(start), int(quiet)
    model = cmd.get_model(selection)
    cmd.iterate(selection, 'atom_it.next().model = model',
                space={'atom_it': iter(model.atom)})
    if startsele is not None:
        startidx = cmd.index('first (' + startsele + ')')[0]
        for atom in model.atom:
            if (atom.model, atom.index) == startidx:
                startatom = atom
                break
        else:
            print(' Error: startsele not in selection')
            raise CmdException
    else:
        startatom = model.atom[0]
    for atom in model.atom:
        atom.adjacent = []
        atom.visited = False
    for bond in model.bond:
        atoms = [model.atom[i] for i in bond.index]
        atoms[0].adjacent.append(atoms[1])
        atoms[1].adjacent.append(atoms[0])
    minmax = [start, start]

    def traverse(atom, resi):
        atom.resi = resi
        atom.visited = True
        for other in atom.adjacent:
            if other.visited:
                continue
            if (atom.name, other.name) in [('C', 'N'), ("O3'", 'P')]:
                minmax[1] = resi + 1
                traverse(other, resi + 1)
            elif (atom.name, other.name) in [('N', 'C'), ('P', "O3'")]:
                minmax[0] = resi - 1
                traverse(other, resi - 1)
            elif (atom.name, other.name) not in [('SG', 'SG')]:
                traverse(other, resi)
    traverse(startatom, start)
    cmd.alter(selection, 'resi = atom_it.next().resi',
              space={'atom_it': iter(model.atom)})
    if not quiet:
        print(' Renumber: range (%d to %d)' % tuple(minmax))
Exemplo n.º 50
0
 def test_sort(self):
     cmd.pseudoatom('m1', name='PS2')
     cmd.pseudoatom('m1', name='PS1')
     cmd.alter('all', 'name = name_list.pop()', space={'name_list': ['PS1', 'PS2']})
     v = [a.name for a in cmd.get_model().atom]
     self.assertEqual(['PS2', 'PS1'], v)
     cmd.sort()
     v = [a.name for a in cmd.get_model().atom]
     self.assertEqual(['PS1', 'PS2'], v)
Exemplo n.º 51
0
def makecx(sel="all", n=5):
    cmd.delete("C%i_*" % n)
    chains = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    for i in range(n):
        cmd.create("C%i_%i" % (n, i), sel + " and (not C%i_*)" % n)
    for i in range(n):
        rot("C%i_%i" % (n, i), Z, 360.0 * float(i) / float(n))
    for i in range(n):
        cmd.alter("C%i_%i" % (n, i), "chain = '%s'" % chains[i])
Exemplo n.º 52
0
def build(object_name, sequence, first_residue = "1"):
   if len(sequence):
      code = sequence[0]
      cmd.fragment(aa_dict[code],object_name)
      cmd.alter(object_name,'resi="%s"'%first_residue)
      cmd.edit(object_name+" and name C")
      for code in sequence[1:]:
         editor.attach_amino_acid("pk1",aa_dict[code])
      cmd.edit()
Exemplo n.º 53
0
    def testMacros(self):
        '''
        Test selection macros: /model/segi/chain/resn`resi/name`alt

        See also tests/jira/PYMOL-2720.py
        '''
        cmd.load(self.datafile("1oky.pdb.gz"), "m1")
        cmd.alter('*', 'segi="X"')
        cmd.alter('resi 200-238', 'chain="B"')
        cmd.alter('resi 239-360', 'chain="C"')
        cmd.alter('resi 150-220', 'segi="Y"')
        cmd.alter('resi 220-', 'segi="Z"')

        # all atoms
        self.assertEqual(cmd.count_atoms('/'), cmd.count_atoms())
        self.assertEqual(cmd.count_atoms('/////'), cmd.count_atoms())

        # model
        self.assertEqual(cmd.count_atoms('/m1'), cmd.count_atoms('all'))
        self.assertEqual(cmd.count_atoms('m1////'), cmd.count_atoms('all'))

        # segi
        self.assertEqual(cmd.count_atoms('//Y'), cmd.count_atoms('segi Y'))
        self.assertEqual(cmd.count_atoms('//Y+Z'), cmd.count_atoms('segi Y+Z'))

        # chains
        self.assertEqual(cmd.count_atoms('///B'), cmd.count_atoms('chain B'))
        self.assertEqual(cmd.count_atoms('///A+B'), cmd.count_atoms('chain A+B'))

        # resn/resi
        self.assertEqual(cmd.count_atoms('////100'), cmd.count_atoms('resi 100'))
        self.assertEqual(cmd.count_atoms('////`100'), cmd.count_atoms('resi 100'))
        self.assertEqual(cmd.count_atoms('////100-110'), cmd.count_atoms('resi 100-110'))
        self.assertEqual(cmd.count_atoms('////ARG`100'), cmd.count_atoms('resi 100'))
        self.assertEqual(cmd.count_atoms('////ALA'), cmd.count_atoms('resn ALA'), )
        self.assertEqual(cmd.count_atoms('ALA/'), cmd.count_atoms('resn ALA'), )
        self.assertEqual(cmd.count_atoms('////ALA`'), cmd.count_atoms('resn ALA'))
        self.assertEqual(cmd.count_atoms('////ALA+GLU'), cmd.count_atoms('resn ALA+GLU'), )

        # name/alt
        self.assertEqual(cmd.count_atoms('/////CG'), cmd.count_atoms('name CG'))
        self.assertEqual(cmd.count_atoms('*/CG'), cmd.count_atoms('name CG'))
        self.assertEqual(cmd.count_atoms('/////CG`B'), cmd.count_atoms('name CG & alt B'))
        self.assertEqual(cmd.count_atoms('/////`B'), cmd.count_atoms('alt B'))

        # combies
        self.assertEqual(cmd.count_atoms('100/CA'), cmd.count_atoms('resi 100 & name CA'))
        self.assertEqual(cmd.count_atoms('A//CA'), cmd.count_atoms('chain A & name CA'))
        self.assertEqual(cmd.count_atoms('A//`B'), cmd.count_atoms('chain A & alt B'))
        self.assertEqual(cmd.count_atoms('/m1/Y/B/*/CA'), cmd.count_atoms('segi Y & chain B & name CA'))

        # or-logic
        ref = cmd.count_atoms('(resi 100 & name CA) (resi 110 & name CB)')
        self.assertEqual(cmd.count_atoms('100/CA|110/CB'), ref)
        self.assertEqual(cmd.count_atoms('100/CA or 110/CB'), ref)
        self.assertEqual(cmd.count_atoms('100/CA 110/CB'), ref)
Exemplo n.º 54
0
def load_weights():
    file_weights = open_it()
    i = 0
    for line in open(file_weights, "r"):
        i = i + 1
        selec = "resi " + str(i)
        ocup = line.split()
        cmd.alter(selec, "b=" + ocup[0])

    cmd.spectrum("b", "blue_red")
Exemplo n.º 55
0
def test_remove_alt():
    cmd.reinitialize()
    cmd.fab('AC', 'm1')
    cmd.alter('resn ALA', 'alt="A"')
    cmd.alter('resn CYS', 'alt="B"')
    cmd.create('m2', 'm1')
    psico.editing.remove_alt('m1')
    psico.editing.remove_alt('m2', keep='B')
    assert cmd.count_atoms('m1') == 10
    assert cmd.count_atoms('m2') == 11
Exemplo n.º 56
0
def aaindex2b(key, selection='all', var='b', quiet=1):
    '''
DESCRIPTION

    Looks up the Amino Acid Index from http://www.genome.jp/aaindex/
    for the given key and assignes b-factors to the given selection. Unknown
    residues get the average index value assigned.

USAGE

    aaindex2b key [, selection ]

ARGUMENTS

    key = string: Key of AAindex entry

    selection = string: atoms to assign b-factors {default: (all)}

EXAMPLE

    # Hydropathy index by Kyte-Doolittle
    aaindex2b KYTJ820101
    spectrumany b, white yellow forest
    show surface

SEE ALSO

    hydropathy2b
    '''
    _assert_package_import()
    from . import one_letter

    quiet = int(quiet)

    aaindex = _get_aaindex1()

    try:
        entry = aaindex[key]
    except KeyError:
        print(' Error: No such key in AAindex:', key)
        raise CmdException

    median = entry.median()

    if not quiet:
        print(entry.desc.strip())

    def lookup(resn):
        aa = one_letter.get(resn, 'X')
        value = entry.get(aa)
        if value is None:
            return median
        return value

    cmd.alter(selection, var + '=lookup(resn)', space=locals())
Exemplo n.º 57
0
def ens_prob():
  print '\n\nEnsemble probability options'
  # get models, mean coords
  models = []
  selection = 'all'
  for i in range(cmd.count_states(selection)):
    models.append(cmd.get_model(selection,state=i+1))

  for n, model in enumerate(models):
    residues = model.get_residues()
    for residue in residues:
      # Get individual atom info
      q_list = []
      q_list_mc  = []
      q_list_sc = []
      for i_seq in range (residue[0], residue[1]):
        # Ignore hydrogens
        if model.atom[i_seq].symbol != 'H':
          q_list.append(float(model.atom[i_seq].q))
          if model.atom[i_seq].name in ['N','CA','C','O']:
            q_list_mc.append(float(model.atom[i_seq].q))
          else:
            q_list_sc.append(float(model.atom[i_seq].q))

      # Set probability per residue
      # Mean p
      if len(q_list) > 0:    p_new = sum(q_list) / len(q_list)
      if len(q_list_mc) > 0: p_new_mc = sum(q_list_mc) / len(q_list_mc)
      if len(q_list_sc) > 0: p_new_sc = sum(q_list_sc) / len(q_list_sc)

#      # Joint
      p_new = q_list[0]
      for p in q_list[1:]:
        p_new *= p

#      # nll
#      p_new = math.log(q_list[0])
#      for p in q_list[1:]:
#        p_new += math.log(max(p,0.001))
#      p_new *= -1

      if i_seq == residue[1]-1:
        for i_seq in range (residue[0], residue[1]):
          if True:
            atom_sel = 'id ' + str(model.atom[i_seq].id) + ' and state ' + str(n+1)
            atom_action = 'b = ' + str(p_new)
            cmd.alter(atom_sel, atom_action)
          else:
            atom_sel = 'id ' + str(model.atom[i_seq].id) + ' and state ' + str(n+1)
            if model.atom[i_seq].name in ['N','CA','C','O']:
              atom_action = 'b = ' + str(p_new_mc)
            else:
              atom_action = 'b = ' + str(p_new_sc)
            cmd.alter(atom_sel, atom_action)
Exemplo n.º 58
0
def test_update_identifiers():
    cmd.reinitialize()
    cmd.fab('ACD', 'm1')
    cmd.fab('ACD', 'm2')
    cmd.remove('m1 and not backbone')
    cmd.alter('m1', '(segi, chain) = ("Segi", "Chain")')
    psico.editing.update_identifiers('m2', 'm1', identifiers='segi chain')
    assert cmd.get_chains('m2') == ['Chain']
    my_values = []
    cmd.iterate('m2', 'my_values.append(segi)', space=locals())
    assert set(my_values) == set(["Segi"])