示例#1
0
文件: system.py 项目: ZY-JLU/garnish
 def draw_bonds(self, selection):
     warn = False
     selection_objects = cmd.get_object_list(selection)
     for obj in selection_objects:
         elastics_obj = obj+"_elastics"
         # Create dummy object to draw elastic bonds in
         cmd.copy(elastics_obj, obj)
         for a, b, data in self.graph.edges(data=True):
             # draw non-elastic bonds
             if data['type'] in ['bonds', 'constr']:
                 try:
                     a += 1
                     b += 1
                     try:
                         cmd.add_bond(obj, a, b)
                     except AttributeError:
                         cmd.bond(f"({obj} and ID {a})", f"({obj} and ID {b})")
                 except KeyError:
                     warn = True
             # Draw elastic network
             if data['type'] == 'harmonic':
                 try:
                     a += 1
                     b += 1
                     try:
                         cmd.add_bond(elastics_obj, a, b)
                     except AttributeError:
                         cmd.bond(f"({elastics_obj} and ID {a})", f"({elastics_obj} and ID {b})")
                 except KeyError:
                     warn = True
         cmd.color("orange", elastics_obj)
     # warn about missing atoms if needed.
     if warn:
         print('WARNING: some atoms present in the tpr file were not found in the loaded '
               'structure.\n Bonds containing those atoms were not drawn.')
示例#2
0
def bond_zns(sel):
    cmd.unbond(sel + " and resn ZNS", sel + " and not resn ZNS")
    # for c, i in getres("resn ZNS"):
    #    cmd.bond(sel+" and chain %s and resi %i and name ZN1"%(c, i),
    #             sel+" and chain %s and resi %i and name S*"%(c, i))
    for c, i in getres("name ZN1"):
        cmd.bond(
            sel + " and chain %s and resi %i and name ZN1" % (c, i),
            sel + " and chain %s and resi %i and name S*, N2, N4" % (c, i),
        )
    allsg = cmd.get_model(sel + " and (resn CYS and (name CB))").atom
    allsf = cmd.get_model(sel + " and (resn ZHC and (name S*, C1, C4))").atom
    while allsg:
        closest = [9e9, None, None]
        for sga in allsg:
            for sfa in allsf:
                sg = Vec(sga.coord)
                sf = Vec(sfa.coord)
                if (sg - sf).length() < closest[0]:
                    closest = [(sg - sf).length(), sga, sfa]
        sga, sfa = closest[1:]
        allsg.remove(sga)
        allsf.remove(sfa)
        if closest[0] > 10.0:
            break
        cmd.bond(
            sel + " and resi %s and chain %s and name %s" % (sga.resi, sga.chain, sga.name),
            sel + " and resi %s and chain %s and name %s" % (sfa.resi, sfa.chain, sfa.name),
        )
示例#3
0
def load_links():
    file_links = open_it()
    for line in open(file_links, "r"):
        edge = line.split()
        for i in range(0, len(edge)):
            edge[i] = "resi " + edge[i]
        cmd.bond(edge[0], edge[1])
示例#4
0
def bond_zns(sel):
    cmd.unbond(sel + " and resn ZNS", sel + " and not resn ZNS")
    # for c,i in getres("resn ZNS"):
    #    cmd.bond(sel+" and chain %s and resi %i and name ZN1"%(c,i),
    #             sel+" and chain %s and resi %i and name S*"%(c,i))
    for c, i in getres("name ZN1"):
        cmd.bond(sel + " and chain %s and resi %i and name ZN1" % (c, i),
                 sel + " and chain %s and resi %i and name S*,N2,N4" % (c, i))
    allsg = cmd.get_model(sel + " and (resn CYS and (name CB))").atom
    allsf = cmd.get_model(sel + " and (resn ZHC and (name S*,C1,C4))").atom
    while allsg:
        closest = [9e9, None, None]
        for sga in allsg:
            for sfa in allsf:
                sg = Vec(sga.coord)
                sf = Vec(sfa.coord)
                if (sg - sf).length() < closest[0]:
                    closest = [(sg - sf).length(), sga, sfa]
        sga, sfa = closest[1:]
        allsg.remove(sga)
        allsf.remove(sfa)
        if closest[0] > 10.0: break
        cmd.bond(
            sel + " and resi %s and chain %s and name %s" %
            (sga.resi, sga.chain, sga.name),
            sel + " and resi %s and chain %s and name %s" %
            (sfa.resi, sfa.chain, sfa.name))
示例#5
0
def bond_connections_from_array(interactiongraph, residuemap, cutoff=0.0):
    # Make strength be proportional to girth of bonds
    graph = numpy.sqrt(numpy.absolute(interactiongraph))
    # Simple min-max scaling parameters
    minimum = numpy.min(graph)
    maximum = numpy.max(graph)
    residues = list(residuemap.keys())
    shown = []
    for i in range(graph.shape[0]):
        for j in range(i, graph.shape[1]):
            # Only draw bonds if interaction strength over cutoff threshold
            if graph[i][j] > cutoff:
                resa = residues[i]
                resb = residues[j]
                shown.append(resa)
                shown.append(resb)
                a = "chain {} and resi {} and name CA".format(
                    resa.split(':')[0],
                    resa.split(':')[1][1:])
                b = "chain {} and resi {} and name CA".format(
                    resb.split(':')[0],
                    resb.split(':')[1][1:])
                cmd.bond(a, b)
                strength = 1.0 if maximum == minimum else 0.1 + (0.9 * (
                    (graph[i][j] - minimum) / (maximum - minimum)))
                cmd.set_bond("stick_radius", strength, a, b)
    return shown
def draw_dist_pairs(drs_inp, molecule, draw_type="line"):
    f_drsinp = open(drs_inp, "r")
    obj = "network"
    cmd.create(obj, molecule)
    cmd.hide("everything", obj)
    for i, line in enumerate(f_drsinp):
        print "Pair No.: ", i
        if line.split()[1] != "LIST" and line.split()[1] != "STOP":
            chainid1, resid1, resname1, atomname1 = line.split(
            )[0], line.split()[1], line.split()[2], line.split()[3]
            chainid2, resid2, resname2, atomname2 = line.split(
            )[4], line.split()[5], line.split()[6], line.split()[7]
            print chainid1, resid1, resname1, atomname1, chainid2, resid2, resname2, atomname2
            if draw_type == "line":
                cmd.bond("%s and chain %s and resi %s and name %s"%(obj,chainid1,resid1,atomname1),\
                         "%s and chain %s and resi %s and name %s"%(obj,chainid2,resid2,atomname2) )
                cmd.show(
                    "lines", "%s and chain %s and resi %s and name %s" %
                    (obj, chainid1, resid1, atomname1))
                cmd.show(
                    "lines", "%s and chain %s and resi %s and name %s" %
                    (obj, chainid2, resid2, atomname2))
            elif draw_type == "dist":
                cmd.distance("dist%s"%i, "chain %s and resi %s and name %s"%(chainid1,str(resid1),atomname1),\
                                         "chain %s and resi %s and name %s"%(chainid2,str(resid2),atomname2) )
            print "chain %s and resi %s and name %s" % (chainid1, resid1,
                                                        atomname1)
        elif line.split()[1] == "STOP":
            print "Reached last line"
            break
示例#7
0
def showcst(fname):
    for l in open(fname).readlines():
        kind, a1, r1, a2, r2 = l.split()[:5]
        a1 = "(resi %s and name %s)" % (r1, a1)
        a2 = "(resi %s and name %s)" % (r2, a2)
        cmd.bond(a1, a2)
        cmd.show("lines", a1)
        cmd.show("lines", a2)
示例#8
0
def bondzn():
    for o in cmd.get_object_list():
        for c, r in getres(o + " and elem ZN"):
            print "add zn bonds for", o, "resi", r, "chain", c
            cmd.bond(
                "(%s and resi %s and chain %s)" % (o, r, c),
                "(%s and elem N) within 2.5 of (%s and resi %s and chain %s)" %
                (o, o, r, c))
示例#9
0
def showcst(fname):
    for l in open(fname).readlines():
        kind, a1, r1, a2, r2 = l.split()[:5]
        a1 = "(resi %s and name %s)" % (r1, a1)
        a2 = "(resi %s and name %s)" % (r2, a2)
        cmd.bond(a1, a2)
        cmd.show("lines", a1)
        cmd.show("lines", a2)
示例#10
0
def bondzn():
    for o in cmd.get_object_list():
        print "add zn bonds for", o
        for r, c in getres(o + " and elem ZN"):
            cmd.bond(
                "(%s and resi %s and chain %s)" % (o, r, c),
                "(%s and resn HIS and elem N) within 2.5 of (%s and resi %s and chain %s)" % (o, o, r, c),
            )
        break
示例#11
0
    def chop(self, sele):
        try:
            model = cmd.get_model(sele)
        except:
            return

        chain2resId2atomNames = {}

        for atom in model.atom:
            resnum = int(atom.resi)
            pdbname = atom.name
            chain = atom.chain

            if not chain in chain2resId2atomNames:
                chain2resId2atomNames[chain] = {resnum: set([pdbname])}
            else:
                if resnum in chain2resId2atomNames[chain]:
                    chain2resId2atomNames[chain][resnum].add(pdbname)
                else:
                    chain2resId2atomNames[chain][resnum] = set([pdbname])

        for chain in chain2resId2atomNames:
            resId2atomNames = chain2resId2atomNames[chain]

            resIds2addN = set([])
            resIds2addC = set([])

            for resnum in resId2atomNames:
                if resId2atomNames[resnum] != set([
                        "CA", "C", "O"
                ]) and resId2atomNames[resnum] != set(["CA", "N"]):
                    resIds2addC.add(resnum + 1)
                    resIds2addN.add(resnum - 1)

            resIds2addN -= set(resId2atomNames.keys())
            resIds2addC -= set(resId2atomNames.keys())

            stateNo = cmd.get_state()
            for resnum in resIds2addC:
                cmd.create(
                    sele, " %" + sele + " or ( ( resi " + str(resnum) +
                    " and chain " + chain + " ) and ( name CA or name N) ) ",
                    stateNo)
                cmd.bond(
                    "%" + sele + " and name N and resi " + str(resnum),
                    "%" + sele + " and name C and resi " + str(resnum - 1), 1)

            for resnum in resIds2addN:
                cmd.create(
                    sele, " %" + sele + " or ( ( resi " + str(resnum) +
                    " and chain " + chain +
                    " ) and ( name CA or name C or name O) ) ", stateNo)
                cmd.bond(
                    "%" + sele + " and name C and resi " + str(resnum),
                    "%" + sele + " and name N and resi " + str(resnum + 1), 1)

        cmd.show("sticks", sele)
示例#12
0
    def test_bond(self):
        cmd.pseudoatom('m1', pos=(0, 0, 0))
        cmd.pseudoatom('m1', pos=(1, 0, 0))
        cmd.pseudoatom('m1', pos=(1, 1, 0))

        cmd.bond('m1`1', 'm1`2')
        count = cmd.count_atoms('(m1`1) extend 1')
        self.assertEqual(count, 2)

        cmd.unbond('m1`1', 'm1`2')
        count = cmd.count_atoms('(m1`1) extend 1')
        self.assertEqual(count, 1)
示例#13
0
    def test_bond(self):
        cmd.pseudoatom('m1', pos=(0,0,0))
        cmd.pseudoatom('m1', pos=(1,0,0))
        cmd.pseudoatom('m1', pos=(1,1,0))

        cmd.bond('m1`1', 'm1`2')
        count = cmd.count_atoms('(m1`1) extend 1')
        self.assertEqual(count, 2)

        cmd.unbond('m1`1', 'm1`2')
        count = cmd.count_atoms('(m1`1) extend 1')
        self.assertEqual(count, 1)
示例#14
0
def load_net():
   file_coors= open_it()
   net=network(file_coors)
   for ii in range(net.num_nodes):
      cmd.pseudoatom('net',pos=net.node[ii].coors,resi=ii,chain='A')
      selec='resi '+str(ii)
      cmd.alter(selec,'resn='+'"'+net.node[ii].label+'"')
      cmd.label(selec,'"'+net.node[ii].label+'"')
      cmd.alter(selec,'b='+str(net.node[ii].weight))
      cmd.alter(selec,'q='+str(net.node[ii].cluster))
   for ii in range(net.num_nodes):
      for jj in net.node[ii].link.keys():
         cmd.bond('resi '+str(ii),'resi '+str(jj))
   cmd.spectrum('b','blue_red')
示例#15
0
def bond_connections(clusters, interactions):
    cutoff=10
##    show_list=["A:240","A:182","A:184","A:204","A:201","A:216"]
#    shell1=["A:240"]
##    shell1=["A:204","A:240"]
#    shell2=["A:182","A:184","A:204","A:201","A:216"]
#    shell3=["A:151","A:155","A:156","A:199","A:205","A:208","A:214","A:238","A:242"]
#    shell4=["A:154","A:158","A:163","A:166","A:167","A:170","A:180","A:185","A:196","A:203","A:207","A:211","A:212","A:219","A:68"]
#    shell5=["A:135","A:136","A:149","A:160","A:162","A:164","A:171","A:173","A:174","A:178","A:192","A:197","A:200","A:206","A:222","A:230","A:235","A:236","A:237","A:26","A:29","A:66","A:69"]
#    shell6=["A:134","A:138","A:139","A:143","A:146","A:152","A:157","A:159","A:169","A:183","A:187","A:19","A:195","A:220","A:223","A:227","A:23","A:232","A:24","A:244","A:46","A:87","A:89","A:90","A:91"]
#     
#    show_list_wt=shell1 + shell2 + shell3 + shell4 + shell5 + shell6
#    show_list_S=shell1
#    show_list=shell1
#    #show_list=show_list_wt
#    #show_list.append(shell1)
#    #show_list.append(shell2)
#    #print(show_list)

    for cluster in clusters:
        #print(cluster)
        for i in range(len(cluster)):
            for j in range(i, len(cluster)):
                resa = cluster[i]
                resb = cluster[j]
                # Only draw bonds if interaction strength at all present
                if resa in interactions:
                    if resb in interactions[resa]:
                        resa_=re.sub(r':\w',':',resa)
                        resb_=re.sub(r':\w',':',resb)
                        a = "chain {} and resi {} and name CA".format(
                            resa_.split(':')[0], resa_.split(':')[1])
                        b = "chain {} and resi {} and name CA".format(
                            resb_.split(':')[0], resb_.split(':')[1])

                        
#                        if interactions[resa][resb] > cutoff and (resa in show_list or resb in show_list):
                        if interactions[resa][resb] > cutoff: #and (resa in show_list or resb in show_list):

                            #if resa not in show_list:
                            #    print(resa)
                            #if resb not in show_list:
                            #    print(resb)
#                            print(resa + " " + resb)
                            print(a + " " + b + " " + str(interactions[resa][resb]))
                            cmd.bond(a, b)
                            cmd.set_bond("line_width",
                                         (interactions[resa][resb]/3),
                                         a, b)
                            cmd.set_bond("line_color",get_color(resa,resb),a,b)
示例#16
0
文件: garnish.py 项目: ZY-JLU/garnish
def garnish(file=None, selection='all', gmx=None):
    """
DESCRIPTION

    Allow a coarse grained structure to be visualized in pymol like an atomistic structure
    by drawing bonds and elastic network.

    Without a top/tpr file, this function only adds bonds between the backbone beads
    so they can be nicely visualized using line or stick representation.
    Adding a top/tpr file provides topology information that can be used
    to draw side chain and elastic bonds.

USAGE

    garnish [file [, selection [, gmx]]]

ARGUMENTS

    file = a tpr or topology file to extract bond information from (default: None)
    selection = any selection to act upon (default: all)
    gmx = gmx executable path (default: inferred by `which gmx`)
    """
    # Retain order so pymol does not sort the atoms, giving a different result when saving the file
    cmd.set("retain_order", 1)

    if file:
        # parse the file
        sys_dict = parse(file, gmx)
        # create System object and draw all the bonds
        system = System(sys_dict)
        system.draw_bonds(selection)
        system.transfer_attributes(selection)
    else:
        bb_beads = get_chain_bb(selection)
        # For each object and chain, draw bonds between BB beads
        for obj, chains in bb_beads.items():
            for _, bbs in chains.items():
                # create bond tuples for "adjacent" backbone beads
                bonds = [(bbs[i], bbs[i + 1]) for i in range(len(bbs) - 1)]
                for a, b in bonds:
                    try:
                        cmd.add_bond(obj, a, b)
                    except AttributeError:
                        cmd.bond(f"{obj} and ID {a}", f"{obj} and ID {b}")

    # Fix the view nicely
    cmd.hide("everything", selection)
    cmd.show_as("sticks", selection)
    cmd.show_as("lines", '*_elastics')
示例#17
0
 def get_best_state_bump():
     best_state = (1, 1e9)
     cmd.create(tmp, '%s and not name CA+C+N+O or (%s within 8.0 of (%s and name CB))' % \
             (mutagenesis.obj_name, cpy, mutagenesis.obj_name), zoom=0, singletons=1)
     cmd.bond('name CB and %s in %s' % (tmp, mutagenesis.obj_name),
             'name CA and %s in %s' % (tmp, res))
     cmd.sculpt_activate(tmp)
     for i in range(1, cmd.count_states(tmp)+1):
         score = cmd.sculpt_iterate(tmp, state=i)
         if not quiet:
             print('Frame %d Score %.2f' % (i, score))
         if score < best_state[1]:
             best_state = (i, score)
     cmd.delete(tmp)
     if not quiet:
         print(' Best: Frame %d Score %.2f' % best_state)
     return best_state
示例#18
0
 def get_best_state_bump():
     best_state = (1, 1e9)
     cmd.create(tmp, '%s and not name CA+C+N+O or (%s within 8.0 of (%s and name CB))' % \
             (mutagenesis.obj_name, cpy, mutagenesis.obj_name), zoom=0, singletons=1)
     cmd.bond('name CB and %s in %s' % (tmp, mutagenesis.obj_name),
             'name CA and %s in %s' % (tmp, res))
     cmd.sculpt_activate(tmp)
     for i in range(1, cmd.count_states(tmp)+1):
         score = cmd.sculpt_iterate(tmp, state=i)
         if not quiet:
             print('Frame %d Score %.2f' % (i, score))
         if score < best_state[1]:
             best_state = (i, score)
     cmd.delete(tmp)
     if not quiet:
         print(' Best: Frame %d Score %.2f' % best_state)
     return best_state
示例#19
0
def bond_connections(clusters, interactions):
    # Quickfix - find min and max
    # this filtering should be done before supplying to this function
    # That is, the "interactions" data should be already formatted
    # as a float in a way that makes it look nice with bond
    # stick_radius
    minimum = None
    maximum = None
    for cluster in clusters:
        for i in range(len(cluster)):
            for j in range(i, len(cluster)):
                resa = cluster[i]
                resb = cluster[j]
                if resa in interactions:
                    if resb in interactions[resa]:
                        strength = interactions[resa][resb][0]
                        if minimum is None:
                            minimum = strength
                        else:
                            minimum = strength if minimum > strength else minimum
                        if maximum is None:
                            maximum = strength
                        else:
                            maximum = strength if maximum < strength else maximum
    for cluster in clusters:
        for i in range(len(cluster)):
            for j in range(i, len(cluster)):
                resa = cluster[i]
                resb = cluster[j]
                # Only draw bonds if interaction strength at all present
                if resa in interactions:
                    if resb in interactions[resa]:
                        a = "chain {} and resi {} and name CA".format(
                            resa.split(':')[0],
                            resa.split(':')[1][1:])
                        b = "chain {} and resi {} and name CA".format(
                            resb.split(':')[0],
                            resb.split(':')[1][1:])
                        cmd.bond(a, b)
                        strength = 1.0 if maximum == minimum else 0.1 + (
                            0.9 * ((interactions[resa][resb][0] - minimum) /
                                   (maximum - minimum)))
                        cmd.set_bond("stick_radius", strength, a, b)
示例#20
0
def test_extinction_coefficient():
    cmd.reinitialize()
    eps_reduced = 2 * 5500 + 3 * 1490
    eps_ss_1 = eps_reduced + 1 * 125
    eps_ss_2 = eps_reduced + 2 * 125
    cmd.fab("AWWYYYCCCC", "m1")
    eps, A_280 = psico.querying.extinction_coefficient("m1")
    assert eps == eps_reduced
    assert A_280 == approx(eps_reduced / 1345.58908)
    cmd.remove("hydro")
    eps, A_280 = psico.querying.extinction_coefficient("m1")
    assert eps == eps_reduced
    assert A_280 == approx(eps_reduced / 1347.60496)
    cmd.bond("7/SG", "8/SG")
    eps, A_280 = psico.querying.extinction_coefficient("m1")
    assert eps == eps_ss_1
    assert A_280 == approx(eps_ss_1 / 1345.58908)
    cmd.bond("9/SG", "10/SG")
    eps, A_280 = psico.querying.extinction_coefficient("m1")
    assert eps == eps_ss_2
    assert A_280 == approx(eps_ss_2 / 1343.5732)
def draw_dist_pairs(drs_inp, molecule, draw_type="line"):
  f_drsinp = open(drs_inp, "r")
  obj = "network"
  cmd.create(obj, molecule)
  cmd.hide("everything", obj)
  for i, line in enumerate(f_drsinp):
    print "Pair No.: ", i
    if line.split()[1] != "LIST" and line.split()[1] != "STOP":
      chainid1, resid1, resname1, atomname1 = line.split()[0], line.split()[1], line.split()[2],line.split()[3]
      chainid2, resid2, resname2, atomname2 = line.split()[4], line.split()[5], line.split()[6],line.split()[7]
      print chainid1, resid1, resname1, atomname1, chainid2, resid2, resname2, atomname2
      if draw_type == "line":
        cmd.bond("%s and chain %s and resi %s and name %s"%(obj,chainid1,resid1,atomname1),\
                 "%s and chain %s and resi %s and name %s"%(obj,chainid2,resid2,atomname2) )
        cmd.show("lines", "%s and chain %s and resi %s and name %s"%(obj, chainid1,resid1,atomname1))
        cmd.show("lines", "%s and chain %s and resi %s and name %s"%(obj, chainid2,resid2,atomname2))
      elif draw_type == "dist":
        cmd.distance("dist%s"%i, "chain %s and resi %s and name %s"%(chainid1,str(resid1),atomname1),\
                                 "chain %s and resi %s and name %s"%(chainid2,str(resid2),atomname2) )
      print "chain %s and resi %s and name %s"%(chainid1,resid1,atomname1)
    elif line.split()[1] == "STOP":
      print "Reached last line"
      break
示例#22
0
def load_network(points, edges):
    with open(points, 'r') as infile:
        for line in infile.readlines():
            field = line.strip().split()
            xyz = map(float, field)
            xyz = [10 * x for x in xyz]
            cmd.pseudoatom("test", elem='O', pos=xyz)

    with open(edges, 'r') as infile:
        for line in infile.readlines():
            field = line.strip().split()
            if float(field[-1]) > 0.1:
                plop = cmd.bond('index %s' % field[0], 'index %s' % field[1])
                cmd.set_bond('line_color', float(field[-1]), 'i. 1')

    cmd.show("sphere", "test")
    cmd.set('line_width', 5.0)
    return 0
示例#23
0
        ligand_name = file.split('_')[0]
        loaded_ligs.append(ligand_name)
        cmd.load('ligs/' + file, ligand_name)

#select the ligand atomes of the original ligand to align with
target_atom1 = 'RA95_target and name C3'
target_atom2 = 'RA95_target and name C4'
target_atom3 = 'RA95_target and name C5'

#select the ligand atomes of the new ligand to align with and align the selected atoms of old and new ligand
for ligand in loaded_ligs:
    mobile_atom1 = ligand + ' and name CL1'
    mobile_atom2 = ligand + ' and name CL'
    mobile_atom3 = ligand + ' and name CL2'
    cmd.pair_fit(mobile_atom1, target_atom1, mobile_atom2, target_atom2,
                 mobile_atom3, target_atom3)

#remove old ligand
cmd.remove('RA95_target and resn PEN')

#build bond between Lys83 and the new ligand and generate pdb file
for ligand in loaded_ligs:
    cmd.copy('RA95_' + ligand, 'RA95_target')
    cmd.fuse(ligand + ' and name CL',
             'RA95_' + ligand + ' and resn LYX and name NZ', '3')
    cmd.bond('RA95_' + ligand + ' and resn LYX and name NZ',
             'RA95_' + ligand + ' and name CL')
    cmd.alter('RA95_' + ligand + ' and resn ' + ligand, 'segi="B"')
    cmd.sort('RA95_' + ligand)
    cmd.save('RA95_' + ligand + '.pdb', 'RA95_' + ligand, '0')
示例#24
0
def format_bonds(
    selection='all',
    bonds=4,
):
    '''
DESCRIPTION
    Formats bonds in aromatic or charged residues
EXAMPLE
    frag PHE
    format_bonds
USAGE
    format_bonds [ selection [, bonds ]]
ARGUMENTS
    selection: <str> input selection {default: 'all'}
    bonds:     <int> toogles format of bonds
               1: single bonds (deactivates valence display)
               2: regular double bonds (activates valence display)
             >=3: delocalized (activates valence display)
    '''
    # Selection
    try:
        # group selection with bracketing and select complete residues
        selection = '(byres (' + str(selection) + '))'
        # checks functional selection
        cmd.count_atoms(selection)
    except:
        print "invalid selection"
        return False

    # PARAMETERS
    try:
        bonds = int(bonds)
    except:
        pass
    if (not (bonds in [1, 2])):
        bonds = 4

    if bonds == 1:
        cmd.set('valence', 0)
        print "Valence display disabled!"
        return bonds
    else:
        cmd.set('valence', 1)
        print "Valence display enabled!"
    # proceed

    ##### SELECTION BY OBJECT AND CHAIN #####
    # variable for the selections
    # get the names of the proteins in the selection
    objects = cmd.get_object_list(selection)
    # include chains

    # subselect chains
    names = []
    for p in objects:
        for chain in cmd.get_chains('model ' + p) or ['']:
            names.append("(model %s and chain '%s')" % (p, chain))

    ##### SELECTION LISTS #####
    # get TRP
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn TRP+NIW) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    # the integer is to ensure unique keys
    TRP_tuple = (1,) + tuple(stored.temp)

    # get PHETYR
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn PHE+TYR+PTR+NIY+PNIY) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    PHETYR_tuple = (2,) + tuple(stored.temp)

    # get HIS
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn HIS) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    HIS_tuple = (3,) + tuple(stored.temp)

    # get NITRO
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn NIY+PNIY+NIW) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    NITRO_tuple = (4,) + tuple(stored.temp)

    # get GLU
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn GLU) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    GLU_tuple = (5,) + tuple(stored.temp)

    # get ASP
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn ASP) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    ASP_tuple = (6,) + tuple(stored.temp)

    # get CTERM
    stored.temp = []
    for p in names:
        cmd.iterate(
            '(byres (last %s)) and (not (hetatm)) '
            'and (name OXT)' % (p),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    CTERM_tuple = (7,) + tuple(stored.temp)

    # get ARG
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn ARG) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    ARG_tuple = (8,) + tuple(stored.temp)

    ##### SELECTION TUPLES DONE #####

    ##### ATOM LISTS #####

    TRP_bonds_all = [
        ['CG', 'CD1'],
        ['CD1', 'NE1'],
        ['NE1', 'CE2'],
        ['CE2', 'CD2'],
        ['CD2', 'CG'],
        ['CD2', 'CE3'],
        ['CE3', 'CZ3'],
        ['CZ3', 'CH2'],
        ['CH2', 'CZ2'],
        ['CZ2', 'CE2']
    ]

    TRP_bonds_double = [
        ['CG', 'CD1'],
        ['CE2', 'CD2'],
        ['CE3', 'CZ3'],
        ['CH2', 'CZ2']
    ]

    PHETYR_bonds_all = [
        ['CG', 'CD1'],
        ['CD1', 'CE1'],
        ['CE1', 'CZ'],
        ['CZ', 'CE2'],
        ['CE2', 'CD2'],
        ['CD2', 'CG']
    ]

    PHETYR_bonds_double = [
        ['CG', 'CD1'],
        ['CE1', 'CZ'],
        ['CE2', 'CD2']
    ]

    HIS_bonds_all = [
        ['CG', 'CD2'],
        ['CD2', 'NE2'],
        ['NE2', 'CE1'],
        ['CE1', 'ND1'],
        ['ND1', 'CG'],
    ]

    HIS_bonds_double = [
        ['CG', 'CD2'],
        ['CE1', 'ND1']
    ]

    NITRO_bonds_all = [
        ['NN', 'O1'],
        ['NN', 'O2']
    ]
    NITRO_bonds_double = [
        ['NN', 'O1']
    ]

    GLU_bonds_all = [
        ['CD', 'OE1'],
        ['CD', 'OE2']
    ]
    GLU_bonds_double = [
        ['CD', 'OE1']
    ]

    ASP_bonds_all = [
        ['CG', 'OD1'],
        ['CG', 'OD2']
    ]
    ASP_bonds_double = [
        ['CG', 'OD1']
    ]

    CTERM_bonds_all = [
        ['C', 'O'],
        ['C', 'OXT']
    ]
    CTERM_bonds_double = [
        ['C', 'O']
    ]

    ARG_bonds_all = [
        ['CZ', 'NH1'],
        ['CZ', 'NH2']
    ]

    ARG_bonds_double=[
    ['CZ','NH1']
    ]

    ##### FORMATING #####

    # dictionary: entries:atoms
    format_dict = {
        TRP_tuple: [TRP_bonds_all, TRP_bonds_double],
        PHETYR_tuple: [PHETYR_bonds_all, PHETYR_bonds_double],
        HIS_tuple: [HIS_bonds_all, HIS_bonds_double],
        NITRO_tuple: [NITRO_bonds_all, NITRO_bonds_double],
        GLU_tuple: [GLU_bonds_all, GLU_bonds_double],
        ASP_tuple: [ASP_bonds_all, ASP_bonds_double],
        CTERM_tuple: [CTERM_bonds_all, CTERM_bonds_double],
        ARG_tuple: [ARG_bonds_all, ARG_bonds_double]
    }

    if bonds != 2:
        lines = 4
        print "Formating as delocalized bonds"
    else:
        lines = 1
        print "Formating as double bonds"

    # for all tuples (i.e format_dict.keys())
    for p in format_dict.keys():
        # go through list except ID at pos 1
        for q in p[1:]:
            # format bonds
            for r in format_dict[p][0]:
                cmd.unbond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]))
                cmd.bond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]), lines)
            if lines == 1:
                # add double bonds
                for r in format_dict[p][1]:
                    cmd.unbond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]))
                    cmd.bond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]), 2)

    return bonds
示例#25
0
def create_object_with_flipkin_coords(mpobj, which_flips='NQ'):
    '''Duplicate the mpobj molecule and apply the flipNQ/H group coordinates.

    PARAMETERS

        mpobj           An MPObject instance

        which_flips     Either 'NQ' or 'H' to specify which flipkin to use

    '''
    flipkin_name = 'flipkin{}'.format(which_flips)
    flipkin = mpobj.kin[flipkin_name]
    flip_group = 'flip{}'.format(which_flips)

    reduced_obj = mpobj.pdb['reduce']
    flipped_obj = mpobj.pdb[flipkin_name]
    cmd.create(flipped_obj, reduced_obj)

    for vl in flipkin.vectorlists():
        # Skip if not coordinates
        if vl[0].vectorlist_name == 'x':
            msg = 'skipping non-coords vectorlist {}'
            logger.debug(msg.format(vl[0].vectorlist_name))
            continue

        # Skip everything except the'flipNQ' (or 'flipH') group
        if vl[0].group[0] != flip_group:
            msg = 'skipping non-{} vectorlist'.format(flip_group)
            logger.debug(msg)
            continue

        logger.debug('begin flipping vectorlist')
        for v in vl:
            if not (v.atom[0] and v.atom[1]):
                msg = 'vector {} was missing atoms: {}'.format(v, v.atom)
                logger.warning(msg)
                continue
            macro = v.macro(1)
            sel = v.sel(1)
            logger.debug('atom to be flipped: {}\n  sel: {}'.format(macro, sel))
            source_coords = v.coords[1]

            target_sel = '{} and {}'.format(flipped_obj, sel)
            msg = 'flipping atom {} to {}'.format(target_sel, source_coords)
            logger.debug(msg)


            ret = cmd.load_coords([source_coords], target_sel)
            if ret == -1:
                success = 0
                a = v.atom[1]

                if a['resn'] == 'HIS':
                    his_h = {
                            'HD1': {
                                'old_h': 'HE2',
                                'old_n': 'NE2',
                                'new_h': 'HD1',
                                'new_n': 'ND1',
                                },
                            'HE2': {
                                'old_h': 'HD1',
                                'old_n': 'ND1',
                                'new_h': 'HE2',
                                'new_n': 'NE2',
                                }
                            }
                    if a['name'] in his_h.keys():
                        # Reduce has switched which N is protonated. Let's move
                        # the old H atom and rename it.
                        resi_sel = '{} and chain {} and resi {}'.format(
                            flipped_obj, a['chain'], a['resi'])
                        h = his_h[a['name']]
                        old_h = '{} and name {}'.format(resi_sel, h['old_h'])
                        old_n = '{} and name {}'.format(resi_sel, h['old_n'])
                        new_h = '{} and name {}'.format(resi_sel, h['new_h'])
                        new_n = '{} and name {}'.format(resi_sel, h['new_n'])

                        # Break the old bond
                        cmd.unbond(old_h, old_n)

                        # Rename the atom
                        cmd.alter(old_h, 'name="{}"'.format(a['name']))

                        # Make the new bond
                        cmd.bond(new_h, new_n)

                        # Retry loading coordinates
                        ret = cmd.load_coords([source_coords], target_sel)
                        if not ret == -1:
                            success = 1

                if not success:
                    msg = 'failed to load coords for {}!'.format(macro)
                    logger.warning(msg)

        logger.debug('end flipping vectorlist')
示例#26
0
# Basic Python Script using PyMol API to bond all the alpha carbons in a protein chain.
# Scripted to visualize knots and slipknots in a protein chain.
__author__ = 'Shashank'
from pymol import cmd, stored

# An array list used to store all the residue numbers which will be fetched.
residues = []
# iterate command used to fetch all the alpha carbon residue numbers from the given PDB
cmd.iterate('(n. CA)', 'residues.append(resi)')
n = residues.__len__()
i = 0
# Bond command in the API is used to connect all the consecutive CA atoms in the chain
while i<n-1:
    cmd.bond(residues[i]+'/CA',residues[i+1]+'/CA')
    print "Bonding "+residues[i]+" And "+residues[i+1]
    i = i+1
# Coloring the bonds using the Spectrum command
# cmd.load("1ALK_A_test.pdb")
# cmd.set("line_color","white")


示例#27
0
def fix_bonds(selection):

    stored.residues = []
    cmd.iterate(selection + ' and n. ca',
                'stored.residues.append((resi,resn))')
    last_residue = stored.residues[-1][0]
    print(last_residue)
    for r1 in range(len(stored.residues)):
        residue1 = selection + " and r. " + stored.residues[r1][
            1] + " and i. " + stored.residues[r1][0]
        sele1 = residue1 + " and n. ca+c+c+o+n"
        sele2 = residue1 + " and !n. ca+c+c+o+n+cb"
        print("unbond ", sele1, ",", sele2)
        cmd.unbond(sele1, sele2)
        for r2 in range(r1 + 1, len(stored.residues)):
            residue2 = selection + " and r. " + stored.residues[r2][
                1] + " and i. " + stored.residues[r2][0]
            if int(stored.residues[r1][0]) != int(stored.residues[r2][0]):
                sele1 = residue1
                sele2 = residue2
                print("unbond ", sele1, ",", sele2)
                cmd.unbond(sele1, sele2)
            if int(stored.residues[r2][0]) == (int(stored.residues[r1][0]) +
                                               1):
                sele1 = residue1 + " and n. c"
                sele2 = residue2 + " and n. n"
                print("bond ", sele1, ",", sele2)
                cmd.bond(sele1, sele2)

        # FIX RESIDUE SIDE CHAIN
        if stored.residues[r1][1] == "PRO":
            sele1 = residue1 + " and n. n"
            sele2 = residue1 + " and n. cd"
            print("bond ", sele1, ",", sele2)
            cmd.bond(sele1, sele2)
        elif stored.residues[r1][1] == "THR":
            sele1 = residue1 + " and !n. ca+og1+cg2+cb"
            sele2 = residue1 + " and n. cb"
            print("unbond ", sele1, ",", sele2)
            cmd.unbond(sele1, sele2)
        elif stored.residues[r1][1] == "ILE" or stored.residues[r1][1] == "VAL":
            for resitype in ["ILE", "VAL"]:
                sele1 = residue1 + " and !n. ca+cg1+cg2+cb"
                sele2 = residue1 + " and n. cb"
                print("unbond ", sele1, ",", sele2)
                cmd.unbond(sele1, sele2)
        elif stored.residues[r1][1] == "SER":
            sele1 = residue1 + " and !n. ca+og+cb"
            sele2 = residue1 + " and n. cb"
            print("unbond ", sele1, ",", sele2)
            cmd.unbond(sele1, sele2)
        elif stored.residues[r1][1] == "CYS":
            sele1 = residue1 + " and !n. ca+sg+cb"
            sele2 = residue1 + " and n. cb"
            print("unbond ", sele1, ",", sele2)
            cmd.unbond(sele1, sele2)
        else:
            sele1 = residue1 + " and !n. ca+cg+cb"
            sele2 = residue1 + " and n. cb"
            print("unbond ", sele1, ",", sele2)
            cmd.unbond(sele1, sele2)

        # FIX CENTROID LEVEL
        sele1 = residue1 + " and n. cen"
        sele2 = residue1 + " and n. cb"
        print("bond ", sele1, ",", sele2)
        cmd.bond(sele1, sele2)

        # FIX C-TERMINAL
        if stored.residues[r1][0] == last_residue:
            sele1 = residue1 + " and n. c"
            sele2 = residue1 + " and n. oxt"
            print("bond ", sele1, ",", sele2)
            cmd.bond(sele1, sele2)

    stored.cys = []
    cmd.iterate(selection + ' and r. CYS and n. cb',
                'stored.cys.append((resi,resn))')
    if len(stored.cys) >= 2:
        for r1 in range(len(stored.cys)):
            for r2 in range(r1 + 1, len(stored.cys)):
                if stored.cys[r1][0] != stored.cys[r2][0]:
                    sele1 = selection + " and i. " + stored.cys[r1][
                        0] + " and n. cb"
                    sele2 = selection + " and i. " + stored.cys[r2][
                        0] + " and n. cb"
                    dist = cmd.distance("tmpdist", sele1, sele2)
                    if dist < 4.0:
                        print(dist, sele1, ",", sele2)
                        sele1 = selection + " and i. " + stored.cys[r1][
                            0] + " and n. sg"
                        sele2 = selection + " and i. " + stored.cys[r2][
                            0] + " and n. sg"
                        print("bond ", sele1, ",", sele2)
                        cmd.bond(sele1, sele2)
    cmd.delete("tmpdist")
示例#28
0
cmd.pseudoatom("1-tess",
               pos=[-2.168, 63.157, 26.015],
               segi="lig",
               resn="LIG",
               resi=0,
               chain=0,
               name="O11")
cmd.select("c_pro", "/1-tess/pro///c*")
cmd.color("tv_green", "c_pro")
cmd.select("n_pro", "/1-tess/pro///n*")
cmd.color("tv_blue", "n_pro")
cmd.select("o_pro", "/1-tess/pro///o*")
cmd.color("tv_red", "o_pro")
cmd.select("s_pro", "/1-tess/pro///s*")
cmd.color("tv_yellow", "s_pro")
cmd.bond("/1-tess/lig/0/0/C1", "/1-tess/lig/0/0/C2")
cmd.bond("/1-tess/lig/0/0/C1", "/1-tess/lig/0/0/C3")
cmd.bond("/1-tess/lig/0/0/C1", "/1-tess/lig/0/0/C5")
cmd.bond("/1-tess/lig/0/0/C1", "/1-tess/lig/0/0/O1")
cmd.bond("/1-tess/lig/0/0/C1", "/1-tess/lig/0/0/O2")
cmd.bond("/1-tess/lig/0/0/C1", "/1-tess/lig/0/0/O5")
cmd.bond("/1-tess/lig/0/0/C1", "/1-tess/lig/0/0/O11")
cmd.bond("/1-tess/lig/0/0/C2", "/1-tess/lig/0/0/O1")
cmd.bond("/1-tess/lig/0/0/C2", "/1-tess/lig/0/0/O2")
cmd.bond("/1-tess/lig/0/0/C2", "/1-tess/lig/0/0/O3")
cmd.bond("/1-tess/lig/0/0/C2", "/1-tess/lig/0/0/O4")
cmd.bond("/1-tess/lig/0/0/C2", "/1-tess/lig/0/0/O5")
cmd.bond("/1-tess/pro/A/29/OG", "/1-tess/lig/0/0/O3")
cmd.bond("/1-tess/lig/0/0/C3", "/1-tess/lig/0/0/C4")
cmd.bond("/1-tess/lig/0/0/C3", "/1-tess/lig/0/0/C5")
cmd.bond("/1-tess/lig/0/0/C3", "/1-tess/lig/0/0/O2")
示例#29
0
def create_object_with_flipkin_coords(mpobj, which_flips='NQ'):
    '''Duplicate the mpobj molecule and apply the flipNQ/H group coordinates.

    PARAMETERS

        mpobj           An MPObject instance

        which_flips     Either 'NQ' or 'H' to specify which flipkin to use

    '''
    flipkin_name = 'flipkin{}'.format(which_flips)
    flipkin = mpobj.kin[flipkin_name]
    flip_group = 'flip{}'.format(which_flips)

    reduced_obj = mpobj.pdb['reduce']
    flipped_obj = mpobj.pdb[flipkin_name]
    cmd.create(flipped_obj, reduced_obj)

    for vl in flipkin.vectorlists():
        # Skip if not coordinates
        if vl[0].vectorlist_name == 'x':
            msg = 'skipping non-coords vectorlist {}'
            logger.debug(msg.format(vl[0].vectorlist_name))
            continue

        # Skip everything except the'flipNQ' (or 'flipH') group
        if vl[0].group[0] != flip_group:
            msg = 'skipping non-{} vectorlist'.format(flip_group)
            logger.debug(msg)
            continue

        logger.debug('begin flipping vectorlist')
        for v in vl:
            if not (v.atom[0] and v.atom[1]):
                msg = 'vector {} was missing atoms: {}'.format(v, v.atom)
                logger.warning(msg)
                continue
            macro = v.macro(1)
            sel = v.sel(1)
            logger.debug('atom to be flipped: {}\n  sel: {}'.format(
                macro, sel))
            source_coords = v.coords[1]

            target_sel = '{} and {}'.format(flipped_obj, sel)
            msg = 'flipping atom {} to {}'.format(target_sel, source_coords)
            logger.debug(msg)

            ret = cmd.load_coords([source_coords], target_sel)
            if ret == -1:
                success = 0
                a = v.atom[1]

                if a['resn'] == 'HIS':
                    his_h = {
                        'HD1': {
                            'old_h': 'HE2',
                            'old_n': 'NE2',
                            'new_h': 'HD1',
                            'new_n': 'ND1',
                        },
                        'HE2': {
                            'old_h': 'HD1',
                            'old_n': 'ND1',
                            'new_h': 'HE2',
                            'new_n': 'NE2',
                        }
                    }
                    if a['name'] in his_h.keys():
                        # Reduce has switched which N is protonated. Let's move
                        # the old H atom and rename it.
                        resi_sel = '{} and chain {} and resi {}'.format(
                            flipped_obj, a['chain'], a['resi'])
                        h = his_h[a['name']]
                        old_h = '{} and name {}'.format(resi_sel, h['old_h'])
                        old_n = '{} and name {}'.format(resi_sel, h['old_n'])
                        new_h = '{} and name {}'.format(resi_sel, h['new_h'])
                        new_n = '{} and name {}'.format(resi_sel, h['new_n'])

                        # Break the old bond
                        cmd.unbond(old_h, old_n)

                        # Rename the atom
                        cmd.alter(old_h, 'name="{}"'.format(a['name']))

                        # Make the new bond
                        cmd.bond(new_h, new_n)

                        # Retry loading coordinates
                        ret = cmd.load_coords([source_coords], target_sel)
                        if not ret == -1:
                            success = 1

                if not success:
                    msg = 'failed to load coords for {}!'.format(macro)
                    logger.warning(msg)

        logger.debug('end flipping vectorlist')
        CTERM_tuple: [CTERM_bonds_all, CTERM_bonds_double],
        ARG_tuple: [ARG_bonds_all, ARG_bonds_double]
    }

    if bonds != 2:
        lines = 4
        print "Formating as delocalized bonds"
    else:
        lines = 1
        print "Formating as double bonds"

    # for all tuples (i.e format_dict.keys())
    for p in format_dict.keys():
        # go through list except ID at pos 1
        for q in p[1:]:
            # format bonds
            for r in format_dict[p][0]:
                cmd.unbond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]))
                cmd.bond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]), lines)
            if lines == 1:
                # add double bonds
                for r in format_dict[p][1]:
                    cmd.unbond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]))
                    cmd.bond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]), 2)

    return bonds
cmd.extend("format_bonds", format_bonds)
cmd.auto_arg[0]['format_bonds'] = [lambda: cmd.Shortcut(['all', 'resn PHE+TYR+PTR+NIY+PNIY+TRP+NIW+HIS', 'resn GLU+ASP', 'resn ARG', 'last all']), 'selection=', ', ']
cmd.auto_arg[1]['format_bonds'] = [lambda: cmd.Shortcut(['4', '2', '1']), 'bonds=', '']
################################################################################
示例#31
0
def format_bonds(
    selection='all',
    bonds=4,
):
    '''
DESCRIPTION
    Formats bonds in aromatic or charged residues
EXAMPLE
    frag PHE
    format_bonds
USAGE
    format_bonds [ selection [, bonds ]]
ARGUMENTS
    selection: <str> input selection {default: 'all'}
    bonds:     <int> toogles format of bonds
               1: single bonds (deactivates valence display)
               2: regular double bonds (activates valence display)
             >=3: delocalized (activates valence display)
    '''
    # Selection
    try:
        # group selection with bracketing and select complete residues
        selection = '(byres (' + str(selection) + '))'
        # checks functional selection
        cmd.count_atoms(selection)
    except:
        print("invalid selection")
        return False

    # PARAMETERS
    try:
        bonds = int(bonds)
    except:
        pass
    if (not (bonds in [1, 2])):
        bonds = 4

    if bonds == 1:
        cmd.set('valence', 0)
        print("Valence display disabled!")
        return bonds
    else:
        cmd.set('valence', 1)
        print("Valence display enabled!")
    # proceed

    ##### SELECTION BY OBJECT AND CHAIN #####
    # variable for the selections
    # get the names of the proteins in the selection
    objects = cmd.get_object_list(selection)
    # include chains

    # subselect chains
    names = []
    for p in objects:
        for chain in cmd.get_chains('model ' + p) or ['']:
            names.append("(model %s and chain '%s')" % (p, chain))

    ##### SELECTION LISTS #####
    # get TRP
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn TRP+NIW) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    # the integer is to ensure unique keys
    TRP_tuple = (1, ) + tuple(stored.temp)

    # get PHETYR
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn PHE+TYR+PTR+NIY+PNIY) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    PHETYR_tuple = (2, ) + tuple(stored.temp)

    # get HIS
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn HIS) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    HIS_tuple = (3, ) + tuple(stored.temp)

    # get NITRO
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn NIY+PNIY+NIW) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    NITRO_tuple = (4, ) + tuple(stored.temp)

    # get GLU
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn GLU) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    GLU_tuple = (5, ) + tuple(stored.temp)

    # get ASP
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn ASP) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    ASP_tuple = (6, ) + tuple(stored.temp)

    # get CTERM
    stored.temp = []
    for p in names:
        cmd.iterate(
            '(byres (last %s)) and (not (hetatm)) '
            'and (name OXT)' % (p),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    CTERM_tuple = (7, ) + tuple(stored.temp)

    # get ARG
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn ARG) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    ARG_tuple = (8, ) + tuple(stored.temp)

    ##### SELECTION TUPLES DONE #####

    ##### ATOM LISTS #####

    TRP_bonds_all = [['CG', 'CD1'], ['CD1', 'NE1'], ['NE1', 'CE2'],
                     ['CE2', 'CD2'], ['CD2', 'CG'], ['CD2', 'CE3'],
                     ['CE3', 'CZ3'], ['CZ3', 'CH2'], ['CH2', 'CZ2'],
                     ['CZ2', 'CE2']]

    TRP_bonds_double = [['CG', 'CD1'], ['CE2', 'CD2'], ['CE3', 'CZ3'],
                        ['CH2', 'CZ2']]

    PHETYR_bonds_all = [['CG', 'CD1'], ['CD1', 'CE1'], ['CE1', 'CZ'],
                        ['CZ', 'CE2'], ['CE2', 'CD2'], ['CD2', 'CG']]

    PHETYR_bonds_double = [['CG', 'CD1'], ['CE1', 'CZ'], ['CE2', 'CD2']]

    HIS_bonds_all = [
        ['CG', 'CD2'],
        ['CD2', 'NE2'],
        ['NE2', 'CE1'],
        ['CE1', 'ND1'],
        ['ND1', 'CG'],
    ]

    HIS_bonds_double = [['CG', 'CD2'], ['CE1', 'ND1']]

    NITRO_bonds_all = [['NN', 'O1'], ['NN', 'O2']]
    NITRO_bonds_double = [['NN', 'O1']]

    GLU_bonds_all = [['CD', 'OE1'], ['CD', 'OE2']]
    GLU_bonds_double = [['CD', 'OE1']]

    ASP_bonds_all = [['CG', 'OD1'], ['CG', 'OD2']]
    ASP_bonds_double = [['CG', 'OD1']]

    CTERM_bonds_all = [['C', 'O'], ['C', 'OXT']]
    CTERM_bonds_double = [['C', 'O']]

    ARG_bonds_all = [['CZ', 'NH1'], ['CZ', 'NH2']]

    ARG_bonds_double = [['CZ', 'NH1']]

    ##### FORMATING #####

    # dictionary: entries:atoms
    format_dict = {
        TRP_tuple: [TRP_bonds_all, TRP_bonds_double],
        PHETYR_tuple: [PHETYR_bonds_all, PHETYR_bonds_double],
        HIS_tuple: [HIS_bonds_all, HIS_bonds_double],
        NITRO_tuple: [NITRO_bonds_all, NITRO_bonds_double],
        GLU_tuple: [GLU_bonds_all, GLU_bonds_double],
        ASP_tuple: [ASP_bonds_all, ASP_bonds_double],
        CTERM_tuple: [CTERM_bonds_all, CTERM_bonds_double],
        ARG_tuple: [ARG_bonds_all, ARG_bonds_double]
    }

    if bonds != 2:
        lines = 4
        print("Formating as delocalized bonds")
    else:
        lines = 1
        print("Formating as double bonds")

    # for all tuples (i.e format_dict.keys())
    for p in list(format_dict.keys()):
        # go through list except ID at pos 1
        for q in p[1:]:
            # format bonds
            for r in format_dict[p][0]:
                cmd.unbond('%s and name %s' % (q, r[0]),
                           '%s and name %s' % (q, r[1]))
                cmd.bond('%s and name %s' % (q, r[0]),
                         '%s and name %s' % (q, r[1]), lines)
            if lines == 1:
                # add double bonds
                for r in format_dict[p][1]:
                    cmd.unbond('%s and name %s' % (q, r[0]),
                               '%s and name %s' % (q, r[1]))
                    cmd.bond('%s and name %s' % (q, r[0]),
                             '%s and name %s' % (q, r[1]), 2)

    return bonds
示例#32
0
    def apply(self):
        cmd=self.cmd
        if self.status==1:
            # find the name of the object which contains the selection
            src_frame = cmd.get_state()
            try:
                new_name = cmd.get_object_list(src_sele)[0]
            except IndexError:
                print(" Mutagenesis: object not found.")
                return

            if True:
                auto_zoom = cmd.get_setting_text('auto_zoom')
                cmd.set('auto_zoom',"0",quiet=1)
                if self.lib_mode!="current":
                    # create copy with mutant in correct frame
                    state = cmd.get_object_state(new_name)
                    cmd.create(tmp_obj2, obj_name, src_frame, state)
                    cmd.set_title(tmp_obj2, state, '')
                    cmd.color(self.stored.identifiers[4], "?%s & elem C" % tmp_obj2)
                    cmd.alter(tmp_obj2, 'ID = -1')

                    # select backbone connection atoms
                    cmd.select(tmp_sele1, 'neighbor ?%s' % (src_sele), 0)

                    # remove residue and neighboring c-cap/n-cap (if any)
                    cmd.remove("?%s | byres (?%s & "
                            "(name N & resn NME+NHH | name C & resn ACE))" % (src_sele, tmp_sele1))

                    # create the merged molecule
                    cmd.create(new_name, "?%s | ?%s" % (new_name, tmp_obj2), state, state)

                    # now connect them
                    cmd.select(tmp_sele2, '/%s/%s/%s/%s' % ((new_name,) + self.stored.identifiers[:3]))
                    cmd.bond('?%s & name C' % (tmp_sele1), '?%s & name N' % (tmp_sele2), quiet=1)
                    cmd.bond('?%s & name N' % (tmp_sele1), '?%s & name C' % (tmp_sele2), quiet=1)
                    cmd.set_geometry('(?%s | ?%s) & name C+N' % (tmp_sele1, tmp_sele2), 3, 3) # make amide planer

                    # fix N-H hydrogen position (if any exists)
                    cmd.h_fix('?%s & name N' % (tmp_sele2))

                    # delete temporary objects/selections
                    cmd.delete(tmp_sele1)
                    cmd.delete(tmp_sele2)
                    cmd.delete(tmp_obj2)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()
                else:
                    # create copy with conformation in correct state
                    cmd.create(tmp_obj2,obj_name,src_frame,1)

                    # remove existing c-cap in copy (if any)
                    cmd.remove("byres (name N and (%s in (neighbor %s)) and resn NME+NHH)"%
                                (new_name,src_sele))
                    cmd.remove("(%s) and name OXT"%src_sele)

                    # remove existing n-cap in copy (if any)
                    cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ACE)"%
                                (new_name,src_sele))

                    # save existing conformation on undo stack
#               cmd.edit("((%s in %s) and name ca)"%(new_name,src_sele))
                    cmd.push_undo("("+src_sele+")")
                    # modify the conformation
                    cmd.update(new_name,tmp_obj2)
#               cmd.unpick()
                    cmd.delete(tmp_obj2)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()
                cmd.set('auto_zoom',auto_zoom,quiet=1)
示例#33
0
def peptide_rebuild(name, selection='all', cycles=1000, state=1, quiet=1):
    '''
DESCRIPTION

    Rebuild the peptide from selection. All atoms which are present in
    selection will be kept fixed, while atoms missing in selection are
    placed by sculpting.

USAGE

    peptide_rebuild name [, selection [, cycles [, state ]]]

SEE ALSO

    stub2ala, add_missing_atoms, peptide_rebuild_modeller
    '''
    from chempy import fragments, feedback, models

    cycles, state, quiet = int(cycles), int(state), int(quiet)

    # suppress feedback for model merging
    feedback['actions'] = False

    # work with named selection
    namedsele = cmd.get_unused_name('_')
    cmd.select(namedsele, selection, 0)

    identifiers = []
    cmd.iterate(namedsele + ' and polymer and guide and alt +A',
            'identifiers.append([segi,chain,resi,resv,resn])', space=locals())

    model = models.Indexed()
    for (segi,chain,resi,resv,resn) in identifiers:
        try:
            fname = resn.lower() if resn != 'MSE' else 'met'
            frag = fragments.get(fname)
        except IOError:
            print(' Warning: unknown residue:', resn)
            continue

        for a in frag.atom:
            a.segi = segi
            a.chain = chain
            a.resi = resi
            a.resi_number = resv
            a.resn = resn

        model.merge(frag)

    if not quiet:
        print(' Loading model...')

    cmd.load_model(model, name, 1, zoom=0)
    if cmd.get_setting_boolean('auto_remove_hydrogens'):
        cmd.remove(name + ' and hydro')

    cmd.protect(name + ' in ' + namedsele)
    cmd.sculpt_activate(name)
    cmd.update(name, namedsele, 1, state)
    cmd.delete(namedsele)

    if not quiet:
        print(' Sculpting...')

    cmd.set('sculpt_field_mask', 0x003, name) # bonds and angles only
    cmd.sculpt_iterate(name, 1, int(cycles / 4))

    cmd.set('sculpt_field_mask', 0x09F, name) # local + torsions
    cmd.sculpt_iterate(name, 1, int(cycles / 4))

    cmd.set('sculpt_field_mask', 0x0FF, name) # ... + vdw
    cmd.sculpt_iterate(name, 1, int(cycles / 2))

    cmd.sculpt_deactivate(name)
    cmd.deprotect(name)
    cmd.unset('sculpt_field_mask', name)

    if not quiet:
        print(' Connecting peptide...')

    pairs = cmd.find_pairs(name + ' and name C', name + ' and name N', 1, 1, 2.0)
    for pair in pairs:
        cmd.bond(*pair)
    cmd.h_fix(name)

    if not quiet:
        print(' peptide_rebuild: done')
示例#34
0
def add_missing_atoms(selection='all', cycles=200, quiet=1):
    '''
DESCRIPTION

    Mutate those residues to themselves which have missing atoms

SEE ALSO

    stub2ala
    '''
    from collections import defaultdict
    from chempy import fragments

    cycles, quiet = int(cycles), int(quiet)

    reference = {
        'ALA': set(['CB']),
        'ARG': set(['CB', 'CG', 'NE', 'CZ', 'NH1', 'NH2', 'CD']),
        'ASN': set(['CB', 'CG', 'OD1', 'ND2']),
        'ASP': set(['CB', 'CG', 'OD1', 'OD2']),
        'CYS': set(['CB', 'SG']),
        'GLN': set(['CB', 'CG', 'CD', 'NE2', 'OE1']),
        'GLU': set(['CB', 'CG', 'OE2', 'CD', 'OE1']),
        'GLY': set([]),
        'HIS': set(['CE1', 'CB', 'CG', 'CD2', 'ND1', 'NE2']),
        'ILE': set(['CB', 'CD1', 'CG1', 'CG2']),
        'LEU': set(['CB', 'CG', 'CD1', 'CD2']),
        'LYS': set(['CB', 'CG', 'NZ', 'CE', 'CD']),
        'MET': set(['CB', 'CG', 'CE', 'SD']),
        'PHE': set(['CE1', 'CB', 'CG', 'CZ', 'CD1', 'CD2', 'CE2']),
        'PRO': set(['CB', 'CG', 'CD']),
        'SER': set(['OG', 'CB']),
        'THR': set(['CB', 'OG1', 'CG2']),
        'TRP': set(['CZ2', 'CB', 'CG', 'CH2', 'CE3', 'CD1', 'CD2', 'CZ3', 'NE1', 'CE2']),
        'TYR': set(['CE1', 'OH', 'CB', 'CG', 'CZ', 'CD1', 'CD2', 'CE2']),
        'VAL': set(['CB', 'CG1', 'CG2']),
    }

    namedsele = cmd.get_unused_name('_')
    cmd.select(namedsele, selection, 0)

    namelists = defaultdict(list)
    cmd.iterate('(%s) and polymer' % namedsele,
            'namelists[model,segi,chain,resn,resi,resv].append(name)',
            space=locals())

    sele_dict = defaultdict(list)
    tmp_name = cmd.get_unused_name('_')

    for key, namelist in namelists.items():
        resn = key[3]
        if resn not in reference:
            if not quiet:
                print(' Unknown residue:', resn)
            continue
        if not reference[resn].issubset(namelist):
            try:
                frag = fragments.get(resn.lower())
                for a in frag.atom:
                    a.segi = key[1]
                    a.chain = key[2]
                    a.resi = key[4]
                    a.resi_number = key[5]
                cmd.load_model(frag, tmp_name, 1, zoom=0)

                skey = '/%s/%s/%s/%s`%s' % key[:5]
                cmd.remove(skey + ' and not name N+C+O+OXT+CA')
                cmd.align(tmp_name, skey + ' and name N+C+CA', cycles=0)
                cmd.remove(tmp_name + ' and (name N+C+O+CA or hydro)')
                cmd.fuse('name CB and ' + tmp_name, 'name CA and ' + skey, move=0)
                if resn == 'PRO':
                    cmd.bond(skey + '/N', skey + '/CD')
                cmd.unpick()
                cmd.delete(tmp_name)

                sele_dict[key[0]].append(skey)

                if not quiet:
                    print(' Mutated ', skey)
            except:
                print(' Mutating', skey, 'failed')

    for model in sele_dict:
        cmd.sort(model)
        sculpt_relax(' '.join(sele_dict[model]), 0, 0, model, cycles)

    cmd.delete(namedsele)
示例#35
0
def load_ff(filename):
    """
        Load a fDynamo force field file (.ff)

        Re-bond ligands accordingly
        Alter properties of all atoms:
         - 'text_type' : atomtypes
         - 'partial_charges' : charges

        Parameters
        ----------
        filename : str
            file path
    """

    print(f" pyDYNAMON: reading \"{filename}\"")

    # residue names excluded from re-bonding
    rebond_excluded = []
    rebond_excluded.extend(aa_dict.keys())
    rebond_excluded.extend(["SOL", "NA", "CL"])

    # read file as list of strings
    with open(filename, "rt") as f:
        ff_file = f.readlines()
        # remove comment lines and blank lines
        ff_file = [
            line.strip() for line in ff_file
            if line.strip() and not line.startswith("!")
        ]

    # read residue atoms and bonds
    topology = dict()
    current_sect = None
    for line in ff_file:
        line = line.split("!")
        keyword = line[0].split()[0].lower()
        content = line[0].split()
        if keyword == 'end':
            current_sect = None
        elif keyword == 'residues':
            current_sect = keyword
        elif current_sect == 'residues' or keyword == 'residue':
            if keyword == 'residue':  # new residue
                current_sect = 'residues'
                resname = content[1]
                topology[resname] = dict()
                continue
            top = topology[resname]
            if not topology[resname]:  # first line (numbers)
                top['natoms'] = int(content[0])
                top['nbonds'] = int(content[1])
                top['nimpropers'] = int(content[2])
                top['atoms'] = dict()
                top['bonds'] = []
                top['impropers'] = []
            elif len(top['atoms']) < top['natoms']:
                param = {
                    'atomtype': str(content[1]).upper(),
                    'charge': float(content[2])
                }
                top['atoms'][str(content[0]).upper()] = param
            elif len(top['bonds']) < top['nbonds']:
                bonds = [(b.split()[0].upper(), b.split()[1].upper())
                         for b in " ".join(content).split(";") if b.strip()]
                top['bonds'].extend(bonds)
            elif len(top['impropers']) < top['nimpropers']:
                impropers = [(i.split()[0].upper(), i.split()[1].upper(),
                              i.split()[2].upper(), i.split()[3].upper())
                             for i in " ".join(content).split(";")
                             if i.strip()]
                top['impropers'].extend(impropers)

    for resname, top in topology.items():
        # atomtypes and partial charges
        for name, param in top['atoms'].items():
            cmd.alter(f"resn {resname} & name {name}",
                      f"partial_charge={param['charge']}")
            cmd.alter(f"resn {resname} & name {name}",
                      f"text_type=\'{param['atomtype']}\'")
        # unbond all and re-bond
        if resname in rebond_excluded: continue
        cmd.unbond(f"resn {resname}", f"resn {resname}")
        for bond in top['bonds']:
            cmd.bond(f"resn {resname} & name {bond[0]}",
                     f"resn {resname} & name {bond[1]}")
示例#36
0
    def apply(self):
        cmd=self.cmd
        if self.status==1:
            # find the name of the object which contains the selection
            src_frame = cmd.get_state()
            try:
                new_name = cmd.get_object_list(src_sele)[0]
            except IndexError:
                print(" Mutagenesis: object not found.")
                return

            if True:
                auto_zoom = cmd.get_setting_text('auto_zoom')
                cmd.set('auto_zoom',"0",quiet=1)
                if self.lib_mode!="current":
                    # create copy with mutant in correct frame
                    state = cmd.get_object_state(new_name)
                    cmd.create(tmp_obj2, obj_name, src_frame, state)
                    cmd.set_title(tmp_obj2, state, '')
                    cmd.color(self.stored.identifiers[4], "?%s & elem C" % tmp_obj2)
                    cmd.alter(tmp_obj2, 'ID = -1')

                    # select backbone connection atoms
                    cmd.select(tmp_sele1, 'neighbor ?%s' % (src_sele), 0)

                    # remove residue and neighboring c-cap/n-cap (if any)
                    cmd.remove("?%s | byres (?%s & "
                            "(name N & resn NME+NHH | name C & resn ACE))" % (src_sele, tmp_sele1))

                    # create the merged molecule
                    cmd.create(new_name, "?%s | ?%s" % (new_name, tmp_obj2), state, state)

                    # now connect them
                    cmd.select(tmp_sele2, '/%s/%s/%s/%s' % ((new_name,) + self.stored.identifiers[:3]))
                    cmd.bond('?%s & name C' % (tmp_sele1), '?%s & name N' % (tmp_sele2), quiet=1)
                    cmd.bond('?%s & name N' % (tmp_sele1), '?%s & name C' % (tmp_sele2), quiet=1)
                    cmd.set_geometry('(?%s | ?%s) & name C+N' % (tmp_sele1, tmp_sele2), 3, 3) # make amide planer

                    # fix N-H hydrogen position (if any exists)
                    cmd.h_fix('?%s & name N' % (tmp_sele2))
                    
                    # delete temporary objects/selections
                    cmd.delete(tmp_sele1)
                    cmd.delete(tmp_sele2)
                    cmd.delete(tmp_obj2)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()               
                else:
                    # create copy with conformation in correct state
                    cmd.create(tmp_obj2,obj_name,src_frame,1)

                    # remove existing c-cap in copy (if any)
                    cmd.remove("byres (name N and (%s in (neighbor %s)) and resn NME+NHH)"%
                                (new_name,src_sele))
                    cmd.remove("(%s) and name OXT"%src_sele)
                    
                    # remove existing n-cap in copy (if any)
                    cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ACE)"%
                                (new_name,src_sele))

                    # save existing conformation on undo stack
#               cmd.edit("((%s in %s) and name ca)"%(new_name,src_sele))
                    cmd.push_undo("("+src_sele+")")
                    # modify the conformation
                    cmd.update(new_name,tmp_obj2)
#               cmd.unpick()
                    cmd.delete(tmp_obj2)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()                              
                cmd.set('auto_zoom',auto_zoom,quiet=1)
示例#37
0
    def do_library(self):
        cmd=self.cmd
        pymol=cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name C"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name O"%src_sele)==1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable","selector","everythin")
        cmd.feedback("disable","editor","actions")
        self.prompt = [ 'Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight",src_sele)
        
        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom',"0",quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele,animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode=="current":
            pymol.stored.resn=""
            cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn)
            if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'):
                self.lib_mode = rot_type # force fragment-based load
            else:
                cmd.create(frag_name,src_sele,1,1)
                if self.c_cap=='open':
                    cmd.remove("%s and name OXT"%frag_name)
                    
        if self.lib_mode!='current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'):
                if not ( cmd.count_atoms(
                    "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"%
                                     (src_sele,src_sele))):
                    # use N-terminal fragment
                    frag_type ="NT_"+frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'):
                if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                     (src_sele,src_sele))):
                    # use C-terminal fragment
                    frag_type ="CT_"+frag_type
            if rot_type[0:3] in [ 'NT_', 'CT_' ]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("("+frag_name+" and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("("+src_sele+") and hydro")==0:
                    cmd.remove("("+frag_name+" and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space)
            cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and
                 (cmd.count_atoms("(%s & name CB)"%src_sele)==1)):
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name CB)"%frag_name,
                             "(%s & name CB)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)
            else:
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]")
            cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)"%src_sele):
                cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]")
                cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)"%frag_name,
                                         "(%s & name CA)"%frag_name,
                                         "(%s & name C)"%frag_name,
                                         "(%s & name O)"%frag_name)
                cmd.protect("(%s & name O)"%frag_name)
                cmd.set_dihedral("(%s & name N)"%frag_name,
                                 "(%s & name CA)"%frag_name,
                                 "(%s & name C)"%frag_name,
                                 "(%s & name OXT)"%frag_name,180.0+angle)
                cmd.deprotect(frag_name)

                
            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1:
                    cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele,
                                      "stored.list=[x,y,z]")
                    cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name,
                                    "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)"%frag_name,
                                             "(%s & name CA)"%frag_name,
                                             "(%s & name N)"%frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)"%frag_name,
                                     "(%s & name CA)"%frag_name,
                                     "(%s & name N)"%frag_name,
                                     "(%s & name H)"%frag_name,180.0+angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in [ 'amin', 'nmet' ]:
                if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name C & (%s)"%(frag_name))==1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh')
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")
                         
            # add n-cap (if appropriate)
            if self.n_cap in [ 'acet' ]:
                if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name N & (%s)"%(frag_name))==1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & (%s)"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")
 

                    

        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0)
            
        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s"%src_sele)
                if len(result)==1:
                    (phi,psi) = list(result.values())[0]
                    (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10))))
                    key = (rot_type,phi,psi)
                    if key not in self.dep_library:
                        (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20))))
                        key = (rot_type,phi,psi)                    
                        if key not in self.dep_library:
                            (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60))))
                            key = (rot_type,phi,psi)
                    lib = self.dep_library.get(key,None)
            except:
                pass
        if lib == None:
            key = rot_type
            lib = self.ind_library.get(key,None)
            if (lib!= None) and self.dep == 'dep':
                print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.')
        if lib != None:
            state = 1
            for a in lib:
                cmd.create(obj_name,frag_name,1,state)
                if state == 1:
                    cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele)) 
                if rot_type=='PRO':
                    cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                for b in a.keys():
                    if b!='FREQ':
                        cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]),
                                         "(%s & n;%s)"%(mut_sele,b[1]),
                                         "(%s & n;%s)"%(mut_sele,b[2]),
                                         "(%s & n;%s)"%(mut_sele,b[3]),
                                         a[b],state=state)
                    else:
                        cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100))
                if rot_type=='PRO':
                    cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)                
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded."%len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(bump_name,
                "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"%
                           (src_sele,mut_sele,src_sele,mut_sele),singletons=1)
                cmd.color("gray50",bump_name+" and elem C")
                cmd.set("seq_view",0,bump_name,quiet=1)
                cmd.hide("everything",bump_name)
                if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2, "(name C & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2,"(name N & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)
                
                cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"%
                            (bump_name,bump_name,mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo",bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode",1,bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name,frag_name,1,1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view",0,obj_name,quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("("+obj_name+")")
        cmd.show(self.rep,obj_name)
        cmd.show('lines',obj_name) #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon",obj_name)
        if sticks:
            cmd.show("sticks",obj_name)
        cmd.set('auto_zoom',auto_zoom,quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)
        cmd.unpick()
        cmd.feedback("pop")
示例#38
0
    def do_library(self):
        cmd=self.cmd
        pymol=cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name C"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name O"%src_sele)==1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable","selector","everythin")
        cmd.feedback("disable","editor","actions")
        self.prompt = [ 'Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight",src_sele)

        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom',"0",quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele,animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode=="current":
            pymol.stored.resn=""
            cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn)
            if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'):
                self.lib_mode = rot_type # force fragment-based load
            else:
                cmd.create(frag_name,src_sele,1,1)
                if self.c_cap=='open':
                    cmd.remove("%s and name OXT"%frag_name)

        if self.lib_mode!='current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'):
                if not ( cmd.count_atoms(
                    "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"%
                                     (src_sele,src_sele))):
                    # use N-terminal fragment
                    frag_type ="NT_"+frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'):
                if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                     (src_sele,src_sele))):
                    # use C-terminal fragment
                    frag_type ="CT_"+frag_type
            if rot_type[0:3] in [ 'NT_', 'CT_' ]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("("+frag_name+" and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("("+src_sele+") and hydro")==0:
                    cmd.remove("("+frag_name+" and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space)
            cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and
                 (cmd.count_atoms("(%s & name CB)"%src_sele)==1)):
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name CB)"%frag_name,
                             "(%s & name CB)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)
            else:
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]")
            cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)"%src_sele):
                cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]")
                cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)"%frag_name,
                                         "(%s & name CA)"%frag_name,
                                         "(%s & name C)"%frag_name,
                                         "(%s & name O)"%frag_name)
                cmd.protect("(%s & name O)"%frag_name)
                cmd.set_dihedral("(%s & name N)"%frag_name,
                                 "(%s & name CA)"%frag_name,
                                 "(%s & name C)"%frag_name,
                                 "(%s & name OXT)"%frag_name,180.0+angle)
                cmd.deprotect(frag_name)


            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1:
                    cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele,
                                      "stored.list=[x,y,z]")
                    cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name,
                                    "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)"%frag_name,
                                             "(%s & name CA)"%frag_name,
                                             "(%s & name N)"%frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)"%frag_name,
                                     "(%s & name CA)"%frag_name,
                                     "(%s & name N)"%frag_name,
                                     "(%s & name H)"%frag_name,180.0+angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in [ 'amin', 'nmet' ]:
                if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name C & (%s)"%(frag_name))==1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh')
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in [ 'acet' ]:
                if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name N & (%s)"%(frag_name))==1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & (%s)"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")




        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0)

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s"%src_sele)
                if len(result)==1:
                    (phi,psi) = list(result.values())[0]
                    (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10))))
                    key = (rot_type,phi,psi)
                    if key not in self.dep_library:
                        (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20))))
                        key = (rot_type,phi,psi)
                        if key not in self.dep_library:
                            (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60))))
                            key = (rot_type,phi,psi)
                    lib = self.dep_library.get(key,None)
            except:
                pass
        if lib is None:
            key = rot_type
            lib = self.ind_library.get(key,None)
            if (lib is not None) and self.dep == 'dep':
                print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.')
        if lib is not None:
            state = 1
            for a in lib:
                cmd.create(obj_name,frag_name,1,state)
                if state == 1:
                    cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele))
                if rot_type=='PRO':
                    cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                for b in a.keys():
                    if b!='FREQ':
                        cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]),
                                         "(%s & n;%s)"%(mut_sele,b[1]),
                                         "(%s & n;%s)"%(mut_sele,b[2]),
                                         "(%s & n;%s)"%(mut_sele,b[3]),
                                         a[b],state=state)
                    else:
                        cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100))
                if rot_type=='PRO':
                    cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded."%len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(bump_name,
                "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"%
                           (src_sele,mut_sele,src_sele,mut_sele),singletons=1)
                cmd.color("gray50",bump_name+" and elem C")
                cmd.set("seq_view",0,bump_name,quiet=1)
                cmd.hide("everything",bump_name)
                if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2, "(name C & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2,"(name N & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"%
                            (bump_name,bump_name,mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo",bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode",1,bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name,frag_name,1,1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view",0,obj_name,quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("("+obj_name+")")
        cmd.show(self.rep,obj_name)
        cmd.show('lines',obj_name) #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon",obj_name)
        if sticks:
            cmd.show("sticks",obj_name)
        cmd.set('auto_zoom',auto_zoom,quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)
        cmd.unpick()
        cmd.feedback("pop")
示例#39
0
    def do_library(self):
        cmd = self.cmd
        pymol = cmd._pymol
        if not (
            (cmd.count_atoms("(%s) and name n" % src_sele) == 1)
            and (cmd.count_atoms("(%s) and name c" % src_sele) == 1)
            and (cmd.count_atoms("(%s) and name o" % src_sele) == 1)
        ):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable", "selector", "everythin")
        cmd.feedback("disable", "editor", "actions")
        self.prompt = ["Loading rotamers..."]

        pymol.stored.name = "residue"
        cmd.iterate("first (%s)" % src_sele, 'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight", src_sele)

        auto_zoom = cmd.get_setting_text("auto_zoom")
        cmd.set("auto_zoom", "0", quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele, animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode == "current":
            pymol.stored.resn = ""
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn, pymol.stored.resn)
            if (self.c_cap != "none") or (self.n_cap != "none") or (self.hyd != "auto"):
                self.lib_mode = rot_type  # force fragment-based load
            else:
                cmd.create(frag_name, src_sele, 1, 1)
                if self.c_cap == "open":
                    cmd.remove("%s and name OXT" % frag_name)

        if self.lib_mode != "current":
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == "posi") and (frag_type[0:3] != "NT_"):
                if not (cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) &! r. ace" % (src_sele, src_sele))):
                    # use N-terminal fragment
                    frag_type = "NT_" + frag_type
            if (self.c_cap == "nega") and (frag_type[0:3] != "CT_"):
                if not (cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele))):
                    # use C-terminal fragment
                    frag_type = "CT_" + frag_type
            if rot_type[0:3] in ["NT_", "CT_"]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(string.lower(frag_type), frag_name)
            # trim off hydrogens
            if self.hyd == "none":
                cmd.remove("(" + frag_name + " and hydro)")
            elif self.hyd == "auto":
                if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                    cmd.remove("(" + frag_name + " and hydro)")
            # copy identifying information
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.chain=chain")
            cmd.alter("(%s)" % frag_name, "chain=stored.chain")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.resi=resi")
            cmd.alter("(%s)" % frag_name, "resi=stored.resi")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.segi=segi")
            cmd.alter("(%s)" % frag_name, "segi=stored.segi")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.ss=ss")
            cmd.alter("(%s)" % frag_name, "ss=stored.ss")
            # move the fragment
            if (cmd.count_atoms("(%s and n;cb)" % frag_name) == 1) and (
                cmd.count_atoms("(%s and n;cb)" % src_sele) == 1
            ):
                cmd.pair_fit(
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;ca)" % src_sele,
                    "(%s and n;cb)" % frag_name,
                    "(%s and n;cb)" % src_sele,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;c)" % src_sele,
                    "(%s and n;n)" % frag_name,
                    "(%s and n;n)" % src_sele,
                )
            else:
                cmd.pair_fit(
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;ca)" % src_sele,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;c)" % src_sele,
                    "(%s and n;n)" % frag_name,
                    "(%s and n;n)" % src_sele,
                )

            # fix the carbonyl position...
            cmd.iterate_state(1, "(%s and n;o)" % src_sele, "stored.list=[x,y,z]")
            cmd.alter_state(1, "(%s and n;o)" % frag_name, "(x,y,z)=stored.list")
            if cmd.count_atoms("(%s and n;oxt)" % src_sele):
                cmd.iterate_state(1, "(%s and n;oxt)" % src_sele, "stored.list=[x,y,z]")
                cmd.alter_state(1, "(%s and n;oxt)" % frag_name, "(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s and n;oxt)" % frag_name):  # place OXT if no template exists
                angle = cmd.get_dihedral(
                    "(%s and n;n)" % frag_name,
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;o)" % frag_name,
                )
                cmd.protect("(%s and n;o)" % frag_name)
                cmd.set_dihedral(
                    "(%s and n;n)" % frag_name,
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;oxt)" % frag_name,
                    180.0 + angle,
                )
                cmd.deprotect(frag_name)

            # fix the hydrogen position (if any)
            if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % frag_name) == 1:
                if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % src_sele) == 1:
                    cmd.iterate_state(1, "(elem h and bound_to (n;n and (%s)))" % src_sele, "stored.list=[x,y,z]")
                    cmd.alter_state(1, "(elem h and bound_to (n;n and (%s)))" % frag_name, "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1, "(n;c and bound_to (%s and e;n))" % src_sele) == 1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral(
                        "(%s and n;c)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;n)" % frag_name, tmp_sele1
                    )
                    cmd.set_dihedral(
                        "(%s and n;c)" % frag_name,
                        "(%s and n;ca)" % frag_name,
                        "(%s and n;n)" % frag_name,
                        "(%s and n;h)" % frag_name,
                        180.0 + angle,
                    )
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in ["amin", "nmet"]:
                if not cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele)):
                    if cmd.count_atoms("n;c & (%s)" % (frag_name)) == 1:
                        if self.c_cap == "amin":
                            editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nhh")
                        elif self.c_cap == "nmet":
                            editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nme")
                        if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name):
                            cmd.h_fix("n;n & bound_to (n;c & (%s))" % frag_name)
                        # trim hydrogens
                        if self.hyd == "none":
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif self.hyd == "auto":
                            if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in ["acet"]:
                if not cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) & !r. ace " % (src_sele, src_sele)):
                    if cmd.count_atoms("n;n & (%s)" % (frag_name)) == 1:
                        if self.n_cap == "acet":
                            editor.attach_amino_acid("n;n & (%s)" % (frag_name), "ace")
                        if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name):
                            cmd.h_fix("n;n & (%s)" % frag_name)
                        # trim hydrogens
                        if self.hyd == "none":
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif self.hyd == "auto":
                            if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

        cartoon = cmd.count_atoms("(%s and n;ca and rep cartoon)" % src_sele) > 0
        sticks = cmd.count_atoms("(%s and n;ca and rep sticks)" % src_sele) > 0

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == "dep":
            try:
                result = cmd.phi_psi("%s" % src_sele)
                if len(result) == 1:
                    (phi, psi) = result[result.keys()[0]]
                    (phi, psi) = (int(10 * round(phi / 10)), int(10 * (round(psi / 10))))
                    key = (rot_type, phi, psi)
                    if not self.dep_library.has_key(key):
                        (phi, psi) = (int(20 * round(phi / 20)), int(20 * (round(psi / 20))))
                        key = (rot_type, phi, psi)
                        if not self.dep_library.has_key(key):
                            (phi, psi) = (int(60 * round(phi / 60)), int(60 * (round(psi / 60))))
                            key = (rot_type, phi, psi)
                    lib = self.dep_library.get(key, None)
            except:
                pass
        if lib == None:
            key = rot_type
            lib = self.ind_library.get(key, None)
            if (lib != None) and self.dep == "dep":
                print " Mutagenesis: no phi/psi, using backbone-independent rotamers."
        if lib != None:
            state = 1
            for a in lib:
                cmd.create(obj_name, frag_name, 1, state)
                if state == 1:
                    cmd.select(mut_sele, "(byres (%s like %s))" % (obj_name, src_sele))
                if rot_type == "PRO":
                    cmd.unbond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele)
                for b in a.keys():
                    if b != "FREQ":
                        cmd.set_dihedral(
                            "(%s & n;%s)" % (mut_sele, b[0]),
                            "(%s & n;%s)" % (mut_sele, b[1]),
                            "(%s & n;%s)" % (mut_sele, b[2]),
                            "(%s & n;%s)" % (mut_sele, b[3]),
                            a[b],
                            state=state,
                        )
                    else:
                        cmd.set_title(obj_name, state, "%1.1f%%" % (a[b] * 100))
                if rot_type == "PRO":
                    cmd.bond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print " Mutagenesis: %d rotamers loaded." % len(lib)
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(
                    bump_name,
                    "(((byobj %s) within 6 of (%s and not name n+c+ca+o+h+ha)) and (not (%s)))|(%s)"
                    % (src_sele, mut_sele, src_sele, mut_sele),
                    singletons=1,
                )
                cmd.color("gray50", bump_name + " and elem c")
                cmd.set("seq_view", 0, bump_name, quiet=1)
                cmd.hide("everything", bump_name)
                if (cmd.select(tmp_sele1, "(n;N and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (
                    cmd.select(tmp_sele2, "(n;C and (%s in %s))" % (bump_name, mut_sele)) == 1
                ):
                    cmd.bond(tmp_sele1, tmp_sele2)
                if (cmd.select(tmp_sele1, "(n;C and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (
                    cmd.select(tmp_sele2, "(n;N and (%s in %s))" % (bump_name, mut_sele)) == 1
                ):
                    cmd.bond(tmp_sele1, tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect("%s and not (%s in (%s and not name n+c+ca+o+h+ha))" % (bump_name, bump_name, mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo", bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode", 1, bump_name)
                state = 1
                for a in lib:
                    cmd.sculpt_iterate(bump_name, state=state)
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name, frag_name, 1, 1)
            print " Mutagenesis: no rotamers found in library."
        cmd.set("seq_view", 0, obj_name, quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("(" + obj_name + ")")
        cmd.show(self.rep, obj_name)
        cmd.show("lines", obj_name)  # neighbor  always show lines
        if cartoon:
            cmd.show("cartoon", obj_name)
        if sticks:
            cmd.show("sticks", obj_name)
        cmd.set("auto_zoom", auto_zoom, quiet=1)
        cmd.delete(frag_name)
        cmd.frame(0)
        cmd.unpick()
        cmd.feedback("pop")
示例#40
0
def visualize_path((path, freq, pdb, outfile)):
    nodes = path.split('=>')
    save_pse = True

    #print outfile
    #print freq
    #sys.exit()
    #print nodes
    node_color = sns.color_palette("Reds", n_colors=len(nodes))
    node_color.reverse()
    #print node_color
    cmd.reinitialize()
    cmd.load(pdb)
    cmd.hide("everything")
    #    cmd.show("ribbon")
    cmd.show("cartoon")
    #resa = re.sub(r':\w', ':', nodes[0])
    (chain, resnum) = re.split(':\w', nodes[0])
    a = "chain {} and resi {} and name CA".format(chain, resnum)
    cmd.show("spheres", a)

    colorname = "color" + str(0)
    cmd.set_color(colorname, node_color[0])
    cmd.color(colorname, a)
    cmd.label(a, '" %s:%s" % (resi, resn)')
    cmd.set("label_color", "red", a)
    #cmd.label(a, '"%s" % (resi)')
    for i in range(1, len(nodes)):

        #resb = re.sub(r':\w', ':', nodes[i])
        (chain, resnum) = re.split(':\w', nodes[i])
        b = "chain {} and resi {} and name CA".format(chain, resnum)
        #print a,b
        cmd.bond(a, b)
        cmd.set_bond("line_width", 5, a, b)
        cmd.set_bond("line_color", "red", a, b)
        cmd.show("lines", a)
        cmd.show("spheres", a)

        cmd.show("lines", b)
        cmd.show("spheres", b)
        colorname = "color" + str(i)
        cmd.set_color(colorname, node_color[i])
        cmd.color(colorname, b)
        #cmd.label(b,'" %s:%s" % (resi, resn)')
        cmd.label(b, '" %s%s" % (one_letter[resn],resi)')
        #cmd.label(b, '"%s" % (resi)')
        a = b
    #cmd.color(node_color[len)],b)
    #cmd.space("cmyk")
    cmd.set("ray_shadow", "off")
    #cmd.bg_color("white")
    #cmd.label_position([3,2,1])
    cmd.set("label_position", (2, 2, 2))
    sele = "chain A and resi 131 and not name H*"
    cmd.show("sticks", sele)

    norm_factor = freq[nodes[0]]

    node_freqs = {k: freq[k] for k in nodes}
    #print node_freqs
    #print freq[nodes]
    #print sorted(node_freqs.values())
    node_freq_min = min(node_freqs.values())
    #print node_freq_min
    #sys.exit()

    scale_cutoff = min(0.25, min(node_freqs.values()) / norm_factor)

    #print nodes
    #print node_freqs
    #print freq
    #sys.exit()

    for res in freq.keys():
        scale = freq[res] / norm_factor
        #print res,freq[res],scale,scale_cutoff
        if scale > scale_cutoff:
            (chain, resnum) = re.split(':\w', res)
            sele = "chain {} and resi {} and name CA".format(chain, resnum)
            cmd.show("spheres", sele)
            cmd.set("sphere_scale", scale, selection=sele)
            if not res in nodes:  #give residue not on highest freq path a different color
                last_color = len(nodes) - 1
                #colorname="color"+str(last_color)
                colorname = "grey60"  #color" + str(last_color)
                cmd.color(colorname, sele)
                cmd.label(sele, '" %s%s" % (one_letter[resn],resi)')

    cmd.util.cnc(sele)
    #cmd.center("chain A")
    cmd.deselect()
    ### cut below here and paste into script ###
    cmd.set_view([\
              0.354133159,   -0.915425777,    0.191264138,\
              -0.626513124,   -0.384070098,   -0.678214610,\
              0.694314659,    0.120348796,   -0.709537089,\
              -0.000188543,   -0.000061929, -119.472831726,\
              33.501632690,   81.432159424,  143.041992188,\
              87.118530273,  151.834289551,  -20.000000000\
              ])

    ### cut above here and paste into script ###

    #outfile="{}cluster{}-{}.png".format(outfolder,cut,freq)
    # if ray:
    #     cmd.ray()
    #     cmd.sync(10)
    cmd.save(outfile)
    cmd.sync(10)
    if save_pse:
        outfile_pse = re.sub('.png', '.pse', outfile)
        cmd.save(outfile_pse)
        cmd.sync(10)
示例#41
0
    def apply(self):
        cmd=self.cmd
        pymol=cmd._pymol
        if self.status==1:
            # find the name of the object which contains the selection
            new_name = None
            obj_list = cmd.get_names('objects')
            for a in obj_list:
                if cmd.get_type(a)=="object:molecule":
                    if cmd.count_atoms("(%s and %s)"%(a,src_sele)):
                        new_name = a
                        break
            src_frame = cmd.get_state()
            if new_name==None:
                print " Mutagenesis: object not found."
            else:
                auto_zoom = cmd.get_setting_text('auto_zoom')
                cmd.set('auto_zoom',"0",quiet=1)
                if self.lib_mode!="current":

                    # create copy w/o residue
                    cmd.create(tmp_obj1,"(%s and not %s)"%(new_name,src_sele))

                    # remove existing c-cap in copy (if any)
                    cmd.remove("byres (name N and (%s in (neighbor %s)) and resn nme,nhh)"%
                                (tmp_obj1,src_sele))
                    # remove existing n-cap in copy (if any)
                    cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ace)"%
                                (tmp_obj1,src_sele))
                    
                    # save copy for bonded atom reference
                    cmd.create(tmp_obj3,new_name)
                    # transfer the selection to copy
                    cmd.select(src_sele,"(%s in %s)"%(tmp_obj3,src_sele))
                    # create copy with mutant in correct frame
                    cmd.create(tmp_obj2,obj_name,src_frame,1)
                    cmd.set_title(tmp_obj2,1,'')
                    cmd.delete(new_name)

                    # create the merged molecule
                    cmd.create(new_name,"(%s or %s)"%(tmp_obj1,tmp_obj2),1) # only one state in merged object...

                    # now connect them
                    cmd.select(mut_sele,"(byres (%s like %s))"%(new_name,src_sele))


                    # bond N+0 to C-1
                    if ((cmd.select(tmp_sele1, "(name C and (%s in (neighbor %s)))"%
                                  (new_name,src_sele)) == 1) and
                        (cmd.select(tmp_sele2, "((%s in %s) and n;N)"%
                                    (mut_sele,tmp_obj2)) == 1)):
                        cmd.bond(tmp_sele1,tmp_sele2)
                        cmd.set_geometry(tmp_sele1,3,3) # make amide planer
                        cmd.set_geometry(tmp_sele2,3,3) # make amide planer
                    # bond C+0 to N+1
                    if ((cmd.select(tmp_sele1, "(name N and (%s in (neighbor %s)))"%
                                (new_name,src_sele)) == 1) and
                        (cmd.select(tmp_sele2,"((%s in %s) and n;C)"%
                                    (mut_sele,tmp_obj2)) == 1)):
                        cmd.bond(tmp_sele1,tmp_sele2)
                        cmd.set_geometry(tmp_sele1,3,3) # make amide planer
                        cmd.set_geometry(tmp_sele2,3,3) # make amide planer

                    
                    cmd.delete(tmp_sele1)
                    cmd.delete(tmp_sele2)

                    # fix N-H hydrogen position (if any exists)
                    cmd.h_fix("(name N and bound_to (%s in %s and n;H))"%(new_name,tmp_obj2))

                    
                    # now transfer selection back to the modified object
                    cmd.delete(tmp_obj1)
                    cmd.delete(tmp_obj2)
                    cmd.delete(tmp_obj3)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()               
                else:
                    # create copy with conformation in correct state
                    cmd.create(tmp_obj2,obj_name,src_frame,1)

                    # remove existing c-cap in copy (if any)
                    cmd.remove("byres (name N and (%s in (neighbor %s)) and resn nme,nhh)"%
                                (new_name,src_sele))
                    cmd.remove("(%s) and name OXT"%src_sele)
                    
                    # remove existing n-cap in copy (if any)
                    cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ace)"%
                                (new_name,src_sele))

                    # save existing conformation on undo stack
#               cmd.edit("((%s in %s) and name ca)"%(new_name,src_sele))
                    cmd.push_undo("("+src_sele+")")
                    # modify the conformation
                    cmd.update(new_name,tmp_obj2)
#               cmd.unpick()
                    cmd.delete(tmp_obj2)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()                              
                cmd.set('auto_zoom',auto_zoom,quiet=1)
示例#42
0
    def apply(self):
        cmd = self.cmd
        pymol = cmd._pymol
        if self.status == 1:
            # find the name of the object which contains the selection
            new_name = None
            obj_list = cmd.get_names("objects")
            for a in obj_list:
                if cmd.get_type(a) == "object:molecule":
                    if cmd.count_atoms("(%s and %s)" % (a, src_sele)):
                        new_name = a
                        break
            src_frame = cmd.get_state()
            if new_name == None:
                print " Mutagenesis: object not found."
            else:
                auto_zoom = cmd.get_setting_text("auto_zoom")
                cmd.set("auto_zoom", "0", quiet=1)
                if self.lib_mode != "current":

                    # create copy w/o residue
                    cmd.create(tmp_obj1, "(%s and not %s)" % (new_name, src_sele))

                    # remove existing c-cap in copy (if any)
                    cmd.remove("byres (name N and (%s in (neighbor %s)) and resn nme,nhh)" % (tmp_obj1, src_sele))
                    # remove existing n-cap in copy (if any)
                    cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ace)" % (tmp_obj1, src_sele))

                    # save copy for bonded atom reference
                    cmd.create(tmp_obj3, new_name)
                    # transfer the selection to copy
                    cmd.select(src_sele, "(%s in %s)" % (tmp_obj3, src_sele))
                    # create copy with mutant in correct frame
                    cmd.create(tmp_obj2, obj_name, src_frame, 1)
                    cmd.set_title(tmp_obj2, 1, "")
                    cmd.delete(new_name)

                    # create the merged molecule
                    cmd.create(new_name, "(%s or %s)" % (tmp_obj1, tmp_obj2), 1)  # only one state in merged object...

                    # now connect them
                    cmd.select(mut_sele, "(byres (%s like %s))" % (new_name, src_sele))

                    # bond N+0 to C-1
                    if (cmd.select(tmp_sele1, "(name C and (%s in (neighbor %s)))" % (new_name, src_sele)) == 1) and (
                        cmd.select(tmp_sele2, "((%s in %s) and n;N)" % (mut_sele, tmp_obj2)) == 1
                    ):
                        cmd.bond(tmp_sele1, tmp_sele2)
                        cmd.set_geometry(tmp_sele1, 3, 3)  # make amide planer
                        cmd.set_geometry(tmp_sele2, 3, 3)  # make amide planer
                    # bond C+0 to N+1
                    if (cmd.select(tmp_sele1, "(name N and (%s in (neighbor %s)))" % (new_name, src_sele)) == 1) and (
                        cmd.select(tmp_sele2, "((%s in %s) and n;C)" % (mut_sele, tmp_obj2)) == 1
                    ):
                        cmd.bond(tmp_sele1, tmp_sele2)
                        cmd.set_geometry(tmp_sele1, 3, 3)  # make amide planer
                        cmd.set_geometry(tmp_sele2, 3, 3)  # make amide planer

                    cmd.delete(tmp_sele1)
                    cmd.delete(tmp_sele2)

                    # fix N-H hydrogen position (if any exists)
                    cmd.h_fix("(name N and bound_to (%s in %s and n;H))" % (new_name, tmp_obj2))

                    # now transfer selection back to the modified object
                    cmd.delete(tmp_obj1)
                    cmd.delete(tmp_obj2)
                    cmd.delete(tmp_obj3)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()
                else:
                    # create copy with conformation in correct state
                    cmd.create(tmp_obj2, obj_name, src_frame, 1)

                    # remove existing c-cap in copy (if any)
                    cmd.remove("byres (name N and (%s in (neighbor %s)) and resn nme,nhh)" % (new_name, src_sele))
                    cmd.remove("(%s) and name OXT" % src_sele)

                    # remove existing n-cap in copy (if any)
                    cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ace)" % (new_name, src_sele))

                    # save existing conformation on undo stack
                    #               cmd.edit("((%s in %s) and name ca)"%(new_name,src_sele))
                    cmd.push_undo("(" + src_sele + ")")
                    # modify the conformation
                    cmd.update(new_name, tmp_obj2)
                    #               cmd.unpick()
                    cmd.delete(tmp_obj2)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()
                cmd.set("auto_zoom", auto_zoom, quiet=1)
示例#43
0
def add_missing_atoms(selection='all', cycles=200, quiet=1):
    '''
DESCRIPTION

    Mutate those residues to themselves which have missing atoms

SEE ALSO

    stub2ala
    '''
    from collections import defaultdict
    from chempy import fragments

    cycles, quiet = int(cycles), int(quiet)

    reference = {
        'ALA': set(['CB']),
        'ARG': set(['CB', 'CG', 'NE', 'CZ', 'NH1', 'NH2', 'CD']),
        'ASN': set(['CB', 'CG', 'OD1', 'ND2']),
        'ASP': set(['CB', 'CG', 'OD1', 'OD2']),
        'CYS': set(['CB', 'SG']),
        'GLN': set(['CB', 'CG', 'CD', 'NE2', 'OE1']),
        'GLU': set(['CB', 'CG', 'OE2', 'CD', 'OE1']),
        'GLY': set([]),
        'HIS': set(['CE1', 'CB', 'CG', 'CD2', 'ND1', 'NE2']),
        'ILE': set(['CB', 'CD1', 'CG1', 'CG2']),
        'LEU': set(['CB', 'CG', 'CD1', 'CD2']),
        'LYS': set(['CB', 'CG', 'NZ', 'CE', 'CD']),
        'MET': set(['CB', 'CG', 'CE', 'SD']),
        'PHE': set(['CE1', 'CB', 'CG', 'CZ', 'CD1', 'CD2', 'CE2']),
        'PRO': set(['CB', 'CG', 'CD']),
        'SER': set(['OG', 'CB']),
        'THR': set(['CB', 'OG1', 'CG2']),
        'TRP': set(['CZ2', 'CB', 'CG', 'CH2', 'CE3', 'CD1', 'CD2', 'CZ3', 'NE1', 'CE2']),
        'TYR': set(['CE1', 'OH', 'CB', 'CG', 'CZ', 'CD1', 'CD2', 'CE2']),
        'VAL': set(['CB', 'CG1', 'CG2']),
    }

    namedsele = cmd.get_unused_name('_')
    cmd.select(namedsele, selection, 0)

    namelists = defaultdict(list)
    cmd.iterate('(%s) and polymer' % namedsele,
            'namelists[model,segi,chain,resn,resi,resv].append(name)',
            space=locals())

    sele_dict = defaultdict(list)
    tmp_name = cmd.get_unused_name('_')

    for key, namelist in namelists.items():
        resn = key[3]
        if resn not in reference:
            if not quiet:
                print(' Unknown residue: + ' + resn)
            continue
        if not reference[resn].issubset(namelist):
            try:
                frag = fragments.get(resn.lower())
                for a in frag.atom:
                    a.segi = key[1]
                    a.chain = key[2]
                    a.resi = key[4]
                    a.resi_number = key[5]
                cmd.load_model(frag, tmp_name, 1, zoom=0)

                skey = '/%s/%s/%s/%s`%s' % key[:5]
                cmd.remove(skey + ' and not name N+C+O+OXT+CA')
                cmd.align(tmp_name, skey + ' and name N+C+CA', cycles=0)
                cmd.remove(tmp_name + ' and (name N+C+O+CA or hydro)')
                cmd.fuse('name CB and ' + tmp_name, 'name CA and ' + skey, move=0)
                if resn == 'PRO':
                    cmd.bond(skey + '/N', skey + '/CD')
                cmd.unpick()
                cmd.delete(tmp_name)

                sele_dict[key[0]].append(skey)

                if not quiet:
                    print(' Mutated ' + skey)
            except:
                print(' Mutating ' + skey + ' failed')

    for model in sele_dict:
        cmd.sort(model)
        sculpt_relax(' '.join(sele_dict[model]), 0, 0, model, cycles)

    cmd.delete(namedsele)
示例#44
0
def garnish(file="topol.top", selection='all', gmx=None, fix_elastics=1, guess_prot=1, show=1):
    """
DESCRIPTION

    Allow a coarse grained structure to be visualized in pymol like an atomistic structure
    by drawing bonds and elastic network.

    Without a top/tpr file, this function only adds bonds between the backbone beads
    so they can be nicely visualized using line or stick representation.
    Adding a top/tpr file provides topology information that can be used
    to draw side chain and elastic bonds.

USAGE

    garnish [file [, selection [, gmx]]]

ARGUMENTS

    file = a tpr or topology file to extract bond information from (default: None)
    selection = any selection to act upon (default: all)
    gmx = gmx executable path (default: inferred by `which gmx`)
    fix_elastics = fix elastic bonds based on atom id. Disable if your beads are
                   numbered non-sequentially (default: 1)
    guess_prot = if file is not present, simply draw bonds between backbone atoms of a protein (default: 1)
    show = adjust representation after drawing bonds (default: 1)
    """
    fix_elastics = bool(int(fix_elastics))
    guess_prot = bool(int(guess_prot))
    show = bool(int(show))

    # Retain order so pymol does not sort the atoms, giving a different result when saving the file
    cmd.set("retain_order", 1)

    if file:
        # parse the file
        sys_dict = parse(file, gmx)
        # create System object and draw all the bonds
        system = System(sys_dict, fix_elastics=fix_elastics)
        system.draw_bonds(selection)
        system.transfer_attributes(selection)

    elif guess_prot:
        bb_beads = get_chain_bb(selection)
        # For each object and chain, draw bonds between BB beads
        for obj, chains in bb_beads.items():
            for _, bbs in chains.items():
                # create bond tuples for "adjacent" backbone beads
                bonds = [(bbs[i], bbs[i+1]) for i in range(len(bbs) - 1)]
                for a, b in bonds:
                    try:
                        cmd.add_bond(obj, a, b)
                    except AttributeError:
                        cmd.bond(f"{obj} and ID {a}", f"{obj} and ID {b}")

    else:
        # show as spheres if no info on bonds is present
        if show:
            cmd.show_as('spheres', selection)
        return

    if show:
        cmd.hide("everything", selection)
        cmd.show_as("sticks", selection)
        # Fix the view for elastics
        cmd.color('orange', '*_elastics')
        cmd.show_as("lines", '*_elastics')

    # We could use this for debugging
    return system
示例#45
0
def peptide_rebuild(name, selection='all', cycles=1000, state=1, quiet=1):
    '''
DESCRIPTION

    Rebuild the peptide from selection. All atoms which are present in
    selection will be kept fixed, while atoms missing in selection are
    placed by sculpting.

USAGE

    peptide_rebuild name [, selection [, cycles [, state ]]]

SEE ALSO

    stub2ala, add_missing_atoms, peptide_rebuild_modeller
    '''
    from chempy import fragments, feedback, models

    cycles, state, quiet = int(cycles), int(state), int(quiet)

    # suppress feedback for model merging
    feedback['actions'] = False

    # work with named selection
    namedsele = cmd.get_unused_name('_')
    cmd.select(namedsele, selection, 0)

    identifiers = []
    cmd.iterate(namedsele + ' and polymer and guide and alt +A',
            'identifiers.append([segi,chain,resi,resv,resn])', space=locals())

    model = models.Indexed()
    for (segi,chain,resi,resv,resn) in identifiers:
        try:
            fname = resn.lower() if resn != 'MSE' else 'met'
            frag = fragments.get(fname)
        except IOError:
            print(' Warning: unknown residue: ' + resn)
            continue

        for a in frag.atom:
            a.segi = segi
            a.chain = chain
            a.resi = resi
            a.resi_number = resv
            a.resn = resn

        model.merge(frag)

    if not quiet:
        print(' Loading model...')

    cmd.load_model(model, name, 1, zoom=0)
    if cmd.get_setting_boolean('auto_remove_hydrogens'):
        cmd.remove(name + ' and hydro')

    cmd.protect(name + ' in ' + namedsele)
    cmd.sculpt_activate(name)
    cmd.update(name, namedsele, 1, state)
    cmd.delete(namedsele)

    if not quiet:
        print(' Sculpting...')

    cmd.set('sculpt_field_mask', 0x003, name) # bonds and angles only
    cmd.sculpt_iterate(name, 1, int(cycles / 4))

    cmd.set('sculpt_field_mask', 0x09F, name) # local + torsions
    cmd.sculpt_iterate(name, 1, int(cycles / 4))

    cmd.set('sculpt_field_mask', 0x0FF, name) # ... + vdw
    cmd.sculpt_iterate(name, 1, int(cycles / 2))

    cmd.sculpt_deactivate(name)
    cmd.deprotect(name)
    cmd.unset('sculpt_field_mask', name)

    if not quiet:
        print(' Connecting peptide...')

    pairs = cmd.find_pairs(name + ' and name C', name + ' and name N', 1, 1, 2.0)
    for pair in pairs:
        cmd.bond(*pair)
    cmd.h_fix(name)

    if not quiet:
        print(' peptide_rebuild: done')