Beispiel #1
0
def get_SASA(pdbfile, pdb1='pdb1'):
    ## set
    cmd.load(pdbfile, pdb1)
    oldDS = cmd.get("dot_solvent")
    cmd.h_add()
    cmd.flag("ignore", "none")
    cmd.set("dot_solvent", 1)
    cmd.set("dot_density", 2)
    cmd.set("solvent_radius", 3)

    ## calculate
    area = cmd.get_area(pdb1, load_b=1)
    stored.r = []
    cmd.iterate(pdb1, 'stored.r.append((model,chain,resi,resn,name,b))')
    areas = {}
    for model, chain, idx, char, name, sasa in stored.r:
        if idx == '653':
            print chain, idx, char, name, sasa
        base = areas.get((chain, idx, char), 0)
        if (char == 'A' and name == 'N1') or (char == 'C' and name == 'N3'):
            base += float(sasa)
        areas[(chain, idx, char)] = base

    ## reset
    cmd.set("dot_solvent", oldDS)
    cmd.delete(pdb1)
    print pdbfile, area, sum(areas.values())
    return areas
Beispiel #2
0
    def test(self):
        cmd.fab('AG')
        cmd.remove('hydro')
        cmd.h_add('resn ALA')

        # with this bug: count = 6
        self.assertEqual(11, cmd.count_atoms('byres (last hydro)'))
Beispiel #3
0
def load():
   cmd.set("valence")
   r = 0
   list = glob("pdb/*/*")

#   list = ["pdb/06/pdb406d"]
#   while list[0]!="pdb/f8/pdb1f8u":
#      list.pop(0)
   for file in list:
      cmd.delete('pdb')
      cmd.load(file,'pdb')
      cmd.remove("not alt ''+A")
      cmd.fix_chemistry("all","all")
      cmd.h_add()
      sys.__stderr__.write(file)
      sys.__stderr__.flush()
      ch = Champ()
      model = cmd.get_model('pdb')
      idx = ch.insert_model(model)

      ch.pattern_orient_bonds(idx)
      print " %5d"%cmd.count_atoms(),"%5d"%len(ch.pattern_get_string(idx)),
      ch.pattern_detect_chirality(idx)
      pat = ch.pattern_get_string(idx)
      print "%5d"%len(pat),pat[0:22]+"..."+pat[-10:]
Beispiel #4
0
def fSumWMCresidue(molecule, SGNameAngle, chain, residue, MCNeighbour,
                   DieElecMC, MCchargeC, MCchargeO, MCchargeN, MCchargeH,
                   AmideName, printMC):
    # print "residue", MCNeighbour
    SumWMCresidue = 0.0
    SGnameselect = "/" + SGNameAngle + "//" + "/" + "/SG"
    NBnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour)
    cmd.select("MC", NBnameselect)
    MCpdbstr = cmd.get_pdbstr("MC")
    MCsplit = MCpdbstr.split()
    residueName = MCsplit[3]
    # print NBnameselect, residueName
    AmideProt = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/H01"
    Hnameselect = "/" + AmideName + "//" + chain + "/" + str(
        MCNeighbour) + "/H01"
    if cmd.count_atoms(AmideProt) == 0 and cmd.count_atoms(Hnameselect) == 0:
        HbuildSelect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/N"
        cmd.h_add(HbuildSelect)
        cmd.create(AmideName, AmideName + " + " + AmideProt)
        cmd.remove(AmideProt)
    # Mainchain AmideH
    ResDist = cmd.dist(residue + 'distResH', SGnameselect, Hnameselect)
    WMC = fWMC(MCchargeH, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC H ", MCNeighbour, " ", MCchargeH, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    # Mainchain C
    Cnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/C"
    ResDist = cmd.dist(residue + 'distResC', SGnameselect, Cnameselect)
    WMC = fWMC(MCchargeC, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC C ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    # Mainchain O
    Onameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/O"
    ResDist = cmd.dist(residue + 'distResO', SGnameselect, Onameselect)
    WMC = fWMC(MCchargeO, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC O ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    # Mainchain N
    Nnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/N"
    ResDist = cmd.dist(residue + 'distResN', SGnameselect, Nnameselect)
    WMC = fWMC(MCchargeN, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC N ", MCNeighbour, " ", MCchargeN, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    cmd.delete(residue + 'distResH')
    cmd.delete(residue + 'distResC')
    cmd.delete(residue + 'distResO')
    cmd.delete(residue + 'distResN')
    cmd.show("nb_spheres", AmideName)
    cmd.delete("MC")
    return SumWMCresidue
Beispiel #5
0
def addHydrogens(model):
    objname = '__tmp{}'.format(random.randint(0, 100000))
    cmd.delete(objname)
    cmd.load_model(model, objname)
    cmd.h_add('model {}'.format(objname))
    model = cmd.get_model(objname)
    cmd.delete(objname)
    return model
Beispiel #6
0
def fSumWMCLast(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC, MCchargeN, MCchargeH, MCchargeProCA, MCchargeProCD, MCchargeProN, AmideName, printMC):
	#print "Last", MCNeighbour
	SumWMCLast = 0.0
	SGnameselect = "/"+SGNameAngle+"//"+"/"+"/SG"
	NBnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)
	cmd.select("MC", NBnameselect)
	MCpdbstr = cmd.get_pdbstr("MC")
	MCsplit = MCpdbstr.split()
	residueName = MCsplit[3]
	#print NBnameselect, residueName
	if residueName == "PRO":
		### Proline CA
		CAnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/CA"
		ResDist = cmd.dist(residue+'distLastProCA', SGnameselect,CAnameselect)
		WMC = fWMC(MCchargeProCA, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC ProCA ", MCNeighbour, " ", MCchargeProCA, " ", DieElecMC, " ", ResDist, " ", WMC
		### Proline CD
		CDnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/CD"
		ResDist = cmd.dist(residue+'distLastProCD', SGnameselect,CDnameselect)
		WMC = fWMC(MCchargeProCD, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC ProCD ", MCNeighbour, " ", MCchargeProCD, " ", DieElecMC, " ", ResDist, " ", WMC
		### Proline N
		Nnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/N"
		ResDist = cmd.dist(residue+'distLastProN', SGnameselect,Nnameselect)
		WMC = fWMC(MCchargeProN, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC ProN ", MCNeighbour, " ", MCchargeProN, " ", DieElecMC, " ", ResDist, " ", WMC
	else:
		AmideProt = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/H01"
		Hnameselect = "/"+AmideName+"//"+chain+"/"+str(MCNeighbour)+"/H01"
		if cmd.count_atoms(AmideProt) == 0 and cmd.count_atoms(Hnameselect) == 0:
			HbuildSelect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/N"
			cmd.h_add(HbuildSelect)
			cmd.create(AmideName, AmideName+" + "+AmideProt)
			cmd.remove(AmideProt)
		### Mainchain AmideH
		ResDist = cmd.dist(residue+'distLastH', SGnameselect,Hnameselect)
		WMC = fWMC(MCchargeH, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC H ", MCNeighbour, " ", MCchargeH, " ", DieElecMC, " ", ResDist, " ", WMC
		### Mainchain N
		Nnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/N"
		ResDist = cmd.dist(residue+'distLastN', SGnameselect,Nnameselect)
		WMC = fWMC(MCchargeN, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC N ", MCNeighbour, " ", MCchargeN, " ", DieElecMC, " ", ResDist, " ", WMC
	cmd.delete(residue+'distLastProCA')
	cmd.delete(residue+'distLastProCD')
	cmd.delete(residue+'distLastProN')
	cmd.delete(residue+'distLastH')
	cmd.delete(residue+'distLastN')
	cmd.show("nb_spheres", AmideName)
	cmd.delete("MC")
	return SumWMCLast
def fSumWMCresidue(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC, MCchargeC, MCchargeO, MCchargeN, MCchargeH, AmideName, printMC):
    # print "residue", MCNeighbour
    SumWMCresidue = 0.0
    SGnameselect = "/" + SGNameAngle + "//" + "/" + "/SG"
    NBnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour)
    cmd.select("MC", NBnameselect)
    MCpdbstr = cmd.get_pdbstr("MC")
    MCsplit = MCpdbstr.split()
    residueName = MCsplit[3]
    # print NBnameselect, residueName
    AmideProt = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/H01"
    Hnameselect = "/" + AmideName + "//" + chain + "/" + str(MCNeighbour) + "/H01"
    if cmd.count_atoms(AmideProt) == 0 and cmd.count_atoms(Hnameselect) == 0:
        HbuildSelect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/N"
        cmd.h_add(HbuildSelect)
        cmd.create(AmideName, AmideName + " + " + AmideProt)
        cmd.remove(AmideProt)
    # Mainchain AmideH
    ResDist = cmd.dist(residue + 'distResH', SGnameselect, Hnameselect)
    WMC = fWMC(MCchargeH, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC H ", MCNeighbour, " ", MCchargeH, " ", DieElecMC, " ", ResDist, " ", WMC)
    # Mainchain C
    Cnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/C"
    ResDist = cmd.dist(residue + 'distResC', SGnameselect, Cnameselect)
    WMC = fWMC(MCchargeC, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC C ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ", ResDist, " ", WMC)
    # Mainchain O
    Onameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/O"
    ResDist = cmd.dist(residue + 'distResO', SGnameselect, Onameselect)
    WMC = fWMC(MCchargeO, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC O ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ", ResDist, " ", WMC)
    # Mainchain N
    Nnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/N"
    ResDist = cmd.dist(residue + 'distResN', SGnameselect, Nnameselect)
    WMC = fWMC(MCchargeN, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC N ", MCNeighbour, " ", MCchargeN, " ", DieElecMC, " ", ResDist, " ", WMC)
    cmd.delete(residue + 'distResH')
    cmd.delete(residue + 'distResC')
    cmd.delete(residue + 'distResO')
    cmd.delete(residue + 'distResN')
    cmd.show("nb_spheres", AmideName)
    cmd.delete("MC")
    return SumWMCresidue
Beispiel #8
0
    def test_h_add_state(self):
        nheavy = 4
        nhydro = 5
        nfull = nheavy + nhydro

        cmd.fragment('gly', 'm1')
        cmd.remove('hydro')
        self.assertEqual(nheavy, cmd.count_atoms())
        cmd.h_add()
        self.assertEqual(nfull, cmd.count_atoms())

        # multi-state
        cmd.remove('hydro')
        cmd.create('m1', 'm1', 1, 2)
        cmd.create('m1', 'm1', 1, 3)
        cmd.h_add(state=2)
        self.assertEqual(nfull, cmd.count_atoms())
        self.assertEqual(nheavy, cmd.count_atoms('state 1'))
        self.assertEqual(nfull, cmd.count_atoms('state 2'))
        self.assertEqual(nheavy, cmd.count_atoms('state 3'))

        # discrete multi-state
        cmd.remove('hydro')
        cmd.create('m2', 'm1', 1, 1, discrete=1)
        cmd.create('m2', 'm2', 1, 2, discrete=1)
        cmd.create('m2', 'm2', 1, 3, discrete=1)
        self.assertEqual(nheavy * 3, cmd.count_atoms('m2'))
        cmd.h_add('m2 & state 2')  # TODO , state=2)
        self.assertEqual(nfull + nheavy * 2, cmd.count_atoms('m2'))
        self.assertEqual(nheavy, cmd.count_atoms('m2 & state 1'))
        self.assertEqual(nfull, cmd.count_atoms('m2 & state 2'))
        self.assertEqual(nheavy, cmd.count_atoms('m2 & state 3'))
        cmd.h_add('m2')
        self.assertEqual(nfull * 3, cmd.count_atoms('m2'))
Beispiel #9
0
    def test_h_add_state(self):
        nheavy = 4
        nhydro = 5
        nfull = nheavy + nhydro

        cmd.fragment('gly', 'm1')
        cmd.remove('hydro')
        self.assertEqual(nheavy, cmd.count_atoms())
        cmd.h_add()
        self.assertEqual(nfull, cmd.count_atoms())

        # multi-state
        cmd.remove('hydro')
        cmd.create('m1', 'm1', 1, 2)
        cmd.create('m1', 'm1', 1, 3)
        cmd.h_add(state=2)
        self.assertEqual(nfull, cmd.count_atoms())
        self.assertEqual(nheavy, cmd.count_atoms('state 1'))
        self.assertEqual(nfull, cmd.count_atoms('state 2'))
        self.assertEqual(nheavy, cmd.count_atoms('state 3'))

        # discrete multi-state
        cmd.remove('hydro')
        cmd.create('m2', 'm1', 1, 1, discrete=1)
        cmd.create('m2', 'm2', 1, 2, discrete=1)
        cmd.create('m2', 'm2', 1, 3, discrete=1)
        self.assertEqual(nheavy * 3, cmd.count_atoms('m2'))
        cmd.h_add('m2 & state 2') # TODO , state=2)
        self.assertEqual(nfull + nheavy * 2, cmd.count_atoms('m2'))
        self.assertEqual(nheavy, cmd.count_atoms('m2 & state 1'))
        self.assertEqual(nfull, cmd.count_atoms('m2 & state 2'))
        self.assertEqual(nheavy, cmd.count_atoms('m2 & state 3'))
        cmd.h_add('m2')
        self.assertEqual(nfull * 3, cmd.count_atoms('m2'))
def disp_ball_stick(selection='all', hydrogens=0, only=False):
    '''
DESCRIPTION

    Formats the passed object into ball and stick

USEAGE

    disp_ball_stick [ selection [, hydrogens [, only ]]]

EXAMPLE

    fetch 1hpv, async=0
    disp_ball_stick
    util.cbaw

PARAMETERS

    NAME=DEFAULT       TYPE    FUNCTION
    selection='all'    <str>   input selection
    hydrogens          <int>   -1: remove; 1: add; else: as is
    only=False         <bool>  if True will use show_as; else show

    '''
    try:
        selection = '(' + selection + ')'
        hydrogens = int(hydrogens)
        only = bool(str(only) != 'False')
    except:
        print("Input error")
        return False

    if hydrogens == 1:
        cmd.h_add('%s' % selection)
    if hydrogens == -1:
        cmd.remove('%s and elem H' % selection)

    for p in cmd.get_object_list(selection):
        cmd.set('valence', 'on', p)
        cmd.set('stick_ball', 'on', p)
        cmd.set('stick_ball_ratio', 3, p)
        cmd.set('stick_radius', 0.12, p)

    if only:
        cmd.show_as('sticks', '%s' % (selection))
    else:
        cmd.show('sticks', '%s' % (selection))
Beispiel #11
0
def disp_ball_stick( selection='all' , hydrogens=0, only=False):
    '''
DESCRIPTION

    Formats the passed object into ball and stick

USEAGE

    disp_ball_stick [ selection [, hydrogens [, only ]]]

EXAMPLE

    fetch 1hpv, async=0
    disp_ball_stick
    util.cbaw

PARAMETERS

    NAME=DEFAULT       TYPE    FUNCTION
    selection='all'    <str>   input selection
    hydrogens          <int>   -1: remove; 1: add; else: as is
    only=False         <bool>  if True will use show_as; else show

    '''
    try:
        selection='('+selection+')'
        hydrogens=int(hydrogens)
        only=bool(str(only)!='False')
    except:
        print "Input error"
        return False

    if hydrogens==1:
        cmd.h_add('%s' %selection)
    if hydrogens==-1:
        cmd.remove('%s and elem H' %selection)
  
    for p in cmd.get_object_list(selection):
        cmd.set('valence', 'on', p)
        cmd.set('stick_ball', 'on', p)
        cmd.set('stick_ball_ratio', 3, p)
        cmd.set('stick_radius', 0.12, p)

    if only:
        cmd.show_as('sticks', '%s' %(selection))
    else:
        cmd.show('sticks', '%s' %(selection))
Beispiel #12
0
def buildGraph(atomlist: List[Atom]) -> nx.Graph:
    """
    turns the given molecule (list of atoms) into a network graph

    Args:
        atomlist (list of Atoms): all Atoms belonging to a molecule

    Returns:
        networkx.Graph
    """

    visitedAtoms = []
    queue = atomlist
    graph = nx.Graph()
    cmd.h_add()

    while len(queue) != 0:
        stored.currNeighbor = []
        currentNode = queue.pop(-1)
        cmd.select("neighborSelection",
                   f"neighbor {currentNode.identifierString}")
        stored.currentResn = currentNode.resn
        cmd.iterate_state(-1, "neighborSelection", """\
if resn == stored.currentResn:
	stored.currNeighbor.append(Atom(x, y, z, model, chain, resn, resi, name, elem))
""")

        graph.add_node(currentNode.identifierString,
                       element=currentNode.element, charge=0)

        for atom in stored.currNeighbor:
            graph.add_edge(currentNode.identifierString, atom.identifierString)

            if atom.identifierString not in visitedAtoms:
                visitedAtoms.append(atom.identifierString)
                queue.append(atom)

    ps.fill_valence(graph, respect_hcount=True, respect_bond_order=False)

    cmd.remove("hydro")
    return graph
def save_image(spath, name_maxlength, prefix = ''):
    fname = os.path.splitext(os.path.basename(spath))[0]
    image_name = prefix + image_filename(fname, name_maxlength)
    if exists(image_name):
        print 'Skip: ' + fname
    else:
        print 'Process: ' + fname
        cmd.load(spath, fname)
        cmd.disable('all')
        cmd.enable(fname)

        cmd.color('green', fname)
        cmd.h_add('(all)')
        cmd.show('surface')

        cmd.rotate([-1, 0.5, 0.5], 60)
        cmd.zoom(fname, -7.0, 0, 1)

        cmd.png(image_name)
        time.sleep(3) # wtf?!
        cmd.delete('all')
def save_image(spath, name_maxlength, prefix=''):
    fname = spath.split('/')[-1].split('.')[0]
    image_name = prefix + image_filename(fname, name_maxlength)
    if exists(image_name):
        print 'Skip: ' + fname
    else:
        print 'Process: ' + fname
        cmd.load(spath, fname)
        cmd.disable('all')
        cmd.enable(fname)

        cmd.color('green', fname)
        cmd.h_add('(all)')
        cmd.show('surface')

        cmd.rotate([-1, 0.5, 0.5], 60)
        cmd.zoom(fname, -7.0, 0, 1)

        cmd.png(image_name)
        time.sleep(3)  # wtf?!
        cmd.delete('all')
Beispiel #15
0
    def convert(self):

        if hasattr(self, 'path_pdbqt'):
            return self.path_pdbqt
        else:
            self.path_pdbqt = Protein(self.with_suffix('.pdbqt'))
            setattr(self.path_pdbqt, 'path_pdbqt', self.path_pdbqt)
            cmd.load(self.__str__())
            cmd.remove('resn HOH')
            cmd.h_add(selection='acceptors or donors')
            cmd.save(self.__str__())
            mols = list(pybel.readfile('pdb', self.path_clean.__str__()))
            writer = pybel.Outputfile(
                'pdbqt', self.path_pdbqt.__str__(), opt={'pdbqt': '-xh'}
            )
            for molecule in mols:
                writer.write(molecule)
                writer.close()
            cmd.reinitialize()
        os.remove(self)

        return self.path_pdbqt
Beispiel #16
0
    # sort the list for easier reading
    hb.sort(lambda x, y: (cmp(x[0][1], y[0][1])))

    for pairs in hb:
        cmd.iterate("%s and index %s" % (pairs[0][0], pairs[0][1]),
                    'print "%1s/%3s`%s/%-4s " % (chain,resn,resi,name),')
        cmd.iterate("%s and index %s" % (pairs[1][0], pairs[1][1]),
                    'print "%1s/%3s`%s/%-4s " % (chain,resn,resi,name),')
        print "%.2f" % cmd.distance(
            hb_list_name, "%s and index %s" %
            (pairs[0][0], pairs[0][1]), "%s and index %s" %
            (pairs[1][0], pairs[1][1]))


#cmd.extend("list_hb",list_hb)
#if __name__ == "__main__":
cmd.load("E:/yunpan/docking/1hsg_prot.pdb", "1hsg")
cmd.h_add("(1hsg)")
cmd.load("E:/yunpan/docking/indinavir.pdbqt", "indinavir")
cmd.h_add("(indinavir)")
h_donator = "elem n,o & (neighbor hydro)"
h_acceptor = "elem o | (elem n & !(neighbor hydro))"

lacc = "indinavir & (elem o | (elem n & !(neighbor hydro)))"
ldon = "indinavir & (elem n,o & (neighbor hydro))"
pacc = "1hsg & (elem o | (elem n & !(neighbor hydro)))"
pdon = "1hsg & (elem n,o & (neighbor hydro))"

list_hb(ldon, pacc, hb_list_name="l2p_hbonds", mode=0)
list_hb(lacc, pdon, hb_list_name="p2l_hbonds", mode=0)
def disp_mesh(selection='all',
              color_m='default',
              hydrogens=0,
              only=False,
              limits=5):
    '''
DESCRIPTION

    Adds a mesh to the object
    Has advanced coloring options and automatically accounts for the hydrogens

USEAGE

    disp_mesh [ selection [, color_m [, hydrogens [, only [, limits]]]]]
    disp_mesh selection=all, color_m=default
    disp_mesh selection=all, color_m=white
    disp_mesh selection=all, color_m=putty

PARAMETERS

    NAME=DEFAULT       TYPE    FUNCTION
    selection='all'    <str>   input selection
    color_m='default'  <str>   'default': as current
                               'name': colors by color or ramp called name
                               'putty': b-factor on surface
    hydrogens=0        <int>   -1: remove; 1: add; else: as is
    only=False         <bool>  if True will use show_as; else show
    limits=5           <list or flaot>
                               applies only if color_m=='putty'
                               sets the b-factor range limits
                               <list> [min,max] # absolute values
                               <float> percentile cutoff (both sides) # relative for each protein
    '''

    try:
        selection = '(' + selection + ')'
        color_m = str(color_m)
        hydrogens = int(hydrogens)
        only = bool(str(only) != 'False')
    except:
        print("Input error")
        return False

    if hydrogens == 1:
        cmd.h_add('%s' % selection)
    if hydrogens == -1:
        cmd.remove('%s and elem H' % selection)

    for p in cmd.get_object_list(selection):
        cmd.set('mesh_width', 0.25, p)
        if (color_m == 'putty'):
            limits = get_b_limits(limits, p)
            if not limits:
                print("Input error (limits must be <list> or <float (<=50)>)!")
                return False

            cmd.set('mesh_color', 'default', p)
            cmd.spectrum('b',
                         'rainbow',
                         '(not hetatm) and %s' % p,
                         minimum='%f' % limits[0],
                         maximum='%f' % limits[1],
                         byres=0)
            print(
                "disp_ss:", p,
                "displayed in putty mode - mesh as putty - limits=[%.4f,%.4f]"
                % (limits[0], limits[1]))
        else:
            cmd.set('mesh_color', color_m, p)
            print("regular mode - mesh - " + p)

        if only:
            cmd.show_as('mesh', '%s and %s' % (selection, p))
        else:
            cmd.show('mesh', '%s and %s' % (selection, p))
        cmd.rebuild()
def disp_surf(selection='all',
              color_s='default',
              transparency=0,
              hydrogens=0,
              solvent=0,
              ramp_above=1,
              only=False,
              limits=5):
    '''
DESCRIPTION

    Advanced surface representation (cf. examples)

USAGE

    disp_surf [ selection [, color_s [, transparency [, hydrogens [, solvent [, ramp_above [, only [, limits]]]]]]]]

EXAMPLES

    disp_surf # opaque surface with default colors
    disp_surf all, white, 0.5 # half-transparent white surface
    disp_surf all, putty # b-factor on surface

PARAMETERS

    NAME=DEFAULT       TYPE    FUNCTION
    selection='all'    <str>   input selection
    color_s='default'  <str>   'default': as current
                               'name': colors by color or ramp called name
                               'putty': b-factor on surface (by resi)
    transparency=0     <float> set surface transparency
    hydrogens=0        <int>   -1: remove; 1: add; else: as is
    solvent=0          <int>   defines 'surface_solvent'
    ramp_above=1       <int>   defines 'surface_ramp_above_mode'
    only=False         <bool>  if True will use show_as; else show
    limits=5           <list or flaot>
                               applies only if color_s=='putty'
                               sets the b-factor range limits
                               <list> [min,max] # absolute values
                               <float> percentile cutoff (both sides) # relative for each protein
    '''
    try:
        selection = '(' + selection + ')'
        color_s = str(color_s)
        transparency = float(transparency)
        hydrogens = int(hydrogens)
        solvent = int(solvent)
        ramp_above = int(ramp_above)
        only = bool(str(only) != 'False')
    except:
        print("Input error")
        return False

    for p in cmd.get_object_list(selection):
        if hydrogens == -1:
            cmd.remove('%s and elem H' % p)
        if hydrogens == 1:
            cmd.h_add(p)
        # if hydrogens==0: as is

        # some defaults (settings can be changed later, too)
        cmd.set('surface_carve_cutoff', '4.5', p)
        cmd.set('surface_quality', '2', p)
        cmd.set('solvent_radius', '1.5', p)
        cmd.set('cavity_cull', '2', p)
        cmd.set('surface_carve_selection', p)

        # defined
        cmd.set('surface_solvent', solvent, p)
        cmd.set('surface_ramp_above_mode', ramp_above, p)
        cmd.set('transparency', transparency, p)

        if (color_s == 'putty'):
            limits = get_b_limits(limits, p)
            if not limits:
                print("Input error (limits must be <list> or <float (<=50)>)!")
                return False

            cmd.set('surface_color', 'default', p)
            cmd.spectrum('b',
                         'rainbow',
                         '(not hetatm) and %s' % p,
                         minimum='%f' % limits[0],
                         maximum='%f' % limits[1],
                         byres=0)
            print(
                "disp_ss:", p,
                "displayed in putty mode - surface as putty - limits=[%.4f,%.4f]"
                % (limits[0], limits[1]))
        else:
            cmd.set('surface_color', color_s, selection)
            print("disp_ss:", p, "displayed as regular surface")
        if only:
            cmd.show_as('surface', '(%s and %s)' % (selection, p))
        else:
            cmd.show('surface', '(%s and %s)' % (selection, p))
Beispiel #19
0
def bbPlane(objSel='(all)', color='white', transp=0.0):
    """
DESCRIPTION
 
    Draws a plane across the backbone for a selection
 
ARGUMENTS
 
    objSel = string: protein object or selection {default: (all)}
 
    color = string: color name or number {default: white}
 
    transp = float: transparency component (0.0--1.0) {default: 0.0}
 
NOTES
 
    You need to pass in an object or selection with at least two
    amino acids.  The plane spans CA_i, O_i, N-H_(i+1), and CA_(i+1)
    """
    # format input
    transp = float(transp)
    stored.AAs = []
    coords = dict()
 
    # need hydrogens on peptide nitrogen
    cmd.h_add('(%s) and n. N' % objSel)
 
    # get the list of residue ids
    for obj in cmd.get_object_list(objSel):
        sel = obj + " and (" + objSel + ")"
        for a in cmd.get_model(sel + " and n. CA").atom:
            key = '/%s/%s/%s/%s' % (obj,a.segi,a.chain,a.resi)
            stored.AAs.append(key)
            coords[key] = [a.coord,None,None]
        for a in cmd.get_model(sel + " and n. O").atom:
            key = '/%s/%s/%s/%s' % (obj,a.segi,a.chain,a.resi)
            if key in coords:
                coords[key][1] = a.coord
        for a in cmd.get_model("(hydro or n. CD) and nbr. (" + sel + " and n. N)").atom:
            key = '/%s/%s/%s/%s' % (obj,a.segi,a.chain,a.resi)
            if key in coords:
                coords[key][2] = a.coord
 
    # need at least two amino acids
    if len(stored.AAs) <= 1:
        print "ERROR: Please provide at least two amino acids, the alpha-carbon on the 2nd is needed."
        return
 
    # prepare the cgo
    obj = [
        BEGIN, TRIANGLES,
        COLOR,
        ]
    obj.extend(cmd.get_color_tuple(color))
 
    for res in range(0, len(stored.AAs)-1):
        curIdx, nextIdx = str(stored.AAs[res]), str(stored.AAs[res+1])
 
        # populate the position array
        pos = [coords[curIdx][0], coords[curIdx][1], coords[nextIdx][2], coords[nextIdx][0]]
 
        # if the data are incomplete for any residues, ignore
        if None in pos:
            print 'peptide bond %s -> %s incomplete' % (curIdx, nextIdx)
            continue
 
        if cpv.distance(pos[0], pos[3]) > 4.0:
            print '%s and %s not adjacent' % (curIdx, nextIdx)
            continue
 
        # fill in the vertex data for the triangles; 
        for i in [0,1,2,3,2,1]:
            obj.append(VERTEX)
            obj.extend(pos[i])
 
    # finish the CGO
    obj.append(END)
 
    # update the UI
    newName =  cmd.get_unused_name("backbonePlane")
    cmd.load_cgo(obj, newName)
    cmd.set("cgo_transparency", transp, newName)
Beispiel #20
0
def pdb_to_mol(pdb_file):
    cmd.load(pdb_file)
    cmd.h_add()
    cmd.save("1gsu_ligand.mol")
Beispiel #21
0
def pdb_to_mol(pdb_file):
    cmd.load(pdb_file)
    cmd.h_add()
    cmd.save("%s_ligand.mol" % (pdb_file[0:4]))
Beispiel #22
0
def displayInPyMOL(outdir, selectedPDBChain, atomNumbersProbDic):
    pdbCWMs = os.path.join(outdir, '%s_withConservedWaters.pdb' % selectedPDBChain)
    pdb = os.path.join(outdir, '%s.pdb' % selectedPDBChain)
    h_bond_dist = 4.0

    queryProteinCWMs = '%s_withConservedWaters' % selectedPDBChain

    cmd.load(pdbCWMs)
    cmd.orient(queryProteinCWMs)
    cmd.h_add(queryProteinCWMs)

    cmd.select('cwm_protein','polymer and %s' % queryProteinCWMs)
    cmd.select('cwm_waters','resn hoh and %s' % queryProteinCWMs)
    cmd.select('cwm_ligand','organic and %s' % queryProteinCWMs)

    cmd.select('don', '(elem n,o and (neighbor hydro)) and %s' % queryProteinCWMs)
    cmd.select('acc', '(elem o or (elem n and not (neighbor hydro))) and %s' % queryProteinCWMs)
    # h bonds between protein and conserved waters
    cmd.distance ('PW_HBA', '(cwm_protein and acc)','(cwm_waters and don)', h_bond_dist)
    cmd.distance ('PW_HBD', '(cwm_protein and don)','(cwm_waters and acc)', h_bond_dist)
    # h bonds between ligands and conserved waters
    cmd.distance ('LW_HBA', '(cwm_ligand and acc)','(cwm_waters and don)', h_bond_dist)
    cmd.distance ('LW_HBD', '(cwm_ligand and don)','(cwm_waters and acc)', h_bond_dist)
    # h bonds in between conserved waters
    cmd.distance ('HW_HBA', '(cwm_waters and acc)','(cwm_waters and don)', h_bond_dist)
    cmd.distance ('HW_HBD', '(cwm_waters and don)','(cwm_waters and acc)', h_bond_dist)

    cmd.delete('don')
    cmd.delete('acc')

    cmd.set('dash_color','yellow')
    cmd.set('dash_gap',0.3)
    cmd.set('dash_length',0.2)
    cmd.set('dash_round_ends','on')
    cmd.set('dash_width',3)

    # color and display
    cmd.util.cbam('cwm_ligand')
    cmd.show_as('sticks','cwm_ligand')

    MinDoc = min(atomNumbersProbDic.values())
    MaxDoc = max(atomNumbersProbDic.values())
    cmd.create ('conserved_waters','cwm_waters')
    for key, value in atomNumbersProbDic.items():
        cmd.alter('/conserved_waters//A/HOH`%s/O' % key, 'b=%s' % value)

    cmd.spectrum('b', 'red_blue', 'conserved_waters',minimum=MinDoc, maximum=MaxDoc)
    cmd.ramp_new('DOC', 'conserved_waters', range = [MinDoc,MaxDoc], color = '[red,blue]')
    cmd.set('sphere_scale',0.40,'conserved_waters')
    cmd.show_as('spheres','conserved_waters')

    cmd.hide('labels','*_HB*')
    cmd.remove('(hydro) and conserved_waters')
    cmd.remove('(hydro) and %s' % queryProteinCWMs)

    cmd.util.cbac('cwm_protein')
    cmd.set('transparency', 0.2)
    cmd.show('surface', 'cwm_protein')
    cmd.set('surface_color', 'gray', 'cwm_protein')

    cmd.load(pdb)
    cmd.create('all waters', 'resn hoh and %s' % selectedPDBChain)
    cmd.color('red','ss h and %s' % selectedPDBChain)
    cmd.color('yellow','ss s and %s' % selectedPDBChain)
    cmd.color('green','ss l+ and %s' % selectedPDBChain)
    cmd.show_as('cartoon', selectedPDBChain)
    cmd.set('ray_shadows', 0)
Beispiel #23
0
        '--format',
        help='output molecular file format. Default: same as the input format')
    parser.add_argument(
        '--hetatm',
        help=
        'force all the atom to be defined as HETATM type. The HETATM atom have CONECT defined by default.',
        action='store_true')
    parser.add_argument('--addh', help='Add hydrogens', action='store_true')
    parser.add_argument('--select',
                        help='Keep only the selected atoms',
                        default='all')
    args = parser.parse_args()

    cmd.load(args.inp, 'inmol')
    if args.addh:
        cmd.h_add('all')
    if args.hetatm:
        cmd.alter('all', 'type="HETATM"')
    cmd.split_states('inmol')
    cmd.remove('inmol')
    basename = os.path.basename(os.path.splitext(args.inp)[0])
    if args.format is None:
        outfmt = os.path.splitext(args.inp)[1][1:]
    else:
        outfmt = args.format
    all_objects = cmd.get_object_list()
    try:
        os.mkdir(args.outdir)
    except FileExistsError:
        pass
    for i, obj in enumerate(all_objects):
Beispiel #24
0
def bbPlane(selection='(all)', color='gray', transp=0.3, state=-1, name=None, quiet=1):
    """
DESCRIPTION

    Draws a plane across the backbone for a selection

ARGUMENTS

    selection = string: protein object or selection {default: (all)}

    color = string: color name or number {default: white}

    transp = float: transparency component (0.0--1.0) {default: 0.0}

    state = integer: object state, 0 for all states {default: 1}

NOTES

    You need to pass in an object or selection with at least two
    amino acids.  The plane spans CA_i, O_i, N-H_(i+1), and CA_(i+1)
    """
    from pymol.cgo import BEGIN, TRIANGLES, COLOR, VERTEX, END
    from pymol import cgo
    from chempy import cpv

    # format input
    transp = float(transp)
    state, quiet = int(state), int(quiet)
    if name is None:
        name = cmd.get_unused_name("backbonePlane")

    if state < 0:
        state = cmd.get_state()
    elif state == 0:
        for state in range(1, cmd.count_states(selection) + 1):
            bbPlane(selection, color, transp, state, name, quiet)
        return

    AAs = []
    coords = dict()

    # need hydrogens on peptide nitrogen
    cmd.h_add('(%s) and n. N' % selection)

    # get the list of residue ids
    for obj in cmd.get_object_list(selection):
        sel = obj + " and (" + selection + ")"
        for a in cmd.get_model(sel + " and n. CA", state).atom:
            key = '/%s/%s/%s/%s' % (obj, a.segi, a.chain, a.resi)
            AAs.append(key)
            coords[key] = [a.coord, None, None]
        for a in cmd.get_model(sel + " and n. O", state).atom:
            key = '/%s/%s/%s/%s' % (obj, a.segi, a.chain, a.resi)
            if key in coords:
                coords[key][1] = a.coord
        for a in cmd.get_model(sel + " and ((n. N extend 1 and e. H) or (r. PRO and n. CD))", state).atom:
            key = '/%s/%s/%s/%s' % (obj, a.segi, a.chain, a.resi)
            if key in coords:
                coords[key][2] = a.coord

    # need at least two amino acids
    if len(AAs) <= 1:
        print("ERROR: Please provide at least two amino acids, the alpha-carbon on the 2nd is needed.")
        return

    # prepare the cgo
    obj = [
        BEGIN, TRIANGLES,
        COLOR,
    ]
    obj.extend(cmd.get_color_tuple(color))

    for res in range(0, len(AAs) - 1):
        curIdx, nextIdx = str(AAs[res]), str(AAs[res + 1])

        # populate the position array
        pos = [coords[curIdx][0], coords[curIdx][1], coords[nextIdx][2], coords[nextIdx][0]]

        # if the data are incomplete for any residues, ignore
        if None in pos:
            if not quiet:
                print(' bbPlane: peptide bond %s -> %s incomplete' % (curIdx, nextIdx))
            continue

        if cpv.distance(pos[0], pos[3]) > 4.0:
            if not quiet:
                print(' bbPlane: %s and %s not adjacent' % (curIdx, nextIdx))
            continue

        normal = cpv.normalize(cpv.cross_product(
            cpv.sub(pos[1], pos[0]),
            cpv.sub(pos[2], pos[0])))

        obj.append(cgo.NORMAL)
        obj.extend(normal)

        # need to order vertices to generate correct triangles for plane
        if cpv.dot_product(cpv.sub(pos[0], pos[1]), cpv.sub(pos[2], pos[3])) < 0:
            vorder = [0, 1, 2, 2, 3, 0]
        else:
            vorder = [0, 1, 2, 3, 2, 1]

        # fill in the vertex data for the triangles;
        for i in vorder:
            obj.append(VERTEX)
            obj.extend(pos[i])

    # finish the CGO
    obj.append(END)

    # update the UI
    cmd.load_cgo(obj, name, state, zoom=0)
    cmd.set("cgo_transparency", transp, name)
Beispiel #25
0
 def test_h_add(self):
     cmd.fragment('gly')
     cmd.h_add()
     self.assertEqual(5, cmd.count_atoms('hydro'))
Beispiel #26
0
 def addHGuest(self):
     cmd.h_add("guest")
Beispiel #27
0
 def addHHost(self):
     cmd.h_add("host")
Beispiel #28
0
def fSumWMC(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC,
            MCchargeC, MCchargeO, MCchargeN, MCchargeH, MCchargeProCA,
            MCchargeProCD, MCchargeProN, AmideName, printMC):
    # print "chain", MCNeighbour
    SumWMC = 0.0
    SGnameselect = "/" + SGNameAngle + "//" + "/" + "/SG"
    NBnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour)
    cmd.select("MC", NBnameselect)
    MCpdbstr = cmd.get_pdbstr("MC")
    MCsplit = MCpdbstr.split()
    residueName = MCsplit[3]
    # print NBnameselect, residueName
    if residueName == "PRO":
        # Proline CA
        CAnameselect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/CA"
        ResDist = cmd.dist(residue + 'distProCA', SGnameselect, CAnameselect)
        WMC = fWMC(MCchargeProCA, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC ProCA ", MCNeighbour, " ", MCchargeProCA, " ", DieElecMC,
                  " ", ResDist, " ", WMC)
        # Proline CD
        CDnameselect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/CD"
        ResDist = cmd.dist(residue + 'distProCD', SGnameselect, CDnameselect)
        WMC = fWMC(MCchargeProCD, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC ProCD ", MCNeighbour, " ", MCchargeProCD, " ", DieElecMC,
                  " ", ResDist, " ", WMC)
        # Proline N
        Nnameselect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/N"
        ResDist = cmd.dist(residue + 'distProN', SGnameselect, Nnameselect)
        WMC = fWMC(MCchargeProN, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC ProN ", MCNeighbour, " ", MCchargeProN, " ", DieElecMC,
                  " ", ResDist, " ", WMC)
        # Proline C
        Cnameselect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/C"
        ResDist = cmd.dist(residue + 'distProC', SGnameselect, Cnameselect)
        WMC = fWMC(MCchargeC, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC ProC ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ",
                  ResDist, " ", WMC)
        # Proline O
        Onameselect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/O"
        ResDist = cmd.dist(residue + 'distProO', SGnameselect, Onameselect)
        WMC = fWMC(MCchargeO, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC ProO ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ",
                  ResDist, " ", WMC)
    else:
        AmideProt = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/H01"
        Hnameselect = "/" + AmideName + "//" + chain + "/" + str(
            MCNeighbour) + "/H01"
        if cmd.count_atoms(AmideProt) == 0 and cmd.count_atoms(
                Hnameselect) == 0:
            HbuildSelect = "/" + molecule + "//" + chain + "/" + str(
                MCNeighbour) + "/N"
            cmd.h_add(HbuildSelect)
            cmd.create(AmideName, AmideName + " + " + AmideProt)
            cmd.remove(AmideProt)
        # Mainchain AmideH
        ResDist = cmd.dist(residue + 'distH', SGnameselect, Hnameselect)
        WMC = fWMC(MCchargeH, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC H ", MCNeighbour, " ", MCchargeH, " ", DieElecMC, " ",
                  ResDist, " ", WMC)
        # Mainchain C
        Cnameselect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/C"
        ResDist = cmd.dist(residue + 'distC', SGnameselect, Cnameselect)
        WMC = fWMC(MCchargeC, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC C ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ",
                  ResDist, " ", WMC)
        # Mainchain O
        Onameselect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/O"
        ResDist = cmd.dist(residue + 'distO', SGnameselect, Onameselect)
        WMC = fWMC(MCchargeO, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC O ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ",
                  ResDist, " ", WMC)
        # Mainchain N
        Nnameselect = "/" + molecule + "//" + chain + "/" + str(
            MCNeighbour) + "/N"
        ResDist = cmd.dist(residue + 'distN', SGnameselect, Nnameselect)
        WMC = fWMC(MCchargeN, DieElecMC, ResDist)
        SumWMC = SumWMC + WMC
        if printMC == 'yes':
            print("MC N ", MCNeighbour, " ", MCchargeN, " ", DieElecMC, " ",
                  ResDist, " ", WMC)
    cmd.delete(residue + 'distProCA')
    cmd.delete(residue + 'distProCD')
    cmd.delete(residue + 'distProN')
    cmd.delete(residue + 'distProC')
    cmd.delete(residue + 'distProO')
    cmd.delete(residue + 'distH')
    cmd.delete(residue + 'distC')
    cmd.delete(residue + 'distO')
    cmd.delete(residue + 'distN')
    cmd.show("nb_spheres", AmideName)
    cmd.delete("MC")
    return SumWMC
Beispiel #29
0
def disp_surf(
selection='all', 
color_s='default', 
transparency=0,
hydrogens=0,
solvent=0,
ramp_above=1,
only=False,
limits=5):
    '''
DESCRIPTION

    Advanced surface representation (cf. examples)

USAGE

    disp_surf [ selection [, color_s [, transparency [, hydrogens [, solvent [, ramp_above [, only [, limits]]]]]]]]

EXAMPLES

    disp_surf # opaque surface with default colors
    disp_surf all, white, 0.5 # half-transparent white surface
    disp_surf all, putty # b-factor on surface

PARAMETERS

    NAME=DEFAULT       TYPE    FUNCTION
    selection='all'    <str>   input selection
    color_s='default'  <str>   'default': as current
                               'name': colors by color or ramp called name
                               'putty': b-factor on surface (by resi)
    transparency=0     <float> set surface transparency
    hydrogens=0        <int>   -1: remove; 1: add; else: as is
    solvent=0          <int>   defines 'surface_solvent'
    ramp_above=1       <int>   defines 'surface_ramp_above_mode'
    only=False         <bool>  if True will use show_as; else show
    limits=5           <list or flaot> 
                               applies only if color_s=='putty'
                               sets the b-factor range limits
                               <list> [min,max] # absolute values
                               <float> percentile cutoff (both sides) # relative for each protein
    '''
    try:
        selection='('+selection+')'
        color_s=str(color_s)
        transparency=float(transparency)
        hydrogens=int(hydrogens)
        solvent=int(solvent)
        ramp_above=int(ramp_above)
        only=bool(str(only)!='False')
    except:
        print "Input error"
        return False

    for p in cmd.get_object_list(selection):
        if hydrogens==-1:
            cmd.remove('%s and elem H' %p)
        if hydrogens==1:
            cmd.h_add(p)
        # if hydrogens==0: as is
        
        # some defaults (settings can be changed later, too)
        cmd.set('surface_carve_cutoff', '4.5', p)
        cmd.set('surface_quality', '2', p)
        cmd.set('solvent_radius', '1.5', p)
        cmd.set('cavity_cull', '2', p)
        cmd.set('surface_carve_selection', p)

        # defined
        cmd.set('surface_solvent', solvent, p)
        cmd.set('surface_ramp_above_mode', ramp_above, p)
        cmd.set('transparency', transparency, p)

        if (color_s == 'putty'):
            limits=get_b_limits(limits,p)
            if not limits:
                print "Input error (limits must be <list> or <float (<=50)>)!"
                return False

            cmd.set('surface_color', 'default', p)      
            cmd.spectrum('b', 'rainbow', 
            '(not hetatm) and %s'%p, minimum='%f'%limits[0], 
            maximum='%f'%limits[1], byres=0)      
            print "disp_ss:",p,"displayed in putty mode - surface as putty - limits=[%.4f,%.4f]"%(limits[0],limits[1])
        else: 
            cmd.set('surface_color', color_s, selection)
            print "disp_ss:",p,"displayed as regular surface"
        if only:
            cmd.show_as('surface', '(%s and %s)' %(selection, p))
        else:
            cmd.show('surface', '(%s and %s)' %(selection, p))
Beispiel #30
0
def disp_mesh( selection='all', color_m='default', hydrogens=0, only=False, limits=5):
    '''
DESCRIPTION

    Adds a mesh to the object
    Has advanced coloring options and automatically accounts for the hydrogens

USEAGE

    disp_mesh [ selection [, color_m [, hydrogens [, only [, limits]]]]]
    disp_mesh selection=all, color_m=default
    disp_mesh selection=all, color_m=white
    disp_mesh selection=all, color_m=putty

PARAMETERS

    NAME=DEFAULT       TYPE    FUNCTION
    selection='all'    <str>   input selection
    color_m='default'  <str>   'default': as current
                               'name': colors by color or ramp called name
                               'putty': b-factor on surface
    hydrogens=0        <int>   -1: remove; 1: add; else: as is
    only=False         <bool>  if True will use show_as; else show
    limits=5           <list or flaot> 
                               applies only if color_m=='putty'
                               sets the b-factor range limits
                               <list> [min,max] # absolute values
                               <float> percentile cutoff (both sides) # relative for each protein
    '''

    try:
        selection='('+selection+')'
        color_m=str(color_m)
        hydrogens=int(hydrogens)
        only=bool(str(only)!='False')
    except:
        print "Input error"
        return False
        
    if hydrogens==1:
        cmd.h_add('%s' %selection)
    if hydrogens==-1:
        cmd.remove('%s and elem H' %selection)

    for p in cmd.get_object_list(selection):
        cmd.set('mesh_width', 0.25, p)
        if (color_m == 'putty'):
            limits=get_b_limits(limits,p)
            if not limits:
                print "Input error (limits must be <list> or <float (<=50)>)!"
                return False

            cmd.set('mesh_color', 'default', p)      
            cmd.spectrum('b', 'rainbow', '(not hetatm) and %s'%p, minimum='%f'%limits[0], maximum='%f'%limits[1], byres=0)     
            print "disp_ss:",p,"displayed in putty mode - mesh as putty - limits=[%.4f,%.4f]"%(limits[0],limits[1])
        else:
            cmd.set('mesh_color', color_m, p)
            print"regular mode - mesh - "+p

        if only:
            cmd.show_as('mesh', '%s and %s'%(selection, p))
        else:
            cmd.show('mesh', '%s and %s'%(selection, p))
        cmd.rebuild()       
    def _create_model_from_template_pymol(self,
                                          savepath,
                                          mhcseq,
                                          pepseq,
                                          pdb,
                                          add_polar_h=False):
        """
        This doesn't work properly
        """
        raise NotImplementedError()

        table = self.pdb_table
        row = table[table.pdb == pdb].iloc[0, :]
        resi_list = row['resi_orig'].split(',')
        tplseq = row['seq_orig']
        pepseq_orig = row['peptide']

        aln = Bio.pairwise2.align.globalds(mhcseq, tplseq, matlist.blosum62,
                                           -14.0, -4.0)[0]
        aln1 = aln[0]
        aln2 = aln[1]

        logger.info('Alignment:')
        logger.info('new sequence: ' + aln1)
        logger.info('old sequence: ' + aln2)
        logger.info('')
        logger.info('new peptide: ' + pepseq)
        logger.info('old peptide: ' + pepseq_orig)

        mhc_mutations = []
        for anew, aold, resi in zip(list(aln1), list(aln2), resi_list):
            if anew != aold:
                if anew != '-' and anew != 'X' and aold != '-' and aold != 'X':
                    mhc_mutations.append((seq3(anew), seq3(aold), resi))
        logger.info('Found %i mutations in MHC' % len(mhc_mutations))

        pep_mutations = []
        pep_resi = map(str, range(1, len(pepseq_orig) + 1))
        for anew, aold, resi in zip(list(pepseq), list(pepseq_orig), pep_resi):
            if anew != aold:
                if anew != '-' and anew != 'X' and aold != '-' and aold != 'X':
                    pep_mutations.append((anew, aold, resi))

        logger.info('Found %i mutations in peptide' % len(pep_mutations))

        cmd.delete('all')
        cmd.load(self._get_mhc_path(pdb), 'mhc')
        cmd.load(self._get_pep_path(pdb), 'pep')

        cmd.wizard('mutagenesis')
        cmd.refresh_wizard()
        cmd.remove("not alt ''+A")
        cmd.alter('all', "alt=''")

        for new, old, resi in mhc_mutations:
            logger.info(resi, old, new)
            cmd.get_wizard().do_select("A/" + resi + "/")
            cmd.get_wizard().set_mode(seq3(new).upper())
            cmd.get_wizard().apply()

        for new, old, resi in pep_mutations:
            logger.info(resi, old, new)
            cmd.get_wizard().do_select("B/" + resi + "/")
            cmd.get_wizard().set_mode(seq3(new).upper())
            cmd.get_wizard().apply()

        cmd.set_wizard()

        if add_polar_h:
            cmd.h_add('donors or acceptors')

        cmd.save(savepath, "all")
        cmd.delete("all")
Beispiel #32
0
                '(%s) and model %s and chain %s' % (selection, model, chain))
        cmd.disable(model)


cmd.extend('split_chains', split_chains)

i = 0
f = open(PDB_TO_LIGAND_MAP_PATH, 'r')
for line in f:
    # if(i>10): break
    linfo = line.strip().split("\t")
    uniprot, protein_class, pdb, ligand = linfo[0], linfo[1], linfo[2], linfo[
        3]
    print(pdb, ligand)

    ### Retrieve PDB and add hydrogens
    cmd.fetch(pdb)
    cmd.h_add("all")

    ### Split across chains
    split_chains()
    chains = cmd.get_object_list()[1:]

    ### Write out pdb parts
    for pdb_c in chains:
        cmd.save(
            "/Users/anthony/Desktop/dror/temp3/DynamicNetworks/data/crystal-analysis/ligand-wetness/watermarks/classA-gpcr-pdbs/"
            + pdb_c + "_pymol_Hadded.pdb", pdb_c)

    cmd.reinitialize()
    i += 1
Beispiel #33
0
 def test_h_add(self):
     cmd.fragment('gly')
     cmd.h_add()
     self.assertEqual(5, cmd.count_atoms('hydro'))